diff --git a/.golangci.yml b/.golangci.yml index cdb8788..7f2ac31 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -32,6 +32,8 @@ linters: - tagalign #не всегда имеет смысл - musttag #у нас собственные правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внених для нас структур - perfsprint #мнимая производительность в угоду читаемости + - gomoddirectives #требует rqlite + - tagliatelle linters-settings: funlen: lines: 80 diff --git a/assembly/locator.go b/assembly/locator.go index c606933..925430c 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -47,6 +47,7 @@ type Config struct { CleanEventWorker *worker.Worker } +//nolint:funlen func (l Locator) Config() Config { moduleRepo := repository.NewModule(l.db) backendRepo := repository.NewBackend(l.db) diff --git a/controller/api/config.go b/controller/api/config.go index 8c40e56..b66d665 100644 --- a/controller/api/config.go +++ b/controller/api/config.go @@ -1,3 +1,4 @@ +//nolint:lll package api import ( diff --git a/controller/module.go b/controller/module.go index 2123515..815f6cf 100644 --- a/controller/module.go +++ b/controller/module.go @@ -13,7 +13,7 @@ import ( ) var ( - ok = []byte("ok") + ok = []byte("ok") //nolint:gochecknoglobals ) type ModuleService interface { diff --git a/entity/xtypes/json.go b/entity/xtypes/json.go index 8d90ccb..29d3dce 100644 --- a/entity/xtypes/json.go +++ b/entity/xtypes/json.go @@ -3,6 +3,7 @@ package xtypes import ( "strconv" + "github.com/pkg/errors" "github.com/txix-open/isp-kit/json" ) @@ -21,7 +22,7 @@ func (l Json[T]) MarshalJSON() ([]byte, error) { func (l *Json[T]) UnmarshalJSON(data []byte) error { s, err := strconv.Unquote(string(data)) if err != nil { - return err + return errors.WithMessage(err, "unquote text") } return l.UnmarshalText([]byte(s)) } @@ -29,11 +30,15 @@ func (l *Json[T]) UnmarshalJSON(data []byte) error { func (l Json[T]) MarshalText() ([]byte, error) { data, err := json.Marshal(l.Value) if err != nil { - return nil, err + return nil, errors.WithMessage(err, "marshal json") } return data, nil } func (l *Json[T]) UnmarshalText(data []byte) error { - return json.Unmarshal(data, &l.Value) + err := json.Unmarshal(data, &l.Value) + if err != nil { + return errors.WithMessage(err, "unmarshal json") + } + return nil } diff --git a/entity/xtypes/time.go b/entity/xtypes/time.go index 6a6dc09..d578271 100644 --- a/entity/xtypes/time.go +++ b/entity/xtypes/time.go @@ -3,6 +3,8 @@ package xtypes import ( "strconv" "time" + + "github.com/pkg/errors" ) type Time time.Time @@ -27,7 +29,7 @@ func (l *Time) UnmarshalText(data []byte) error { } value, err := strconv.Atoi(string(data)) if err != nil { - return err + return errors.WithMessagef(err, "parse int: %s", string(data)) } *l = Time(time.Unix(int64(value), 0)) return nil diff --git a/middlewares/sql.go b/middlewares/sql.go index 5c836ce..3a0d44c 100644 --- a/middlewares/sql.go +++ b/middlewares/sql.go @@ -11,6 +11,7 @@ import ( ) func SqlOperationMiddleware() httpcli.Middleware { + //nolint:promlinter sqlQueryDuration := metrics.GetOrRegister(metrics.DefaultRegistry, prometheus.NewSummaryVec(prometheus.SummaryOpts{ Subsystem: "sql", Name: "query_duration_ms", @@ -26,7 +27,7 @@ func SqlOperationMiddleware() httpcli.Middleware { duration := time.Since(now) sqlQueryDuration.WithLabelValues(label).Observe(metrics.Milliseconds(duration)) } - return resp, err + return resp, err //nolint:wrapcheck }) } } diff --git a/middlewares/ws_log.go b/middlewares/ws_log.go index fe9b2dd..9a7d766 100644 --- a/middlewares/ws_log.go +++ b/middlewares/ws_log.go @@ -24,6 +24,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-- { root = middlewares[i](root) diff --git a/migrations/20240503120009_init.sql b/migrations/20240503120009_init.sql index 7463305..46ddb0c 100644 --- a/migrations/20240503120009_init.sql +++ b/migrations/20240503120009_init.sql @@ -69,7 +69,7 @@ create table isp_config_service__event id integer, payload blob not null, created_at integer not null default (unixepoch()), - primary key (id desc) + primary key (id) ); -- +goose Down diff --git a/repository/config_schema.go b/repository/config_schema.go index 63f1aa1..9bf141e 100644 --- a/repository/config_schema.go +++ b/repository/config_schema.go @@ -69,6 +69,7 @@ func (r ConfigSchema) GetByModuleId(ctx context.Context, moduleId string) (*enti return selectRow[entity.ConfigSchema](ctx, r.db, query, args...) } +//nolint:nilnil func selectRow[T any](ctx context.Context, db db.DB, query string, args ...interface{}) (*T, error) { var result T err := db.SelectRow(ctx, &result, query, args...) diff --git a/repository/event.go b/repository/event.go index ad37df0..b09762a 100644 --- a/repository/event.go +++ b/repository/event.go @@ -35,7 +35,7 @@ func (r Event) Insert(ctx context.Context, event entity.Event) error { func (r Event) Get(ctx context.Context, lastEventId int, limit int) ([]entity.Event, error) { ctx = sql_metrics.OperationLabelToContext(ctx, "Event.Get") - query := fmt.Sprintf("select * from %s where id > ? order by id desc limit ?", Table("event")) + query := fmt.Sprintf("select * from %s where id > ? order by id limit ?", Table("event")) result := make([]entity.Event, 0) err := r.db.Select(ctx, &result, query, lastEventId, limit) if err != nil { diff --git a/service/api/config.go b/service/api/config.go index 3b9a52d..13c646c 100644 --- a/service/api/config.go +++ b/service/api/config.go @@ -111,21 +111,7 @@ func (c Config) CreateUpdateConfig( } if req.Id == "" { - config := entity.Config{ - Id: uuid.NewString(), - Name: req.Name, - ModuleId: req.ModuleId, - Data: req.Data, - Version: 1, - Active: false, - AdminId: adminId, - } - err := c.configRepo.Insert(ctx, config) - if err != nil { - return nil, errors.WithMessage(err, "insert new config") - } - result := configToDto(config, nil) - return &result, nil + return c.insertNewConfig(ctx, adminId, req) } oldConfig, err := c.configRepo.GetById(ctx, req.Id) @@ -239,6 +225,24 @@ func (c Config) DeleteConfig(ctx context.Context, configId string) error { return nil } +func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (*domain.Config, error) { + config := entity.Config{ + Id: uuid.NewString(), + Name: req.Name, + ModuleId: req.ModuleId, + Data: req.Data, + Version: 1, + Active: false, + AdminId: adminId, + } + err := c.configRepo.Insert(ctx, config) + if err != nil { + return nil, errors.WithMessage(err, "insert new config") + } + result := configToDto(config, nil) + return &result, nil +} + func (c Config) validateConfigUpdate(ctx context.Context, moduleId string, configData []byte) error { schema, err := c.schemaRepo.GetByModuleId(ctx, moduleId) if err != nil { diff --git a/service/api/module.go b/service/api/module.go index f9ae576..3e16139 100644 --- a/service/api/module.go +++ b/service/api/module.go @@ -50,22 +50,24 @@ func (s Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) { modules []entity.Module backends []entity.Backend schemas []entity.ConfigSchema - err error ) group, ctx := errgroup.WithContext(ctx) group.Go(func() error { + var err error modules, err = s.moduleRepo.All(ctx) return errors.WithMessage(err, "get all modules") }) group.Go(func() error { + var err error backends, err = s.backendsRepo.All(ctx) return errors.WithMessage(err, "get all backends") }) group.Go(func() error { + var err error schemas, err = s.schemaRepo.All(ctx) return errors.WithMessage(err, "get all schemas") }) - err = group.Wait() + err := group.Wait() if err != nil { return nil, errors.WithMessage(err, "wait") } diff --git a/service/module/service.go b/service/module/service.go index 0562aaf..94434fc 100644 --- a/service/module/service.go +++ b/service/module/service.go @@ -2,7 +2,7 @@ package module import ( "context" - "crypto/md5" + "crypto/sha256" "encoding/hex" "fmt" @@ -235,8 +235,8 @@ func (s Service) OnModuleConfigSchema( config, err := s.configRepo.GetActive(ctx, moduleId) if config == nil { - md5Sum := md5.Sum([]byte(moduleId)) - initialConfigId := hex.EncodeToString(md5Sum[:]) + hash := sha256.Sum256([]byte(moduleId)) + initialConfigId := hex.EncodeToString(hash[:]) initialConfig := entity.Config{ Id: initialConfigId, Name: helpers.ModuleName(conn), diff --git a/service/rqlite/db/consistency.go b/service/rqlite/db/consistency.go index 673704a..e19ae30 100644 --- a/service/rqlite/db/consistency.go +++ b/service/rqlite/db/consistency.go @@ -8,7 +8,7 @@ import ( type consistencyCtxKey struct{} var ( - consistencyCtxValue = consistencyCtxKey{} + consistencyCtxValue = consistencyCtxKey{} //nolint:gochecknoglobals ) func consistencyFromContext(ctx context.Context) Consistency { diff --git a/service/rqlite/goose_store/store.go b/service/rqlite/goose_store/store.go index 4b9b254..6a3f56a 100644 --- a/service/rqlite/goose_store/store.go +++ b/service/rqlite/goose_store/store.go @@ -56,23 +56,16 @@ func (s Store) GetMigration(ctx context.Context, db database.DBTxConn, version i q := s.querier.GetMigrationByVersion(s.tablename) var result database.GetMigrationResult - rows, err := s.db.QueryContext(ctx, q, version) + isApplied := float64(0) + err := s.db.QueryRowContext(ctx, q, version).Scan(&result.Timestamp, &isApplied) + if errors.Is(err, sql.ErrNoRows) { + return nil, fmt.Errorf("%w: %d", database.ErrVersionNotFound, version) + } if err != nil { return nil, fmt.Errorf("failed to get migration %d: %w", version, err) } - for rows.Next() { - isApplied := float64(0) - err := rows.Scan(&result.Timestamp, &isApplied) - if err != nil { - return nil, fmt.Errorf("failed to get migration %d: %w", version, err) - } - result.IsApplied = isApplied == 0 - return &result, nil - } - if err := rows.Err(); err != nil { - return nil, fmt.Errorf("failed to get migration %d: %w", version, err) - } - return nil, fmt.Errorf("%w: %d", database.ErrVersionNotFound, version) + result.IsApplied = isApplied == 0 + return &result, nil } func (s Store) GetLatestVersion(ctx context.Context, db database.DBTxConn) (int64, error) { @@ -100,7 +93,7 @@ func (s Store) ListMigrations(ctx context.Context, db database.DBTxConn) ([]*dat migrations = append(migrations, &result) } if err := rows.Err(); err != nil { - return nil, err + return nil, errors.WithMessage(err, "fetch rows") } return migrations, nil } diff --git a/service/rqlite/runner.go b/service/rqlite/runner.go index 1c9286b..c77187c 100644 --- a/service/rqlite/runner.go +++ b/service/rqlite/runner.go @@ -62,7 +62,11 @@ func (r *Rqlite) SqlDB() (*sql.DB, error) { return nil, ErrNotRun } - return sql.Open("rqlite", r.Dsn()) + db, err := sql.Open("rqlite", r.Dsn()) + if err != nil { + return nil, errors.WithMessage(err, "open sql db") + } + return db, nil } func (r *Rqlite) Dsn() string { diff --git a/service/startup/service.go b/service/startup/service.go index 98e04a2..93e3ad1 100644 --- a/service/startup/service.go +++ b/service/startup/service.go @@ -38,7 +38,7 @@ type Service struct { clusterCli *cluster.Client logger log.Logger - //initialized in Run + // initialized in Run etpSrv *etp.Server handleEventWorker *worker.Worker cleanEventWorker *worker.Worker @@ -56,6 +56,7 @@ func New(boot *bootstrap.Bootstrap) *Service { } } +// nolint:funlen func (s *Service) Run(ctx context.Context) error { localConfig := conf.Local{} err := s.boot.App.Config().Read(&localConfig) @@ -70,7 +71,7 @@ func (s *Service) Run(ctx context.Context) error { s.boot.Fatal(errors.WithMessage(err, "run embedded rqlite")) } }() - time.Sleep(1 * time.Second) //optimistically wait for store initialization + time.Sleep(1 * time.Second) // optimistically wait for store initialization s.logger.Debug(ctx, fmt.Sprintf("waiting for cluster startup for %s...", waitForLeaderTimeout)) err = s.rqlite.WaitForLeader(waitForLeaderTimeout) @@ -123,7 +124,7 @@ func (s *Service) Run(ctx context.Context) error { s.boot.Fatal(errors.WithMessage(err, "start http server")) } }() - time.Sleep(1 * time.Second) //wait for http start + time.Sleep(1 * time.Second) // wait for http start go func() { err = s.clusterCli.Run(ctx, cluster.NewEventHandler()) @@ -142,7 +143,7 @@ func (s *Service) Closers() []app.Closer { return nil }), app.CloserFunc(func() error { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() return s.httpSrv.Shutdown(ctx) }), diff --git a/tests/acceptance_test.go b/tests/acceptance_test.go index 6af2fe1..53e5cf8 100644 --- a/tests/acceptance_test.go +++ b/tests/acceptance_test.go @@ -5,7 +5,6 @@ import ( "crypto/rand" "encoding/hex" "os" - "sync" "testing" "time" @@ -21,47 +20,12 @@ import ( "isp-config-service/service/startup" ) -type clusterEventHandler struct { - receivedConfigs [][]byte - receivedHosts [][]string - receivedRoutes []cluster.RoutingConfig - lock sync.Locker -} - -func newClusterEventHandler() *clusterEventHandler { - return &clusterEventHandler{ - lock: &sync.Mutex{}, - } -} - -func (c *clusterEventHandler) ReceiveConfig(ctx context.Context, remoteConfig []byte) error { - c.lock.Lock() - defer c.lock.Unlock() - c.receivedConfigs = append(c.receivedConfigs, remoteConfig) - return nil -} - -func (c *clusterEventHandler) Upgrade(hosts []string) { - c.lock.Lock() - defer c.lock.Unlock() - c.receivedHosts = append(c.receivedHosts, hosts) -} - -func (c *clusterEventHandler) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error { - c.lock.Lock() - defer c.lock.Unlock() - c.receivedRoutes = append(c.receivedRoutes, routes) - return nil -} - +//nolint:funlen func TestAcceptance(t *testing.T) { - t.Parallel() require := require.New(t) - err := os.Setenv("APP_CONFIG_PATH", "../conf/config.yml") - require.NoError(err) - err = os.Setenv("DefaultRemoteConfigPath", "../conf/default_remote_config.json") - require.NoError(err) + t.Setenv("APP_CONFIG_PATH", "../conf/config.yml") + t.Setenv("DefaultRemoteConfigPath", "../conf/default_remote_config.json") boot := bootstrap.New("1.0.0", conf.Remote{}, nil) boot.App.Logger().SetLevel(log.DebugLevel) boot.MigrationsDir = "../migrations" @@ -76,7 +40,7 @@ func TestAcceptance(t *testing.T) { require.NoError(err) } }) - err = startup.Run(context.Background()) + err := startup.Run(context.Background()) require.NoError(err) time.Sleep(1 * time.Second) @@ -84,7 +48,7 @@ func TestAcceptance(t *testing.T) { go func() { handler := cluster.NewEventHandler() err := clientA1.Run(context.Background(), handler) - require.NoError(err) + require.NoError(err) //nolint:testifylint }() clientA2 := newClusterClient("A", "10.2.9.2", logger) @@ -92,7 +56,7 @@ func TestAcceptance(t *testing.T) { go func() { handler := cluster.NewEventHandler() err := clientA2.Run(clientA2Ctx, handler) - require.NoError(err) + require.NoError(err) //nolint:testifylint }() time.Sleep(2 * time.Second) @@ -104,7 +68,7 @@ func TestAcceptance(t *testing.T) { RequireModule("A", eventHandler). RoutesReceiver(eventHandler) err := clientB.Run(context.Background(), handler) - require.NoError(err) + require.NoError(err) //nolint:testifylint }() time.Sleep(2 * time.Second) @@ -135,14 +99,14 @@ func TestAcceptance(t *testing.T) { require.NoError(err) time.Sleep(2 * time.Second) - require.Len(eventHandler.receivedConfigs, 2) - require.EqualValues([]byte("{}"), eventHandler.receivedConfigs[0]) + require.Len(eventHandler.ReceivedConfigs(), 2) + require.EqualValues([]byte("{}"), eventHandler.ReceivedConfigs()[0]) - require.Len(eventHandler.receivedHosts, 2) - require.EqualValues([]string{"10.2.9.1:9999", "10.2.9.2:9999"}, eventHandler.receivedHosts[0]) - require.EqualValues([]string{"10.2.9.1:9999"}, eventHandler.receivedHosts[1]) + require.Len(eventHandler.ReceivedHosts(), 2) + require.EqualValues([]string{"10.2.9.1:9999", "10.2.9.2:9999"}, eventHandler.ReceivedHosts()[0]) + require.EqualValues([]string{"10.2.9.1:9999"}, eventHandler.ReceivedHosts()[1]) - require.Len(eventHandler.receivedRoutes, 3) + require.Len(eventHandler.ReceivedRoutes(), 3) statusResponse := make([]domain.ModuleInfo, 0) err = apiCli.Invoke("config/module/get_modules_info"). diff --git a/tests/handler_test.go b/tests/handler_test.go new file mode 100644 index 0000000..795b240 --- /dev/null +++ b/tests/handler_test.go @@ -0,0 +1,64 @@ +package tests_test + +import ( + "context" + "sync" + + "github.com/txix-open/isp-kit/cluster" +) + +type clusterEventHandler struct { + receivedConfigs [][]byte + receivedHosts [][]string + receivedRoutes []cluster.RoutingConfig + lock sync.Locker +} + +func newClusterEventHandler() *clusterEventHandler { + return &clusterEventHandler{ + lock: &sync.Mutex{}, + } +} + +func (c *clusterEventHandler) ReceivedConfigs() [][]byte { + c.lock.Lock() + defer c.lock.Unlock() + return c.receivedConfigs +} + +func (c *clusterEventHandler) ReceivedRoutes() []cluster.RoutingConfig { + c.lock.Lock() + defer c.lock.Unlock() + + return c.receivedRoutes +} + +func (c *clusterEventHandler) ReceivedHosts() [][]string { + c.lock.Lock() + defer c.lock.Unlock() + + return c.receivedHosts +} + +func (c *clusterEventHandler) ReceiveConfig(ctx context.Context, remoteConfig []byte) error { + c.lock.Lock() + defer c.lock.Unlock() + + c.receivedConfigs = append(c.receivedConfigs, remoteConfig) + return nil +} + +func (c *clusterEventHandler) Upgrade(hosts []string) { + c.lock.Lock() + defer c.lock.Unlock() + + c.receivedHosts = append(c.receivedHosts, hosts) +} + +func (c *clusterEventHandler) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error { + c.lock.Lock() + defer c.lock.Unlock() + + c.receivedRoutes = append(c.receivedRoutes, routes) + return nil +}