Compare commits

...
1 Commits
Author SHA1 Message Date
txix cf59e61916 2026-10-28 11:42:14: merge [main:780c2232fbac671ac83e2dff49114323f66f8e1b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-10-28 11:42:14 +03:00
10 changed files with 130 additions and 25 deletions

No files matched your search

+2
View File
@@ -8,6 +8,8 @@ linters:
- depguard # не всегда имеет смысл - depguard # не всегда имеет смысл
- dupword # не имеет смысла - dupword # не имеет смысла
- exhaustruct # не имеет смысла - exhaustruct # не имеет смысла
- exhaustruct_v5 # не имеет смысла
- goconst # не всегда имеет смысл
- godot # не актуально для swagger - godot # не актуально для swagger
- godox # не позволяет оставлять todo - godox # не позволяет оставлять todo
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур - musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
+1 -1
View File
@@ -1 +1 @@
3.11.0 3.11.1
+4
View File
@@ -1,3 +1,7 @@
### v3.11.1
* Исправлено: при сохранении конфига с многократным использованием одной переменной через `_Var()` терялись все связи переменной с конфигами (конфликт PK в транзакции ссылок)
* Ошибки statement в rqlite-транзакциях больше не игнорируются молча, возвращаются как ошибка запроса
* Отключены линтеры `exhaustruct_v5`, `goconst`
### v3.11.0 ### v3.11.0
* Добавлены `admin` permission к endpoint'ам * Добавлены `admin` permission к endpoint'ам
### v3.10.0 ### v3.10.0
+2 -1
View File
@@ -2,6 +2,7 @@ package middlewares
import ( import (
"context" "context"
"slices"
"github.com/txix-open/etp/v4" "github.com/txix-open/etp/v4"
@@ -27,7 +28,7 @@ func EtpLogger(logger log.Logger) EtpMiddleware {
//nolint:ireturn //nolint:ireturn
func EtpChain(root etp.Handler, middlewares ...EtpMiddleware) etp.Handler { 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) root = middlewares[i](root)
} }
return root return root
+4 -8
View File
@@ -157,14 +157,10 @@ func (r Variable) UpsertLinks(ctx context.Context, configId string, links []enti
} }
for _, variable := range links { for _, variable := range links {
query, args, err := squirrel.Insert(Table("config_has_variable")). requests = append(requests, db.Request(
Columns("config_id", "variable_name"). `insert or ignore into `+Table("config_has_variable")+` (config_id, variable_name) values (?, ?)`,
Values(variable.ConfigId, variable.VariableName). variable.ConfigId, variable.VariableName,
ToSql() ))
if err != nil {
return errors.WithMessage(err, "build query")
}
requests = append(requests, db.Request(query, args...))
} }
_, err = r.db.ExecTransaction(ctx, requests) _, err = r.db.ExecTransaction(ctx, requests)
+7 -7
View File
@@ -295,15 +295,15 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre
Active: false, Active: false,
AdminId: adminId, AdminId: adminId,
} }
err := c.configRepo.Insert(ctx, config) // Check variables before insert so a config with missing variables is never persisted without links.
if err != nil {
return domain.Config{}, errors.WithMessage(err, "insert new config")
}
extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data) extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data)
if err != nil { if err != nil {
return domain.Config{}, err 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) err = c.variableService.SaveVariableLinks(ctx, config.Id, extractResult.VariableLinks)
if err != nil { if err != nil {
return domain.Config{}, errors.WithMessage(err, "save variable links") 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 { for _, variable := range variableExtractionResult.AbsentVariables {
details[variable] = "variable is not defined" details[variable] = "variable is not defined"
} }
return nil, domain.NewConfigValidationError(details) return nil, errors.WithMessage(domain.NewConfigValidationError(details), "config validation")
} }
return variableExtractionResult, nil return variableExtractionResult, nil
} }
@@ -345,7 +345,7 @@ func (c Config) validateConfigUpdate(ctx context.Context, moduleId string, confi
return nil return nil
} }
return domain.NewConfigValidationError(details) return errors.WithMessage(domain.NewConfigValidationError(details), "config validation")
} }
func (c Config) emitChangeActiveConfigEvent(ctx context.Context, moduleId string) error { func (c Config) emitChangeActiveConfigEvent(ctx context.Context, moduleId string) error {
+6 -5
View File
@@ -221,18 +221,19 @@ func (s Service) OnModuleConfigSchema(
Version: 1, Version: 1,
Active: xtypes.Bool(true), 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) result, err := s.variableService.ExtractVariables(ctx, initialConfig.Id, initialConfig.Data)
if err != nil { 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 { if len(result.AbsentVariables) > 0 {
return errors.Errorf("missing variables in initial config: [%s]", strings.Join(result.AbsentVariables, ",")) 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) err = s.variableService.SaveVariableLinks(ctx, initialConfig.Id, result.VariableLinks)
if err != nil { if err != nil {
return errors.WithMessage(err, "save variable links in store") return errors.WithMessage(err, "save variable links in store")
+6
View File
@@ -148,6 +148,12 @@ func (d Adapter) exec(ctx context.Context, inTx bool, requests [][]any) ([]sql.R
results := make([]sql.Result, 0, len(requests)) results := make([]sql.Result, 0, len(requests))
for _, result := range resp.Results { 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) results = append(results, result)
} }
+9 -3
View File
@@ -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) { func (s Service) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) {
matches := s.variableRegexp.FindAllStringSubmatch(string(input), -1) matches := s.variableRegexp.FindAllStringSubmatch(string(input), -1)
varNames := make([]string, len(matches)) seen := make(map[string]bool, len(matches))
for i, match := range matches { varNames := make([]string, 0, len(matches))
varNames[i] = match[1] for _, match := range matches {
name := match[1]
if seen[name] {
continue
}
seen[name] = true
varNames = append(varNames, name)
} }
if len(varNames) == 0 { if len(varNames) == 0 {
return &domain.VariableExtractionResult{ return &domain.VariableExtractionResult{
+89
View File
@@ -124,6 +124,95 @@ func TestVariableAcceptance(t *testing.T) {
require.Empty(allResponse[1].Value) // secret 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 { func unmarshalConfig(require *require.Assertions, configData []byte) configWithVars {
firstConfig := configWithVars{} firstConfig := configWithVars{}
err := json.Unmarshal(configData, &firstConfig) err := json.Unmarshal(configData, &firstConfig)