From cf59e619167c6c14246b4edba380c67c7014e871 Mon Sep 17 00:00:00 2001 From: txix Date: Wed, 28 Oct 2026 11:42:14 +0300 Subject: [PATCH] 2026-10-28 11:42:14: merge [main:780c2232fbac671ac83e2dff49114323f66f8e1b]; --- .golangci.yml | 2 + .version | 2 +- changelog.md | 4 ++ middlewares/ws_log.go | 3 +- repository/variable.go | 12 ++--- service/api/config.go | 14 +++--- service/module/service.go | 11 ++--- service/rqlite/db/db.go | 6 +++ service/variable/service.go | 12 +++-- tests/variable_test.go | 89 +++++++++++++++++++++++++++++++++++++ 10 files changed, 130 insertions(+), 25 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 7b7ce16..ea9c85c 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -8,6 +8,8 @@ linters: - depguard # не всегда имеет смысл - dupword # не имеет смысла - exhaustruct # не имеет смысла + - exhaustruct_v5 # не имеет смысла + - goconst # не всегда имеет смысл - godot # не актуально для swagger - godox # не позволяет оставлять todo - musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур diff --git a/.version b/.version index afad818..371cfe3 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -3.11.0 +3.11.1 diff --git a/changelog.md b/changelog.md index 2ec007d..c2340cb 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,7 @@ +### v3.11.1 +* Исправлено: при сохранении конфига с многократным использованием одной переменной через `_Var()` терялись все связи переменной с конфигами (конфликт PK в транзакции ссылок) +* Ошибки statement в rqlite-транзакциях больше не игнорируются молча, возвращаются как ошибка запроса +* Отключены линтеры `exhaustruct_v5`, `goconst` ### v3.11.0 * Добавлены `admin` permission к endpoint'ам ### v3.10.0 diff --git a/middlewares/ws_log.go b/middlewares/ws_log.go index 4c20c7c..59d1736 100644 --- a/middlewares/ws_log.go +++ b/middlewares/ws_log.go @@ -2,6 +2,7 @@ package middlewares import ( "context" + "slices" "github.com/txix-open/etp/v4" @@ -27,7 +28,7 @@ func EtpLogger(logger log.Logger) EtpMiddleware { //nolint:ireturn func EtpChain(root etp.Handler, middlewares ...EtpMiddleware) etp.Handler { - for i := len(middlewares) - 1; i >= 0; i-- { + for i := range slices.Backward(middlewares) { root = middlewares[i](root) } return root diff --git a/repository/variable.go b/repository/variable.go index f424092..773f23a 100644 --- a/repository/variable.go +++ b/repository/variable.go @@ -157,14 +157,10 @@ func (r Variable) UpsertLinks(ctx context.Context, configId string, links []enti } for _, variable := range links { - query, args, err := squirrel.Insert(Table("config_has_variable")). - Columns("config_id", "variable_name"). - Values(variable.ConfigId, variable.VariableName). - ToSql() - if err != nil { - return errors.WithMessage(err, "build query") - } - requests = append(requests, db.Request(query, args...)) + requests = append(requests, db.Request( + `insert or ignore into `+Table("config_has_variable")+` (config_id, variable_name) values (?, ?)`, + variable.ConfigId, variable.VariableName, + )) } _, err = r.db.ExecTransaction(ctx, requests) diff --git a/service/api/config.go b/service/api/config.go index f4ec769..6f8079c 100644 --- a/service/api/config.go +++ b/service/api/config.go @@ -295,15 +295,15 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre Active: false, AdminId: adminId, } - err := c.configRepo.Insert(ctx, config) - if err != nil { - return domain.Config{}, errors.WithMessage(err, "insert new config") - } - + // Check variables before insert so a config with missing variables is never persisted without links. extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data) if err != nil { return domain.Config{}, err } + err = c.configRepo.Insert(ctx, config) + if err != nil { + return domain.Config{}, errors.WithMessage(err, "insert new config") + } err = c.variableService.SaveVariableLinks(ctx, config.Id, extractResult.VariableLinks) if err != nil { return domain.Config{}, errors.WithMessage(err, "save variable links") @@ -323,7 +323,7 @@ func (c Config) extractAndCheckVariables(ctx context.Context, configId string, i for _, variable := range variableExtractionResult.AbsentVariables { details[variable] = "variable is not defined" } - return nil, domain.NewConfigValidationError(details) + return nil, errors.WithMessage(domain.NewConfigValidationError(details), "config validation") } return variableExtractionResult, nil } @@ -345,7 +345,7 @@ func (c Config) validateConfigUpdate(ctx context.Context, moduleId string, confi return nil } - return domain.NewConfigValidationError(details) + return errors.WithMessage(domain.NewConfigValidationError(details), "config validation") } func (c Config) emitChangeActiveConfigEvent(ctx context.Context, moduleId string) error { diff --git a/service/module/service.go b/service/module/service.go index 248abe9..7f24341 100644 --- a/service/module/service.go +++ b/service/module/service.go @@ -221,18 +221,19 @@ func (s Service) OnModuleConfigSchema( Version: 1, Active: xtypes.Bool(true), } - err := s.configRepo.Insert(ctx, initialConfig) - if err != nil { - return errors.WithMessage(err, "insert config in store") - } result, err := s.variableService.ExtractVariables(ctx, initialConfig.Id, initialConfig.Data) if err != nil { - return errors.WithMessage(err, "extract and save variable links in store") + return errors.WithMessage(err, "extract variables from initial config") } if len(result.AbsentVariables) > 0 { return errors.Errorf("missing variables in initial config: [%s]", strings.Join(result.AbsentVariables, ",")) } + + err = s.configRepo.Insert(ctx, initialConfig) + if err != nil { + return errors.WithMessage(err, "insert config in store") + } err = s.variableService.SaveVariableLinks(ctx, initialConfig.Id, result.VariableLinks) if err != nil { return errors.WithMessage(err, "save variable links in store") diff --git a/service/rqlite/db/db.go b/service/rqlite/db/db.go index 76e3097..4969f4f 100644 --- a/service/rqlite/db/db.go +++ b/service/rqlite/db/db.go @@ -148,6 +148,12 @@ func (d Adapter) exec(ctx context.Context, inTx bool, requests [][]any) ([]sql.R results := make([]sql.Result, 0, len(requests)) for _, result := range resp.Results { + // rqlite reports per-statement failures in individual results with HTTP 200, + // and aborts the whole transaction on the first failed statement. + err := catchError(nil, result) + if err != nil { + return nil, errors.WithMessagef(err, "exec transaction on statement: %v", requests[min(len(results), len(requests)-1)]) + } results = append(results, result) } diff --git a/service/variable/service.go b/service/variable/service.go index a87676e..30dd800 100644 --- a/service/variable/service.go +++ b/service/variable/service.go @@ -215,9 +215,15 @@ func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) func (s Service) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) { matches := s.variableRegexp.FindAllStringSubmatch(string(input), -1) - varNames := make([]string, len(matches)) - for i, match := range matches { - varNames[i] = match[1] + seen := make(map[string]bool, len(matches)) + varNames := make([]string, 0, len(matches)) + for _, match := range matches { + name := match[1] + if seen[name] { + continue + } + seen[name] = true + varNames = append(varNames, name) } if len(varNames) == 0 { return &domain.VariableExtractionResult{ diff --git a/tests/variable_test.go b/tests/variable_test.go index 249879d..97d3606 100644 --- a/tests/variable_test.go +++ b/tests/variable_test.go @@ -124,6 +124,95 @@ func TestVariableAcceptance(t *testing.T) { require.Empty(allResponse[1].Value) // secret } +//nolint:funlen,paralleltest +func TestVariableLinksAfterConfigUpdate(t *testing.T) { + require := require.New(t) + logger := setupTest(t) + + apiCli, err := client.Default() + require.NoError(err) + apiCli.Upgrade([]string{"127.0.0.1:9002"}) + + err = apiCli.Invoke("config/variable/create"). + JsonRequestBody(domain.CreateVariableRequest{ + Name: "linkVar", + Description: "test", + Type: "TEXT", + Value: fake.It[string](), + }). + Do(t.Context()) + require.NoError(err) + + type linkTestConfig struct { + Addr string + Alias string + } + clientC := newClusterClientWith( + t, + "LinkTestModule", + "10.2.9.77", + linkTestConfig{}, + []byte(`{"addr":"init","alias":"init"}`), + nil, + logger, + ) + go func() { + handler := cluster.NewEventHandler() + err := clientC.Run(t.Context(), handler) + require.NoError(err) //nolint:testifylint + }() + time.Sleep(2 * time.Second) + + activeConfig := domain.Config{} + err = apiCli.Invoke("config/config/get_active_config_by_module_name"). + JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "LinkTestModule"}). + JsonResponseBody(&activeConfig). + Do(t.Context()) + require.NoError(err) + + // The same variable is referenced twice in the config data. + err = apiCli.Invoke("config/config/create_update_config"). + JsonRequestBody(domain.CreateUpdateConfigRequest{ + Id: activeConfig.Id, + Name: activeConfig.Name, + ModuleId: activeConfig.ModuleId, + Version: activeConfig.Version, + Data: []byte(`{"addr":"_Var(linkVar)","alias":"prefix/_Var(linkVar)"}`), + }). + Do(t.Context()) + require.NoError(err) + + varResponse := []domain.Variable{} + err = apiCli.Invoke("config/variable/all"). + JsonResponseBody(&varResponse). + Do(t.Context()) + require.NoError(err) + require.Len(varResponse, 1) + require.Equal("linkVar", varResponse[0].Name) + require.Len(varResponse[0].ContainsInConfigs, 1) + require.Equal(activeConfig.Id, varResponse[0].ContainsInConfigs[0].Id) + + // Re-saving identical config data must keep the links. + err = apiCli.Invoke("config/config/create_update_config"). + JsonRequestBody(domain.CreateUpdateConfigRequest{ + Id: activeConfig.Id, + Name: activeConfig.Name, + ModuleId: activeConfig.ModuleId, + Version: activeConfig.Version, + Data: []byte(`{"alias":"prefix/_Var(linkVar)","addr":"_Var(linkVar)"}`), + }). + Do(t.Context()) + require.NoError(err) + + varResponse = []domain.Variable{} + err = apiCli.Invoke("config/variable/all"). + JsonResponseBody(&varResponse). + Do(t.Context()) + require.NoError(err) + require.Len(varResponse[0].ContainsInConfigs, 1) + require.Equal(activeConfig.Id, varResponse[0].ContainsInConfigs[0].Id) +} + func unmarshalConfig(require *require.Assertions, configData []byte) configWithVars { firstConfig := configWithVars{} err := json.Unmarshal(configData, &firstConfig)