From ecf2d06cfaefb91fa2215302aeb3395630b89be3 Mon Sep 17 00:00:00 2001 From: yankomissarov Date: Wed, 5 Mar 2025 17:38:59 +0300 Subject: [PATCH] MSP-5013 add full variable support --- assembly/locator.go | 10 +- cmd/migrate/go.mod | 45 ++--- cmd/migrate/go.sum | 115 +++++++------ cmd/migrate/main.go | 12 +- controller/api/variable.go | 43 ++--- domain/variable.go | 13 +- entity/config.go | 8 + entity/variable.go | 16 +- go.mod | 4 +- go.sum | 4 +- repository/config.go | 29 +++- repository/variable.go | 167 +++++++++++++++++- routes/routes.go | 6 +- service/api/config.go | 43 +++++ service/module/service.go | 30 +++- service/rqlite/db/db.go | 60 +++++-- service/rqlite/db/iface.go | 1 + service/rqlite/db/request.go | 4 +- service/subscription/service.go | 37 ++-- service/variable/service.go | 295 +++++++++++++++++++++++++++++++- 20 files changed, 786 insertions(+), 156 deletions(-) diff --git a/assembly/locator.go b/assembly/locator.go index fa2979d..925795f 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -86,6 +86,10 @@ func (l Locator) Config() *Config { configRepo := repository.NewConfig(l.db) configSchemaRepo := repository.NewConfigSchema(l.db) configHistoryRepo := repository.NewConfigHistory(l.db) + variableRepo := repository.NewVariable(l.db) + + variableService := variable.NewService(variableRepo, configRepo, eventRepo) + variableController := api.NewVariable(variableService) etpSrv := etp.NewServer( etp.WithServerReadLimit(wsReadLimit), @@ -100,6 +104,7 @@ func (l Locator) Config() *Config { configRepo, etpSrv.Rooms(), emitter, + variableService, l.logger, ) @@ -120,6 +125,7 @@ func (l Locator) Config() *Config { configSchemaRepo, subscriptionService, emitter, + variableService, l.logger, ) moduleController := controller.NewModule(moduleService, l.logger) @@ -136,15 +142,13 @@ func (l Locator) Config() *Config { configSchemaRepo, eventRepo, configHistoryApiService, + variableService, ) configApiController := api.NewConfig(configApiService) configSchemaApiService := apisvs.NewConfigSchema(configSchemaRepo) configSchemaController := api.NewConfigSchema(configSchemaApiService) - variableService := variable.NewService() - variableController := api.NewVariable(variableService) - controllers := routes.Controllers{ Module: moduleController, ModuleApi: moduleApiController, diff --git a/cmd/migrate/go.mod b/cmd/migrate/go.mod index 7b4f5e9..2d38ad1 100644 --- a/cmd/migrate/go.mod +++ b/cmd/migrate/go.mod @@ -8,8 +8,8 @@ require ( github.com/jmoiron/sqlx v1.4.0 github.com/mattn/go-sqlite3 v1.14.22 github.com/pkg/errors v0.9.1 - github.com/pressly/goose/v3 v3.22.1 - github.com/txix-open/isp-kit v1.39.2 + github.com/pressly/goose/v3 v3.24.1 + github.com/txix-open/isp-kit v1.43.0 isp-config-service v0.0.0-00010101000000-000000000000 ) @@ -19,17 +19,17 @@ require ( 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/gabriel-vasile/mimetype v1.4.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.8 // 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.22.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1 // indirect github.com/iancoleman/strcase v0.3.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/pgx/v5 v5.7.1 // indirect + github.com/jackc/pgx/v5 v5.7.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.17.11 // indirect @@ -52,25 +52,26 @@ require ( github.com/txix-open/bellows v1.2.0 // indirect github.com/txix-open/etp/v4 v4.0.1 // indirect github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.56.0 // indirect - go.opentelemetry.io/otel v1.31.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0 // indirect - go.opentelemetry.io/otel/metric v1.31.0 // indirect - go.opentelemetry.io/otel/sdk v1.31.0 // indirect - go.opentelemetry.io/otel/trace v1.31.0 // indirect - go.opentelemetry.io/proto/otlp v1.3.1 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.58.0 // indirect + go.opentelemetry.io/otel v1.33.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.33.0 // indirect + go.opentelemetry.io/otel/metric v1.33.0 // indirect + go.opentelemetry.io/otel/sdk v1.33.0 // indirect + go.opentelemetry.io/otel/trace v1.33.0 // indirect + go.opentelemetry.io/proto/otlp v1.5.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/crypto v0.28.0 // indirect - golang.org/x/net v0.30.0 // indirect - golang.org/x/sync v0.8.0 // indirect - golang.org/x/sys v0.26.0 // indirect - golang.org/x/text v0.19.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20241021214115-324edc3d5d38 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20241021214115-324edc3d5d38 // indirect - google.golang.org/grpc v1.67.1 // indirect - google.golang.org/protobuf v1.35.1 // indirect + golang.org/x/crypto v0.35.0 // indirect + golang.org/x/net v0.35.0 // indirect + golang.org/x/sync v0.11.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250227231956-55c901821b1e // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250227231956-55c901821b1e // indirect + google.golang.org/grpc v1.70.0 // indirect + google.golang.org/protobuf v1.36.5 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/cmd/migrate/go.sum b/cmd/migrate/go.sum index 0198f44..d715ed7 100644 --- a/cmd/migrate/go.sum +++ b/cmd/migrate/go.sum @@ -20,10 +20,10 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkp github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/gabriel-vasile/mimetype v1.4.6 h1:3+PzJTKLkvgjeTbts6msPJt4DixhT4YtFNf1gtGe3zc= -github.com/gabriel-vasile/mimetype v1.4.6/go.mod h1:JX1qVKqZd40hUPpAfiNTe0Sne7hdfKSbOqqmkq8GCXc= -github.com/getsentry/sentry-go v0.29.1 h1:DyZuChN8Hz3ARxGVV8ePaNXh1dQ7d76AiB117xcREwA= -github.com/getsentry/sentry-go v0.29.1/go.mod h1:x3AtIzN01d6SiWkderzaH28Tm0lgkafpJ5Bm3li39O0= +github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM= +github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8= +github.com/getsentry/sentry-go v0.31.1 h1:ELVc0h7gwyhnXHDouXkhqTFSO5oslsRDk0++eyE0KJ4= +github.com/getsentry/sentry-go v0.31.1/go.mod h1:CYNcMMz73YigoHljQRG+qPF+eMq8gG72XcGN/p71BAY= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -35,17 +35,19 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-resty/resty/v2 v2.15.3 h1:bqff+hcqAflpiF591hhJzNdkRsFhlB96CYfBwSFvql8= -github.com/go-resty/resty/v2 v2.15.3/go.mod h1:0fHAoK7JoBy/Ch36N8VFeMsK7xQOHhvWaC3iOktwmIU= +github.com/go-resty/resty/v2 v2.16.3 h1:zacNT7lt4b8M/io2Ahj6yPypL7bqx9n1iprfQuodV+E= +github.com/go-resty/resty/v2 v2.16.3/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0 h1:asbCHRVmodnJTuQ3qamDwqVOIjwqUPTYmYuemVOx+Ys= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.22.0/go.mod h1:ggCgvZ2r7uOoQjOyu2Y1NhHmEPPzzuhWgcza5M1Ji1I= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1 h1:VNqngBF40hVlDloBruUehVYC3ArSgIyScOAyMRqBxRg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1/go.mod h1:RBRO7fro65R6tjKzYgLAFo0t1QEXY1Dp+i/bvpRiqiQ= github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= @@ -55,8 +57,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.7.1 h1:x7SYsPBYDkHDksogeSmZZ5xzThcTgRz++I5E+ePFUcs= -github.com/jackc/pgx/v5 v5.7.1/go.mod h1:e7O26IywZZ+naJtWWos6i6fvWK+29etgITqrqHLfoZA= +github.com/jackc/pgx/v5 v5.7.2 h1:mLoDLV6sonKlvjIEsV56SkWNCnuNv531l94GaIzO+XI= +github.com/jackc/pgx/v5 v5.7.2/go.mod h1:ncY89UGWxg82EykZUwSpUKEfccBGGYq1xjrOpsbsfGQ= github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= @@ -103,8 +105,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pressly/goose/v3 v3.22.1 h1:2zICEfr1O3yTP9BRZMGPj7qFxQ+ik6yeo+z1LMuioLc= -github.com/pressly/goose/v3 v3.22.1/go.mod h1:xtMpbstWyCpyH+0cxLTMCENWBG+0CSxvTsXhW95d5eo= +github.com/pressly/goose/v3 v3.24.1 h1:bZmxRco2uy5uu5Ng1MMVEfYsFlrMJI+e/VMXHQ3C4LY= +github.com/pressly/goose/v3 v3.24.1/go.mod h1:rEWreU9uVtt0DHCyLzF9gRcWiiTF/V+528DV+4DORug= github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= @@ -129,8 +131,9 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= @@ -142,52 +145,56 @@ github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgj github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o= github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA= github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8= -github.com/txix-open/isp-kit v1.39.2 h1:2L2LFwi+sNop9NeLDQ4scIy8LuohzXh4EBejHApAeDM= -github.com/txix-open/isp-kit v1.39.2/go.mod h1:xB6mkoOewZBI1ND8kjU5TR6kvLu3VQI3Rdkh6g6FE4I= +github.com/txix-open/isp-kit v1.43.0 h1:fVVa8WNGSShtK935ypOAN1eQCY7Y4bqr17A3JCbp6mA= +github.com/txix-open/isp-kit v1.43.0/go.mod h1:BHRF3AYRcQtEtNvoQZXxTVj/CYOVMKhOcCD3n8CdsxE= github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To= github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99/go.mod h1:pA0NYmhL0uEkkxj55S+S7MZU4e2QIt46x9XSrzrWc3c= -go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.56.0 h1:4BZHA+B1wXEQoGNHxW8mURaLhcdGwvRnmhGbm+odRbc= -go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.56.0/go.mod h1:3qi2EEwMgB4xnKgPLqsDP3j9qxnHDZeHsnAxfjQqTko= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 h1:UP6IpuHFkUgOQL9FFQFrZ+5LiwhhYRbi7VZSIx6Nj5s= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0/go.mod h1:qxuZLtbq5QDtdeSHsS7bcf6EH6uO6jUAgk764zd3rhM= -go.opentelemetry.io/otel v1.31.0 h1:NsJcKPIW0D0H3NgzPDHmo0WW6SptzPdqg/L1zsIm2hY= -go.opentelemetry.io/otel v1.31.0/go.mod h1:O0C14Yl9FgkjqcCZAsE053C13OaddMYr/hz6clDkEJE= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0 h1:K0XaT3DwHAcV4nKLzcQvwAgSyisUghWoY20I7huthMk= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.31.0/go.mod h1:B5Ki776z/MBnVha1Nzwp5arlzBbE3+1jk+pGmaP5HME= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0 h1:lUsI2TYsQw2r1IASwoROaCnjdj2cvC2+Jbxvk6nHnWU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.31.0/go.mod h1:2HpZxxQurfGxJlJDblybejHB6RX6pmExPNe517hREw4= -go.opentelemetry.io/otel/metric v1.31.0 h1:FSErL0ATQAmYHUIzSezZibnyVlft1ybhy4ozRPcF2fE= -go.opentelemetry.io/otel/metric v1.31.0/go.mod h1:C3dEloVbLuYoX41KpmAhOqNriGbA+qqH6PQ5E5mUfnY= -go.opentelemetry.io/otel/sdk v1.31.0 h1:xLY3abVHYZ5HSfOg3l2E5LUj2Cwva5Y7yGxnSW9H5Gk= -go.opentelemetry.io/otel/sdk v1.31.0/go.mod h1:TfRbMdhvxIIr/B2N2LQW2S5v9m3gOQ/08KsbbO5BPT0= -go.opentelemetry.io/otel/trace v1.31.0 h1:ffjsj1aRouKewfr85U2aGagJ46+MvodynlQ1HYdmJys= -go.opentelemetry.io/otel/trace v1.31.0/go.mod h1:TXZkRk7SM2ZQLtR6eoAWQFIHPvzQ06FJAsO1tJg480A= -go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0= -go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.58.0 h1:xwH3QJv6zL4u+gkPUu59NeT1Gyw9nScWT8FQpKLUJJI= +go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.58.0/go.mod h1:uosvgpqTcTXtcPQORTbEkZNDQTCDOgTz1fe6aLSyqrQ= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0 h1:yd02MEjBdJkG3uabWP9apV+OuWRIXGDuJEUJbOHmCFU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.58.0/go.mod h1:umTcuxiv1n/s/S6/c2AT/g2CQ7u5C59sHDNmfSwgz7Q= +go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw= +go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0 h1:Vh5HayB/0HHfOQA7Ctx69E/Y/DcQSMPpKANYVMQ7fBA= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.33.0/go.mod h1:cpgtDBaqD/6ok/UG0jT15/uKjAY8mRA53diogHBg3UI= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.33.0 h1:wpMfgF8E1rkrT1Z6meFh1NDtownE9Ii3n3X2GJYjsaU= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.33.0/go.mod h1:wAy0T/dUbs468uOlkT31xjvqQgEVXv58BRFWEgn5v/0= +go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ= +go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M= +go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM= +go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM= +go.opentelemetry.io/otel/sdk/metric v1.32.0 h1:rZvFnvmvawYb0alrYkjraqJq0Z4ZUJAiyYCU9snn1CU= +go.opentelemetry.io/otel/sdk/metric v1.32.0/go.mod h1:PWeZlq0zt9YkYAp3gjKZ0eicRYvOh1Gd+X99x6GHpCQ= +go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s= +go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck= +go.opentelemetry.io/proto/otlp v1.5.0 h1:xJvq7gMzB31/d406fB8U5CBdyQGw4P399D1aQWU/3i4= +go.opentelemetry.io/proto/otlp v1.5.0/go.mod h1:keN8WnHxOy8PG0rQZjJJ5A2ebUoafqWp0eVQ4yIXvJ4= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= -golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= -golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= -golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4= -golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU= -golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= -golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo= -golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= -golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= -google.golang.org/genproto/googleapis/api v0.0.0-20241021214115-324edc3d5d38 h1:2oV8dfuIkM1Ti7DwXc0BJfnwr9csz4TDXI9EmiI+Rbw= -google.golang.org/genproto/googleapis/api v0.0.0-20241021214115-324edc3d5d38/go.mod h1:vuAjtvlwkDKF6L1GQ0SokiRLCGFfeBUXWr/aFFkHACc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241021214115-324edc3d5d38 h1:zciRKQ4kBpFgpfC5QQCVtnnNAcLIqweL7plyZRQHVpI= -google.golang.org/genproto/googleapis/rpc v0.0.0-20241021214115-324edc3d5d38/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI= -google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E= -google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA= -google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= -google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs= +golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ= +golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8= +golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= +google.golang.org/genproto/googleapis/api v0.0.0-20250227231956-55c901821b1e h1:nsxey/MfoGzYNduN0NN/+hqP9iiCIYsrVbXb/8hjFM8= +google.golang.org/genproto/googleapis/api v0.0.0-20250227231956-55c901821b1e/go.mod h1:Xsh8gBVxGCcbV8ZeTB9wI5XPyZ5RvC6V3CTeeplHbiA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250227231956-55c901821b1e h1:YA5lmSs3zc/5w+xsRcHqpETkaYyK63ivEPzNTcUUlSA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250227231956-55c901821b1e/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= +google.golang.org/grpc v1.70.0 h1:pWFv03aZoHzlRKHWicjsZytKAiYCtNS0dHbXnIdq7jQ= +google.golang.org/grpc v1.70.0/go.mod h1:ofIJqVKDXx/JiXrwr2IG4/zwdH9txy3IlF40RmcJSQw= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -198,12 +205,14 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= -modernc.org/sqlite v1.33.0 h1:WWkA/T2G17okiLGgKAj4/RMIvgyMT19yQ038160IeYk= -modernc.org/sqlite v1.33.0/go.mod h1:9uQ9hF/pCZoYZK73D/ud5Z7cIRIILSZI8NdIemVMTX8= +modernc.org/sqlite v1.34.1 h1:u3Yi6M0N8t9yKRDwhXcyp1eS5/ErhPTBggxWFuR6Hfk= +modernc.org/sqlite v1.34.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k= modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= diff --git a/cmd/migrate/main.go b/cmd/migrate/main.go index 7bf02a3..5afa018 100644 --- a/cmd/migrate/main.go +++ b/cmd/migrate/main.go @@ -1,6 +1,8 @@ package main import ( + "context" + "database/sql" "fmt" "github.com/pressly/goose/v3" "github.com/txix-open/isp-kit/config" @@ -34,6 +36,14 @@ type Cfg struct { } } +type dbClient struct { + *db.Client +} + +func (d dbClient) ExecTransaction(ctx context.Context, requests [][]any) ([]sql.Result, error) { + panic("implement me") +} + func main() { app, err := app.New(app.WithConfigOptions( config.WithValidator(validator.Default), @@ -58,7 +68,7 @@ func main() { defer pgDb.Close() fileName := fmt.Sprintf("db_%d.sqlite", time.Now().Unix()) - dbClient := &db.Client{} + dbClient := dbClient{&db.Client{}} dbClient.DB, err = sqlx.Open("sqlite3", fileName) dbClient.DB.MapperFunc(db.ToSnakeCase) if err != nil { diff --git a/controller/api/variable.go b/controller/api/variable.go index cb2c16c..f32c610 100644 --- a/controller/api/variable.go +++ b/controller/api/variable.go @@ -1,3 +1,4 @@ +//nolint:lll package api import ( @@ -12,10 +13,10 @@ import ( type Service interface { All(ctx context.Context) ([]domain.Variable, error) GetByName(ctx context.Context, name string) (*domain.Variable, error) - Create(ctx context.Context, req domain.CreateVariableRequest) (*domain.Variable, error) - Update(ctx context.Context, req domain.UpdateVariableRequest) (*domain.Variable, error) + Create(ctx context.Context, req domain.CreateVariableRequest) error + Update(ctx context.Context, req domain.UpdateVariableRequest) error Upsert(ctx context.Context, req []domain.UpsertVariableRequest) error - Delete(ctx context.Context, name string) (*domain.Variable, error) + Delete(ctx context.Context, name string) error } type Variable struct { @@ -68,19 +69,19 @@ func (c Variable) GetByName(ctx context.Context, req domain.VariableByNameReques // @Accept json // @Produce json // @Param body body domain.CreateVariableRequest true "тело запроса" -// @Success 200 {object} domain.Variable +// @Success 200 // @Failure 400 {object} apierrors.Error "`errorCode: 2007` - переменная с таким именем уже существует
" // @Failure 500 {object} apierrors.Error // @Router /variable/create [POST] -func (c Variable) Create(ctx context.Context, req domain.CreateVariableRequest) (*domain.Variable, error) { - v, err := c.service.Create(ctx, req) +func (c Variable) Create(ctx context.Context, req domain.CreateVariableRequest) error { + err := c.service.Create(ctx, req) switch { case errors.Is(err, entity.ErrVariableAlreadyExists): - return nil, apierrors.NewBusinessError(domain.ErrorCodeVariableAlreadyExists, "variable with the same name already exists", err) + return apierrors.NewBusinessError(domain.ErrorCodeVariableAlreadyExists, "variable with the same name already exists", err) case err != nil: - return nil, apierrors.NewInternalServiceError(err) + return apierrors.NewInternalServiceError(err) } - return v, nil + return nil } // Update @@ -90,19 +91,19 @@ func (c Variable) Create(ctx context.Context, req domain.CreateVariableRequest) // @Accept json // @Produce json // @Param body body domain.UpdateVariableRequest true "тело запроса" -// @Success 200 {object} domain.Variable +// @Success 200 // @Failure 400 {object} apierrors.Error "`errorCode: 2006` - переменная по имени не найдена
" // @Failure 500 {object} apierrors.Error // @Router /variable/update [POST] -func (c Variable) Update(ctx context.Context, req domain.UpdateVariableRequest) (*domain.Variable, error) { - v, err := c.service.Update(ctx, req) +func (c Variable) Update(ctx context.Context, req domain.UpdateVariableRequest) error { + err := c.service.Update(ctx, req) switch { case errors.Is(err, entity.ErrVariableNotFound): - return nil, apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err) + return apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err) case err != nil: - return nil, apierrors.NewInternalServiceError(err) + return apierrors.NewInternalServiceError(err) } - return v, nil + return nil } // Upsert @@ -135,15 +136,15 @@ func (c Variable) Upsert(ctx context.Context, req []domain.UpsertVariableRequest // @Failure 400 {object} apierrors.Error "`errorCode: 2006` - переменная по имени не найдена
`errorCode: 2008` - переменная используется в конфигурациях
" // @Failure 500 {object} apierrors.Error // @Router /variable/delete [POST] -func (c Variable) Delete(ctx context.Context, req domain.VariableByNameRequest) (*domain.Variable, error) { - v, err := c.service.Delete(ctx, req.Name) +func (c Variable) Delete(ctx context.Context, req domain.VariableByNameRequest) error { + err := c.service.Delete(ctx, req.Name) switch { case errors.Is(err, entity.ErrConfigNotFound): - return nil, apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err) + return apierrors.NewBusinessError(domain.ErrorCodeVariableNotFound, "variable by name not found", err) case errors.Is(err, entity.ErrVariableUsedInConfigs): - return nil, apierrors.NewBusinessError(domain.ErrorCodeVariableUsedInConfigs, "variable used in configs", err) + return apierrors.NewBusinessError(domain.ErrorCodeVariableUsedInConfigs, "variable used in configs", err) case err != nil: - return nil, apierrors.NewInternalServiceError(err) + return apierrors.NewInternalServiceError(err) } - return v, nil + return nil } diff --git a/domain/variable.go b/domain/variable.go index e812970..cd2b5a0 100644 --- a/domain/variable.go +++ b/domain/variable.go @@ -1,6 +1,9 @@ package domain -import "time" +import ( + "isp-config-service/entity" + "time" +) type Variable struct { Name string @@ -21,7 +24,7 @@ type LinkedConfig struct { type CreateVariableRequest struct { Name string `validate:"required"` Description string - Type string `validate:"required"` + Type string `validate:"required,oneof=SECRET TEXT"` Value string `validate:"required"` } @@ -34,9 +37,15 @@ type UpdateVariableRequest struct { type UpsertVariableRequest struct { Name string `validate:"required"` Description string `validate:"required"` + Type string `validate:"required,oneof=SECRET TEXT"` Value string `validate:"required"` } type VariableByNameRequest struct { Name string `validate:"required"` } + +type VariableExtractionResult struct { + VariableLinks []entity.ConfigHasVariable + AbsentVariables []string +} diff --git a/entity/config.go b/entity/config.go index ac3d8d4..d6f53a2 100644 --- a/entity/config.go +++ b/entity/config.go @@ -16,6 +16,14 @@ type Config struct { UpdatedAt xtypes.Time `json:"updated_at"` } +type ConfigMetaWithVariable struct { + Id string `json:"id"` + Name string `json:"name"` + ModuleId string `json:"module_id"` + VariableName string `json:"variable_name"` + Active xtypes.Bool `json:"active"` +} + type ConfigHistory struct { Id string `json:"id"` ConfigId string `json:"config_id"` diff --git a/entity/variable.go b/entity/variable.go index c532b94..7cbed2d 100644 --- a/entity/variable.go +++ b/entity/variable.go @@ -5,15 +5,15 @@ import ( ) type Variable struct { - Name string - Description string - Type string - Value string - CreatedAt xtypes.Time - UpdatedAt xtypes.Time + Name string `json:"name"` + Description string `json:"description"` + Type string `json:"type"` + Value string `json:"value"` + CreatedAt xtypes.Time `json:"created_at"` + UpdatedAt xtypes.Time `json:"updated_at"` } type ConfigHasVariable struct { - ConfigId string - VariableName string + ConfigId string `json:"config_id"` + VariableName string `json:"variable_name"` } diff --git a/go.mod b/go.mod index e949f5a..c4a355a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module isp-config-service -go 1.23.0 +go 1.23 require ( github.com/Masterminds/squirrel v1.5.4 @@ -16,7 +16,7 @@ require ( github.com/txix-open/etp/v4 v4.0.1 github.com/txix-open/isp-kit v1.43.0 github.com/xeipuuv/gojsonschema v1.2.0 - golang.org/x/sync v0.10.0 + golang.org/x/sync v0.11.0 google.golang.org/grpc v1.70.0 ) diff --git a/go.sum b/go.sum index 01ce039..25385f5 100644 --- a/go.sum +++ b/go.sum @@ -341,8 +341,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= diff --git a/repository/config.go b/repository/config.go index 0192a91..365ad7f 100644 --- a/repository/config.go +++ b/repository/config.go @@ -2,7 +2,7 @@ package repository import ( "context" - + "fmt" "github.com/Masterminds/squirrel" "github.com/pkg/errors" "isp-config-service/entity" @@ -170,3 +170,30 @@ func (r Config) SetActive(ctx context.Context, configId string, active xtypes.Bo return nil } + +func (r Config) GetMetaByVariables(ctx context.Context, variables []string) (map[string][]entity.ConfigMetaWithVariable, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetMetaByVariables") + + query, args, err := squirrel.Select("c.id", "c.name", "c.module_id", "c.active", "l.variable_name"). + From(Table("config c")). + Join(fmt.Sprintf("%s l on c.id = l.config_id", Table("config_has_variable"))). + Where(squirrel.Eq{ + "l.variable_name": variables, + }).ToSql() + if err != nil { + return nil, errors.WithMessage(err, "build query") + } + + list := make([]entity.ConfigMetaWithVariable, 0) + err = r.db.Select(ctx, &list, query, args...) + if err != nil { + return nil, errors.WithMessagef(err, "select: %s", query) + } + + result := make(map[string][]entity.ConfigMetaWithVariable) + for _, variable := range list { + result[variable.VariableName] = append(result[variable.VariableName], variable) + } + + return result, nil +} diff --git a/repository/variable.go b/repository/variable.go index 9e338b0..65ad391 100644 --- a/repository/variable.go +++ b/repository/variable.go @@ -1,6 +1,15 @@ package repository -import "isp-config-service/service/rqlite/db" +import ( + "context" + "database/sql" + "fmt" + "github.com/Masterminds/squirrel" + "github.com/pkg/errors" + "isp-config-service/entity" + "isp-config-service/middlewares/sql_metrics" + "isp-config-service/service/rqlite/db" +) type Variable struct { db db.DB @@ -11,3 +20,159 @@ func NewVariable(db db.DB) Variable { db: db, } } + +func (r Variable) All(ctx context.Context) ([]entity.Variable, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.All") + + result := make([]entity.Variable, 0) + query := fmt.Sprintf("SELECT * FROM %s order by created_at desc", Table("variable")) + err := r.db.Select(ctx, &result, query) + if err != nil { + return nil, errors.WithMessagef(err, "select: %s", query) + } + return result, nil +} + +func (r Variable) GetByName(ctx context.Context, name string) (*entity.Variable, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.GetByName") + + query, args, err := squirrel.Select().From(Table("variable")).Where(squirrel.Eq{"name": name}).ToSql() + if err != nil { + return nil, errors.WithMessage(err, "build query") + } + + result := entity.Variable{} + err = r.db.SelectRow(ctx, &result, query, args...) + if errors.Is(err, sql.ErrNoRows) { + return nil, nil //nolint:nilnil + } + if err != nil { + return nil, errors.WithMessagef(err, "select: %s", query) + } + return &result, nil +} + +func (r Variable) Insert(ctx context.Context, variable entity.Variable) error { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Insert") + + query, args, err := squirrel.Insert(Table("variable")). + Columns("name", "description", "type", "value"). + Values(variable.Name, variable.Description, variable.Type, variable.Value). + ToSql() + if err != nil { + return errors.WithMessage(err, "build query") + } + + _, err = r.db.Exec(ctx, query, args...) + if err != nil { + return errors.WithMessagef(err, "exec: %s", query) + } + + return nil +} + +func (r Variable) Update(ctx context.Context, variable entity.Variable) (bool, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Update") + + query, args, err := squirrel.Update(Table("variable")). + SetMap(map[string]any{ + "description": variable.Description, + "value": variable.Value, + "updated_at": squirrel.Expr("unixepoch()"), + }).Where(squirrel.Eq{ + "name": variable.Name, + }).ToSql() + if err != nil { + return false, errors.WithMessage(err, "build query") + } + + result, err := r.db.Exec(ctx, query, args...) + if err != nil { + return false, errors.WithMessagef(err, "exec: %s", query) + } + + affected, err := result.RowsAffected() + if err != nil { + return false, errors.WithMessage(err, "get rows affected") + } + return affected > 0, nil +} + +func (r Variable) Upsert(ctx context.Context, variables []entity.Variable) error { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Upsert") + + requests := make([][]any, 0, len(variables)) + for _, variable := range variables { + query, args, err := squirrel.Insert(Table("variable")). + Columns("name", "description", "type", "value"). + Values(variable.Name, variable.Description, variable.Type, variable.Value). + Suffix(`on conflict (name) do update + set description = excluded.description, type = excluded.type, value = excluded.value, updated_at = unixepoch()`, + ).ToSql() + if err != nil { + return errors.WithMessage(err, "build query") + } + requests = append(requests, db.Request(query, args...)) + } + + _, err := r.db.ExecTransaction(ctx, requests) + if err != nil { + return errors.WithMessagef(err, "exec transaction: %v", requests) + } + + return nil +} + +func (r Variable) UpsertLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.UpsertLinks") + + deleteQuery, args, err := squirrel.Delete(Table("config_has_variable")).Where(squirrel.Eq{ + "config_id": configId, + }).ToSql() + if err != nil { + return errors.WithMessage(err, "build delete query") + } + requests := [][]any{ + db.Request(deleteQuery, args...), + } + 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...)) + } + + _, 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") + + query, args, err := squirrel.Delete(Table("variable")). + Where(squirrel.Eq{ + "name": name, + }).ToSql() + if err != nil { + return false, errors.WithMessage(err, "build query") + } + + result, err := r.db.Exec(ctx, query, args...) + if err != nil { + return false, errors.WithMessagef(err, "exec: %s", query) + } + + affected, err := result.RowsAffected() + if err != nil { + return false, errors.WithMessage(err, "get rows affected") + } + return affected > 0, nil +} diff --git a/routes/routes.go b/routes/routes.go index 260d93a..b075f90 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -65,7 +65,7 @@ func HttpHandler(etpSrv *etp.Server, conf conf.Local, rqliteProxy http.Handler) func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { return []cluster.EndpointDescriptor{ - //modules + // modules { Path: "config/module/get_modules_info", Inner: true, @@ -79,7 +79,7 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.ModuleApi.Connections, }, - //configs + // configs { Path: "config/config/get_active_config_by_module_name", Inner: true, @@ -117,7 +117,7 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.ConfigSchemaApi.SchemaByModuleId, }, - //variables + // variables { Path: "variable/all", Inner: true, diff --git a/service/api/config.go b/service/api/config.go index 1ac29c5..fb43cff 100644 --- a/service/api/config.go +++ b/service/api/config.go @@ -30,12 +30,18 @@ type ConfigHistoryService interface { OnUpdateConfig(ctx context.Context, oldConfig entity.Config) error } +type VariableService interface { + ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) + SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error +} + type Config struct { configRepo ConfigRepo moduleRepo ModuleRepo schemaRepo SchemaRepo eventRepo EventRepo configHistoryService ConfigHistoryService + variableService VariableService } func NewConfig( @@ -44,6 +50,7 @@ func NewConfig( schemaRepo SchemaRepo, eventRepo EventRepo, configHistoryService ConfigHistoryService, + variableService VariableService, ) Config { return Config{ configRepo: configRepo, @@ -51,6 +58,7 @@ func NewConfig( schemaRepo: schemaRepo, eventRepo: eventRepo, configHistoryService: configHistoryService, + variableService: variableService, } } @@ -118,6 +126,11 @@ func (c Config) CreateUpdateConfig( return c.insertNewConfig(ctx, adminId, req) } + variableExtractionResult, err := c.extractAndCheckVariables(ctx, req.Id, req.Data) + if err != nil { + return nil, errors.WithMessage(err, "extract variables") + } + oldConfig, err := c.configRepo.GetById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get old config") @@ -146,6 +159,11 @@ func (c Config) CreateUpdateConfig( return nil, errors.WithMessage(err, "change config history") } + err = c.variableService.SaveVariableLinks(ctx, config.Id, variableExtractionResult.VariableLinks) + if err != nil { + return nil, errors.WithMessage(err, "save variable links") + } + if oldConfig.Active { err = c.emitChangeActiveConfigEvent(ctx, oldConfig.ModuleId) if err != nil { @@ -236,10 +254,35 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre if err != nil { return nil, errors.WithMessage(err, "insert new config") } + + extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data) + if err != nil { + return nil, err + } + err = c.variableService.SaveVariableLinks(ctx, config.Id, extractResult.VariableLinks) + if err != nil { + return nil, errors.WithMessage(err, "save variable links") + } + result := configToDto(config, nil) return &result, nil } +func (c Config) extractAndCheckVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) { + variableExtractionResult, err := c.variableService.ExtractVariables(ctx, configId, input) + if err != nil { + return nil, errors.WithMessage(err, "extract variables") + } + if len(variableExtractionResult.AbsentVariables) > 0 { + details := make(map[string]string) + for _, variable := range variableExtractionResult.AbsentVariables { + details[variable] = "variable is not defined" + } + return nil, domain.NewConfigValidationError(details) + } + return variableExtractionResult, 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/module/service.go b/service/module/service.go index 115d46c..d10baa1 100644 --- a/service/module/service.go +++ b/service/module/service.go @@ -10,9 +10,11 @@ import ( "github.com/txix-open/etp/v4/store" "github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/log" + "isp-config-service/domain" "isp-config-service/entity" "isp-config-service/entity/xtypes" "isp-config-service/helpers" + "strings" ) const ( @@ -42,6 +44,12 @@ type ConfigRepo interface { GetActive(ctx context.Context, moduleId string) (*entity.Config, error) } +type VariableService interface { + RenderConfig(ctx context.Context, input []byte) ([]byte, error) + ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) + SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error +} + type SubscriptionService interface { SubscribeToConfigChanges(conn *etp.Conn, moduleId string) SubscribeToBackendsChanges(ctx context.Context, conn *etp.Conn, requiredModuleNames []string) error @@ -55,6 +63,7 @@ type Service struct { configSchemaRepo ConfigSchemaRepo subscriptionService SubscriptionService emitter Emitter + variableService VariableService logger log.Logger } @@ -65,6 +74,7 @@ func NewService( configSchemaRepo ConfigSchemaRepo, subscriptionService SubscriptionService, emitter Emitter, + variableService VariableService, logger log.Logger, ) Service { return Service{ @@ -74,6 +84,7 @@ func NewService( configSchemaRepo: configSchemaRepo, subscriptionService: subscriptionService, emitter: emitter, + variableService: variableService, logger: logger, } } @@ -213,10 +224,27 @@ func (s Service) OnModuleConfigSchema( 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") + } + if len(result.AbsentVariables) > 0 { + return errors.Errorf("missing variables in initial config: [%s]", strings.Join(result.AbsentVariables, ",")) + } + err = s.variableService.SaveVariableLinks(ctx, initialConfig.Id, result.VariableLinks) + if err != nil { + return errors.WithMessage(err, "save variable links in store") + } + config = &initialConfig } - s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigWhenConnected, config.Data) + configData, err := s.variableService.RenderConfig(ctx, config.Data) + if err != nil { + return errors.WithMessage(err, "render config") + } + s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigWhenConnected, configData) s.subscriptionService.SubscribeToConfigChanges(conn, moduleId) diff --git a/service/rqlite/db/db.go b/service/rqlite/db/db.go index 196d7ba..1edfa8c 100644 --- a/service/rqlite/db/db.go +++ b/service/rqlite/db/db.go @@ -42,7 +42,7 @@ func (d Adapter) Select(ctx context.Context, ptr any, query string, args ...any) consistencyFromContext(ctx).appendParams(params) err := d.cli.Post("/db/query"). QueryParams(params). - JsonRequestBody(requests(request(query, args...))). + JsonRequestBody(Requests(Request(query, args...))). JsonResponseBody(resp). StatusCodeToError(). DoWithoutResponse(ctx) @@ -69,7 +69,7 @@ func (d Adapter) SelectRow(ctx context.Context, ptr any, query string, args ...a consistencyFromContext(ctx).appendParams(params) httpResp, err := d.cli.Post("/db/request"). QueryParams(params). - JsonRequestBody(requests(request(query, args...))). + JsonRequestBody(Requests(Request(query, args...))). JsonResponseBody(resp). StatusCodeToError(). Do(ctx) @@ -98,21 +98,19 @@ func (d Adapter) SelectRow(ctx context.Context, ptr any, query string, args ...a } func (d Adapter) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) { - result := &Result{} - resp := &Response{ - Results: []*Result{result}, - } - err := d.cli.Post("/db/execute"). - QueryParams(map[string]any{ - "timings": true, - }).JsonRequestBody(requests(request(query, args...))). - JsonResponseBody(resp). - StatusCodeToError(). - DoWithoutResponse(ctx) + results, err := d.exec(ctx, false, Requests(Request(query, args...))) if err != nil { - return nil, errors.WithMessage(err, "call rqlite") + return nil, err } - err = catchError(resp, result) + + if len(results) == 0 { + return nil, errors.Errorf("unexpected empty results") + } + result, ok := results[0].(*Result) + if !ok { + return nil, errors.Errorf("unexpected result type: %T", results[0]) + } + err = catchError(nil, result) if err != nil { return nil, err } @@ -124,6 +122,38 @@ func (d Adapter) ExecNamed(ctx context.Context, query string, arg any) (sql.Resu return d.Exec(ctx, query, arg) } +func (d Adapter) ExecTransaction(ctx context.Context, requests [][]any) ([]sql.Result, error) { + return d.exec(ctx, true, requests) +} + +func (d Adapter) exec(ctx context.Context, inTx bool, requests [][]any) ([]sql.Result, error) { + resp := &Response{ + Results: []*Result{}, + } + err := d.cli.Post("/db/execute"). + QueryParams(map[string]any{ + "timings": true, + "transaction": inTx, + }).JsonRequestBody(requests). + JsonResponseBody(resp). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessage(err, "call rqlite") + } + err = catchError(resp, nil) + if err != nil { + return nil, err + } + + results := make([]sql.Result, 0, len(requests)) + for _, result := range resp.Results { + results = append(results, result) + } + + return results, nil +} + func catchError(resp *Response, result *Result) error { if resp != nil && resp.Error != "" { return errors.Errorf("rqlite api: %s", resp.Error) diff --git a/service/rqlite/db/iface.go b/service/rqlite/db/iface.go index 1626c76..5ceb2a7 100644 --- a/service/rqlite/db/iface.go +++ b/service/rqlite/db/iface.go @@ -10,4 +10,5 @@ type DB interface { SelectRow(ctx context.Context, ptr any, query string, args ...any) error Exec(ctx context.Context, query string, args ...any) (sql.Result, error) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) + ExecTransaction(ctx context.Context, requests [][]any) ([]sql.Result, error) } diff --git a/service/rqlite/db/request.go b/service/rqlite/db/request.go index 789868c..5560ede 100644 --- a/service/rqlite/db/request.go +++ b/service/rqlite/db/request.go @@ -1,9 +1,9 @@ package db -func request(query string, args ...any) []any { +func Request(query string, args ...any) []any { return append([]any{query}, args...) } -func requests(requests ...[]any) [][]any { +func Requests(requests ...[]any) [][]any { return requests } diff --git a/service/subscription/service.go b/service/subscription/service.go index 23287fa..d6572ee 100644 --- a/service/subscription/service.go +++ b/service/subscription/service.go @@ -27,17 +27,22 @@ type ConfigRepo interface { GetActive(ctx context.Context, moduleId string) (*entity.Config, error) } +type VariableService interface { + RenderConfig(ctx context.Context, input []byte) ([]byte, error) +} + type Emitter interface { Emit(ctx context.Context, conn *etp.Conn, event string, data []byte) } type Service struct { - moduleRepo ModuleRepo - backendRepo BackendRepo - configRepo ConfigRepo - rooms *etp.Rooms - emitter Emitter - logger log.Logger + moduleRepo ModuleRepo + backendRepo BackendRepo + configRepo ConfigRepo + rooms *etp.Rooms + emitter Emitter + variableService VariableService + logger log.Logger } func NewService( @@ -46,15 +51,17 @@ func NewService( configRepo ConfigRepo, rooms *etp.Rooms, emitter Emitter, + variableService VariableService, logger log.Logger, ) Service { return Service{ - moduleRepo: moduleRepo, - backendRepo: backendRepo, - configRepo: configRepo, - rooms: rooms, - emitter: emitter, - logger: logger, + moduleRepo: moduleRepo, + backendRepo: backendRepo, + configRepo: configRepo, + rooms: rooms, + emitter: emitter, + variableService: variableService, + logger: logger, } } @@ -73,10 +80,14 @@ func (s Service) NotifyConfigChanged(ctx context.Context, moduleId string) error if err != nil { return errors.WithMessage(err, "get active config") } + configData, err := s.variableService.RenderConfig(ctx, config.Data) + if err != nil { + return errors.WithMessage(err, "render config") + } for _, conn := range conns { go func() { - s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigChanged, config.Data) + s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigChanged, configData) }() } diff --git a/service/variable/service.go b/service/variable/service.go index 628f0ff..b60efca 100644 --- a/service/variable/service.go +++ b/service/variable/service.go @@ -1,40 +1,323 @@ package variable import ( + "bytes" "context" + "github.com/pkg/errors" "isp-config-service/domain" + "isp-config-service/entity" + "isp-config-service/entity/xtypes" + "regexp" + "text/template" + "time" ) type Repo interface { + All(ctx context.Context) ([]entity.Variable, error) + GetByName(ctx context.Context, name string) (*entity.Variable, error) + Insert(ctx context.Context, variable entity.Variable) error + Update(ctx context.Context, variable entity.Variable) (bool, error) + 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 +} + +type ConfigRepo interface { + GetMetaByVariables(ctx context.Context, variables []string) (map[string][]entity.ConfigMetaWithVariable, error) +} + +type EventRepo interface { + Insert(ctx context.Context, event entity.Event) error } type Service struct { + repo Repo + configRepo ConfigRepo + eventRepo EventRepo + stringToIntRegexp *regexp.Regexp + extractVariableRegexp *regexp.Regexp + replaceVariableRegexp *regexp.Regexp } -func NewService() Service { - +func NewService( + repo Repo, + configRepo ConfigRepo, + eventRepo EventRepo, +) Service { + return Service{ + repo: repo, + configRepo: configRepo, + eventRepo: eventRepo, + stringToIntRegexp: regexp.MustCompile(`"_ToInt\((\d+)\)"`), + extractVariableRegexp: regexp.MustCompile(`_Var\(\{\{ \.(.*?) \}\}\)`), + replaceVariableRegexp: regexp.MustCompile(`_Var\((.*?)\)`), + } } func (s Service) All(ctx context.Context) ([]domain.Variable, error) { + variables, err := s.repo.All(ctx) + if err != nil { + return nil, errors.WithMessage(err, "get all variables") + } + if len(variables) == 0 { + return []domain.Variable{}, nil + } + varNames := make([]string, 0, len(variables)) + for _, v := range variables { + varNames = append(varNames, v.Name) + } + metaByVariables, err := s.configRepo.GetMetaByVariables(ctx, varNames) + if err != nil { + return nil, errors.WithMessage(err, "get meta by variables") + } + + result := make([]domain.Variable, 0, len(variables)) + for _, v := range variables { + result = append(result, s.toDto(v, metaByVariables)) + } + + return result, nil } func (s Service) GetByName(ctx context.Context, name string) (*domain.Variable, error) { + variable, err := s.repo.GetByName(ctx, name) + if err != nil { + return nil, errors.WithMessage(err, "get variable by name") + } + if variable == nil { + return nil, entity.ErrVariableNotFound + } + metaByVariables, err := s.configRepo.GetMetaByVariables(ctx, []string{name}) + if err != nil { + return nil, errors.WithMessage(err, "get meta by variables") + } + + result := s.toDto(*variable, metaByVariables) + return &result, nil } -func (s Service) Create(ctx context.Context, req domain.CreateVariableRequest) (*domain.Variable, error) { - +func (s Service) Create(ctx context.Context, req domain.CreateVariableRequest) error { + variable := entity.Variable{ + Name: req.Name, + Description: req.Description, + Type: req.Type, + Value: req.Value, + } + err := s.repo.Insert(ctx, variable) + if err != nil { + return errors.WithMessage(err, "insert variable") + } + return nil } -func (s Service) Update(ctx context.Context, req domain.UpdateVariableRequest) (*domain.Variable, error) { +func (s Service) Update(ctx context.Context, req domain.UpdateVariableRequest) error { + variable := entity.Variable{ + Name: req.Name, + Description: req.Description, + Value: req.Value, + } + updated, err := s.repo.Update(ctx, variable) + if err != nil { + return errors.WithMessage(err, "update variable") + } + if !updated { + return entity.ErrVariableNotFound + } + err = s.syncConfigsByVariables(ctx, []string{variable.Name}) + if err != nil { + return errors.WithMessage(err, "sync configs by variables") + } + return nil } func (s Service) Upsert(ctx context.Context, req []domain.UpsertVariableRequest) error { + if len(req) == 0 { + return nil + } + variables := make([]entity.Variable, 0, len(req)) + variableNames := make([]string, 0, len(req)) + for _, request := range req { + variables = append(variables, entity.Variable{ + Name: request.Name, + Description: request.Description, + Type: request.Type, + Value: request.Value, + }) + variableNames = append(variableNames, request.Name) + } + err := s.repo.Upsert(ctx, variables) + if err != nil { + return errors.WithMessage(err, "upsert variables") + } + + err = s.syncConfigsByVariables(ctx, variableNames) + if err != nil { + return errors.WithMessage(err, "sync configs by variables") + } + + return nil } -func (s Service) Delete(ctx context.Context, name string) (*domain.Variable, error) { +func (s Service) Delete(ctx context.Context, name string) error { + metaByVariables, err := s.configRepo.GetMetaByVariables(ctx, []string{name}) + if err != nil { + return errors.WithMessage(err, "get meta by variables") + } + if len(metaByVariables[name]) > 0 { + return entity.ErrVariableUsedInConfigs + } + deleted, err := s.repo.Delete(ctx, name) + if err != nil { + return errors.WithMessage(err, "delete variable") + } + if !deleted { + return entity.ErrVariableNotFound + } + + return nil +} + +func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) { + variables, err := s.repo.All(ctx) + if err != nil { + return nil, errors.WithMessage(err, "get all variables") + } + if len(variables) == 0 { + return input, nil + } + varsMap := make(map[string]string, len(variables)) + for _, variable := range variables { + varsMap[variable.Name] = variable.Value + } + + tt := template.New("config") + _, err = tt.Parse(string(input)) + if err != nil { + return nil, errors.WithMessage(err, "parse template") + } + out := bytes.NewBuffer(make([]byte, len(input))) + err = tt.Execute(out, varsMap) + if err != nil { + return nil, errors.WithMessage(err, "execute template") + } + + result := s.replaceVariableRegexp.ReplaceAll(out.Bytes(), []byte("$1")) + result = s.stringToIntRegexp.ReplaceAll(result, []byte("$1")) + return result, nil +} + +func (s Service) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) { + matches := s.extractVariableRegexp.FindAllStringSubmatch(string(input), -1) + varNames := make([]string, len(matches)) + for i, match := range matches { + varNames[i] = match[1] + } + if len(varNames) == 0 { + return &domain.VariableExtractionResult{ + VariableLinks: []entity.ConfigHasVariable{}, + AbsentVariables: []string{}, + }, nil + } + + allVariables, err := s.repo.All(ctx) + if err != nil { + return nil, errors.WithMessage(err, "get all variables") + } + allVariablesMap := make(map[string]bool, len(allVariables)) + for _, variable := range allVariables { + allVariablesMap[variable.Name] = true + } + + absentVariables := make([]string, 0) + variableLinks := make([]entity.ConfigHasVariable, 0) + for _, name := range varNames { + if !allVariablesMap[name] { + absentVariables = append(absentVariables, name) + continue + } + variableLinks = append(variableLinks, entity.ConfigHasVariable{ + ConfigId: configId, + VariableName: name, + }) + } + + return &domain.VariableExtractionResult{ + VariableLinks: variableLinks, + AbsentVariables: absentVariables, + }, nil +} + +func (s Service) SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error { + if len(links) == 0 { + return nil + } + + err := s.repo.UpsertLinks(ctx, configId, links) + if err != nil { + return errors.WithMessage(err, "upsert links") + } + + return nil +} + +func (s Service) toDto(variable entity.Variable, metaByVariables map[string][]entity.ConfigMetaWithVariable) domain.Variable { + value := variable.Value + if variable.Type == "SECRET" { + value = "" + } + containsInConfigs := []domain.LinkedConfig{} + for _, metaWithVariable := range metaByVariables[variable.Name] { + containsInConfigs = append(containsInConfigs, domain.LinkedConfig{ + Id: metaWithVariable.Id, + ModuleId: metaWithVariable.ModuleId, + Name: metaWithVariable.Name, + }) + } + return domain.Variable{ + Name: variable.Name, + Description: variable.Description, + Type: variable.Type, + Value: value, + CreatedAt: time.Time(variable.CreatedAt), + UpdatedAt: time.Time(variable.UpdatedAt), + ContainsInConfigs: containsInConfigs, + } +} + +func (s Service) syncConfigsByVariables(ctx context.Context, variables []string) error { + metaByVariables, err := s.configRepo.GetMetaByVariables(ctx, variables) + if err != nil { + return errors.WithMessage(err, "get meta by variables") + } + modulesToSync := make(map[string]bool) + for _, variable := range variables { + for _, withVariable := range metaByVariables[variable] { + if !withVariable.Active { + continue + } + modulesToSync[withVariable.ModuleId] = true + } + } + + for moduleId := range modulesToSync { + err := s.eventRepo.Insert(ctx, entity.Event{ + Payload: xtypes.Json[entity.EventPayload]{ + Value: entity.EventPayload{ + ConfigUpdated: &entity.PayloadConfigUpdated{ + ModuleId: moduleId, + }, + }, + }, + }) + if err != nil { + return errors.WithMessagef(err, "insert change config event for moduleId: %s", moduleId) + } + } + + return nil }