Align to CI

This commit is contained in:
d1slike committed 2024-05-15 12:44:39 +03:00
1 parent 125013ba0a
commit 8275c01d21
20 files changed
+144 -98

No files matched your search

+2
View File
@@ -32,6 +32,8 @@ linters:
- tagalign #не всегда имеет смысл
- musttag #у нас собственные правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внених для нас структур
- perfsprint #мнимая производительность в угоду читаемости
- gomoddirectives #требует rqlite
- tagliatelle
linters-settings:
funlen:
lines: 80
+1
View File
@@ -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)
+1
View File
@@ -1,3 +1,4 @@
//nolint:lll
package api
import (
+1 -1
View File
@@ -13,7 +13,7 @@ import (
)
var (
ok = []byte("ok")
ok = []byte("ok") //nolint:gochecknoglobals
)
type ModuleService interface {
+8 -3
View File
@@ -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
}
+3 -1
View File
@@ -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
+2 -1
View File
@@ -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
})
}
}
+1
View File
@@ -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)
+1 -1
View File
@@ -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
+1
View File
@@ -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...)
+1 -1
View File
@@ -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 {
+19 -15
View File
@@ -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 {
+4 -2
View File
@@ -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")
}
+3 -3
View File
@@ -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),
+1 -1
View File
@@ -8,7 +8,7 @@ import (
type consistencyCtxKey struct{}
var (
consistencyCtxValue = consistencyCtxKey{}
consistencyCtxValue = consistencyCtxKey{} //nolint:gochecknoglobals
)
func consistencyFromContext(ctx context.Context) Consistency {
+8 -15
View File
@@ -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
}
+5 -1
View File
@@ -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 {
+5 -4
View File
@@ -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)
}),
+13 -49
View File
@@ -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").
+64
View File
@@ -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
}