Reimplement baseline

This commit is contained in:
komissarovyv committed 2024-09-08 15:25:01 +03:00
1 parent f062aada42
commit 33b4e2d965
36 files changed
+653 -3262

No files matched your search

+51 -64
View File
@@ -1,69 +1,56 @@
run:
timeout: 2m
allow-parallel-runners: true
issues:
exclude-rules:
- path: controller #достаточное кол-во контекса на уровне контроллеров
linters:
- wrapcheck
- path: transaction #транзакции прозрачны
linters:
- wrapcheck
linters:
disable-all: true
enable:
- asciicheck
- bodyclose
- deadcode
- dogsled
- errcheck
- funlen
- goconst
- gocritic
- gocyclo
- gofmt
- gomnd
- goprintffuncname
- gosimple
- govet
- nakedret
- nestif
- nolintlint
- prealloc
- rowserrcheck
- staticcheck
- structcheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- gosec
- misspell
- whitespace
- exhaustive #смотрит на соответствие между элементами enum и swich кейсами
- exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ }
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
enable-all: true
disable:
- goimports #у нас собственные правила форматирования импортов
- wsl #расставление пробелов очень индивидуально
- exhaustivestruct #не имеет смысла
- varnamelen #очень индивидуально (db)
- exhaustruct #не имеет смысла
- golint #устарел
- contextcheck #не имеет смысла
- gci #у нас собственные правила форматирования импортов
- gofumpt #у нас собственные правила форматирования импортов
- nolintlint #Goland все равно форматирует с отступом
- nlreturn #не всегда имеет смысл
- godot #не актуально для свагера
- ifshort #приняли решение, что мы так не пишем if err := ...; err != nil {}
- godox #не позволяет оставлять todo
- maligned #аллокацией памяти для структур конфликтует с удобством их чтения
- nosnakecase #не позволяет заводить пакеты используя snake_case
- depguard #не всегда имеет смысл
- dupword #не имеет смысла
- tagalign #не всегда имеет смысл
- musttag #у нас собственные правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внених для нас структур
- perfsprint #мнимая производительность в угоду читаемости
- gomnd #устарел
linters-settings:
funlen:
lines: 80
statements: 40
prealloc:
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: true
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: true # Report preallocation suggestions on for loops, false by default
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- diagnostic
- performance
disabled-checks:
- hugeParam
- rangeValCopy
- ifElseChain
exhaustive:
default-signifies-exhaustive: true
issues:
exclude-rules:
- path: _test\.go # to exclude all test files for linter errcheck
linters:
- errcheck
- linters:
- gosec
text: "G101:"
lll:
line-length: 150
cyclop:
max-complexity: 15 #по умолчанию 10 мало
revive:
rules:
- name: var-naming #отключаем Id -> ID
disabled: true
stylecheck:
checks: #отключаем Id -> ID
- "-ST1000"
- "-ST1016"
- "-ST1020"
- "-ST1021"
- "-ST1022"
testifylint:
disable:
- compares
+1 -1
View File
@@ -1 +1 @@
4.0.0
5.0.0
+10
View File
@@ -1,3 +1,13 @@
### v5.0.0
* изменен механизм инициализации токена панели администратора
* для механизма инициализации используется поле `baseline.initialAdminUiToken` в конфигурации
* если поле не заполнено, механизм не запускается
* иначе проверяется существование токена в базе, если токен уже создан, механизм не запускается
* иначе создаются все сущности и выпускается бессрочный токен, приложению выдается доступ к методу `admin/auth/login`
* механизм запускается при получении конфигурации
* при конкурентном запуске модуля, механизм запускается только на одном инстансе
* логи механизма маркируются полем "worker": "baseline"
* обновлена зависимости
### v4.0.0
* Удален `InstanceUuid`
* Удалена интеграция с Redis
+20 -21
View File
@@ -2,17 +2,17 @@ package assembly
import (
"context"
"github.com/txix-open/isp-kit/rc"
"github.com/integration-system/isp-kit/app"
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/dbrx"
"github.com/integration-system/isp-kit/dbx"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/log"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/dbrx"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/migrations"
)
type Assembly struct {
@@ -23,9 +23,8 @@ type Assembly struct {
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
dbCli := dbrx.New(dbx.WithMigration(boot.MigrationsDir))
dbCli := dbrx.New(dbx.WithMigrationRunner(boot.MigrationsDir, boot.App.Logger()))
server := grpc.NewServer()
return &Assembly{
boot: boot,
db: dbCli,
@@ -35,27 +34,27 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
}
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
var (
newCfg conf.Remote
prevCfg conf.Remote
)
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
newCfg, _, err := rc.Upgrade[conf.Remote](a.boot.RemoteConfig, remoteConfig)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
a.boot.Fatal(errors.WithMessage(err, "upgrade remote config"))
}
migrations.Initialize.SetParams(a.boot.MigrationsDir, newCfg.Database.Schema)
a.logger.SetLevel(newCfg.LogLevel)
err = a.db.Upgrade(ctx, newCfg.Database)
if err != nil {
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", newCfg.Database))
a.boot.Fatal(errors.WithMessage(err, "upgrade db client"))
}
locator := NewLocator(a.db, a.logger)
handler := locator.Handler(newCfg)
a.server.Upgrade(handler)
config := locator.Config(newCfg)
err = config.Baseline.Do(a.boot.App.Context())
if err != nil {
a.boot.Fatal(errors.WithMessage(err, "run baseline"))
}
a.server.Upgrade(config.Handler)
return nil
}
+17 -6
View File
@@ -1,15 +1,16 @@
package assembly
import (
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"github.com/integration-system/isp-kit/log"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/controller"
"isp-system-service/repository"
"isp-system-service/routes"
"isp-system-service/service"
"isp-system-service/service/baseline"
"isp-system-service/service/secure"
"isp-system-service/transaction"
)
@@ -31,7 +32,12 @@ func NewLocator(db DB, logger log.Logger) Locator {
}
}
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
type Config struct {
Handler *grpc.Mux
Baseline baseline.Service
}
func (l Locator) Config(cfg conf.Remote) Config {
txManager := transaction.NewManager(l.db)
accessListRep := repository.NewAccessList(l.db)
applicationRep := repository.NewApplication(l.db)
@@ -67,5 +73,10 @@ func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
}
mapper := endpoint.DefaultWrapper(l.logger, endpoint.BodyLogger(l.logger))
server := routes.Handler(mapper, c)
return server
baselineService := baseline.NewService(cfg.Baseline, txManager, l.logger)
return Config{
Handler: server,
Baseline: baselineService,
}
}
+3
View File
@@ -7,5 +7,8 @@
"username": "{{ msp_pgsql_user }}",
"host": "{{ msp_pgsql_address }}",
"port": 5432
},
"baseline": {
"initialAdminUiToken": "{{ isp_service_admin_token }}"
}
}
+12 -6
View File
@@ -3,14 +3,15 @@ package conf
import (
"reflect"
"github.com/integration-system/isp-kit/dbx"
"github.com/integration-system/isp-kit/log"
"github.com/integration-system/isp-kit/rc/schema"
"github.com/integration-system/jsonschema"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/rc/schema"
"github.com/txix-open/jsonschema"
)
//nolint:gochecknoinits
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Type) {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
t.Type = "string"
t.Enum = []interface{}{"debug", "info", "error", "fatal"}
})
@@ -18,5 +19,10 @@ func init() {
type Remote struct {
Database dbx.Config `schema:"Настройка базы данных"`
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
Baseline Baseline
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
}
type Baseline struct {
InitialAdminUiToken string
}
+13
View File
@@ -0,0 +1,13 @@
package conf_test
import (
"isp-system-service/conf"
"testing"
"github.com/txix-open/isp-kit/test/rct"
)
func TestDefaultRemoteConfig(t *testing.T) {
t.Parallel()
rct.Test(t, "default_remote_config.json", conf.Remote{})
}
-1563
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -180,8 +180,7 @@ definitions:
domain.GrpcError:
properties:
details:
items:
type: object
items: {}
type: array
errorCode:
type: string
@@ -263,6 +262,7 @@ definitions:
type: integer
required:
- appId
- expireTimeMs
type: object
domain.TokenRevokeRequest:
properties:
+3 -3
View File
@@ -1,8 +1,8 @@
package domain
type AccessListSetOneRequest struct {
AppId int `valid:"required~Required"`
Method string `valid:"required~Required"`
AppId int `validate:"required"`
Method string `validate:"required"`
Value bool
}
@@ -11,7 +11,7 @@ type AccessListSetOneResponse struct {
}
type AccessListSetListRequest struct {
AppId int `valid:"required~Required"`
AppId int `validate:"required"`
RemoveOld bool
Methods []MethodInfo
}
+3 -3
View File
@@ -16,10 +16,10 @@ type Application struct {
type ApplicationCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Name string `validate:"required"`
Description string
ServiceId int `valid:"required~Required"`
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
ServiceId int `validate:"required"`
Type string `validate:"required,oneof=SYSTEM MOBILE"`
}
type ApplicationWithTokens struct {
+1 -1
View File
@@ -2,7 +2,7 @@ package domain
type (
Identity struct {
Id int `valid:"required~Required"`
Id int `validate:"required"`
}
DeleteResponse struct {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
type DomainCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Name string `validate:"required"`
Description string
}
+3 -3
View File
@@ -1,7 +1,7 @@
package domain
type AuthenticateRequest struct {
Token string `valid:"required~Required"`
Token string `validate:"required"`
}
type AuthenticateResponse struct {
@@ -18,8 +18,8 @@ type AuthData struct {
}
type AuthorizeRequest struct {
ApplicationId int `valid:"required~Required"`
Endpoint string `valid:"required~Required"`
ApplicationId int `validate:"required"`
Endpoint string `validate:"required"`
}
type AuthorizeResponse struct {
+2 -2
View File
@@ -15,9 +15,9 @@ type Service struct {
type ServiceCreateUpdateRequest struct {
Id int
Name string `valid:"required~Required"`
Name string `validate:"required"`
Description string
DomainId int `valid:"required~Required"`
DomainId int `validate:"required"`
}
type ServiceWithApps struct {
+3 -3
View File
@@ -12,11 +12,11 @@ type Token struct {
}
type TokenRevokeRequest struct {
AppId int `valid:"required~Required"`
AppId int `validate:"required"`
Tokens []string
}
type TokenCreateRequest struct {
AppId int `valid:"required~Required"`
ExpireTimeMs int `valid:"required~Required"`
AppId int `validate:"required"`
ExpireTimeMs int `validate:"required"`
}
+59 -65
View File
@@ -1,86 +1,80 @@
module isp-system-service
go 1.17
go 1.22
require (
github.com/Masterminds/squirrel v1.5.3
github.com/integration-system/isp-kit v1.10.4
github.com/integration-system/isp-lib/v2 v2.10.0
github.com/integration-system/jsonschema v1.0.1
github.com/Masterminds/squirrel v1.5.4
github.com/pkg/errors v0.9.1
github.com/pressly/goose v2.7.0+incompatible
github.com/stretchr/testify v1.8.0
google.golang.org/grpc v1.48.0
github.com/stretchr/testify v1.9.0
github.com/txix-open/isp-kit v1.38.1
github.com/txix-open/jsonschema v1.2.0
google.golang.org/grpc v1.66.0
)
require (
github.com/BurntSushi/toml v1.1.0 // indirect
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/buger/jsonparser v1.1.1 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.12 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/jsonreference v0.20.0 // indirect
github.com/go-openapi/spec v0.20.5 // indirect
github.com/go-openapi/swag v0.21.1 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect
github.com/integration-system/bellows v1.0.1 // indirect
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.12.1 // indirect
github.com/jackc/pgio v1.0.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.5 // indirect
github.com/getsentry/sentry-go v0.28.1 // indirect
github.com/go-faker/faker/v4 v4.4.2 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.21.0 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgproto3/v2 v2.3.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
github.com/jackc/pgtype v1.11.0 // indirect
github.com/jackc/pgx/v4 v4.16.1 // indirect
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.6.0 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jmoiron/sqlx v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.15.8 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.36.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.12.0 // indirect
github.com/subosito/gotenv v1.4.0 // indirect
github.com/swaggo/swag v1.7.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.8.0 // indirect
go.uber.org/zap v1.21.0 // indirect
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect
golang.org/x/net v0.0.0-20220708220712-1185a9018129 // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.10 // indirect
google.golang.org/genproto v0.0.0-20220713161829-9c7dac0a6568 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.66.6 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
github.com/pressly/goose/v3 v3.21.1 // indirect
github.com/prometheus/client_golang v1.19.1 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v3 v3.2.0 // indirect
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.opentelemetry.io/otel v1.28.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.28.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.28.0 // indirect
go.opentelemetry.io/otel/metric v1.28.0 // indirect
go.opentelemetry.io/otel/sdk v1.28.0 // indirect
go.opentelemetry.io/otel/trace v1.28.0 // indirect
go.opentelemetry.io/proto/otlp v1.3.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/text v0.17.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240812133136-8ffd90a71988 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240812133136-8ffd90a71988 // indirect
google.golang.org/protobuf v1.34.2 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.7 // indirect
)
+173 -1263
View File
File diff suppressed because it is too large. Load diff
+3 -4
View File
@@ -1,8 +1,8 @@
package main
import (
"github.com/integration-system/isp-kit/bootstrap"
"github.com/integration-system/isp-kit/shutdown"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/shutdown"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/routes"
@@ -43,7 +43,6 @@ func main() {
err = app.Run()
if err != nil {
app.Shutdown()
logger.Fatal(app.Context(), err)
boot.Fatal(err)
}
}
-160
View File
@@ -1,160 +0,0 @@
package migrations
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"github.com/pkg/errors"
"github.com/pressly/goose"
"isp-system-service/domain"
)
const (
insertDomain = "INSERT INTO %s.domain (id, name, description, system_id) VALUES (%d, '%s', '%s', %d) RETURNING id;"
insertService = "INSERT INTO %s.service (id, name, description, domain_id) VALUES (%d, '%s', '%s', %d) RETURNING id;"
insertApp = "INSERT INTO %s.application (id, name, description, service_id, type) VALUES (%d, '%s', '%s', %d, '%s') RETURNING id;"
insertToken = "INSERT INTO %s.token (token, app_id, expire_time) VALUES ('%s', %d, %d);"
setSeqQuery = "SELECT setval('%s.%s_id_seq' :: regclass, %d);"
initFile = "init.json"
)
func init() {
goose.AddMigration(Initialize.Up, Initialize.Down)
}
var Initialize = &initializeMigration{}
type initializeMigration struct {
migrationDir string
schema string
}
type identity struct {
domainId int
appId int
serviceId int
}
func (i *initializeMigration) SetParams(migrationDir string, schema string) {
i.migrationDir = migrationDir
i.schema = schema
}
func (i *initializeMigration) Up(tx *sql.Tx) error {
path := filepath.Join(i.migrationDir, initFile)
bytes, err := ioutil.ReadFile(path)
if err != nil {
return errors.WithMessage(err, "read file")
}
list := make([]domain.DomainWithService, 0)
err = json.Unmarshal(bytes, &list)
if err != nil {
return errors.WithMessage(err, "json unmarshal")
}
lastDomainId := 0
lastServiceId := 0
lastAppId := 0
for _, domainInfo := range list {
last, err := i.insert(tx, domainInfo)
if err != nil {
return errors.WithMessage(err, "")
}
if last.domainId > lastDomainId {
lastDomainId = last.domainId
}
if last.serviceId > lastServiceId {
lastServiceId = last.serviceId
}
if last.appId > lastAppId {
lastAppId = last.appId
}
}
err = i.setSeq(tx, "domain", lastDomainId)
if err != nil {
return errors.WithMessage(err, "set domain")
}
err = i.setSeq(tx, "service", lastServiceId)
if err != nil {
return errors.WithMessage(err, "set service")
}
err = i.setSeq(tx, "application", lastAppId)
if err != nil {
return errors.WithMessage(err, "set application")
}
return nil
}
func (i *initializeMigration) Down(tx *sql.Tx) error {
return nil
}
func (i *initializeMigration) insert(tx *sql.Tx, domainInfo domain.DomainWithService) (*identity, error) {
domainId, err := i.insertNode(tx, insertDomain, true, i.schema, domainInfo.Id, domainInfo.Name, domainInfo.Description, 1)
if err != nil {
return nil, errors.WithMessage(err, "insert domain")
}
serviceId := 0
appId := 0
for _, service := range domainInfo.Services {
serviceId, err = i.insertNode(tx, insertService, true, i.schema, service.Id, service.Name, service.Description, domainId)
if err != nil {
return nil, errors.WithMessage(err, "insert service")
}
for _, app := range service.Apps {
appId, err = i.insertNode(tx, insertApp, true, i.schema, app.Id, app.Name, app.Description, serviceId, app.Type)
if err != nil {
return nil, errors.WithMessage(err, "insert application")
}
for _, t := range app.Tokens {
_, err = i.insertNode(tx, insertToken, false, i.schema, t.Token, appId, t.ExpireTime)
if err != nil {
return nil, errors.WithMessage(err, "insert token")
}
}
}
}
return &identity{
domainId: domainId,
appId: appId,
serviceId: serviceId,
}, nil
}
func (i *initializeMigration) insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int, error) {
var id int
query = fmt.Sprintf(query, args...)
row := tx.QueryRow(query)
if scan {
err := row.Scan(&id)
if err != nil {
return 0, errors.WithMessage(err, "row scan")
}
}
return id, nil
}
func (i *initializeMigration) setSeq(tx *sql.Tx, table string, value int) error {
q := fmt.Sprintf(setSeqQuery, i.schema, table, value)
_, err := tx.Exec(q)
if err != nil {
return errors.WithMessage(err, "exec db")
}
return nil
}
@@ -1,7 +0,0 @@
-- +goose Up
insert into access_list (app_id, method, value)
values (1, 'admin/auth/login', true)
on conflict (app_id, method) do update set value = true;
-- +goose Down
-28
View File
@@ -1,28 +0,0 @@
[
{
"id": 1,
"name": "rootDomain",
"description": "",
"services": [
{
"id": 1,
"name": "rootService",
"description": "",
"apps": [
{
"id": 1,
"name": "admin",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_admin_token }}",
"expireTime": -1
}
]
}
]
}
]
}
]
+3 -3
View File
@@ -5,9 +5,9 @@ import (
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
@@ -31,7 +31,7 @@ func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int
result := entity.AccessList{}
err := r.db.SelectRow(ctx, &result, q, appId, method)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrAccessListNotFound
}
return nil, errors.WithMessagef(err, "select db")
+5 -5
View File
@@ -5,9 +5,9 @@ import (
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
@@ -31,7 +31,7 @@ func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Ap
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrApplicationNotFound
}
return nil, errors.WithMessage(err, "select row db")
@@ -89,8 +89,8 @@ func (r Application) GetApplicationByNameAndServiceId(ctx context.Context, name
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, serviceId)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
if errors.Is(err, sql.ErrNoRows) {
return nil, nil //nolint:nilnil
}
return nil, errors.WithMessagef(err, "select row db")
}
+6 -6
View File
@@ -5,9 +5,9 @@ import (
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
@@ -31,7 +31,7 @@ func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, erro
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
@@ -84,7 +84,7 @@ func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, sys
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, systemId)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
@@ -103,7 +103,7 @@ func (r Domain) CreateDomain(ctx context.Context, name string, desc string, syst
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, desc, systemId)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
@@ -122,7 +122,7 @@ func (r Domain) UpdateDomain(ctx context.Context, id int, name string, descripti
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
+40
View File
@@ -0,0 +1,40 @@
package repository
import (
"context"
"hash/fnv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
const (
prefix = "msp-service-template"
)
type Locker struct {
db db.DB
}
func NewLocker(db db.DB) Locker {
return Locker{db: db}
}
func (l Locker) TryLock(ctx context.Context, key string) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Locker.TryLock")
hash := fnv.New32a()
_, err := hash.Write([]byte(prefix + key))
if err != nil {
return false, errors.WithMessage(err, "generate hash")
}
sum := hash.Sum32()
acquired := false
err = l.db.SelectRow(ctx, &acquired, "SELECT pg_try_advisory_xact_lock($1)", sum)
if err != nil {
return false, errors.WithMessage(err, "pg try acquire advisory lock")
}
return acquired, nil
}
+5 -5
View File
@@ -5,9 +5,9 @@ import (
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
@@ -31,7 +31,7 @@ func (r Service) GetServiceById(ctx context.Context, id int) (*entity.Service, e
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select row db")
@@ -89,7 +89,7 @@ func (r Service) GetServiceByNameAndDomainId(ctx context.Context, name string, d
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, domainId)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select db")
@@ -124,7 +124,7 @@ func (r Service) UpdateService(ctx context.Context, id int, name string, descrip
result := entity.Service{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrServiceNotFound
}
return nil, errors.WithMessage(err, "select row db")
+7 -4
View File
@@ -5,9 +5,9 @@ import (
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/integration-system/isp-kit/db"
"github.com/integration-system/isp-kit/db/query"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
@@ -41,11 +41,14 @@ func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTim
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
q := `
SELECT token, app_id, expire_time, created_at
FROM system
FROM token
WHERE token = $1
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil //nolint:nilnil
}
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
@@ -110,7 +113,7 @@ WHERE token = $1
result := entity.AuthData{}
err := r.db.SelectRow(ctx, &result, q, token)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return nil, domain.ErrTokenNotFound
}
return nil, errors.WithMessage(err, "select row db")
+4 -5
View File
@@ -1,10 +1,9 @@
package routes
import (
"github.com/integration-system/isp-kit/cluster"
"github.com/integration-system/isp-kit/grpc"
"github.com/integration-system/isp-kit/grpc/endpoint"
"github.com/integration-system/isp-kit/grpc/isp"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"isp-system-service/controller"
)
@@ -21,7 +20,7 @@ func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
}
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
+107
View File
@@ -0,0 +1,107 @@
package baseline
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/entity"
)
type Transaction interface {
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error)
CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error)
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
TryLock(ctx context.Context, key string) (bool, error)
}
type TxRunner interface {
BaselineTx(ctx context.Context, tx func(ctx context.Context, tx Transaction) error) error
}
type Service struct {
cfg conf.Baseline
txRunner TxRunner
logger log.Logger
}
func NewService(cfg conf.Baseline, txRunner TxRunner, logger log.Logger) Service {
return Service{
cfg: cfg,
txRunner: txRunner,
logger: logger,
}
}
func (s Service) Do(ctx context.Context) error {
ctx = log.ToContext(ctx, log.String("worker", "baseline"))
if s.cfg.InitialAdminUiToken == "" {
s.logger.Info(ctx, "initial admin ui token is empty, skip baseline")
return nil
}
err := s.txRunner.BaselineTx(ctx, s.transaction)
if err != nil {
return errors.WithMessage(err, "run baseline transaction")
}
return nil
}
func (s Service) transaction(ctx context.Context, tx Transaction) error {
locked, err := tx.TryLock(ctx, "isp-system-service.baseline")
if err != nil {
return errors.WithMessage(err, "try lock isp-system-service.baseline")
}
if !locked {
s.logger.Info(ctx, "baseline is locked, skip baseline")
return nil
}
token, err := tx.GetTokenById(ctx, s.cfg.InitialAdminUiToken)
if err != nil {
return errors.WithMessage(err, "get token by id")
}
if token != nil {
s.logger.Info(ctx, "initial admin ui token is exist, skip baseline")
return nil
}
s.logger.Info(ctx, "initial admin ui token is empty, run baseline")
domain, err := tx.CreateDomain(ctx, "root", "", 1)
if err != nil {
return errors.WithMessage(err, "create domain")
}
service, err := tx.CreateService(ctx, "rootService", "", domain.Id)
if err != nil {
return errors.WithMessage(err, "create service")
}
app, err := tx.CreateApplication(ctx, "admin", "", service.Id, "SYSTEM")
if err != nil {
return errors.WithMessage(err, "create application")
}
_, err = tx.SaveToken(ctx, s.cfg.InitialAdminUiToken, app.Id, -1)
if err != nil {
return errors.WithMessage(err, "save token")
}
_, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: app.Id,
Method: "admin/auth/login",
Value: true,
})
if err != nil {
return errors.WithMessage(err, "upsert access list")
}
s.logger.Info(ctx, "baseline done")
return nil
}
+1 -1
View File
@@ -15,7 +15,7 @@ func NewTokenSource() TokenSource {
}
func (s TokenSource) CreateApplicationToken() (string, error) {
cryptoRand := make([]byte, 128) //nolint:gomnd
cryptoRand := make([]byte, 128) //nolint:mnd
_, err := rand.Read(cryptoRand)
if err != nil {
return "", errors.WithMessage(err, "crypto/rand read")
+52
View File
@@ -0,0 +1,52 @@
package tests_test
import (
"context"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/service/baseline"
"testing"
)
func TestBaselineSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &BaselineSuite{})
}
type BaselineSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
baseline baseline.Service
api *client.Client
}
func (s *BaselineSuite) SetupSuite() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{
Baseline: conf.Baseline{
InitialAdminUiToken: fake.It[string](),
},
})
s.baseline = config.Baseline
_, s.api = grpct.TestServer(s.test, config.Handler)
}
func (s *BaselineSuite) TestBaselineSuccess() {
err := s.baseline.Do(context.Background())
s.Require().NoError(err)
err = s.baseline.Do(context.Background())
s.Require().NoError(err)
}
@@ -1,7 +1,7 @@
package tests
package tests_test
import (
"github.com/integration-system/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/dbt"
"isp-system-service/entity"
)
+17 -24
View File
@@ -1,25 +1,25 @@
package tests
package tests_test
import (
"context"
"github.com/txix-open/isp-kit/dbx"
"testing"
"time"
"github.com/integration-system/isp-kit/dbx/migration"
"github.com/integration-system/isp-kit/grpc/client"
"github.com/integration-system/isp-kit/test"
"github.com/integration-system/isp-kit/test/dbt"
"github.com/integration-system/isp-kit/test/grpct"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/migrations"
)
func TestSecureSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &SecureSuite{})
}
@@ -34,18 +34,11 @@ type SecureSuite struct {
func (s *SecureSuite) SetupSuite() {
s.test, s.require = test.New(s.T())
s.testDb = dbt.New(s.test)
migrations.Initialize.SetParams("../migrations", s.testDb.Schema())
db, err := s.testDb.DB()
s.require.NoError(err)
err = migration.NewRunner(db.DB.DB, "../migrations").Run()
s.require.NoError(err)
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
handler := locator.Handler(conf.Remote{})
_, s.api = grpct.TestServer(s.test, handler)
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
createdTime := time.Now().UTC()
InsertDomain(s.testDb, entity.Domain{
@@ -69,7 +62,7 @@ func (s *SecureSuite) TestAuthenticate_Success() {
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_success",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
@@ -90,7 +83,7 @@ func (s *SecureSuite) TestAuthenticate_NotFound() {
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_not_found",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
@@ -110,7 +103,7 @@ func (s *SecureSuite) TestAuthenticate_NotExpired() {
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_not_expired",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
@@ -135,7 +128,7 @@ func (s *SecureSuite) TestAuthenticate_Expired() {
JsonRequestBody(domain.AuthenticateRequest{
Token: "test_token_expired",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
@@ -158,7 +151,7 @@ func (s *SecureSuite) TestAuthorize_Success_True() {
ApplicationId: 7,
Endpoint: "endpoint/available",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
@@ -179,7 +172,7 @@ func (s *SecureSuite) TestAuthorize_Success_False() {
ApplicationId: 7,
Endpoint: "endpoint/not_available",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
@@ -194,7 +187,7 @@ func (s *SecureSuite) TestAuthorize_NotFound() {
ApplicationId: 7,
Endpoint: "endpoint/not_found",
}).
ReadJsonResponse(&result).
JsonResponseBody(&result).
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
+24 -1
View File
@@ -2,8 +2,9 @@ package transaction
import (
"context"
"isp-system-service/service/baseline"
"github.com/integration-system/isp-kit/db"
"github.com/txix-open/isp-kit/db"
"isp-system-service/repository"
"isp-system-service/service"
)
@@ -82,3 +83,25 @@ func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Conte
})
})
}
type baselineTx struct {
repository.Locker
repository.Domain
repository.Service
repository.Application
repository.AccessList
repository.Token
}
func (m Manager) BaselineTx(ctx context.Context, txTx func(ctx context.Context, tx baseline.Transaction) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
return txTx(ctx, baselineTx{
Locker: repository.NewLocker(tx),
Domain: repository.NewDomain(tx),
Service: repository.NewService(tx),
Application: repository.NewApplication(tx),
AccessList: repository.NewAccessList(tx),
Token: repository.NewToken(tx),
})
})
}