Fix variable links not persisted when variable is used multiple times in config
- Dedupe extracted variable names (duplicate INSERTs aborted the config_has_variable transaction on PK conflict) - Check per-statement rqlite errors in ExecTransaction: a failed statement silently returned success before - Make link upserts idempotent (insert or ignore) and add link backfill on variable create/upsert from existing configs - Validate config variables before insert (no orphaned configs) - Resync active config links on module reconnect and on no-op config update (self-healing)
This commit is contained in:
1 parent
5c8a554d4f
commit
7f4e3ef028
7 files changed
+227
-21
No files matched your search
@@ -3,6 +3,7 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
@@ -203,6 +204,37 @@ func (r Config) GetMetaByVariables(ctx context.Context, variables []string) (map
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r Config) FindIdsByVariableReference(ctx context.Context, variableName string) ([]string, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.FindIdsByVariableReference")
|
||||
|
||||
escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(variableName)
|
||||
pattern := `%\_Var\(` + escaped + `)%`
|
||||
|
||||
// nolint:unqueryvet
|
||||
query, args, err := squirrel.Select("id").
|
||||
From(Table("config")).
|
||||
Where(squirrel.Expr(`data like ? escape '\'`, pattern)).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
type configIdRow struct {
|
||||
Id string `json:"id"`
|
||||
}
|
||||
rows := make([]configIdRow, 0)
|
||||
err = r.db.Select(ctx, &rows, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.Id)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (r Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) (bool, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.UpdateConfigName")
|
||||
|
||||
|
||||
+27
-8
@@ -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)
|
||||
@@ -175,6 +171,29 @@ func (r Variable) UpsertLinks(ctx context.Context, configId string, links []enti
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Variable) InsertLinks(ctx context.Context, links []entity.ConfigHasVariable) error {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.InsertLinks")
|
||||
|
||||
if len(links) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
requests := make([][]any, 0, len(links))
|
||||
for _, link := range links {
|
||||
requests = append(requests, db.Request(
|
||||
`insert or ignore into `+Table("config_has_variable")+` (config_id, variable_name) values (?, ?)`,
|
||||
link.ConfigId, link.VariableName,
|
||||
))
|
||||
}
|
||||
|
||||
_, err := r.db.ExecTransaction(ctx, requests)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "exec transaction: %v", requests)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Variable) Delete(ctx context.Context, name string) (bool, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Delete")
|
||||
|
||||
|
||||
+10
-5
@@ -152,6 +152,11 @@ func (c Config) CreateUpdateConfig(
|
||||
return nil, errors.WithMessage(err, "compare data configs")
|
||||
}
|
||||
if isMatch {
|
||||
// Links may be missing after a partially failed update; re-save them even when data is unchanged.
|
||||
err = c.variableService.SaveVariableLinks(ctx, req.Id, variableExtractionResult.VariableLinks)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "save variable links")
|
||||
}
|
||||
c.logger.Info(ctx, "no changes in config; skip update")
|
||||
return &domain.CreateUpdateConfigResponse{Config: configToDto(*oldConfig, nil), IsChanged: false}, nil
|
||||
}
|
||||
@@ -295,15 +300,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")
|
||||
|
||||
@@ -221,24 +221,35 @@ 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")
|
||||
}
|
||||
|
||||
config = &initialConfig
|
||||
} else {
|
||||
// Re-sync links on every connect: they are derived data and may be missing after a partially failed update.
|
||||
result, err := s.variableService.ExtractVariables(ctx, config.Id, config.Data)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "extract variables from active config")
|
||||
}
|
||||
err = s.variableService.SaveVariableLinks(ctx, config.Id, result.VariableLinks)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "resync variable links in store")
|
||||
}
|
||||
}
|
||||
|
||||
configData, err := s.variableService.RenderConfig(ctx, config.Data)
|
||||
|
||||
@@ -148,6 +148,11 @@ 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.
|
||||
if err := catchError(nil, result); err != nil {
|
||||
return nil, errors.WithMessagef(err, "exec transaction on statement: %v", requests[min(len(results), len(requests)-1)])
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
|
||||
@@ -20,10 +20,12 @@ type Repo interface {
|
||||
Upsert(ctx context.Context, variables []entity.Variable) error
|
||||
Delete(ctx context.Context, name string) (bool, error)
|
||||
UpsertLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error
|
||||
InsertLinks(ctx context.Context, links []entity.ConfigHasVariable) error
|
||||
}
|
||||
|
||||
type ConfigRepo interface {
|
||||
GetMetaByVariables(ctx context.Context, variables []string) (map[string][]entity.ConfigMetaWithVariable, error)
|
||||
FindIdsByVariableReference(ctx context.Context, variableName string) ([]string, error)
|
||||
}
|
||||
|
||||
type EventRepo interface {
|
||||
@@ -106,6 +108,16 @@ func (s Service) Create(ctx context.Context, req domain.CreateVariableRequest) e
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert variable")
|
||||
}
|
||||
|
||||
err = s.syncVariableLinks(ctx, []string{variable.Name})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "sync variable links")
|
||||
}
|
||||
|
||||
err = s.syncConfigsByVariables(ctx, []string{variable.Name})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "sync configs by variables")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -151,6 +163,11 @@ func (s Service) Upsert(ctx context.Context, req []domain.UpsertVariableRequest)
|
||||
return errors.WithMessage(err, "upsert variables")
|
||||
}
|
||||
|
||||
err = s.syncVariableLinks(ctx, variableNames)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "sync variable links")
|
||||
}
|
||||
|
||||
err = s.syncConfigsByVariables(ctx, variableNames)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "sync configs by variables")
|
||||
@@ -215,9 +232,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{
|
||||
@@ -287,6 +310,28 @@ func (s Service) toDto(variable entity.Variable, metaByVariables map[string][]en
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) syncVariableLinks(ctx context.Context, variableNames []string) error {
|
||||
for _, name := range variableNames {
|
||||
configIds, err := s.configRepo.FindIdsByVariableReference(ctx, name)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "find configs referencing variable: %s", name)
|
||||
}
|
||||
links := make([]entity.ConfigHasVariable, 0, len(configIds))
|
||||
for _, configId := range configIds {
|
||||
links = append(links, entity.ConfigHasVariable{
|
||||
ConfigId: configId,
|
||||
VariableName: name,
|
||||
})
|
||||
}
|
||||
err = s.repo.InsertLinks(ctx, links)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "insert links for variable: %s", name)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) syncConfigsByVariables(ctx context.Context, variables []string) error {
|
||||
metaByVariables, err := s.configRepo.GetMetaByVariables(ctx, variables)
|
||||
if err != nil {
|
||||
|
||||
@@ -124,6 +124,95 @@ func TestVariableAcceptance(t *testing.T) {
|
||||
require.Empty(allResponse[1].Value) // secret
|
||||
}
|
||||
|
||||
//nolint: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