Merge branch 'fix-variable-links-persist' into 'main'
Fix: variable links not saved when a variable is used multiple times in config See merge request isp/isp-config-service!20
This commit is contained in:
commit
780c2232fb
10 files changed
+130
-25
No files matched your search
@@ -8,6 +8,8 @@ linters:
|
||||
- depguard # не всегда имеет смысл
|
||||
- dupword # не имеет смысла
|
||||
- exhaustruct # не имеет смысла
|
||||
- exhaustruct_v5 # не имеет смысла
|
||||
- goconst # не всегда имеет смысл
|
||||
- godot # не актуально для swagger
|
||||
- godox # не позволяет оставлять todo
|
||||
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
### v3.11.1
|
||||
* Исправлено: при сохранении конфига с многократным использованием одной переменной через `_Var()` терялись все связи переменной с конфигами (конфликт PK в транзакции ссылок)
|
||||
* Ошибки statement в rqlite-транзакциях больше не игнорируются молча, возвращаются как ошибка запроса
|
||||
* Отключены линтеры `exhaustruct_v5`, `goconst`
|
||||
### v3.11.0
|
||||
* Добавлены `admin` permission к endpoint'ам
|
||||
### v3.10.0
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user