From 28cff347aba050c9e2e5ef585c61d4f4731e362e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 15:54:50 +0300 Subject: [PATCH 01/30] MSP-5186 Update lint --- .golangci.yml | 7 ++----- service/access_list.go | 2 +- service/application.go | 2 +- service/service.go | 2 +- service/token.go | 6 +++--- 5 files changed, 8 insertions(+), 11 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index d594308..a740dc8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -13,26 +13,23 @@ linters: 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 #устарел + - exportloopref #устарел + - execinquery #устарел linters-settings: funlen: lines: 80 diff --git a/service/access_list.go b/service/access_list.go index 103f343..82f54a1 100644 --- a/service/access_list.go +++ b/service/access_list.go @@ -12,7 +12,7 @@ type IAccessListAccessListRep interface { GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) } -type IAccessListApplicationRep interface { +type IAccessListApplicationRep interface { // nolint:iface GetApplicationById(ctx context.Context, id int) (*entity.Application, error) } diff --git a/service/application.go b/service/application.go index 24c94f5..5849b81 100644 --- a/service/application.go +++ b/service/application.go @@ -17,7 +17,7 @@ type IApplicationApplicationRep interface { UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) } -type IApplicationTokenRep interface { +type IApplicationTokenRep interface { // nolint:iface GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) } diff --git a/service/service.go b/service/service.go index 58d7d3b..3b11fe3 100644 --- a/service/service.go +++ b/service/service.go @@ -18,7 +18,7 @@ type IServiceServiceRep interface { DeleteService(ctx context.Context, idList []int) (int, error) } -type IServiceDomainRep interface { +type IServiceDomainRep interface { // nolint:iface GetDomainById(ctx context.Context, id int) (*entity.Domain, error) } diff --git a/service/token.go b/service/token.go index b03b02d..89c3ed2 100644 --- a/service/token.go +++ b/service/token.go @@ -16,7 +16,7 @@ type ITokenAppEnrich interface { EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error) } -type ITokenApplicationRep interface { +type ITokenApplicationRep interface { // nolint:iface GetApplicationById(ctx context.Context, id int) (*entity.Application, error) } @@ -24,11 +24,11 @@ type ITokenServiceRep interface { GetServiceById(ctx context.Context, id int) (*entity.Service, error) } -type ITokenDomainRep interface { +type ITokenDomainRep interface { // nolint:iface GetDomainById(ctx context.Context, id int) (*entity.Domain, error) } -type ITokenTokenRep interface { +type ITokenTokenRep interface { // nolint:iface GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) } From f095d338cfe3182bbb74ef39dc3a79864c583f6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 16:44:25 +0300 Subject: [PATCH 02/30] MSP-5186 Remove redundant I prefix from interfaces --- controller/token.go | 6 ++--- service/access_list.go | 33 +++++++++++++------------- service/application.go | 41 ++++++++++++++++---------------- service/domain.go | 22 ++++++++--------- service/service.go | 12 +++++----- service/token.go | 54 +++++++++++++++++++++--------------------- transaction/manager.go | 7 +++--- 7 files changed, 89 insertions(+), 86 deletions(-) diff --git a/controller/token.go b/controller/token.go index 81ff848..16155ea 100644 --- a/controller/token.go +++ b/controller/token.go @@ -9,7 +9,7 @@ import ( "isp-system-service/domain" ) -type ITokenService interface { +type TokenService interface { GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) @@ -17,10 +17,10 @@ type ITokenService interface { } type Token struct { - service ITokenService + service TokenService } -func NewToken(service ITokenService) Token { +func NewToken(service TokenService) Token { return Token{ service: service, } diff --git a/service/access_list.go b/service/access_list.go index 82f54a1..2b80b33 100644 --- a/service/access_list.go +++ b/service/access_list.go @@ -3,45 +3,46 @@ package service import ( "context" - "github.com/pkg/errors" "isp-system-service/domain" "isp-system-service/entity" + + "github.com/pkg/errors" ) -type IAccessListAccessListRep interface { +type AccessListAccessListRep interface { GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) } -type IAccessListApplicationRep interface { // nolint:iface +type AccessListApplicationRep interface { // nolint:iface GetApplicationById(ctx context.Context, id int) (*entity.Application, error) } -type IAccessListSetOneTx interface { +type AccessListSetOneTx interface { UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) } -type IAccessListSetListTx interface { +type AccessListSetListTx interface { GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error DeleteAccessList(ctx context.Context, appId int, methods []string) error DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) } -type IAccessListTxRunner interface { - AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetOneTx) error) error - AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetListTx) error) error +type AccessListTxRunner interface { + AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetOneTx) error) error + AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetListTx) error) error } type AccessList struct { - tx IAccessListTxRunner - accessListRep IAccessListAccessListRep - applicationRep IAccessListApplicationRep + tx AccessListTxRunner + accessListRep AccessListAccessListRep + applicationRep AccessListApplicationRep } func NewAccessList( - tx IAccessListTxRunner, - accessListRep IAccessListAccessListRep, - applicationRep IAccessListApplicationRep, + tx AccessListTxRunner, + accessListRep AccessListAccessListRep, + applicationRep AccessListApplicationRep, ) AccessList { return AccessList{ tx: tx, @@ -79,7 +80,7 @@ func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneR } var resp int - err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx IAccessListSetOneTx) error { + err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx AccessListSetOneTx) error { resp, err = tx.UpsertAccessList(ctx, entity.AccessList{ AppId: request.AppId, Method: request.Method, @@ -106,7 +107,7 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq return nil, errors.WithMessage(err, "get application by id") } - err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx IAccessListSetListTx) error { + err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx AccessListSetListTx) error { if req.RemoveOld { _, err = tx.DeleteAccessListByAppId(ctx, req.AppId) if err != nil { diff --git a/service/application.go b/service/application.go index 5849b81..74cd6a3 100644 --- a/service/application.go +++ b/service/application.go @@ -3,12 +3,13 @@ package service import ( "context" - "github.com/pkg/errors" "isp-system-service/domain" "isp-system-service/entity" + + "github.com/pkg/errors" ) -type IApplicationApplicationRep interface { +type ApplicationApplicationRep interface { GetApplicationById(ctx context.Context, id int) (*entity.Application, error) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) @@ -17,44 +18,44 @@ type IApplicationApplicationRep interface { UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) } -type IApplicationTokenRep interface { // nolint:iface +type ApplicationTokenRep interface { // nolint:iface GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) } -type IApplicationServiceRep interface { +type ApplicationServiceRep interface { GetServiceById(ctx context.Context, id int) (*entity.Service, error) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) } -type IApplicationDomainRep interface { +type ApplicationDomainRep interface { GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) } -type IApplicationDeleteTx interface { +type ApplicationDeleteTx interface { DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) } -type IApplicationTxRunner interface { - ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx IApplicationDeleteTx) error) error +type ApplicationTxRunner interface { + ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx ApplicationDeleteTx) error) error } type Application struct { - tx IApplicationTxRunner - applicationRep IApplicationApplicationRep - domainRep IApplicationDomainRep - serviceRep IApplicationServiceRep - tokenRep IApplicationTokenRep + txRunner ApplicationTxRunner + applicationRep ApplicationApplicationRep + domainRep ApplicationDomainRep + serviceRep ApplicationServiceRep + tokenRep ApplicationTokenRep } func NewApplication( - tx IApplicationTxRunner, - applicationRep IApplicationApplicationRep, - domainRep IApplicationDomainRep, - serviceRep IApplicationServiceRep, - tokenRep IApplicationTokenRep, + txRunner ApplicationTxRunner, + applicationRep ApplicationApplicationRep, + domainRep ApplicationDomainRep, + serviceRep ApplicationServiceRep, + tokenRep ApplicationTokenRep, ) Application { return Application{ - tx: tx, + txRunner: txRunner, applicationRep: applicationRep, domainRep: domainRep, serviceRep: serviceRep, @@ -229,7 +230,7 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre func (s Application) Delete(ctx context.Context, idList []int) (int, error) { count := 0 - err := s.tx.ApplicationDeleteTx(ctx, func(ctx context.Context, tx IApplicationDeleteTx) error { + err := s.txRunner.ApplicationDeleteTx(ctx, func(ctx context.Context, tx ApplicationDeleteTx) error { deletedApp, err := tx.DeleteApplicationByIdList(ctx, idList) if err != nil { return errors.WithMessage(err, "delete application by id list") diff --git a/service/domain.go b/service/domain.go index 52dce98..4914ca4 100644 --- a/service/domain.go +++ b/service/domain.go @@ -8,7 +8,7 @@ import ( "isp-system-service/entity" ) -type IDomainDomainRep interface { +type DomainDomainRep interface { GetDomainById(ctx context.Context, id int) (*entity.Domain, error) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) @@ -18,19 +18,19 @@ type IDomainDomainRep interface { } type Domain struct { - domainRep IDomainDomainRep + repo DomainDomainRep } func NewDomain( - domainRep IDomainDomainRep, + repo DomainDomainRep, ) Domain { return Domain{ - domainRep: domainRep, + repo: repo, } } func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) { - domainEntity, err := s.domainRep.GetDomainById(ctx, id) + domainEntity, err := s.repo.GetDomainById(ctx, id) if err != nil { return nil, errors.WithMessage(err, "get domain by id") } @@ -40,7 +40,7 @@ func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) { } func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) { - domainEntity, err := s.domainRep.GetDomainBySystemId(ctx, systemId) + domainEntity, err := s.repo.GetDomainBySystemId(ctx, systemId) if err != nil { return nil, errors.WithMessage(err, "get domain by system_id") } @@ -53,7 +53,7 @@ func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domai } func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) { - existed, err := s.domainRep.GetDomainByNameAndSystemId(ctx, req.Name, systemId) + existed, err := s.repo.GetDomainByNameAndSystemId(ctx, req.Name, systemId) switch { case errors.Is(err, domain.ErrDomainNotFound): case err != nil: @@ -65,7 +65,7 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR return nil, domain.ErrDomainDuplicateName } - domainEntity, err := s.domainRep.CreateDomain(ctx, req.Name, req.Description, systemId) + domainEntity, err := s.repo.CreateDomain(ctx, req.Name, req.Description, systemId) if err != nil { return nil, errors.WithMessagef(err, "create domain") } @@ -78,12 +78,12 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR return nil, domain.ErrDomainDuplicateName } - _, err = s.domainRep.GetDomainById(ctx, req.Id) + _, err = s.repo.GetDomainById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get domain by id") } - domainEntity, err := s.domainRep.UpdateDomain(ctx, req.Id, req.Name, req.Description) + domainEntity, err := s.repo.UpdateDomain(ctx, req.Id, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update domain") } @@ -93,7 +93,7 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR } func (s Domain) Delete(ctx context.Context, idList []int) (int, error) { - result, err := s.domainRep.DeleteDomain(ctx, idList) + result, err := s.repo.DeleteDomain(ctx, idList) if err != nil { return 0, errors.WithMessage(err, "delete domain") } diff --git a/service/service.go b/service/service.go index 3b11fe3..b504858 100644 --- a/service/service.go +++ b/service/service.go @@ -8,7 +8,7 @@ import ( "isp-system-service/entity" ) -type IServiceServiceRep interface { +type ServiceServiceRep interface { GetServiceById(ctx context.Context, id int) (*entity.Service, error) GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) @@ -18,18 +18,18 @@ type IServiceServiceRep interface { DeleteService(ctx context.Context, idList []int) (int, error) } -type IServiceDomainRep interface { // nolint:iface +type ServiceDomainRep interface { // nolint:iface GetDomainById(ctx context.Context, id int) (*entity.Domain, error) } type Service struct { - domainRep IServiceDomainRep - serviceRep IServiceServiceRep + domainRep ServiceDomainRep + serviceRep ServiceServiceRep } func NewService( - domainRep IServiceDomainRep, - serviceRep IServiceServiceRep, + domainRep ServiceDomainRep, + serviceRep ServiceServiceRep, ) Service { return Service{ domainRep: domainRep, diff --git a/service/token.go b/service/token.go index 89c3ed2..70674fe 100644 --- a/service/token.go +++ b/service/token.go @@ -8,61 +8,61 @@ import ( "isp-system-service/entity" ) -type ITokenSource interface { +type ApplicationTokenCreator interface { CreateApplicationToken() (string, error) } -type ITokenAppEnrich interface { +type TokenAppEnrich interface { EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error) } -type ITokenApplicationRep interface { // nolint:iface +type TokenApplicationRep interface { // nolint:iface GetApplicationById(ctx context.Context, id int) (*entity.Application, error) } -type ITokenServiceRep interface { +type TokenServiceRep interface { GetServiceById(ctx context.Context, id int) (*entity.Service, error) } -type ITokenDomainRep interface { // nolint:iface +type TokenDomainRep interface { // nolint:iface GetDomainById(ctx context.Context, id int) (*entity.Domain, error) } -type ITokenTokenRep interface { // nolint:iface +type TokenTokenRep interface { // nolint:iface GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) } -type ITokenCreateTx interface { +type TokenCreateTx interface { SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) } -type ITokenRevokeTx interface { +type TokenRevokeTx interface { DeleteToken(ctx context.Context, tokens []string) (int, error) } -type ITokenTxRunner interface { - TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx ITokenCreateTx) error) error - TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx ITokenRevokeTx) error) error +type TokenTxRunner interface { + TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx TokenCreateTx) error) error + TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx TokenRevokeTx) error) error } type Token struct { - jwt ITokenSource - appEnrich ITokenAppEnrich - tx ITokenTxRunner - appRep ITokenApplicationRep - domainRep ITokenDomainRep - serviceRep ITokenServiceRep - tokenRep ITokenTokenRep + jwt ApplicationTokenCreator + appEnrich TokenAppEnrich + tx TokenTxRunner + appRep TokenApplicationRep + domainRep TokenDomainRep + serviceRep TokenServiceRep + tokenRep TokenTokenRep } func NewToken( - jwtGenerate ITokenSource, - appEnrich ITokenAppEnrich, - tx ITokenTxRunner, - appRep ITokenApplicationRep, - domainRep ITokenDomainRep, - serviceRep ITokenServiceRep, - tokenRep ITokenTokenRep, + jwtGenerate ApplicationTokenCreator, + appEnrich TokenAppEnrich, + tx TokenTxRunner, + appRep TokenApplicationRep, + domainRep TokenDomainRep, + serviceRep TokenServiceRep, + tokenRep TokenTokenRep, ) Token { return Token{ appEnrich: appEnrich, @@ -110,7 +110,7 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma return nil, errors.WithMessagef(err, "create application token") } - err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx ITokenCreateTx) error { + err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx TokenCreateTx) error { _, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs) if err != nil { return errors.WithMessagef(err, "tx save token") @@ -169,7 +169,7 @@ func (s Token) revokeTokens(ctx context.Context, tokens []string) (*domain.Delet } var count int - err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx ITokenRevokeTx) error { + err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx TokenRevokeTx) error { deleted, err := tx.DeleteToken(ctx, tokens) if err != nil { return errors.WithMessagef(err, "tx delete token") diff --git a/transaction/manager.go b/transaction/manager.go index cddec1a..628608f 100644 --- a/transaction/manager.go +++ b/transaction/manager.go @@ -4,9 +4,10 @@ import ( "context" "isp-system-service/service/baseline" - "github.com/txix-open/isp-kit/db" "isp-system-service/repository" "isp-system-service/service" + + "github.com/txix-open/isp-kit/db" ) type Manager struct { @@ -23,7 +24,7 @@ type accessListSetOneTx struct { repository.AccessList } -func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetOneTx) error) error { +func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.AccessListSetOneTx) error) error { return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error { accessListRepository := repository.NewAccessList(tx) return msgTx(ctx, accessListSetOneTx{ @@ -49,7 +50,7 @@ type applicationDeleteTx struct { repository.Application } -func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IApplicationDeleteTx) error) error { +func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ApplicationDeleteTx) error) error { return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error { applicationRep := repository.NewApplication(tx) return msgTx(ctx, applicationDeleteTx{ From 84ebd8b5a91c4a4b325eb963ef46aa2d5e9fa287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 16:59:39 +0300 Subject: [PATCH 03/30] MSP-5186 Interfaces working --- service/access_list.go | 28 +++++++--------- service/application.go | 71 ++++++++++++++++------------------------- service/domain.go | 15 ++------- service/interfaces.go | 38 ++++++++++++++++++++++ service/service.go | 44 +++++++++---------------- service/token.go | 71 ++++++++++++++++------------------------- service/token_source.go | 3 +- transaction/manager.go | 6 ++-- 8 files changed, 126 insertions(+), 150 deletions(-) create mode 100644 service/interfaces.go diff --git a/service/access_list.go b/service/access_list.go index 2b80b33..8fd7bfd 100644 --- a/service/access_list.go +++ b/service/access_list.go @@ -9,14 +9,10 @@ import ( "github.com/pkg/errors" ) -type AccessListAccessListRep interface { +type AccessListRepo interface { GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) } -type AccessListApplicationRep interface { // nolint:iface - GetApplicationById(ctx context.Context, id int) (*entity.Application, error) -} - type AccessListSetOneTx interface { UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) } @@ -35,29 +31,29 @@ type AccessListTxRunner interface { type AccessList struct { tx AccessListTxRunner - accessListRep AccessListAccessListRep - applicationRep AccessListApplicationRep + accessListRepo AccessListRepo + appRepo ApplicationRepo } func NewAccessList( tx AccessListTxRunner, - accessListRep AccessListAccessListRep, - applicationRep AccessListApplicationRep, + accessListRepo AccessListRepo, + appRepo ApplicationRepo, ) AccessList { return AccessList{ tx: tx, - accessListRep: accessListRep, - applicationRep: applicationRep, + accessListRepo: accessListRepo, + appRepo: appRepo, } } func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) { - _, err := s.applicationRep.GetApplicationById(ctx, appId) + _, err := s.appRepo.GetApplicationById(ctx, appId) if err != nil { return nil, errors.WithMessage(err, "get application by id") } - accessList, err := s.accessListRep.GetAccessListByAppId(ctx, appId) + accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, appId) if err != nil { return nil, errors.WithMessagef(err, "get access list by app_id") } @@ -74,7 +70,7 @@ func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo } func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) { - _, err := s.applicationRep.GetApplicationById(ctx, request.AppId) + _, err := s.appRepo.GetApplicationById(ctx, request.AppId) if err != nil { return nil, errors.WithMessage(err, "get application by id") } @@ -102,7 +98,7 @@ func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneR } func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) { - _, err := s.applicationRep.GetApplicationById(ctx, req.AppId) + _, err := s.appRepo.GetApplicationById(ctx, req.AppId) if err != nil { return nil, errors.WithMessage(err, "get application by id") } @@ -144,7 +140,7 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq return nil, errors.WithMessage(err, "transaction access list set list") } - accessList, err := s.accessListRep.GetAccessListByAppId(ctx, req.AppId) + accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, req.AppId) if err != nil { return nil, errors.WithMessagef(err, "get access list by app_id") } diff --git a/service/application.go b/service/application.go index 74cd6a3..9a56032 100644 --- a/service/application.go +++ b/service/application.go @@ -9,28 +9,11 @@ import ( "github.com/pkg/errors" ) -type ApplicationApplicationRep interface { - GetApplicationById(ctx context.Context, id int) (*entity.Application, error) - GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) - GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) - GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) - CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error) - UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) -} - -type ApplicationTokenRep interface { // nolint:iface - GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) -} - type ApplicationServiceRep interface { GetServiceById(ctx context.Context, id int) (*entity.Service, error) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) } -type ApplicationDomainRep interface { - GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) -} - type ApplicationDeleteTx interface { DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) } @@ -40,31 +23,31 @@ type ApplicationTxRunner interface { } type Application struct { - txRunner ApplicationTxRunner - applicationRep ApplicationApplicationRep - domainRep ApplicationDomainRep - serviceRep ApplicationServiceRep - tokenRep ApplicationTokenRep + txRunner ApplicationTxRunner + appRepo ApplicationRepo + domainRepo DomainRepo + serviceRepo ApplicationServiceRep + tokenRepo TokenRepo } func NewApplication( txRunner ApplicationTxRunner, - applicationRep ApplicationApplicationRep, - domainRep ApplicationDomainRep, - serviceRep ApplicationServiceRep, - tokenRep ApplicationTokenRep, + applicationRepo ApplicationRepo, + domainRepo DomainRepo, + serviceRepo ApplicationServiceRep, + tokenRepo TokenRepo, ) Application { return Application{ - txRunner: txRunner, - applicationRep: applicationRep, - domainRep: domainRep, - serviceRep: serviceRep, - tokenRep: tokenRep, + txRunner: txRunner, + appRepo: applicationRepo, + domainRepo: domainRepo, + serviceRepo: serviceRepo, + tokenRepo: tokenRepo, } } func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) { - application, err := s.applicationRep.GetApplicationById(ctx, appId) + application, err := s.appRepo.GetApplicationById(ctx, appId) if err != nil { return nil, errors.WithMessage(err, "get application by id") } @@ -78,7 +61,7 @@ func (s Application) GetById(ctx context.Context, appId int) (*domain.Applicatio } func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) { - res, err := s.applicationRep.GetApplicationByIdList(ctx, idList) + res, err := s.appRepo.GetApplicationByIdList(ctx, idList) if err != nil { return nil, errors.WithMessage(err, "get application by id list") } @@ -87,7 +70,7 @@ func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.A } func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) { - arr, err := s.applicationRep.GetApplicationByServiceIdList(ctx, []int{id}) + arr, err := s.appRepo.GetApplicationByServiceIdList(ctx, []int{id}) if err != nil { return nil, errors.WithMessage(err, "get application by service_id") } @@ -96,7 +79,7 @@ func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.Appl } func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) { - domainEntityList, err := s.domainRep.GetDomainBySystemId(ctx, systemId) + domainEntityList, err := s.domainRepo.GetDomainBySystemId(ctx, systemId) if err != nil { return nil, errors.WithMessage(err, "get domains by system_id") } @@ -123,7 +106,7 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do result[i] = r } - serviceEntityList, err := s.serviceRep.GetServiceByDomainId(ctx, domainIdList) + serviceEntityList, err := s.serviceRepo.GetServiceByDomainId(ctx, domainIdList) if err != nil { return nil, errors.WithMessage(err, "get service by domain_id") } @@ -147,7 +130,7 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do resultServiceByServiceId[serviceEntity.Id] = resultService } - applicationEntityList, err := s.applicationRep.GetApplicationByServiceIdList(ctx, serviceIdList) + applicationEntityList, err := s.appRepo.GetApplicationByServiceIdList(ctx, serviceIdList) if err != nil { return nil, errors.WithMessagef(err, "get application by service_id") } @@ -171,14 +154,14 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do } func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { - existed, err := s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId) + existed, err := s.appRepo.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId) switch { case errors.Is(err, domain.ErrApplicationNotFound): case err != nil: return nil, errors.WithMessage(err, "get application by name and service_id") } - _, err = s.serviceRep.GetServiceById(ctx, req.ServiceId) + _, err = s.serviceRepo.GetServiceById(ctx, req.ServiceId) if err != nil { return nil, errors.WithMessage(err, "get service by id") } @@ -188,12 +171,12 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return nil, domain.ErrApplicationDuplicateName } - _, err = s.applicationRep.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId) + _, err = s.appRepo.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId) if err != nil { return nil, errors.WithMessage(err, "get application by name and service_id") } - app, err := s.applicationRep.CreateApplication(ctx, req.Name, req.Description, req.ServiceId, req.Type) + app, err := s.appRepo.CreateApplication(ctx, req.Name, req.Description, req.ServiceId, req.Type) if err != nil { return nil, errors.WithMessage(err, "create application") } @@ -210,12 +193,12 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return nil, domain.ErrApplicationDuplicateName } - _, err = s.applicationRep.GetApplicationById(ctx, req.Id) + _, err = s.appRepo.GetApplicationById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get application by id") } - app, err := s.applicationRep.UpdateApplication(ctx, req.Id, req.Name, req.Description) + app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update application") } @@ -264,7 +247,7 @@ func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Applica result[i] = awt } - tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, appIdList) + tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, appIdList) if err != nil { return nil, errors.WithMessage(err, "get token by app_id list") } diff --git a/service/domain.go b/service/domain.go index 4914ca4..a5a3305 100644 --- a/service/domain.go +++ b/service/domain.go @@ -8,22 +8,11 @@ import ( "isp-system-service/entity" ) -type DomainDomainRep interface { - GetDomainById(ctx context.Context, id int) (*entity.Domain, error) - GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) - GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) - CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) - UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) - DeleteDomain(ctx context.Context, idList []int) (int, error) -} - type Domain struct { - repo DomainDomainRep + repo DomainRepo } -func NewDomain( - repo DomainDomainRep, -) Domain { +func NewDomain(repo DomainRepo) Domain { return Domain{ repo: repo, } diff --git a/service/interfaces.go b/service/interfaces.go new file mode 100644 index 0000000..064ebf3 --- /dev/null +++ b/service/interfaces.go @@ -0,0 +1,38 @@ +package service + +import ( + "context" + "isp-system-service/entity" +) + +type TokenRepo interface { + GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) +} + +type DomainRepo interface { + GetDomainById(ctx context.Context, id int) (*entity.Domain, error) + GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) + GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) + CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) + UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) + DeleteDomain(ctx context.Context, idList []int) (int, error) +} + +type ApplicationRepo interface { + GetApplicationById(ctx context.Context, id int) (*entity.Application, error) + GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) + GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) + GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) + CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error) + UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) +} + +type ServiceRepo interface { + GetServiceById(ctx context.Context, id int) (*entity.Service, error) + GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) + GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) + GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) + CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) + UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) + DeleteService(ctx context.Context, idList []int) (int, error) +} diff --git a/service/service.go b/service/service.go index b504858..f370978 100644 --- a/service/service.go +++ b/service/service.go @@ -8,37 +8,23 @@ import ( "isp-system-service/entity" ) -type ServiceServiceRep interface { - GetServiceById(ctx context.Context, id int) (*entity.Service, error) - GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) - GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) - GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) - CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) - UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) - DeleteService(ctx context.Context, idList []int) (int, error) -} - -type ServiceDomainRep interface { // nolint:iface - GetDomainById(ctx context.Context, id int) (*entity.Domain, error) -} - type Service struct { - domainRep ServiceDomainRep - serviceRep ServiceServiceRep + domainRepo DomainRepo + serviceRepo ServiceRepo } func NewService( - domainRep ServiceDomainRep, - serviceRep ServiceServiceRep, + domainRepo DomainRepo, + serviceRepo ServiceRepo, ) Service { return Service{ - domainRep: domainRep, - serviceRep: serviceRep, + domainRepo: domainRepo, + serviceRepo: serviceRepo, } } func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) { - serviceEntity, err := s.serviceRep.GetServiceById(ctx, id) + serviceEntity, err := s.serviceRepo.GetServiceById(ctx, id) if err != nil { return nil, errors.WithMessagef(err, "get service by id") } @@ -48,7 +34,7 @@ func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) { } func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) { - serviceEntity, err := s.serviceRep.GetServiceByIdList(ctx, idList) + serviceEntity, err := s.serviceRepo.GetServiceByIdList(ctx, idList) if err != nil { return nil, errors.WithMessage(err, "get system by id list") } @@ -61,7 +47,7 @@ func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Servic } func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) { - serviceEntity, err := s.serviceRep.GetServiceByDomainId(ctx, []int{domainId}) + serviceEntity, err := s.serviceRepo.GetServiceByDomainId(ctx, []int{domainId}) if err != nil { return nil, errors.WithMessage(err, "get system by id list") } @@ -76,14 +62,14 @@ func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Serv func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { req.DomainId = 1 // temporary use only 1 domain, soon domain entity will be removed - existed, err := s.serviceRep.GetServiceByNameAndDomainId(ctx, req.Name, req.DomainId) + existed, err := s.serviceRepo.GetServiceByNameAndDomainId(ctx, req.Name, req.DomainId) switch { case errors.Is(err, domain.ErrServiceNotFound): case err != nil: return nil, errors.WithMessage(err, "get service by name and domain_id") } - _, err = s.domainRep.GetDomainById(ctx, req.DomainId) + _, err = s.domainRepo.GetDomainById(ctx, req.DomainId) if err != nil { return nil, errors.WithMessage(err, "get domain by id") } @@ -93,7 +79,7 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat return nil, domain.ErrDomainDuplicateName } - serviceEntity, err := s.serviceRep.CreateService(ctx, req.Name, req.Description, req.DomainId) + serviceEntity, err := s.serviceRepo.CreateService(ctx, req.Name, req.Description, req.DomainId) if err != nil { return nil, errors.WithMessage(err, "create service") } @@ -106,12 +92,12 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat return nil, domain.ErrDomainDuplicateName } - _, err = s.serviceRep.GetServiceById(ctx, req.Id) + _, err = s.serviceRepo.GetServiceById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get service by id") } - serviceEntity, err := s.serviceRep.UpdateService(ctx, req.Id, req.Name, req.Description) + serviceEntity, err := s.serviceRepo.UpdateService(ctx, req.Id, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update service") } @@ -121,7 +107,7 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat } func (s Service) Delete(ctx context.Context, idList []int) (int, error) { - result, err := s.serviceRep.DeleteService(ctx, idList) + result, err := s.serviceRepo.DeleteService(ctx, idList) if err != nil { return 0, errors.WithMessage(err, "delete service") } diff --git a/service/token.go b/service/token.go index 70674fe..b975794 100644 --- a/service/token.go +++ b/service/token.go @@ -3,35 +3,20 @@ package service import ( "context" - "github.com/pkg/errors" "isp-system-service/domain" "isp-system-service/entity" + + "github.com/pkg/errors" ) type ApplicationTokenCreator interface { CreateApplicationToken() (string, error) } -type TokenAppEnrich interface { +type TokenAppEnricher interface { EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error) } -type TokenApplicationRep interface { // nolint:iface - GetApplicationById(ctx context.Context, id int) (*entity.Application, error) -} - -type TokenServiceRep interface { - GetServiceById(ctx context.Context, id int) (*entity.Service, error) -} - -type TokenDomainRep interface { // nolint:iface - GetDomainById(ctx context.Context, id int) (*entity.Domain, error) -} - -type TokenTokenRep interface { // nolint:iface - GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) -} - type TokenCreateTx interface { SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) } @@ -46,37 +31,37 @@ type TokenTxRunner interface { } type Token struct { - jwt ApplicationTokenCreator - appEnrich TokenAppEnrich - tx TokenTxRunner - appRep TokenApplicationRep - domainRep TokenDomainRep - serviceRep TokenServiceRep - tokenRep TokenTokenRep + jwt ApplicationTokenCreator + appEnrich TokenAppEnricher + tx TokenTxRunner + appRepo ApplicationRepo + domainRepo DomainRepo + serviceRepo ServiceRepo + tokenRepo TokenRepo } func NewToken( jwtGenerate ApplicationTokenCreator, - appEnrich TokenAppEnrich, + appEnrich TokenAppEnricher, tx TokenTxRunner, - appRep TokenApplicationRep, - domainRep TokenDomainRep, - serviceRep TokenServiceRep, - tokenRep TokenTokenRep, + appRepo ApplicationRepo, + domainRepo DomainRepo, + serviceRepo ServiceRepo, + tokenRepo TokenRepo, ) Token { return Token{ - appEnrich: appEnrich, - jwt: jwtGenerate, - tx: tx, - appRep: appRep, - domainRep: domainRep, - serviceRep: serviceRep, - tokenRep: tokenRep, + appEnrich: appEnrich, + jwt: jwtGenerate, + tx: tx, + appRepo: appRepo, + domainRepo: domainRepo, + serviceRepo: serviceRepo, + tokenRepo: tokenRepo, } } func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) { - tokenEntity, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId}) + tokenEntity, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId}) if err != nil { return nil, errors.WithMessage(err, "get token by app_id list") } @@ -90,17 +75,17 @@ func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error } func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) { - applicationEntity, err := s.appRep.GetApplicationById(ctx, req.AppId) + applicationEntity, err := s.appRepo.GetApplicationById(ctx, req.AppId) if err != nil { return nil, errors.WithMessagef(err, "get application by id") } - serviceEntity, err := s.serviceRep.GetServiceById(ctx, applicationEntity.ServiceId) + serviceEntity, err := s.serviceRepo.GetServiceById(ctx, applicationEntity.ServiceId) if err != nil { return nil, errors.WithMessagef(err, "get service by id") } - _, err = s.domainRep.GetDomainById(ctx, serviceEntity.DomainId) + _, err = s.domainRepo.GetDomainById(ctx, serviceEntity.DomainId) if err != nil { return nil, errors.WithMessagef(err, "get domain by id") } @@ -131,7 +116,7 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma } func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) { - app, err := s.appRep.GetApplicationById(ctx, req.AppId) + app, err := s.appRepo.GetApplicationById(ctx, req.AppId) if err != nil { return nil, errors.WithMessagef(err, "get application by id") } @@ -150,7 +135,7 @@ func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*doma } func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) { - tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId}) + tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId}) if err != nil { return nil, errors.WithMessage(err, "get token by app_id list") } diff --git a/service/token_source.go b/service/token_source.go index 03fe570..938b52e 100644 --- a/service/token_source.go +++ b/service/token_source.go @@ -7,8 +7,7 @@ import ( "github.com/pkg/errors" ) -type TokenSource struct { -} +type TokenSource struct{} func NewTokenSource() TokenSource { return TokenSource{} diff --git a/transaction/manager.go b/transaction/manager.go index 628608f..0f6cd0f 100644 --- a/transaction/manager.go +++ b/transaction/manager.go @@ -37,7 +37,7 @@ type accessListSetListTx struct { repository.AccessList } -func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetListTx) error) error { +func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.AccessListSetListTx) error) error { return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error { accessListRep := repository.NewAccessList(tx) return msgTx(ctx, accessListSetListTx{ @@ -63,7 +63,7 @@ type tokenCreateTx struct { repository.Token } -func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenCreateTx) error) error { +func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.TokenCreateTx) error) error { return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error { tokenRep := repository.NewToken(tx) return msgTx(ctx, tokenCreateTx{ @@ -76,7 +76,7 @@ type tokenRevokeTx struct { repository.Token } -func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenRevokeTx) error) error { +func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.TokenRevokeTx) error) error { return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error { tokenRep := repository.NewToken(tx) return msgTx(ctx, tokenRevokeTx{ From 264ea2d3ae006c35297902f3b4f0b6ba4cefb270 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 17:11:43 +0300 Subject: [PATCH 04/30] MSP-5186 Replace errors.WithMessagef --- service/access_list.go | 6 +++--- service/application.go | 2 +- service/domain.go | 2 +- service/service.go | 2 +- service/token.go | 20 ++++++++++---------- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/service/access_list.go b/service/access_list.go index 8fd7bfd..adf9692 100644 --- a/service/access_list.go +++ b/service/access_list.go @@ -55,7 +55,7 @@ func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, appId) if err != nil { - return nil, errors.WithMessagef(err, "get access list by app_id") + return nil, errors.WithMessage(err, "get access list by app_id") } methodInfos := make([]domain.MethodInfo, len(accessList)) @@ -83,7 +83,7 @@ func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneR Value: request.Value, }) if err != nil { - return errors.WithMessagef(err, "upsert access list") + return errors.WithMessage(err, "upsert access list") } return nil @@ -142,7 +142,7 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, req.AppId) if err != nil { - return nil, errors.WithMessagef(err, "get access list by app_id") + return nil, errors.WithMessage(err, "get access list by app_id") } methodInfos := make([]domain.MethodInfo, len(accessList)) diff --git a/service/application.go b/service/application.go index 9a56032..aff2c45 100644 --- a/service/application.go +++ b/service/application.go @@ -132,7 +132,7 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do applicationEntityList, err := s.appRepo.GetApplicationByServiceIdList(ctx, serviceIdList) if err != nil { - return nil, errors.WithMessagef(err, "get application by service_id") + return nil, errors.WithMessage(err, "get application by service_id") } for _, applicationEntity := range applicationEntityList { diff --git a/service/domain.go b/service/domain.go index a5a3305..ca58c24 100644 --- a/service/domain.go +++ b/service/domain.go @@ -56,7 +56,7 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR domainEntity, err := s.repo.CreateDomain(ctx, req.Name, req.Description, systemId) if err != nil { - return nil, errors.WithMessagef(err, "create domain") + return nil, errors.WithMessage(err, "create domain") } result := s.convertDomain(*domainEntity) diff --git a/service/service.go b/service/service.go index f370978..06fd18c 100644 --- a/service/service.go +++ b/service/service.go @@ -26,7 +26,7 @@ func NewService( func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) { serviceEntity, err := s.serviceRepo.GetServiceById(ctx, id) if err != nil { - return nil, errors.WithMessagef(err, "get service by id") + return nil, errors.WithMessage(err, "get service by id") } result := s.convertService(*serviceEntity) diff --git a/service/token.go b/service/token.go index b975794..b43db48 100644 --- a/service/token.go +++ b/service/token.go @@ -77,28 +77,28 @@ func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) { applicationEntity, err := s.appRepo.GetApplicationById(ctx, req.AppId) if err != nil { - return nil, errors.WithMessagef(err, "get application by id") + return nil, errors.WithMessage(err, "get application by id") } serviceEntity, err := s.serviceRepo.GetServiceById(ctx, applicationEntity.ServiceId) if err != nil { - return nil, errors.WithMessagef(err, "get service by id") + return nil, errors.WithMessage(err, "get service by id") } _, err = s.domainRepo.GetDomainById(ctx, serviceEntity.DomainId) if err != nil { - return nil, errors.WithMessagef(err, "get domain by id") + return nil, errors.WithMessage(err, "get domain by id") } token, err := s.jwt.CreateApplicationToken() if err != nil { - return nil, errors.WithMessagef(err, "create application token") + return nil, errors.WithMessage(err, "create application token") } err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx TokenCreateTx) error { _, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs) if err != nil { - return errors.WithMessagef(err, "tx save token") + return errors.WithMessage(err, "tx save token") } return nil @@ -109,7 +109,7 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma arr, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*applicationEntity}) if err != nil { - return nil, errors.WithMessagef(err, "application enrich with tokens") + return nil, errors.WithMessage(err, "application enrich with tokens") } return arr[0], nil @@ -118,17 +118,17 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) { app, err := s.appRepo.GetApplicationById(ctx, req.AppId) if err != nil { - return nil, errors.WithMessagef(err, "get application by id") + return nil, errors.WithMessage(err, "get application by id") } _, err = s.revokeTokens(ctx, req.Tokens) if err != nil { - return nil, errors.WithMessagef(err, "reboke tokens") + return nil, errors.WithMessage(err, "reboke tokens") } res, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*app}) if err != nil { - return nil, errors.WithMessagef(err, "application enrich") + return nil, errors.WithMessage(err, "application enrich") } return res[0], nil @@ -157,7 +157,7 @@ func (s Token) revokeTokens(ctx context.Context, tokens []string) (*domain.Delet err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx TokenRevokeTx) error { deleted, err := tx.DeleteToken(ctx, tokens) if err != nil { - return errors.WithMessagef(err, "tx delete token") + return errors.WithMessage(err, "tx delete token") } count = deleted From 94b435262ca05cedbf2d0b6962dd7f9b61355c76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 17:20:14 +0300 Subject: [PATCH 05/30] MSP-5186 appEnrich -> appEnricher --- service/token.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/service/token.go b/service/token.go index b43db48..29d78e3 100644 --- a/service/token.go +++ b/service/token.go @@ -13,7 +13,7 @@ type ApplicationTokenCreator interface { CreateApplicationToken() (string, error) } -type TokenAppEnricher interface { +type AppEnricher interface { EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error) } @@ -32,7 +32,7 @@ type TokenTxRunner interface { type Token struct { jwt ApplicationTokenCreator - appEnrich TokenAppEnricher + appEnricher AppEnricher tx TokenTxRunner appRepo ApplicationRepo domainRepo DomainRepo @@ -42,7 +42,7 @@ type Token struct { func NewToken( jwtGenerate ApplicationTokenCreator, - appEnrich TokenAppEnricher, + appEnricher AppEnricher, tx TokenTxRunner, appRepo ApplicationRepo, domainRepo DomainRepo, @@ -50,7 +50,7 @@ func NewToken( tokenRepo TokenRepo, ) Token { return Token{ - appEnrich: appEnrich, + appEnricher: appEnricher, jwt: jwtGenerate, tx: tx, appRepo: appRepo, @@ -107,7 +107,7 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma return nil, errors.WithMessage(err, "token create transaction") } - arr, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*applicationEntity}) + arr, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*applicationEntity}) if err != nil { return nil, errors.WithMessage(err, "application enrich with tokens") } @@ -126,7 +126,7 @@ func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*doma return nil, errors.WithMessage(err, "reboke tokens") } - res, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*app}) + res, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*app}) if err != nil { return nil, errors.WithMessage(err, "application enrich") } From 6a93a316fa4c6185e1e830ce7e917976ba9e1036 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 17:20:43 +0300 Subject: [PATCH 06/30] MSP-5186 Fix typo --- service/token.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/service/token.go b/service/token.go index 29d78e3..3354d15 100644 --- a/service/token.go +++ b/service/token.go @@ -123,7 +123,7 @@ func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*doma _, err = s.revokeTokens(ctx, req.Tokens) if err != nil { - return nil, errors.WithMessage(err, "reboke tokens") + return nil, errors.WithMessage(err, "revoke tokens") } res, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*app}) From 6a66ffa70e0ab0eb9add757c5d46db508a4c0d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 17:23:41 +0300 Subject: [PATCH 07/30] MSP-5186 Up deps --- assembly/locator.go | 12 +++--- go.mod | 44 +++++++++++----------- go.sum | 92 ++++++++++++++++++++++----------------------- 3 files changed, 75 insertions(+), 73 deletions(-) diff --git a/assembly/locator.go b/assembly/locator.go index a124f12..43b58ff 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -1,10 +1,6 @@ package assembly import ( - "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" @@ -13,6 +9,12 @@ import ( "isp-system-service/service/baseline" "isp-system-service/service/secure" "isp-system-service/transaction" + + "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/grpc/endpoint/grpclog" + "github.com/txix-open/isp-kit/log" ) type DB interface { @@ -71,7 +73,7 @@ func (l Locator) Config(cfg conf.Remote) Config { Application: applicationController, Token: tokenController, } - mapper := endpoint.DefaultWrapper(l.logger, endpoint.Log(l.logger, true)) + mapper := endpoint.DefaultWrapper(l.logger, grpclog.Log(l.logger, true)) server := routes.Handler(mapper, c) baselineService := baseline.NewService(cfg.Baseline, txManager, l.logger) diff --git a/go.mod b/go.mod index a4789c1..941ba7a 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,14 @@ module isp-system-service -go 1.23 +go 1.24 require ( github.com/Masterminds/squirrel v1.5.4 github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.10.0 - github.com/txix-open/isp-kit v1.42.1 + github.com/txix-open/isp-kit v1.45.0 github.com/txix-open/jsonschema v1.2.0 - google.golang.org/grpc v1.69.4 + google.golang.org/grpc v1.71.0 ) require ( @@ -21,13 +21,13 @@ require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect github.com/getsentry/sentry-go v0.31.1 // indirect - github.com/go-faker/faker/v4 v4.5.0 // indirect + github.com/go-faker/faker/v4 v4.6.0 // 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.25.1 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // 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 @@ -35,7 +35,7 @@ require ( github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jmoiron/sqlx v1.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.17.11 // indirect + github.com/klauspost/compress v1.18.0 // 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.4.0 // indirect @@ -47,9 +47,9 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pressly/goose/v3 v3.24.1 // indirect - github.com/prometheus/client_golang v1.20.5 // indirect + github.com/prometheus/client_golang v1.21.1 // indirect github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.60.1 // indirect + github.com/prometheus/common v0.62.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 @@ -60,23 +60,23 @@ require ( github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect go.opentelemetry.io/auto/sdk v1.1.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/otel v1.35.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 // indirect + go.opentelemetry.io/otel/metric v1.35.0 // indirect + go.opentelemetry.io/otel/sdk v1.35.0 // indirect + go.opentelemetry.io/otel/trace v1.35.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.32.0 // indirect - golang.org/x/net v0.34.0 // indirect - golang.org/x/sync v0.10.0 // indirect - golang.org/x/sys v0.29.0 // indirect - golang.org/x/text v0.21.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250106144421-5f5ef82da422 // indirect - google.golang.org/protobuf v1.36.2 // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/sync v0.12.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250311190419-81fb87f6b8bf // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250311190419-81fb87f6b8bf // 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/go.sum b/go.sum index 22f34e2..924b02b 100644 --- a/go.sum +++ b/go.sum @@ -27,8 +27,8 @@ github.com/getsentry/sentry-go v0.31.1 h1:ELVc0h7gwyhnXHDouXkhqTFSO5oslsRDk0++ey github.com/getsentry/sentry-go v0.31.1/go.mod h1:CYNcMMz73YigoHljQRG+qPF+eMq8gG72XcGN/p71BAY= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-faker/faker/v4 v4.5.0 h1:ARzAY2XoOL9tOUK+KSecUQzyXQsUaZHefjyF8x6YFHc= -github.com/go-faker/faker/v4 v4.5.0/go.mod h1:p3oq1GRjG2PZ7yqeFFfQI20Xm61DoBDlCA8RiSyZ48M= +github.com/go-faker/faker/v4 v4.6.0 h1:6aOPzNptRiDwD14HuAnEtlTa+D1IfFuEHO8+vEFwjTs= +github.com/go-faker/faker/v4 v4.6.0/go.mod h1:ZmrHuVtTTm2Em9e0Du6CJ9CADaLEzGXW62z1YqFH0m0= 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= @@ -44,13 +44,13 @@ github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpv 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/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 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.25.1 h1:VNqngBF40hVlDloBruUehVYC3ArSgIyScOAyMRqBxRg= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.25.1/go.mod h1:RBRO7fro65R6tjKzYgLAFo0t1QEXY1Dp+i/bvpRiqiQ= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI= 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= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= @@ -67,8 +67,8 @@ github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= -github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -110,12 +110,12 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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_golang v1.21.1 h1:DOvXXTqVzvkIewV/CDPFdejpMCGeMcbGCQ8YOmu+Ibk= +github.com/prometheus/client_golang v1.21.1/go.mod h1:U9NM32ykUErtVBxdvD3zfi+EuFkkaBvMb09mIfe0Zgg= github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.60.1 h1:FUas6GcOw66yB/73KC+BOZoFJmbo/1pojoILArPAaSc= -github.com/prometheus/common v0.60.1/go.mod h1:h0LYf1R1deLSKtD4Vdg8gy4RuOvENW2J/h19V5NADQw= +github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= +github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= @@ -145,8 +145,8 @@ github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIg github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8= github.com/txix-open/grmq v1.7.0 h1:nwenrlxEjXpK0EBCa/WbIxK+y0mF2pZxNKbheFjQVsI= github.com/txix-open/grmq v1.7.0/go.mod h1:DAfbV4jLyxQBLG8OYJVy8kCbhucdlu/C/wl+nUDc9p8= -github.com/txix-open/isp-kit v1.42.1 h1:1YB0AqO3Mu0mUrghmtpsBdFJV20rsoxq68nqBWLyYQU= -github.com/txix-open/isp-kit v1.42.1/go.mod h1:BHRF3AYRcQtEtNvoQZXxTVj/CYOVMKhOcCD3n8CdsxE= +github.com/txix-open/isp-kit v1.45.0 h1:GPrr4F5SLQsrXgUTCqHL7C90vygjmNPOimUCAuXr2dw= +github.com/txix-open/isp-kit v1.45.0/go.mod h1:efg4qDdAuw9Doi1OoT+OYSbr34B3j9u2ubz9R5BXYto= github.com/txix-open/jsonschema v1.2.0 h1:B8TrdSsPhDvYv67oi/LVqf7/+PuqFlMsNwUzGeHfl1s= github.com/txix-open/jsonschema v1.2.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To= @@ -162,20 +162,20 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17 github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= 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/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.31.0 h1:i9hxxLJF/9kkvfHppyLL55aW7iIJz4JjxTeYusH7zMc= -go.opentelemetry.io/otel/sdk/metric v1.31.0/go.mod h1:CRInTMVvNhUKgSAMbKyTMxqOBC0zgyxzW55lZzX43Y8= -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/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ= +go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0 h1:1fTNlAIJZGWLP5FVu0fikVry1IsiUnXjf7QFvoNN3Xw= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.35.0/go.mod h1:zjPK58DtkqQFn+YUMbx0M2XV3QgKU0gS9LeGohREyK4= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0 h1:xJ2qHD0C1BeYVTLLR9sX12+Qb95kfeD/byKj6Ky1pXg= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.35.0/go.mod h1:u5BF1xyjstDowA1R5QAO9JHzqK+ublenEW/dyqTjBVk= +go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M= +go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE= +go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY= +go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg= +go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= +go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= +go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs= +go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc= 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= @@ -184,24 +184,24 @@ 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.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= -golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= -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/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= -golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422 h1:GVIKPyP/kLIyVOgOnTwFOrvQaQUzOzGMCxgFUOEmm24= -google.golang.org/genproto/googleapis/api v0.0.0-20250106144421-5f5ef82da422/go.mod h1:b6h1vNKhxaSoEI+5jc3PJUCustfli/mRab7295pY7rw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250106144421-5f5ef82da422 h1:3UsHvIr4Wc2aW4brOaSCmcxh9ksica6fHEr8P1XhkYw= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250106144421-5f5ef82da422/go.mod h1:3ENsm/5D1mzDyhpzeRi1NR784I0BcofWBoSc5QqqMK4= -google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A= -google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= -google.golang.org/protobuf v1.36.2 h1:R8FeyR1/eLmkutZOM5CWghmo5itiG9z0ktFlTVLuTmU= -google.golang.org/protobuf v1.36.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= +golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +google.golang.org/genproto/googleapis/api v0.0.0-20250311190419-81fb87f6b8bf h1:BdIVRm+fyDUn8lrZLPSlBCfM/YKDwUBYgDoLv9+DYo0= +google.golang.org/genproto/googleapis/api v0.0.0-20250311190419-81fb87f6b8bf/go.mod h1:jbe3Bkdp+Dh2IrslsFCklNhweNTBgSYanP1UXhJDhKg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250311190419-81fb87f6b8bf h1:dHDlF3CWxQkefK9IJx+O8ldY0gLygvrlYRBNbPqDWuY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250311190419-81fb87f6b8bf/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= +google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= +google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +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= From d012a022d855f2a9f3c41b16d9f3c4b07809d80e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 17:52:44 +0300 Subject: [PATCH 08/30] MSP-5186 Add change app id type migration --- ...50401144357_change_application_pk_type.sql | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 migrations/20250401144357_change_application_pk_type.sql diff --git a/migrations/20250401144357_change_application_pk_type.sql b/migrations/20250401144357_change_application_pk_type.sql new file mode 100644 index 0000000..3c64b07 --- /dev/null +++ b/migrations/20250401144357_change_application_pk_type.sql @@ -0,0 +1,22 @@ +-- +goose Up +ALTER TABLE application +ALTER COLUMN id +DROP DEFAULT; + +DROP SEQUENCE application_id_seq; + +-- +goose Down +CREATE SEQUENCE application_id_seq; + +SELECT setval( + 'application_id_seq', COALESCE( + ( + SELECT MAX(id) + FROM isp_system_service.application + ), 1 + ) + ); + +ALTER TABLE application +ALTER COLUMN id +SET DEFAULT nextval('application_id_seq'); \ No newline at end of file From 42b0dbd0dc08880c3d46a04b6ffa1f41ad4f853c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 18:25:51 +0300 Subject: [PATCH 09/30] MSP-5186 Rename Service to AppGroup (without update controller and service names and endpoints) --- assembly/locator.go | 8 +-- controller/application.go | 5 +- controller/service.go | 9 +-- controller/token.go | 5 +- domain/error.go | 5 +- entity/application.go | 14 ++-- entity/service.go | 2 +- entity/token.go | 12 ++-- .../20250401144357_application_service.sql | 42 +++++++++++ ...50401144357_change_application_pk_type.sql | 22 ------ repository/application.go | 71 ++++++++++++------- repository/service.go | 57 +++++++-------- repository/token.go | 8 +-- service/application.go | 36 +++++----- service/baseline/service.go | 15 ++-- service/interfaces.go | 23 +++--- service/secure/service.go | 5 +- service/service.go | 27 +++---- service/token.go | 8 +-- tests/general_insert_db_test.go | 11 +-- tests/secure_test.go | 18 ++--- transaction/manager.go | 4 +- 22 files changed, 230 insertions(+), 177 deletions(-) create mode 100644 migrations/20250401144357_application_service.sql delete mode 100644 migrations/20250401144357_change_application_pk_type.sql diff --git a/assembly/locator.go b/assembly/locator.go index 43b58ff..88779ec 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -44,18 +44,18 @@ func (l Locator) Config(cfg conf.Remote) Config { accessListRep := repository.NewAccessList(l.db) applicationRep := repository.NewApplication(l.db) domainRep := repository.NewDomain(l.db) - serviceRep := repository.NewService(l.db) + appGroupRep := repository.NewAppGroup(l.db) tokenRep := repository.NewToken(l.db) secureService := secure.NewService(tokenRep, accessListRep) accessListService := service.NewAccessList(txManager, accessListRep, applicationRep) - applicationService := service.NewApplication(txManager, applicationRep, domainRep, serviceRep, tokenRep) + applicationService := service.NewApplication(txManager, applicationRep, domainRep, appGroupRep, tokenRep) domainService := service.NewDomain(domainRep) - serviceService := service.NewService(domainRep, serviceRep) + serviceService := service.NewService(domainRep, appGroupRep) jwtService := service.NewTokenSource() tokenService := service.NewToken(jwtService, applicationService, txManager, - applicationRep, domainRep, serviceRep, tokenRep, + applicationRep, domainRep, appGroupRep, tokenRep, ) secureController := controller.NewSecure(secureService) diff --git a/controller/application.go b/controller/application.go index 6eb3004..b3f28a3 100644 --- a/controller/application.go +++ b/controller/application.go @@ -3,10 +3,11 @@ package controller import ( "context" + "isp-system-service/domain" + "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "isp-system-service/domain" ) type ApplicationService interface { @@ -109,7 +110,7 @@ func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithSer func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.CreateUpdate(ctx, req) switch { - case errors.Is(err, domain.ErrServiceNotFound): + case errors.Is(err, domain.ErrAppGroupNotFound): return nil, status.Errorf(codes.InvalidArgument, "service with id %d not found", req.ServiceId) case errors.Is(err, domain.ErrApplicationDuplicateName): return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) diff --git a/controller/service.go b/controller/service.go index f60a6fd..973cf62 100644 --- a/controller/service.go +++ b/controller/service.go @@ -3,10 +3,11 @@ package controller import ( "context" + "isp-system-service/domain" + "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "isp-system-service/domain" ) type ServiceService interface { @@ -41,7 +42,7 @@ func NewService(service ServiceService) Service { func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) { result, err := c.service.GetById(ctx, req.Id) switch { - case errors.Is(err, domain.ErrServiceNotFound): + case errors.Is(err, domain.ErrAppGroupNotFound): return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id) case err != nil: return nil, err @@ -96,9 +97,9 @@ func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat switch { case errors.Is(err, domain.ErrDomainNotFound): return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId) - case errors.Is(err, domain.ErrServiceNotFound): + case errors.Is(err, domain.ErrAppGroupNotFound): return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id) - case errors.Is(err, domain.ErrServiceDuplicateName): + case errors.Is(err, domain.ErrAppGroupDuplicateName): return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name) case err != nil: return nil, err diff --git a/controller/token.go b/controller/token.go index 16155ea..e78eca7 100644 --- a/controller/token.go +++ b/controller/token.go @@ -3,10 +3,11 @@ package controller import ( "context" + "isp-system-service/domain" + "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - "isp-system-service/domain" ) type TokenService interface { @@ -55,7 +56,7 @@ func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma switch { case errors.Is(err, domain.ErrApplicationNotFound): return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId) - case errors.Is(err, domain.ErrServiceNotFound): + case errors.Is(err, domain.ErrAppGroupNotFound): return nil, status.Errorf(codes.NotFound, "service for app_id id %d not found", req.AppId) case errors.Is(err, domain.ErrDomainNotFound): return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId) diff --git a/domain/error.go b/domain/error.go index ad9a284..eb64a99 100644 --- a/domain/error.go +++ b/domain/error.go @@ -8,13 +8,14 @@ var ( ErrDomainNotFound = errors.New("domain not found") ErrDomainDuplicateName = errors.New("domain name already exist") - ErrServiceNotFound = errors.New("service not found") - ErrServiceDuplicateName = errors.New("service name already exist") + ErrAppGroupNotFound = errors.New("application group not found") + ErrAppGroupDuplicateName = errors.New("application group name already exist") ErrSystemNotFound = errors.New("system not found") ErrApplicationNotFound = errors.New("application not found") ErrApplicationDuplicateName = errors.New("application name already exist") + ErrApplicationDuplicateId = errors.New("application id already exist") ErrTokenNotFound = errors.New("token not found") ErrTokenExpired = errors.New("token is expired") diff --git a/entity/application.go b/entity/application.go index 4d38c74..1fcf51d 100644 --- a/entity/application.go +++ b/entity/application.go @@ -5,11 +5,11 @@ import ( ) type Application struct { - Id int - Name string - Description *string - ServiceId int - Type string - CreatedAt time.Time - UpdatedAt time.Time + Id int + Name string + Description *string + ApplicationGroupId int + Type string + CreatedAt time.Time + UpdatedAt time.Time } diff --git a/entity/service.go b/entity/service.go index 9a791d9..82e7d92 100644 --- a/entity/service.go +++ b/entity/service.go @@ -4,7 +4,7 @@ import ( "time" ) -type Service struct { +type AppGroup struct { Id int Name string Description *string diff --git a/entity/token.go b/entity/token.go index c4277f1..5074262 100644 --- a/entity/token.go +++ b/entity/token.go @@ -12,10 +12,10 @@ type Token struct { } type AuthData struct { - SystemId int - DomainId int - ServiceId int - AppId int - ExpireTime int - CreatedAt time.Time + SystemId int + DomainId int + ApplicationGroupId int + AppId int + ExpireTime int + CreatedAt time.Time } diff --git a/migrations/20250401144357_application_service.sql b/migrations/20250401144357_application_service.sql new file mode 100644 index 0000000..bc64391 --- /dev/null +++ b/migrations/20250401144357_application_service.sql @@ -0,0 +1,42 @@ +-- +goose Up +ALTER TABLE application ALTER COLUMN id DROP DEFAULT; + +DROP SEQUENCE application_id_seq; + +ALTER TABLE service RENAME TO application_group; + +ALTER TABLE application +RENAME COLUMN service_id TO application_group_id; + +ALTER INDEX uq_name_service_id +RENAME TO uq_name_application_group_id; + +ALTER TABLE application +RENAME CONSTRAINT "fk_service_id__domain_id" TO "fk_application_group_id"; + +-- +goose Down +ALTER TABLE application +RENAME CONSTRAINT "fk_application_group_id" TO "fk_service_id__domain_id"; + +ALTER INDEX uq_name_application_group_id +RENAME TO uq_name_service_id; + +ALTER TABLE application +RENAME COLUMN application_group_id TO service_id; + +ALTER TABLE application_group RENAME TO service; + +CREATE SEQUENCE application_id_seq; + +SELECT setval( + 'application_id_seq', COALESCE( + ( + SELECT MAX(id) + FROM isp_system_service.application + ), 1 + ) + ); + +ALTER TABLE application +ALTER COLUMN id +SET DEFAULT nextval('application_id_seq'); \ No newline at end of file diff --git a/migrations/20250401144357_change_application_pk_type.sql b/migrations/20250401144357_change_application_pk_type.sql deleted file mode 100644 index 3c64b07..0000000 --- a/migrations/20250401144357_change_application_pk_type.sql +++ /dev/null @@ -1,22 +0,0 @@ --- +goose Up -ALTER TABLE application -ALTER COLUMN id -DROP DEFAULT; - -DROP SEQUENCE application_id_seq; - --- +goose Down -CREATE SEQUENCE application_id_seq; - -SELECT setval( - 'application_id_seq', COALESCE( - ( - SELECT MAX(id) - FROM isp_system_service.application - ), 1 - ) - ); - -ALTER TABLE application -ALTER COLUMN id -SET DEFAULT nextval('application_id_seq'); \ No newline at end of file diff --git a/repository/application.go b/repository/application.go index 5d42bbe..3812c14 100644 --- a/repository/application.go +++ b/repository/application.go @@ -24,7 +24,7 @@ func NewApplication(db db.DB) Application { func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) { q := ` - SELECT id, name, description, service_id, type, created_at, updated_at + SELECT id, name, description, application_group_id, type, created_at, updated_at FROM application WHERE id = $1 ` @@ -34,7 +34,7 @@ func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Ap if errors.Is(err, sql.ErrNoRows) { return nil, domain.ErrApplicationNotFound } - return nil, errors.WithMessage(err, "select row db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return &result, nil @@ -42,7 +42,7 @@ func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Ap func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) { q, args, err := query.New(). - Select("id", "name", "description", "service_id", "type", "created_at", "updated_at"). + Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at"). From("application"). Where(squirrel.Eq{"id": idList}). OrderBy("created_at DESC"). @@ -54,37 +54,37 @@ func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ( result := make([]entity.Application, 0) err = r.db.Select(ctx, &result, q, args...) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil } -func (r Application) GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) { +func (r Application) GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) { q, args, err := query.New(). - Select("id", "name", "description", "service_id", "type", "created_at", "updated_at"). + Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at"). From("application"). - Where(squirrel.Eq{"service_id": serviceIdList}). + Where(squirrel.Eq{"application_group_id": appGroupIdList}). OrderBy("created_at DESC"). ToSql() if err != nil { - return nil, errors.WithMessage(err, "build query") + return nil, errors.WithMessagef(err, "exec query %s", q) } result := make([]entity.Application, 0) err = r.db.Select(ctx, &result, q, args...) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil } -func (r Application) GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) { +func (r Application) GetApplicationByNameAndAppGroupId(ctx context.Context, name string, serviceId int) (*entity.Application, error) { q := ` - SELECT id, name, description, service_id, type, created_at, updated_at + SELECT id, name, description, application_group_id, type, created_at, updated_at FROM application - WHERE name = $1 AND service_id = $2 + WHERE name = $1 AND application_group_id = $2 ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, name, serviceId) @@ -92,41 +92,50 @@ func (r Application) GetApplicationByNameAndServiceId(ctx context.Context, name if errors.Is(err, sql.ErrNoRows) { return nil, nil //nolint:nilnil } - return nil, errors.WithMessagef(err, "select row db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return &result, nil } -func (r Application) CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) ( +func (r Application) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) ( *entity.Application, error) { q := ` INSERT INTO application - (name, description, service_id, type) - VALUES ($1, $2, $3, $4) - RETURNING id, name, description, service_id, type, created_at, updated_at + (id, name, description, application_group_id, type) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (id) DO NOTHING + RETURNING id, name, description, application_group_id, type, created_at, updated_at ` result := entity.Application{} - err := r.db.SelectRow(ctx, &result, q, name, desc, serviceId, appType) - if err != nil { - return nil, errors.WithMessagef(err, "select row db") + err := r.db.SelectRow(ctx, &result, q, id, name, desc, appGroupId, appType) + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrApplicationDuplicateId + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } -func (r Application) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) { +func (r Application) UpdateApplication( + ctx context.Context, + appGroupId int, + name string, + description string, +) (*entity.Application, error) { q := ` UPDATE application SET name = $2, description = $3 WHERE id = $1 - RETURNING id, name, description, service_id, type, created_at, updated_at + RETURNING id, name, description, application_group_id, type, created_at, updated_at ` result := entity.Application{} - err := r.db.SelectRow(ctx, &result, q, id, name, description) + err := r.db.SelectRow(ctx, &result, q, appGroupId, name, description) if err != nil { - return nil, errors.WithMessagef(err, "select row db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return &result, nil @@ -153,3 +162,13 @@ func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int return int(rowsAffected), nil } + +func (r Application) NextApplicationId(ctx context.Context) (int, error) { + q := `SELECT COALESCE(MAX(id)+1, 1) FROM application;` + nextAppId := 0 + err := r.db.SelectRow(ctx, &nextAppId, q) + if err != nil { + return -1, errors.WithMessagef(err, "exec query %s", q) + } + return nextAppId, nil +} diff --git a/repository/service.go b/repository/service.go index 150db01..bf28b8b 100644 --- a/repository/service.go +++ b/repository/service.go @@ -4,35 +4,36 @@ import ( "context" "database/sql" + "isp-system-service/domain" + "isp-system-service/entity" + "github.com/Masterminds/squirrel" "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" ) -type Service struct { +type AppGroup struct { db db.DB } -func NewService(db db.DB) Service { - return Service{ +func NewAppGroup(db db.DB) AppGroup { + return AppGroup{ db: db, } } -func (r Service) GetServiceById(ctx context.Context, id int) (*entity.Service, error) { +func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) { q := ` SELECT id, name, description, domain_id, created_at, updated_at - FROM service + FROM application_group WHERE id = $1 ` - result := entity.Service{} + result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, id) if err != nil { if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrServiceNotFound + return nil, domain.ErrAppGroupNotFound } return nil, errors.WithMessage(err, "select row db") } @@ -40,10 +41,10 @@ func (r Service) GetServiceById(ctx context.Context, id int) (*entity.Service, e return &result, nil } -func (r Service) GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) { +func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) { q, arg, err := query.New(). Select("id", "name", "description", "domain_id", "created_at", "updated_at"). - From("service"). + From("application_group"). Where(squirrel.Eq{"id": idList}). OrderBy("created_at DESC"). ToSql() @@ -51,7 +52,7 @@ func (r Service) GetServiceByIdList(ctx context.Context, idList []int) ([]entity return nil, errors.WithMessage(err, "build query") } - result := make([]entity.Service, 0) + result := make([]entity.AppGroup, 0) err = r.db.Select(ctx, &result, q, arg...) if err != nil { return nil, errors.WithMessagef(err, "select db") @@ -60,10 +61,10 @@ func (r Service) GetServiceByIdList(ctx context.Context, idList []int) ([]entity return result, nil } -func (r Service) GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) { +func (r AppGroup) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) { q, arg, err := query.New(). Select("id", "name", "description", "domain_id", "created_at", "updated_at"). - From("service"). + From("application_group"). Where(squirrel.Eq{"domain_id": domainIdList}). OrderBy("created_at DESC"). ToSql() @@ -71,7 +72,7 @@ func (r Service) GetServiceByDomainId(ctx context.Context, domainIdList []int) ( return nil, errors.WithMessage(err, "build query") } - result := make([]entity.Service, 0) + result := make([]entity.AppGroup, 0) err = r.db.Select(ctx, &result, q, arg...) if err != nil { return nil, errors.WithMessagef(err, "select db") @@ -80,17 +81,17 @@ func (r Service) GetServiceByDomainId(ctx context.Context, domainIdList []int) ( return result, nil } -func (r Service) GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) { +func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) { q := ` SELECT id, name, description, domain_id, created_at, updated_at - FROM service + FROM application_group WHERE name = $1 AND domain_id = $2 ` - result := entity.Service{} + result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, domainId) if err != nil { if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrServiceNotFound + return nil, domain.ErrAppGroupNotFound } return nil, errors.WithMessage(err, "select db") } @@ -98,14 +99,14 @@ func (r Service) GetServiceByNameAndDomainId(ctx context.Context, name string, d return &result, nil } -func (r Service) CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) { +func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) { q := ` - INSERT INTO service + INSERT INTO application_group (name, description, domain_id) VALUES ($1, $2, $3) RETURNING id, name, description, domain_id, created_at, updated_at ` - result := entity.Service{} + result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, desc, domainId) if err != nil { return nil, errors.WithMessage(err, "select row db") @@ -114,18 +115,18 @@ func (r Service) CreateService(ctx context.Context, name string, desc string, do return &result, nil } -func (r Service) UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) { +func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) { q := ` - UPDATE service + UPDATE application_group SET name = $1, description = $2 WHERE id = $3 RETURNING id, name, description, domain_id, created_at, updated_at ` - result := entity.Service{} + result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, description, id) if err != nil { if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrServiceNotFound + return nil, domain.ErrAppGroupNotFound } return nil, errors.WithMessage(err, "select row db") } @@ -133,9 +134,9 @@ func (r Service) UpdateService(ctx context.Context, id int, name string, descrip return &result, nil } -func (r Service) DeleteService(ctx context.Context, idList []int) (int, error) { +func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) { q, args, err := query.New(). - Delete("service"). + Delete("application_group"). Where(squirrel.Eq{"id": idList}). ToSql() if err != nil { diff --git a/repository/token.go b/repository/token.go index 14b47fa..953cfc3 100644 --- a/repository/token.go +++ b/repository/token.go @@ -100,14 +100,14 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) { func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) { q := ` -SELECT system_id, domain_id, service_id, app_id, token.expire_time, token.created_at +SELECT system_id, domain_id, application_group_id, app_id, token.expire_time, token.created_at FROM token LEFT JOIN application ON token.app_id = application.id - LEFT JOIN service - ON application.service_id = service.id + LEFT JOIN application_group + ON application.application_group_id = application_group.id LEFT JOIN domain - ON service.domain_id = domain.id + ON application_group.domain_id = domain.id WHERE token = $1 ` result := entity.AuthData{} diff --git a/service/application.go b/service/application.go index aff2c45..9c5fa15 100644 --- a/service/application.go +++ b/service/application.go @@ -9,11 +9,6 @@ import ( "github.com/pkg/errors" ) -type ApplicationServiceRep interface { - GetServiceById(ctx context.Context, id int) (*entity.Service, error) - GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) -} - type ApplicationDeleteTx interface { DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) } @@ -26,7 +21,7 @@ type Application struct { txRunner ApplicationTxRunner appRepo ApplicationRepo domainRepo DomainRepo - serviceRepo ApplicationServiceRep + serviceRepo AppGroupRepo tokenRepo TokenRepo } @@ -34,14 +29,14 @@ func NewApplication( txRunner ApplicationTxRunner, applicationRepo ApplicationRepo, domainRepo DomainRepo, - serviceRepo ApplicationServiceRep, + appGroupRepo AppGroupRepo, tokenRepo TokenRepo, ) Application { return Application{ txRunner: txRunner, appRepo: applicationRepo, domainRepo: domainRepo, - serviceRepo: serviceRepo, + serviceRepo: appGroupRepo, tokenRepo: tokenRepo, } } @@ -70,9 +65,9 @@ func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.A } func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) { - arr, err := s.appRepo.GetApplicationByServiceIdList(ctx, []int{id}) + arr, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{id}) if err != nil { - return nil, errors.WithMessage(err, "get application by service_id") + return nil, errors.WithMessage(err, "get application by app_group_id") } return s.EnrichWithTokens(ctx, arr) @@ -106,7 +101,7 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do result[i] = r } - serviceEntityList, err := s.serviceRepo.GetServiceByDomainId(ctx, domainIdList) + serviceEntityList, err := s.serviceRepo.GetAppGroupByDomainId(ctx, domainIdList) if err != nil { return nil, errors.WithMessage(err, "get service by domain_id") } @@ -130,13 +125,13 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do resultServiceByServiceId[serviceEntity.Id] = resultService } - applicationEntityList, err := s.appRepo.GetApplicationByServiceIdList(ctx, serviceIdList) + applicationEntityList, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, serviceIdList) if err != nil { return nil, errors.WithMessage(err, "get application by service_id") } for _, applicationEntity := range applicationEntityList { - resultService := resultServiceByServiceId[applicationEntity.ServiceId] + resultService := resultServiceByServiceId[applicationEntity.ApplicationGroupId] description := "" if applicationEntity.Description != nil { description = *applicationEntity.Description @@ -154,14 +149,14 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do } func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { - existed, err := s.appRepo.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId) + existed, err := s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) switch { case errors.Is(err, domain.ErrApplicationNotFound): case err != nil: return nil, errors.WithMessage(err, "get application by name and service_id") } - _, err = s.serviceRepo.GetServiceById(ctx, req.ServiceId) + _, err = s.serviceRepo.GetAppGroupById(ctx, req.ServiceId) if err != nil { return nil, errors.WithMessage(err, "get service by id") } @@ -171,12 +166,17 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return nil, domain.ErrApplicationDuplicateName } - _, err = s.appRepo.GetApplicationByNameAndServiceId(ctx, req.Name, req.ServiceId) + _, err = s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) if err != nil { return nil, errors.WithMessage(err, "get application by name and service_id") } - app, err := s.appRepo.CreateApplication(ctx, req.Name, req.Description, req.ServiceId, req.Type) + appId, err := s.appRepo.NextApplicationId(ctx) + if err != nil { + return nil, errors.WithMessage(err, "next app id") + } + + app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ServiceId, req.Type) if err != nil { return nil, errors.WithMessage(err, "create application") } @@ -270,7 +270,7 @@ func (s Application) convertApplication(req entity.Application) domain.Applicati Id: req.Id, Name: req.Name, Description: desc, - ServiceId: req.ServiceId, + ServiceId: req.ApplicationGroupId, Type: req.Type, CreatedAt: req.CreatedAt, UpdatedAt: req.UpdatedAt, diff --git a/service/baseline/service.go b/service/baseline/service.go index 9221eae..e085137 100644 --- a/service/baseline/service.go +++ b/service/baseline/service.go @@ -2,16 +2,19 @@ package baseline import ( "context" - "github.com/pkg/errors" - "github.com/txix-open/isp-kit/log" "isp-system-service/conf" "isp-system-service/entity" + + "github.com/pkg/errors" + "github.com/txix-open/isp-kit/log" ) +const adminAppId = 1 + 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) + CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) + CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId 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) @@ -77,12 +80,12 @@ func (s Service) transaction(ctx context.Context, tx Transaction) error { return errors.WithMessage(err, "create domain") } - service, err := tx.CreateService(ctx, "rootService", "", domain.Id) + service, err := tx.CreateAppGroup(ctx, "rootService", "", domain.Id) if err != nil { return errors.WithMessage(err, "create service") } - app, err := tx.CreateApplication(ctx, "admin", "", service.Id, "SYSTEM") + app, err := tx.CreateApplication(ctx, adminAppId, "admin", "", service.Id, "SYSTEM") if err != nil { return errors.WithMessage(err, "create application") } diff --git a/service/interfaces.go b/service/interfaces.go index 064ebf3..6cb94cf 100644 --- a/service/interfaces.go +++ b/service/interfaces.go @@ -21,18 +21,19 @@ type DomainRepo interface { type ApplicationRepo interface { GetApplicationById(ctx context.Context, id int) (*entity.Application, error) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) - GetApplicationByServiceIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error) - GetApplicationByNameAndServiceId(ctx context.Context, name string, serviceId int) (*entity.Application, error) - CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error) + GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) + GetApplicationByNameAndAppGroupId(ctx context.Context, name string, appGroupId int) (*entity.Application, error) + CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) + NextApplicationId(ctx context.Context) (int, error) } -type ServiceRepo interface { - GetServiceById(ctx context.Context, id int) (*entity.Service, error) - GetServiceByIdList(ctx context.Context, idList []int) ([]entity.Service, error) - GetServiceByDomainId(ctx context.Context, domainIdList []int) ([]entity.Service, error) - GetServiceByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.Service, error) - CreateService(ctx context.Context, name string, desc string, domainId int) (*entity.Service, error) - UpdateService(ctx context.Context, id int, name string, description string) (*entity.Service, error) - DeleteService(ctx context.Context, idList []int) (int, error) +type AppGroupRepo interface { + GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) + GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) + GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) + GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) + CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) + UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) + DeleteAppGroup(ctx context.Context, idList []int) (int, error) } diff --git a/service/secure/service.go b/service/secure/service.go index 39abbc9..6c630d0 100644 --- a/service/secure/service.go +++ b/service/secure/service.go @@ -4,9 +4,10 @@ import ( "context" "time" - "github.com/pkg/errors" "isp-system-service/domain" "isp-system-service/entity" + + "github.com/pkg/errors" ) type TokenRep interface { @@ -46,7 +47,7 @@ func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthDa return &domain.AuthData{ SystemId: authData.SystemId, DomainId: authData.DomainId, - ServiceId: authData.ServiceId, + ServiceId: authData.ApplicationGroupId, ApplicationId: authData.AppId, }, nil } diff --git a/service/service.go b/service/service.go index 06fd18c..fd0ac21 100644 --- a/service/service.go +++ b/service/service.go @@ -3,19 +3,20 @@ package service import ( "context" - "github.com/pkg/errors" "isp-system-service/domain" "isp-system-service/entity" + + "github.com/pkg/errors" ) type Service struct { domainRepo DomainRepo - serviceRepo ServiceRepo + serviceRepo AppGroupRepo } func NewService( domainRepo DomainRepo, - serviceRepo ServiceRepo, + serviceRepo AppGroupRepo, ) Service { return Service{ domainRepo: domainRepo, @@ -24,7 +25,7 @@ func NewService( } func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) { - serviceEntity, err := s.serviceRepo.GetServiceById(ctx, id) + serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, id) if err != nil { return nil, errors.WithMessage(err, "get service by id") } @@ -34,7 +35,7 @@ func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) { } func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) { - serviceEntity, err := s.serviceRepo.GetServiceByIdList(ctx, idList) + serviceEntity, err := s.serviceRepo.GetAppGroupByIdList(ctx, idList) if err != nil { return nil, errors.WithMessage(err, "get system by id list") } @@ -47,7 +48,7 @@ func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Servic } func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) { - serviceEntity, err := s.serviceRepo.GetServiceByDomainId(ctx, []int{domainId}) + serviceEntity, err := s.serviceRepo.GetAppGroupByDomainId(ctx, []int{domainId}) if err != nil { return nil, errors.WithMessage(err, "get system by id list") } @@ -62,9 +63,9 @@ func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Serv func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { req.DomainId = 1 // temporary use only 1 domain, soon domain entity will be removed - existed, err := s.serviceRepo.GetServiceByNameAndDomainId(ctx, req.Name, req.DomainId) + existed, err := s.serviceRepo.GetAppGroupByNameAndDomainId(ctx, req.Name, req.DomainId) switch { - case errors.Is(err, domain.ErrServiceNotFound): + case errors.Is(err, domain.ErrAppGroupNotFound): case err != nil: return nil, errors.WithMessage(err, "get service by name and domain_id") } @@ -79,7 +80,7 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat return nil, domain.ErrDomainDuplicateName } - serviceEntity, err := s.serviceRepo.CreateService(ctx, req.Name, req.Description, req.DomainId) + serviceEntity, err := s.serviceRepo.CreateAppGroup(ctx, req.Name, req.Description, req.DomainId) if err != nil { return nil, errors.WithMessage(err, "create service") } @@ -92,12 +93,12 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat return nil, domain.ErrDomainDuplicateName } - _, err = s.serviceRepo.GetServiceById(ctx, req.Id) + _, err = s.serviceRepo.GetAppGroupById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get service by id") } - serviceEntity, err := s.serviceRepo.UpdateService(ctx, req.Id, req.Name, req.Description) + serviceEntity, err := s.serviceRepo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update service") } @@ -107,7 +108,7 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat } func (s Service) Delete(ctx context.Context, idList []int) (int, error) { - result, err := s.serviceRepo.DeleteService(ctx, idList) + result, err := s.serviceRepo.DeleteAppGroup(ctx, idList) if err != nil { return 0, errors.WithMessage(err, "delete service") } @@ -115,7 +116,7 @@ func (s Service) Delete(ctx context.Context, idList []int) (int, error) { return result, nil } -func (s Service) convertService(req entity.Service) domain.Service { +func (s Service) convertService(req entity.AppGroup) domain.Service { desc := "" if req.Description != nil { desc = *req.Description diff --git a/service/token.go b/service/token.go index 3354d15..5a37acf 100644 --- a/service/token.go +++ b/service/token.go @@ -36,7 +36,7 @@ type Token struct { tx TokenTxRunner appRepo ApplicationRepo domainRepo DomainRepo - serviceRepo ServiceRepo + serviceRepo AppGroupRepo tokenRepo TokenRepo } @@ -46,7 +46,7 @@ func NewToken( tx TokenTxRunner, appRepo ApplicationRepo, domainRepo DomainRepo, - serviceRepo ServiceRepo, + appGroupRepo AppGroupRepo, tokenRepo TokenRepo, ) Token { return Token{ @@ -55,7 +55,7 @@ func NewToken( tx: tx, appRepo: appRepo, domainRepo: domainRepo, - serviceRepo: serviceRepo, + serviceRepo: appGroupRepo, tokenRepo: tokenRepo, } } @@ -80,7 +80,7 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma return nil, errors.WithMessage(err, "get application by id") } - serviceEntity, err := s.serviceRepo.GetServiceById(ctx, applicationEntity.ServiceId) + serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, applicationEntity.ApplicationGroupId) if err != nil { return nil, errors.WithMessage(err, "get service by id") } diff --git a/tests/general_insert_db_test.go b/tests/general_insert_db_test.go index d29e26f..33bf508 100644 --- a/tests/general_insert_db_test.go +++ b/tests/general_insert_db_test.go @@ -1,8 +1,9 @@ package tests_test import ( - "github.com/txix-open/isp-kit/test/dbt" "isp-system-service/entity" + + "github.com/txix-open/isp-kit/test/dbt" ) func InsertDomain(db *dbt.TestDb, value entity.Domain) { @@ -15,9 +16,9 @@ func InsertDomain(db *dbt.TestDb, value entity.Domain) { db.Must().ExecNamed(q, value) } -func InsertService(db *dbt.TestDb, value entity.Service) { +func InsertAppGroup(db *dbt.TestDb, value entity.AppGroup) { q := ` - INSERT INTO service + INSERT INTO application_group (id, name, description, domain_id, created_at, updated_at) VALUES (:id, :name, :description, :domain_id, :created_at, :updated_at) @@ -28,9 +29,9 @@ func InsertService(db *dbt.TestDb, value entity.Service) { func InsertApplication(db *dbt.TestDb, value entity.Application) { q := ` INSERT INTO application - (id, name, description, service_id, created_at, updated_at) + (id, name, description, application_group_id, created_at, updated_at) VALUES - (:id, :name, :description, :service_id, :created_at, :updated_at) + (:id, :name, :description, :application_group_id, :created_at, :updated_at) ` db.Must().ExecNamed(q, value) } diff --git a/tests/secure_test.go b/tests/secure_test.go index b82cfd0..b5e51d6 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -2,20 +2,22 @@ package tests_test import ( "context" - "github.com/txix-open/isp-kit/dbx" "testing" "time" + "github.com/txix-open/isp-kit/dbx" + + "isp-system-service/assembly" + "isp-system-service/conf" + "isp-system-service/domain" + "isp-system-service/entity" + "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" ) func TestSecureSuite(t *testing.T) { @@ -44,11 +46,11 @@ func (s *SecureSuite) SetupSuite() { InsertDomain(s.testDb, entity.Domain{ Id: 3, Name: "test_domain", SystemId: 1, CreatedAt: createdTime, UpdatedAt: createdTime, }) - InsertService(s.testDb, entity.Service{ - Id: 5, Name: "test_service", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime, + InsertAppGroup(s.testDb, entity.AppGroup{ + Id: 5, Name: "test_application_group", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime, }) InsertApplication(s.testDb, entity.Application{ - Id: 7, Name: "test_application", ServiceId: 5, CreatedAt: createdTime, UpdatedAt: createdTime, + Id: 7, Name: "test_application", ApplicationGroupId: 5, CreatedAt: createdTime, UpdatedAt: createdTime, }) } diff --git a/transaction/manager.go b/transaction/manager.go index 0f6cd0f..fc76758 100644 --- a/transaction/manager.go +++ b/transaction/manager.go @@ -88,7 +88,7 @@ func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Conte type baselineTx struct { repository.Locker repository.Domain - repository.Service + repository.AppGroup repository.Application repository.AccessList repository.Token @@ -99,7 +99,7 @@ func (m Manager) BaselineTx(ctx context.Context, txTx func(ctx context.Context, return txTx(ctx, baselineTx{ Locker: repository.NewLocker(tx), Domain: repository.NewDomain(tx), - Service: repository.NewService(tx), + AppGroup: repository.NewAppGroup(tx), Application: repository.NewApplication(tx), AccessList: repository.NewAccessList(tx), Token: repository.NewToken(tx), From 1818bf8b457127947420742171ff709d10b26253 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 19:04:24 +0300 Subject: [PATCH 10/30] MSP-5186 Update repository errors --- repository/access_list.go | 22 ++++++++--------- repository/application.go | 24 +++++++++--------- repository/domain.go | 51 ++++++++++++++++++--------------------- repository/service.go | 50 +++++++++++++++++++------------------- repository/token.go | 30 +++++++++++------------ 5 files changed, 87 insertions(+), 90 deletions(-) diff --git a/repository/access_list.go b/repository/access_list.go index 34fc390..1799a03 100644 --- a/repository/access_list.go +++ b/repository/access_list.go @@ -30,14 +30,14 @@ 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 errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrAccessListNotFound - } - return nil, errors.WithMessagef(err, "select db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrAccessListNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) { @@ -68,7 +68,7 @@ func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []in result := make([]entity.AccessList, 0) err = r.db.Select(ctx, &result, q, args...) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil @@ -88,7 +88,7 @@ func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.A _, err = r.db.Exec(ctx, q, args...) if err != nil { - return errors.WithMessage(err, "exec db") + return errors.WithMessagef(err, "exec query %s", q) } return nil @@ -105,7 +105,7 @@ func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) ( ` result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value) if err != nil { - return 0, errors.WithMessage(err, "exec db") + return 0, errors.WithMessagef(err, "exec query %s", q) } rowsAffected, err := result.RowsAffected() @@ -146,7 +146,7 @@ func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]e result := make([]entity.AccessList, 0) err := r.db.Select(ctx, &result, q, appId) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil diff --git a/repository/application.go b/repository/application.go index 3812c14..36d9e04 100644 --- a/repository/application.go +++ b/repository/application.go @@ -30,14 +30,14 @@ 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 errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrApplicationNotFound - } + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrApplicationNotFound + case err != nil: return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) { @@ -88,14 +88,14 @@ func (r Application) GetApplicationByNameAndAppGroupId(ctx context.Context, name ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, name, serviceId) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, nil //nolint:nilnil - } + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, nil // nolint:nilnil + case err != nil: return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r Application) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) ( diff --git a/repository/domain.go b/repository/domain.go index f0acb5b..8c85251 100644 --- a/repository/domain.go +++ b/repository/domain.go @@ -30,14 +30,14 @@ 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 errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrDomainNotFound - } - return nil, errors.WithMessage(err, "select row db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrDomainNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) { @@ -69,7 +69,7 @@ func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity result := make([]entity.Domain, 0) err := r.db.Select(ctx, &result, q, systemId) if err != nil { - return nil, errors.WithMessage(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil @@ -83,14 +83,14 @@ 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 errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrDomainNotFound - } - return nil, errors.WithMessage(err, "select row db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrDomainNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) { @@ -103,12 +103,8 @@ 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 errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrDomainNotFound - } - return nil, errors.WithMessage(err, "select row db") + return nil, errors.WithMessagef(err, "exec query %s", q) } - return &result, nil } @@ -121,13 +117,14 @@ 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 errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrDomainNotFound - } - return nil, errors.WithMessage(err, "select row db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrDomainNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - return &result, nil } func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) { @@ -141,7 +138,7 @@ func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) { result, err := r.db.Exec(ctx, q, args...) if err != nil { - return 0, errors.WithMessagef(err, "exec db") + return 0, errors.WithMessagef(err, "exec query %s", q) } rowsAffected, err := result.RowsAffected() diff --git a/repository/service.go b/repository/service.go index bf28b8b..bd853c3 100644 --- a/repository/service.go +++ b/repository/service.go @@ -31,14 +31,14 @@ func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, id) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrAppGroupNotFound - } - return nil, errors.WithMessage(err, "select row db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrAppGroupNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) { @@ -55,7 +55,7 @@ func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]enti result := make([]entity.AppGroup, 0) err = r.db.Select(ctx, &result, q, arg...) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil @@ -75,7 +75,7 @@ func (r AppGroup) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) result := make([]entity.AppGroup, 0) err = r.db.Select(ctx, &result, q, arg...) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil @@ -89,14 +89,14 @@ func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, domainId) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrAppGroupNotFound - } - return nil, errors.WithMessage(err, "select db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrAppGroupNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) { @@ -109,7 +109,7 @@ func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, desc, domainId) if err != nil { - return nil, errors.WithMessage(err, "select row db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return &result, nil @@ -124,14 +124,14 @@ func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, descr ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, description, id) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrAppGroupNotFound - } - return nil, errors.WithMessage(err, "select row db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrAppGroupNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) { @@ -145,7 +145,7 @@ func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) result, err := r.db.Exec(ctx, q, args...) if err != nil { - return 0, errors.WithMessagef(err, "exec db") + return 0, errors.WithMessagef(err, "exec query %s", q) } rowsAffected, err := result.RowsAffected() diff --git a/repository/token.go b/repository/token.go index 953cfc3..810c5b8 100644 --- a/repository/token.go +++ b/repository/token.go @@ -46,14 +46,14 @@ func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, e ` result := entity.Token{} err := r.db.SelectRow(ctx, &result, q, token) - if errors.Is(err, sql.ErrNoRows) { + switch { + case errors.Is(err, sql.ErrNoRows): return nil, nil //nolint:nilnil + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - if err != nil { - return nil, errors.WithMessage(err, "select row db") - } - - return &result, nil } func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) { @@ -70,7 +70,7 @@ func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]enti result := make([]entity.Token, 0) err = r.db.Select(ctx, &result, q, args...) if err != nil { - return nil, errors.WithMessagef(err, "select db") + return nil, errors.WithMessagef(err, "exec query %s", q) } return result, nil @@ -87,7 +87,7 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) { result, err := r.db.Exec(ctx, q, args...) if err != nil { - return 0, errors.WithMessagef(err, "exec db") + return 0, errors.WithMessagef(err, "exec query %s", q) } rowsAffected, err := result.RowsAffected() @@ -112,12 +112,12 @@ WHERE token = $1 ` result := entity.AuthData{} err := r.db.SelectRow(ctx, &result, q, token) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, domain.ErrTokenNotFound - } - return nil, errors.WithMessage(err, "select row db") + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrTokenNotFound + case err != nil: + return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } From 141650417a363748aebc76b3de3fe4604b2c9988 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 19:10:41 +0300 Subject: [PATCH 11/30] MSP-5186 Check app duplicate name before check req.Id --- service/application.go | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/service/application.go b/service/application.go index 9c5fa15..4e3abdb 100644 --- a/service/application.go +++ b/service/application.go @@ -161,11 +161,11 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return nil, errors.WithMessage(err, "get service by id") } - if req.Id == 0 { - if existed != nil { - return nil, domain.ErrApplicationDuplicateName - } + if existed != nil && (existed.Id != req.Id || req.Id == 0) { + return nil, domain.ErrApplicationDuplicateName + } + if req.Id == 0 { _, err = s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) if err != nil { return nil, errors.WithMessage(err, "get application by name and service_id") @@ -189,10 +189,6 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return result[0], nil } - if existed != nil && existed.Id != req.Id { - return nil, domain.ErrApplicationDuplicateName - } - _, err = s.appRepo.GetApplicationById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get application by id") From 89f4eea28058de2d72776c04a400210a0096b89b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 19:39:14 +0300 Subject: [PATCH 12/30] MSP-5186 Implement application next id endpoint --- controller/application.go | 14 ++++++++++++++ docs/swagger.yaml | 19 +++++++++++++++++++ routes/routes.go | 5 +++++ service/application.go | 8 ++++++++ 4 files changed, 46 insertions(+) diff --git a/controller/application.go b/controller/application.go index b3f28a3..c2defca 100644 --- a/controller/application.go +++ b/controller/application.go @@ -17,6 +17,7 @@ type ApplicationService interface { SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) Delete(ctx context.Context, idList []int) (int, error) + NextId(ctx context.Context) (int, error) } type Application struct { @@ -148,3 +149,16 @@ func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteRespo Deleted: result, }, nil } + +// NextId godoc +// @Tags application +// @Summary Получить следующий идентификатор приложения +// @Description Возвращает следующий идентификатор приложения +// @Accept json +// @Produce json +// @Success 200 {object} integer +// @Failure 500 {object} domain.GrpcError +// @Router /application/next_id [POST] +func (c Application) NextId(ctx context.Context) (int, error) { + return c.service.NextId(ctx) +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 82295fe..db4b8c9 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -571,6 +571,25 @@ paths: summary: Метод получения системного дерева tags: - application + /application/next_id: + post: + consumes: + - application/json + description: Возвращает следующий идентификатор приложения + produces: + - application/json + responses: + "200": + description: OK + schema: + type: integer + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Получить следующий идентификатор приложения + tags: + - application /domain/create_update_domain: post: consumes: diff --git a/routes/routes.go b/routes/routes.go index ec6b2ae..9c886ef 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -161,6 +161,11 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.Application.GetSystemTree, }, + { + Path: "system/application/next_id", + Inner: true, + Handler: c.Application.NextId, + }, } } diff --git a/service/application.go b/service/application.go index 4e3abdb..ed2e31f 100644 --- a/service/application.go +++ b/service/application.go @@ -256,6 +256,14 @@ func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Applica return result, nil } +func (s Application) NextId(ctx context.Context) (int, error) { + nextId, err := s.appRepo.NextApplicationId(ctx) + if err != nil { + return 0, errors.WithMessage(err, "get next application id") + } + return nextId, nil +} + func (s Application) convertApplication(req entity.Application) domain.Application { desc := "" if req.Description != nil { From f8fa58a09c1916e82af1c4fc12a944102b1ddcff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 20:13:48 +0300 Subject: [PATCH 13/30] MSP-5186 Move service repo and entity to app_group --- entity/{service.go => app_group.go} | 0 repository/{service.go => app_group.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename entity/{service.go => app_group.go} (100%) rename repository/{service.go => app_group.go} (100%) diff --git a/entity/service.go b/entity/app_group.go similarity index 100% rename from entity/service.go rename to entity/app_group.go diff --git a/repository/service.go b/repository/app_group.go similarity index 100% rename from repository/service.go rename to repository/app_group.go From fa2f88c869da21b7595c4cbe8181537fd0104c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Tue, 1 Apr 2025 20:25:42 +0300 Subject: [PATCH 14/30] MSP-5186 Add /application/get_all endpoint --- controller/application.go | 14 +++++ docs/swagger.yaml | 21 ++++++++ repository/application.go | 19 +++++++ routes/routes.go | 5 ++ service/application.go | 13 +++++ service/interfaces.go | 1 + tests/application_test.go | 109 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 182 insertions(+) create mode 100644 tests/application_test.go diff --git a/controller/application.go b/controller/application.go index c2defca..e272ea0 100644 --- a/controller/application.go +++ b/controller/application.go @@ -18,6 +18,7 @@ type ApplicationService interface { CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) Delete(ctx context.Context, idList []int) (int, error) NextId(ctx context.Context) (int, error) + GetAll(ctx context.Context) ([]domain.Application, error) } type Application struct { @@ -162,3 +163,16 @@ func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteRespo func (c Application) NextId(ctx context.Context) (int, error) { return c.service.NextId(ctx) } + +// GetAll godoc +// @Tags application +// @Summary Получить список приложений +// @Description Возвращает список приложений +// @Accept json +// @Produce json +// @Success 200 {array} domain.Application +// @Failure 500 {object} domain.GrpcError +// @Router /application/get_all [POST] +func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { + return c.service.GetAll(ctx) +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index db4b8c9..3819452 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -459,6 +459,27 @@ paths: summary: Удалить приложения tags: - application + /application/get_all: + post: + consumes: + - application/json + description: Возвращает список приложений + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/domain.Application' + type: array + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Получить список приложений + tags: + - application /application/get_application_by_id: post: consumes: diff --git a/repository/application.go b/repository/application.go index 36d9e04..0e788f7 100644 --- a/repository/application.go +++ b/repository/application.go @@ -172,3 +172,22 @@ func (r Application) NextApplicationId(ctx context.Context) (int, error) { } return nextAppId, nil } + +func (r Application) GetAllApplications(ctx context.Context) ([]entity.Application, error) { + q, args, err := query.New(). + Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at"). + From("application"). + OrderBy("created_at DESC"). + ToSql() + if err != nil { + return nil, errors.WithMessagef(err, "exec query %s", q) + } + + result := make([]entity.Application, 0) + err = r.db.Select(ctx, &result, q, args...) + if err != nil { + return nil, errors.WithMessagef(err, "exec query %s", q) + } + + return result, nil +} diff --git a/routes/routes.go b/routes/routes.go index 9c886ef..07b1b3a 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -166,6 +166,11 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.Application.NextId, }, + { + Path: "system/application/get_all", + Inner: true, + Handler: c.Application.GetAll, + }, } } diff --git a/service/application.go b/service/application.go index ed2e31f..01ade9b 100644 --- a/service/application.go +++ b/service/application.go @@ -264,6 +264,19 @@ func (s Application) NextId(ctx context.Context) (int, error) { return nextId, nil } +func (s Application) GetAll(ctx context.Context) ([]domain.Application, error) { + apps, err := s.appRepo.GetAllApplications(ctx) + if err != nil { + return nil, errors.WithMessage(err, "get applications list") + } + + result := make([]domain.Application, 0, len(apps)) + for _, app := range apps { + result = append(result, s.convertApplication(app)) + } + return result, nil +} + func (s Application) convertApplication(req entity.Application) domain.Application { desc := "" if req.Description != nil { diff --git a/service/interfaces.go b/service/interfaces.go index 6cb94cf..5d3773c 100644 --- a/service/interfaces.go +++ b/service/interfaces.go @@ -26,6 +26,7 @@ type ApplicationRepo interface { CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) NextApplicationId(ctx context.Context) (int, error) + GetAllApplications(ctx context.Context) ([]entity.Application, error) } type AppGroupRepo interface { diff --git a/tests/application_test.go b/tests/application_test.go new file mode 100644 index 0000000..810c5a8 --- /dev/null +++ b/tests/application_test.go @@ -0,0 +1,109 @@ +package tests_test + +import ( + "isp-system-service/assembly" + "isp-system-service/conf" + "isp-system-service/domain" + "isp-system-service/repository" + "testing" + "time" + + "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" +) + +func TestApplicationSuite(t *testing.T) { + t.Parallel() + suite.Run(t, &ApplicationSuite{}) +} + +type ApplicationSuite struct { + suite.Suite + test *test.Test + testDb *dbt.TestDb + domainRepo repository.Domain + appRepo repository.Application + appGroupRepo repository.AppGroup + api *client.Client +} + +func (s *ApplicationSuite) SetupTest() { + 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{}) + _, s.api = grpct.TestServer(s.test, config.Handler) + s.domainRepo = repository.NewDomain(s.testDb) + s.appRepo = repository.NewApplication(s.testDb) + s.appGroupRepo = repository.NewAppGroup(s.testDb) +} + +func (s *ApplicationSuite) TestGetAllApplications() { + toInsert := fake.It[[]domain.Application](fake.MaxSliceSize(2), fake.MinSliceSize(2)) + expectedApps := s.insertApps(toInsert) + + result := []domain.Application{} + err := s.api.Invoke("system/application/get_all"). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + for i := range result { + s.Require().NotEmpty(result[i].CreatedAt) + result[i].CreatedAt = time.Time{} + + s.Require().NotEmpty(result[i].UpdatedAt) + result[i].UpdatedAt = time.Time{} + } + s.Require().ElementsMatch(expectedApps, result) +} + +func (s *ApplicationSuite) insertApps(toInsert []domain.Application) []domain.Application { + createdDomain, err := s.domainRepo.CreateDomain( + s.T().Context(), + fake.It[string](), + fake.It[string](), + 1, + ) + s.Require().NoError(err) + + appGroup, err := s.appGroupRepo.CreateAppGroup( + s.T().Context(), + fake.It[string](), + fake.It[string](), + createdDomain.Id, + ) + s.Require().NoError(err) + + toExpect := make([]domain.Application, 0, len(toInsert)) + for _, app := range toInsert { + createdApp, err := s.appRepo.CreateApplication( + s.T().Context(), + app.Id, + app.Name, + app.Description, + appGroup.Id, + app.Type, + ) + s.Require().NoError(err) + s.Require().NotEmpty(createdApp.CreatedAt) + s.Require().NotEmpty(createdApp.UpdatedAt) + + toExpect = append(toExpect, domain.Application{ + Id: createdApp.Id, + Name: createdApp.Name, + Description: *createdApp.Description, + ServiceId: createdApp.ApplicationGroupId, + Type: createdApp.Type, + CreatedAt: time.Time{}, + UpdatedAt: time.Time{}, + }) + } + return toExpect +} From e2ed71196b100502fbc605ca001afef9a04bfa11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 09:54:11 +0300 Subject: [PATCH 15/30] MSP-5186 Add /application/create_application endpoint --- controller/application.go | 30 +++++++++- docs/swagger.yaml | 59 ++++++++++++++++++ domain/application.go | 13 ++++ repository/application.go | 44 ++++++++++---- routes/routes.go | 5 ++ service/application.go | 20 +++++++ tests/application_test.go | 122 +++++++++++++++++++++++++++++++++++++- 7 files changed, 281 insertions(+), 12 deletions(-) diff --git a/controller/application.go b/controller/application.go index e272ea0..37bb000 100644 --- a/controller/application.go +++ b/controller/application.go @@ -19,6 +19,7 @@ type ApplicationService interface { Delete(ctx context.Context, idList []int) (int, error) NextId(ctx context.Context) (int, error) GetAll(ctx context.Context) ([]domain.Application, error) + Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) } type Application struct { @@ -117,7 +118,7 @@ func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre case errors.Is(err, domain.ErrApplicationDuplicateName): return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "Application with id %d not found", req.Id) + return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id) case err != nil: return nil, err default: @@ -176,3 +177,30 @@ func (c Application) NextId(ctx context.Context) (int, error) { func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { return c.service.GetAll(ctx) } + +// Create godoc +// @Tags application +// @Summary Создать приложение +// @Description Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` существует, то возвращает ошибку +// @Accept json +// @Produce json +// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/create_application [POST] +func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { + result, err := c.service.Create(ctx, req) + switch { + case errors.Is(err, domain.ErrAppGroupNotFound): + return nil, status.Errorf(codes.InvalidArgument, "application group with id %d not found", req.ApplicationGroupId) + case errors.Is(err, domain.ErrApplicationDuplicateName): + return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) + case errors.Is(err, domain.ErrApplicationDuplicateId): + return nil, status.Errorf(codes.AlreadyExists, "application with id %d already exists", req.Id) + default: + return result, err + } +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 3819452..362cf26 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -133,6 +133,26 @@ definitions: authorized: type: boolean type: object + domain.CreateApplicationRequest: + properties: + applicationGroupId: + type: integer + description: + type: string + id: + type: integer + name: + type: string + type: + enum: + - SYSTEM + - MOBILE + type: string + required: + - applicationGroupId + - name + - type + type: object domain.DeleteResponse: properties: deleted: @@ -388,6 +408,45 @@ paths: summary: Настроить доступность метода для приложения tags: - accessList + /application/create_application: + post: + consumes: + - application/json + description: Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` + существует, то возвращает ошибку + parameters: + - description: Объект приложения + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.CreateApplicationRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.ApplicationWithTokens' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.GrpcError' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.GrpcError' + "409": + description: Conflict + schema: + $ref: '#/definitions/domain.GrpcError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Создать приложение + tags: + - application /application/create_update_application: post: consumes: diff --git a/domain/application.go b/domain/application.go index abb0917..dd054e9 100644 --- a/domain/application.go +++ b/domain/application.go @@ -4,6 +4,11 @@ import ( "time" ) +const ( + ApplicationSystemType = "SYSTEM" + ApplicationMobileType = "MOBILE" +) + type Application struct { Id int Name string @@ -34,3 +39,11 @@ type ApplicationSimple struct { Type string Tokens []Token } + +type CreateApplicationRequest struct { + Id int + Name string `validate:"required"` + Description string + ApplicationGroupId int `validate:"required"` + Type string `validate:"required,oneof=SYSTEM MOBILE"` +} diff --git a/repository/application.go b/repository/application.go index 0e788f7..3965283 100644 --- a/repository/application.go +++ b/repository/application.go @@ -4,12 +4,22 @@ import ( "context" "database/sql" + "isp-system-service/domain" + "isp-system-service/entity" + "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5/pgconn" "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" +) + +const ( + pgUniqueViolationErrorCode = "23505" + pgFkViolationErrorCode = "23503" + applicationPkConstrainName = "application_pkey" + applicationUniqueNameConstrainName = "uq_name_application_group_id" + applicationFkAppGroupConstraintName = "fk_application_group_id" ) type Application struct { @@ -104,19 +114,14 @@ func (r Application) CreateApplication(ctx context.Context, id int, name string, INSERT INTO application (id, name, description, application_group_id, type) VALUES ($1, $2, $3, $4, $5) - ON CONFLICT (id) DO NOTHING RETURNING id, name, description, application_group_id, type, created_at, updated_at ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, id, name, desc, appGroupId, appType) - switch { - case errors.Is(err, sql.ErrNoRows): - return nil, domain.ErrApplicationDuplicateId - case err != nil: - return nil, errors.WithMessagef(err, "exec query %s", q) - default: - return &result, nil + if err != nil { + return nil, r.handleCreateError(err, q) } + return &result, nil } func (r Application) UpdateApplication( @@ -191,3 +196,22 @@ func (r Application) GetAllApplications(ctx context.Context) ([]entity.Applicati return result, nil } + +func (r Application) handleCreateError(err error, q string) error { + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) { + return errors.WithMessagef(err, "exec query %s", q) + } + switch { + case pgErr.Code == pgUniqueViolationErrorCode: + switch pgErr.ConstraintName { + case applicationPkConstrainName: + return domain.ErrApplicationDuplicateId + case applicationUniqueNameConstrainName: + return domain.ErrApplicationDuplicateName + } + case pgErr.Code == pgFkViolationErrorCode && pgErr.ConstraintName == applicationFkAppGroupConstraintName: + return domain.ErrAppGroupNotFound + } + return errors.WithMessagef(err, "exec query %s", q) +} diff --git a/routes/routes.go b/routes/routes.go index 07b1b3a..ab64a37 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -171,6 +171,11 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.Application.GetAll, }, + { + Path: "system/application/create_application", + Inner: true, + Handler: c.Application.Create, + }, } } diff --git a/service/application.go b/service/application.go index 01ade9b..37e46df 100644 --- a/service/application.go +++ b/service/application.go @@ -277,6 +277,26 @@ func (s Application) GetAll(ctx context.Context) ([]domain.Application, error) { return result, nil } +func (s Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { + appId := req.Id + var err error + if appId == 0 { + appId, err = s.appRepo.NextApplicationId(ctx) + if err != nil { + return nil, errors.WithMessage(err, "next application id") + } + } + app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ApplicationGroupId, req.Type) + if err != nil { + return nil, errors.WithMessage(err, "create application") + } + + return &domain.ApplicationWithTokens{ + App: s.convertApplication(*app), + Tokens: make([]domain.Token, 0), + }, nil +} + func (s Application) convertApplication(req entity.Application) domain.Application { desc := "" if req.Description != nil { diff --git a/tests/application_test.go b/tests/application_test.go index 810c5a8..00ebfc4 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -4,6 +4,7 @@ import ( "isp-system-service/assembly" "isp-system-service/conf" "isp-system-service/domain" + "isp-system-service/entity" "isp-system-service/repository" "testing" "time" @@ -15,6 +16,8 @@ import ( "github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/fake" "github.com/txix-open/isp-kit/test/grpct" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func TestApplicationSuite(t *testing.T) { @@ -64,7 +67,120 @@ func (s *ApplicationSuite) TestGetAllApplications() { s.Require().ElementsMatch(expectedApps, result) } -func (s *ApplicationSuite) insertApps(toInsert []domain.Application) []domain.Application { +func (s *ApplicationSuite) TestCreate_HappyPath() { + result := domain.ApplicationWithTokens{} + apiReq := fake.It[domain.CreateApplicationRequest]() + apiReq.Type = domain.ApplicationSystemType + appGroup := s.createAppGroup() + apiReq.ApplicationGroupId = appGroup.Id + + err := s.api.Invoke("system/application/create_application"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + + s.Require().NotEmpty(result.App.CreatedAt) + result.App.CreatedAt = time.Time{} + + s.Require().NotEmpty(result.App.UpdatedAt) + result.App.UpdatedAt = time.Time{} + + expectedApp := domain.Application{ + Id: apiReq.Id, + Name: apiReq.Name, + Description: apiReq.Description, + Type: apiReq.Type, + ServiceId: apiReq.ApplicationGroupId, + } + s.Require().Equal(expectedApp, result.App) + s.Require().Empty(result.Tokens) +} + +func (s *ApplicationSuite) TestCreate_WithEmptyAppId_HappyPath() { + nextAppId, err := s.appRepo.NextApplicationId(s.T().Context()) + s.Require().NoError(err) + + result := domain.ApplicationWithTokens{} + apiReq := fake.It[domain.CreateApplicationRequest]() + apiReq.Type = domain.ApplicationMobileType + appGroup := s.createAppGroup() + apiReq.ApplicationGroupId = appGroup.Id + apiReq.Id = 0 + + err = s.api.Invoke("system/application/create_application"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + + s.Require().NotEmpty(result.App.CreatedAt) + result.App.CreatedAt = time.Time{} + + s.Require().NotEmpty(result.App.UpdatedAt) + result.App.UpdatedAt = time.Time{} + + expectedApp := domain.Application{ + Id: nextAppId, + Name: apiReq.Name, + Description: apiReq.Description, + Type: apiReq.Type, + ServiceId: apiReq.ApplicationGroupId, + } + s.Require().Equal(expectedApp, result.App) + s.Require().Empty(result.Tokens) +} + +func (s *ApplicationSuite) TestCreate_AppGroupNotFound() { + apiReq := fake.It[domain.CreateApplicationRequest]() + apiReq.Type = domain.ApplicationSystemType + + err := s.api.Invoke("system/application/create_application"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.InvalidArgument, statusErr.Code()) +} + +func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() { + apiReq := fake.It[domain.CreateApplicationRequest]() + apiReq.Type = domain.ApplicationSystemType + + inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1))) + + apiReq.ApplicationGroupId = inserted[0].ServiceId + apiReq.Name = inserted[0].Name + + err := s.api.Invoke("system/application/create_application"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.AlreadyExists, statusErr.Code()) +} + +func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() { + apiReq := fake.It[domain.CreateApplicationRequest]() + apiReq.Type = "SYSTEM" + appGroup := s.createAppGroup() + apiReq.ApplicationGroupId = appGroup.Id + + inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1))) + apiReq.Id = inserted[0].Id + + err := s.api.Invoke("system/application/create_application"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.AlreadyExists, statusErr.Code()) +} + +func (s *ApplicationSuite) createAppGroup() *entity.AppGroup { createdDomain, err := s.domainRepo.CreateDomain( s.T().Context(), fake.It[string](), @@ -80,7 +196,11 @@ func (s *ApplicationSuite) insertApps(toInsert []domain.Application) []domain.Ap createdDomain.Id, ) s.Require().NoError(err) + return appGroup +} +func (s *ApplicationSuite) insertApps(toInsert []domain.Application) []domain.Application { + appGroup := s.createAppGroup() toExpect := make([]domain.Application, 0, len(toInsert)) for _, app := range toInsert { createdApp, err := s.appRepo.CreateApplication( From aae74ef611b34abdb7f7cab0ca10346d9d572b59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 10:40:13 +0300 Subject: [PATCH 16/30] MSP-5186 Add /application/update_application endpoint --- controller/application.go | 28 ++++++++++++- docs/swagger.yaml | 51 ++++++++++++++++++++++++ domain/application.go | 6 +++ go.mod | 2 +- repository/application.go | 17 +++++--- routes/routes.go | 4 ++ service/application.go | 14 +++++++ tests/application_test.go | 84 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 199 insertions(+), 7 deletions(-) diff --git a/controller/application.go b/controller/application.go index 37bb000..ad30bdc 100644 --- a/controller/application.go +++ b/controller/application.go @@ -20,6 +20,7 @@ type ApplicationService interface { NextId(ctx context.Context) (int, error) GetAll(ctx context.Context) ([]domain.Application, error) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) + Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) } type Application struct { @@ -184,7 +185,7 @@ func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { // @Description Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` существует, то возвращает ошибку // @Accept json // @Produce json -// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения" +// @Param body body domain.CreateApplicationRequest true "Объект приложения" // @Success 200 {object} domain.ApplicationWithTokens // @Failure 400 {object} domain.GrpcError // @Failure 404 {object} domain.GrpcError @@ -204,3 +205,28 @@ func (c Application) Create(ctx context.Context, req domain.CreateApplicationReq return result, err } } + +// Update godoc +// @Tags application +// @Summary Обновить приложение +// @Description Если приложение с связкой `applicationGroupId`-`name` существует или приложение не найдено, то возвращает ошибку +// @Accept json +// @Produce json +// @Param body body domain.UpdateApplicationRequest true "Объект приложения" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/update_application [POST] +func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { + result, err := c.service.Update(ctx, req) + switch { + case errors.Is(err, domain.ErrApplicationDuplicateName): + return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) + case errors.Is(err, domain.ErrApplicationNotFound): + return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id) + default: + return result, err + } +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 362cf26..bafbb57 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -295,6 +295,18 @@ definitions: required: - appId type: object + domain.UpdateApplicationRequest: + properties: + description: + type: string + id: + type: integer + name: + type: string + required: + - id + - name + type: object entity.Token: properties: appId: @@ -670,6 +682,45 @@ paths: summary: Получить следующий идентификатор приложения tags: - application + /application/update_application: + post: + consumes: + - application/json + description: Если приложение с связкой `applicationGroupId`-`name` существует + или приложение не найдено, то возвращает ошибку + parameters: + - description: Объект приложения + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.UpdateApplicationRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.ApplicationWithTokens' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.GrpcError' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.GrpcError' + "409": + description: Conflict + schema: + $ref: '#/definitions/domain.GrpcError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Обновить приложение + tags: + - application /domain/create_update_domain: post: consumes: diff --git a/domain/application.go b/domain/application.go index dd054e9..b66e3af 100644 --- a/domain/application.go +++ b/domain/application.go @@ -47,3 +47,9 @@ type CreateApplicationRequest struct { ApplicationGroupId int `validate:"required"` Type string `validate:"required,oneof=SYSTEM MOBILE"` } + +type UpdateApplicationRequest struct { + Id int `validate:"required"` + Name string `validate:"required"` + Description string +} diff --git a/go.mod b/go.mod index 941ba7a..e518e0c 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.24 require ( github.com/Masterminds/squirrel v1.5.4 + github.com/jackc/pgx/v5 v5.7.2 github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.10.0 github.com/txix-open/isp-kit v1.45.0 @@ -31,7 +32,6 @@ require ( 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.2 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jmoiron/sqlx v1.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect diff --git a/repository/application.go b/repository/application.go index 3965283..d30375c 100644 --- a/repository/application.go +++ b/repository/application.go @@ -126,7 +126,7 @@ func (r Application) CreateApplication(ctx context.Context, id int, name string, func (r Application) UpdateApplication( ctx context.Context, - appGroupId int, + id int, name string, description string, ) (*entity.Application, error) { @@ -138,12 +138,19 @@ func (r Application) UpdateApplication( RETURNING id, name, description, application_group_id, type, created_at, updated_at ` result := entity.Application{} - err := r.db.SelectRow(ctx, &result, q, appGroupId, name, description) - if err != nil { + err := r.db.SelectRow(ctx, &result, q, id, name, description) + var pgErr *pgconn.PgError + switch { + case errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolationErrorCode && + pgErr.ConstraintName == applicationUniqueNameConstrainName: + return nil, domain.ErrApplicationDuplicateName + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrApplicationNotFound + case err != nil: return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) { diff --git a/routes/routes.go b/routes/routes.go index ab64a37..baac098 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -175,6 +175,10 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor { Path: "system/application/create_application", Inner: true, Handler: c.Application.Create, + }, { + Path: "system/application/update_application", + Inner: true, + Handler: c.Application.Update, }, } } diff --git a/service/application.go b/service/application.go index 37e46df..50561ea 100644 --- a/service/application.go +++ b/service/application.go @@ -297,6 +297,20 @@ func (s Application) Create(ctx context.Context, req domain.CreateApplicationReq }, nil } +func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { + app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description) + if err != nil { + return nil, errors.WithMessage(err, "update application") + } + + result, err := s.EnrichWithTokens(ctx, []entity.Application{*app}) + if err != nil { + return nil, errors.WithMessage(err, "enrich application with tokens") + } + + return result[0], nil +} + func (s Application) convertApplication(req entity.Application) domain.Application { desc := "" if req.Description != nil { diff --git a/tests/application_test.go b/tests/application_test.go index 00ebfc4..a2f1b81 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -180,6 +180,90 @@ func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() { s.Require().Equal(codes.AlreadyExists, statusErr.Code()) } +func (s *ApplicationSuite) TestUpdate_HappyPath() { + inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1))) + apiReq := domain.UpdateApplicationRequest{ + Id: inserted[0].Id, + Name: fake.It[string](), + Description: fake.It[string](), + } + + var result domain.ApplicationWithTokens + err := s.api.Invoke("system/application/update_application"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + + s.Require().NotEmpty(result.App.CreatedAt) + result.App.CreatedAt = time.Time{} + + s.Require().NotEmpty(result.App.UpdatedAt) + result.App.UpdatedAt = time.Time{} + + expectedApp := domain.Application{ + Id: apiReq.Id, + Name: apiReq.Name, + Description: apiReq.Description, + Type: inserted[0].Type, + ServiceId: inserted[0].ServiceId, + } + s.Require().Equal(expectedApp, result.App) + s.Require().Empty(result.Tokens) + + app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.Id) + s.Require().NoError(err) + + expectedDbApp := entity.Application{ + Id: apiReq.Id, + Name: apiReq.Name, + Type: inserted[0].Type, + ApplicationGroupId: inserted[0].ServiceId, + } + s.Require().Equal(apiReq.Description, *app.Description) + app.Description = nil + + s.Require().NotEmpty(app.CreatedAt) + app.CreatedAt = time.Time{} + + s.Require().NotEmpty(app.UpdatedAt) + app.UpdatedAt = time.Time{} + s.Require().Equal(expectedDbApp, *app) +} + +func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() { + inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(2), fake.MaxSliceSize(2))) + apiReq := domain.UpdateApplicationRequest{ + Id: inserted[0].Id, + Name: inserted[1].Name, + Description: fake.It[string](), + } + + err := s.api.Invoke("system/application/update_application"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.AlreadyExists, statusErr.Code()) +} + +func (s *ApplicationSuite) TestUpdate_AppNotFound() { + apiReq := domain.UpdateApplicationRequest{ + Id: fake.It[int](), + Name: fake.It[string](), + Description: fake.It[string](), + } + + err := s.api.Invoke("system/application/update_application"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.NotFound, statusErr.Code()) +} + func (s *ApplicationSuite) createAppGroup() *entity.AppGroup { createdDomain, err := s.domainRepo.CreateDomain( s.T().Context(), From 3b28cf7d088ef21615590f112b5872a4d0a87051 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 10:45:02 +0300 Subject: [PATCH 17/30] MSP-5186 Simplify CreateUpdate --- service/application.go | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/service/application.go b/service/application.go index 50561ea..590d694 100644 --- a/service/application.go +++ b/service/application.go @@ -149,24 +149,8 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do } func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { - existed, err := s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) - switch { - case errors.Is(err, domain.ErrApplicationNotFound): - case err != nil: - return nil, errors.WithMessage(err, "get application by name and service_id") - } - - _, err = s.serviceRepo.GetAppGroupById(ctx, req.ServiceId) - if err != nil { - return nil, errors.WithMessage(err, "get service by id") - } - - if existed != nil && (existed.Id != req.Id || req.Id == 0) { - return nil, domain.ErrApplicationDuplicateName - } - if req.Id == 0 { - _, err = s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) + _, err := s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId) if err != nil { return nil, errors.WithMessage(err, "get application by name and service_id") } @@ -189,7 +173,7 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return result[0], nil } - _, err = s.appRepo.GetApplicationById(ctx, req.Id) + _, err := s.appRepo.GetApplicationById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get application by id") } From 1ec17938e0a24f8d45f7a812796d356fee03f782 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 10:50:32 +0300 Subject: [PATCH 18/30] MSP-5186 Update concatCluster param type --- routes/routes.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/routes/routes.go b/routes/routes.go index baac098..8c4fd50 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -29,7 +29,7 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux { } func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { - return concatCluster([][]cluster.EndpointDescriptor{ + return concatCluster( secureCluster(c), accessListCluster(c), domainCluster(c), @@ -208,7 +208,7 @@ func tokenCluster(c Controllers) []cluster.EndpointDescriptor { } } -func concatCluster(clusters [][]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { +func concatCluster(clusters ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { var result []cluster.EndpointDescriptor for _, c := range clusters { result = append(result, c...) From d46980910762e3a054bd4413d91b30939dc0a129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 11:48:00 +0300 Subject: [PATCH 19/30] MSP-5186 Move repository consts --- repository/application.go | 8 -------- repository/consts.go | 10 ++++++++++ 2 files changed, 10 insertions(+), 8 deletions(-) create mode 100644 repository/consts.go diff --git a/repository/application.go b/repository/application.go index d30375c..4f1c6f3 100644 --- a/repository/application.go +++ b/repository/application.go @@ -14,14 +14,6 @@ import ( "github.com/txix-open/isp-kit/db/query" ) -const ( - pgUniqueViolationErrorCode = "23505" - pgFkViolationErrorCode = "23503" - applicationPkConstrainName = "application_pkey" - applicationUniqueNameConstrainName = "uq_name_application_group_id" - applicationFkAppGroupConstraintName = "fk_application_group_id" -) - type Application struct { db db.DB } diff --git a/repository/consts.go b/repository/consts.go new file mode 100644 index 0000000..cef95fd --- /dev/null +++ b/repository/consts.go @@ -0,0 +1,10 @@ +package repository + +const ( + pgUniqueViolationErrorCode = "23505" + pgFkViolationErrorCode = "23503" + + applicationPkConstrainName = "application_pkey" + applicationUniqueNameConstrainName = "uq_name_application_group_id" + applicationFkAppGroupConstraintName = "fk_application_group_id" +) From 3a94df1eb0749531356b25278d7e37d5ff39e67f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 11:49:09 +0300 Subject: [PATCH 20/30] MSP-5186 Swag fmt --- controller/access_list.go | 63 ++++++------ controller/application.go | 207 ++++++++++++++++++++------------------ controller/domain.go | 80 ++++++++------- controller/secure.go | 38 +++---- controller/service.go | 105 ++++++++++--------- controller/token.go | 76 +++++++------- main.go | 12 +-- 7 files changed, 304 insertions(+), 277 deletions(-) diff --git a/controller/access_list.go b/controller/access_list.go index 0a49998..ba53652 100644 --- a/controller/access_list.go +++ b/controller/access_list.go @@ -26,16 +26,17 @@ func NewAccessList(service AccessListService) AccessList { } // GetById godoc -// @Tags accessList -// @Summary Получить список доступности методов для приложения -// @Description Возвращает список методов для приложения, для которых заданы настройки доступа -// @Accept json -// @Produce json -// @Param body body domain.Identity false "идентификатор приложения" -// @Success 200 {array} domain.MethodInfo "список доступности методов" -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /access_list/get_by_id [POST] +// +// @Tags accessList +// @Summary Получить список доступности методов для приложения +// @Description Возвращает список методов для приложения, для которых заданы настройки доступа +// @Accept json +// @Produce json +// @Param body body domain.Identity false "идентификатор приложения" +// @Success 200 {array} domain.MethodInfo "список доступности методов" +// @Failure 404 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /access_list/get_by_id [POST] func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) { result, err := c.service.GetById(ctx, req.Id) switch { @@ -49,16 +50,17 @@ func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain. } // SetOne godoc -// @Tags accessList -// @Summary Настроить доступность метода для приложения -// @Description Возвращает количество измененных строк -// @Accept json -// @Produce json -// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа" -// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк" -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /access_list/set_one [POST] +// +// @Tags accessList +// @Summary Настроить доступность метода для приложения +// @Description Возвращает количество измененных строк +// @Accept json +// @Produce json +// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа" +// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк" +// @Failure 404 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /access_list/set_one [POST] func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) { result, err := c.service.SetOne(ctx, req) switch { @@ -72,16 +74,17 @@ func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneReque } // SetList godoc -// @Tags accessList -// @Summary Настроить доступность списка методов для приложения -// @Description Возвращает список методов для приложения, для которых заданы настройки доступа -// @Accept json -// @Produce json -// @Param body body domain.AccessListSetListRequest false "объект настройки доступа" -// @Success 200 {array} domain.MethodInfo "список доступности методов" -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /access_list/set_list [POST] +// +// @Tags accessList +// @Summary Настроить доступность списка методов для приложения +// @Description Возвращает список методов для приложения, для которых заданы настройки доступа +// @Accept json +// @Produce json +// @Param body body domain.AccessListSetListRequest false "объект настройки доступа" +// @Success 200 {array} domain.MethodInfo "список доступности методов" +// @Failure 404 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /access_list/set_list [POST] func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) { result, err := c.service.SetList(ctx, req) switch { diff --git a/controller/application.go b/controller/application.go index ad30bdc..c91ab89 100644 --- a/controller/application.go +++ b/controller/application.go @@ -34,17 +34,18 @@ func NewApplication(service ApplicationService) Application { } // GetById godoc -// @Tags application -// @Summary Получить приложение по идентификатору -// @Description Возвращает описание приложения по его идентификатору -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор приложения" -// @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /application/get_application_by_id [POST] +// +// @Tags application +// @Summary Получить приложение по идентификатору +// @Description Возвращает описание приложения по его идентификатору +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор приложения" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/get_application_by_id [POST] func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) { result, err := c.service.GetById(ctx, req.Id) switch { @@ -58,59 +59,63 @@ func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain. } // GetByIdList godoc -// @Tags application -// @Summary Получить список приложений -// @Description Возвращает массив приложений с токенами по их идентификаторам -// @Accept json -// @Produce json -// @Param body body []integer false "Массив идентификаторов приложений" -// @Success 200 {array} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError -// @Router /application/get_applications [POST] +// +// @Tags application +// @Summary Получить список приложений +// @Description Возвращает массив приложений с токенами по их идентификаторам +// @Accept json +// @Produce json +// @Param body body []integer false "Массив идентификаторов приложений" +// @Success 200 {array} domain.ApplicationWithTokens +// @Failure 500 {object} domain.GrpcError +// @Router /application/get_applications [POST] func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) { return c.service.GetByIdList(ctx, req) } // GetByServiceId godoc -// @Tags application -// @Summary Получить список приложений по идентификатору сервиса -// @Description Возвращает список приложений по запрошенному идентификатору сервиса -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор сервиса" -// @Success 200 {array} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError -// @Router /application/get_applications_by_service_id [POST] +// +// @Tags application +// @Summary Получить список приложений по идентификатору сервиса +// @Description Возвращает список приложений по запрошенному идентификатору сервиса +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор сервиса" +// @Success 200 {array} domain.ApplicationWithTokens +// @Failure 500 {object} domain.GrpcError +// @Router /application/get_applications_by_service_id [POST] func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) { return c.service.GetByServiceId(ctx, req.Id) } // GetSystemTree godoc -// @Tags application -// @Summary Метод получения системного дерева -// @Description Возвращает описание взаимосвязей сервисов и приложений -// @Accept json -// @Produce json -// @Success 200 {array} domain.DomainWithService -// @Failure 500 {object} domain.GrpcError -// @Router /application/get_system_tree [POST] +// +// @Tags application +// @Summary Метод получения системного дерева +// @Description Возвращает описание взаимосвязей сервисов и приложений +// @Accept json +// @Produce json +// @Success 200 {array} domain.DomainWithService +// @Failure 500 {object} domain.GrpcError +// @Router /application/get_system_tree [POST] func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) { return c.service.SystemTree(ctx, domain.DefaultSystemId) } // CreateUpdate godoc -// @Tags application -// @Summary Создать/обновить приложение -// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу -// @Accept json -// @Produce json -// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения" -// @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /application/create_update_application [POST] +// +// @Tags application +// @Summary Создать/обновить приложение +// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу +// @Accept json +// @Produce json +// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/create_update_application [POST] func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.CreateUpdate(ctx, req) switch { @@ -128,16 +133,17 @@ func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre } // Delete godoc -// @Tags application -// @Summary Удалить приложения -// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений -// @Accept json -// @Produce json -// @Param body body []integer false "Массив идентификаторов приложений" -// @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /application/delete_applications [POST] +// +// @Tags application +// @Summary Удалить приложения +// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений +// @Accept json +// @Produce json +// @Param body body []integer false "Массив идентификаторов приложений" +// @Success 200 {object} domain.DeleteResponse +// @Failure 400 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/delete_applications [POST] func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { if len(req) == 0 { return nil, status.Errorf(codes.InvalidArgument, "At least one id are required") @@ -154,44 +160,46 @@ func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteRespo } // NextId godoc -// @Tags application -// @Summary Получить следующий идентификатор приложения -// @Description Возвращает следующий идентификатор приложения -// @Accept json -// @Produce json -// @Success 200 {object} integer -// @Failure 500 {object} domain.GrpcError -// @Router /application/next_id [POST] +// +// @Tags application +// @Summary Получить следующий идентификатор приложения +// @Description Возвращает следующий идентификатор приложения +// @Accept json +// @Produce json +// @Success 200 {object} integer +// @Failure 500 {object} domain.GrpcError +// @Router /application/next_id [POST] func (c Application) NextId(ctx context.Context) (int, error) { return c.service.NextId(ctx) } // GetAll godoc -// @Tags application -// @Summary Получить список приложений -// @Description Возвращает список приложений -// @Accept json -// @Produce json -// @Success 200 {array} domain.Application -// @Failure 500 {object} domain.GrpcError -// @Router /application/get_all [POST] +// +// @Tags application +// @Summary Получить список приложений +// @Description Возвращает список приложений +// @Accept json +// @Produce json +// @Success 200 {array} domain.Application +// @Failure 500 {object} domain.GrpcError +// @Router /application/get_all [POST] func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { return c.service.GetAll(ctx) } // Create godoc -// @Tags application -// @Summary Создать приложение -// @Description Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` существует, то возвращает ошибку -// @Accept json -// @Produce json -// @Param body body domain.CreateApplicationRequest true "Объект приложения" -// @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /application/create_application [POST] +// +// @Tags application +// @Summary Создать приложение +// @Description Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` существует, то возвращает ошибку +// @Accept json +// @Produce json +// @Param body body domain.CreateApplicationRequest true "Объект приложения" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 400 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/create_application [POST] func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.Create(ctx, req) switch { @@ -207,18 +215,19 @@ func (c Application) Create(ctx context.Context, req domain.CreateApplicationReq } // Update godoc -// @Tags application -// @Summary Обновить приложение -// @Description Если приложение с связкой `applicationGroupId`-`name` существует или приложение не найдено, то возвращает ошибку -// @Accept json -// @Produce json -// @Param body body domain.UpdateApplicationRequest true "Объект приложения" -// @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /application/update_application [POST] +// +// @Tags application +// @Summary Обновить приложение +// @Description Если приложение с связкой `applicationGroupId`-`name` существует или приложение не найдено, то возвращает ошибку +// @Accept json +// @Produce json +// @Param body body domain.UpdateApplicationRequest true "Объект приложения" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application/update_application [POST] func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.Update(ctx, req) switch { diff --git a/controller/domain.go b/controller/domain.go index 75ef850..4e479f9 100644 --- a/controller/domain.go +++ b/controller/domain.go @@ -27,16 +27,17 @@ func NewDomain(service DomainService) Domain { } // GetById godoc -// @Tags domain -// @Summary Получить домен по идентификатору -// @Description Возвращает описание домена по его идентификатору -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор домена" -// @Success 200 {object} domain.Domain -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /domain/get_domain_by_id [POST] +// +// @Tags domain +// @Summary Получить домен по идентификатору +// @Description Возвращает описание домена по его идентификатору +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор домена" +// @Success 200 {object} domain.Domain +// @Failure 404 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /domain/get_domain_by_id [POST] func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) { result, err := c.service.GetById(ctx, req.Id) switch { @@ -50,29 +51,31 @@ func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domai } // GetBySystemId godoc -// @Tags domain -// @Summary Получить домены по идентификатору системы -// @Description Возвращает список доменов по системному идентификатору -// @Accept json -// @Produce json -// @Param body body integer false "Идентификатор системы" -// @Success 200 {array} domain.Domain -// @Failure 500 {object} domain.GrpcError -// @Router /domain/get_domains_by_system_id [POST] +// +// @Tags domain +// @Summary Получить домены по идентификатору системы +// @Description Возвращает список доменов по системному идентификатору +// @Accept json +// @Produce json +// @Param body body integer false "Идентификатор системы" +// @Success 200 {array} domain.Domain +// @Failure 500 {object} domain.GrpcError +// @Router /domain/get_domains_by_system_id [POST] func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) { return c.service.GetBySystemId(ctx, domain.DefaultSystemId) } // CreateUpdate godoc -// @Tags domain -// @Summary Создать/обновить домен -// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу -// @Accept json -// @Produce json -// @Param body body domain.DomainCreateUpdateRequest true "Объект домена" -// @Success 200 {object} domain.Domain -// @Failure 500 {object} domain.GrpcError -// @Router /domain/create_update_domain [POST] +// +// @Tags domain +// @Summary Создать/обновить домен +// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу +// @Accept json +// @Produce json +// @Param body body domain.DomainCreateUpdateRequest true "Объект домена" +// @Success 200 {object} domain.Domain +// @Failure 500 {object} domain.GrpcError +// @Router /domain/create_update_domain [POST] func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) { result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId) switch { @@ -90,16 +93,17 @@ func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR } // Delete godoc -// @Tags domain -// @Summary Удаление доменов -// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов -// @Accept json -// @Produce json -// @Param body body []integer false "Массив идентификаторов доменов" -// @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /domain/delete_domains [POST] +// +// @Tags domain +// @Summary Удаление доменов +// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов +// @Accept json +// @Produce json +// @Param body body []integer false "Массив идентификаторов доменов" +// @Success 200 {object} domain.DeleteResponse +// @Failure 400 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /domain/delete_domains [POST] func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { if len(req) == 0 { return nil, status.Errorf(codes.InvalidArgument, "at least one id are required") diff --git a/controller/secure.go b/controller/secure.go index b4a6de5..f0eb07b 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -23,15 +23,16 @@ func NewSecure(service SecureService) Secure { } // Authenticate godoc -// @Tags secure -// @Summary Метод аутентификации токена -// @Description Проверяет наличие токена в системе, -// @Accept json -// @Produce json -// @Param body body domain.AuthenticateRequest true "Тело запроса" -// @Success 200 {array} domain.AuthenticateResponse -// @Failure 500 {object} domain.GrpcError -// @Router /secure/authenticate [POST] +// +// @Tags secure +// @Summary Метод аутентификации токена +// @Description Проверяет наличие токена в системе, +// @Accept json +// @Produce json +// @Param body body domain.AuthenticateRequest true "Тело запроса" +// @Success 200 {array} domain.AuthenticateResponse +// @Failure 500 {object} domain.GrpcError +// @Router /secure/authenticate [POST] func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) { result, err := c.service.Authenticate(ctx, req.Token) switch { @@ -56,15 +57,16 @@ func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest } // Authorize godoc -// @Tags secure -// @Summary Метод авторизации приложения -// @Description Проверяет доступ приложения к запрашиваемому ендпоинту -// @Accept json -// @Produce json -// @Param body body domain.AuthorizeRequest true "Тело запрос" -// @Success 200 {array} domain.AuthorizeResponse -// @Failure 500 {object} domain.GrpcError -// @Router /secure/authorize [POST] +// +// @Tags secure +// @Summary Метод авторизации приложения +// @Description Проверяет доступ приложения к запрашиваемому ендпоинту +// @Accept json +// @Produce json +// @Param body body domain.AuthorizeRequest true "Тело запрос" +// @Success 200 {array} domain.AuthorizeResponse +// @Failure 500 {object} domain.GrpcError +// @Router /secure/authorize [POST] func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) { result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint) switch { diff --git a/controller/service.go b/controller/service.go index 973cf62..6117153 100644 --- a/controller/service.go +++ b/controller/service.go @@ -29,16 +29,17 @@ func NewService(service ServiceService) Service { } // GetById godoc -// @Tags service -// @Summary Получить сервис по идентификатору -// @Description Возвращает описание сервиса по его идентификатору -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор сервиса" -// @Success 200 {object} domain.Service -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /service/get_service_by_id [POST] +// +// @Tags service +// @Summary Получить сервис по идентификатору +// @Description Возвращает описание сервиса по его идентификатору +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор сервиса" +// @Success 200 {object} domain.Service +// @Failure 404 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /service/get_service_by_id [POST] func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) { result, err := c.service.GetById(ctx, req.Id) switch { @@ -52,46 +53,49 @@ func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Serv } // Get godoc -// @Tags service -// @Summary Получить список сервисов -// @Description Возвращает список сервисов по их идентификаторам -// @Accept json -// @Produce json -// @Param body body []integer false "Массив идентификаторов сервисов" -// @Success 200 {array} domain.Service -// @Failure 500 {object} domain.GrpcError -// @Router /service/get_service [POST] +// +// @Tags service +// @Summary Получить список сервисов +// @Description Возвращает список сервисов по их идентификаторам +// @Accept json +// @Produce json +// @Param body body []integer false "Массив идентификаторов сервисов" +// @Success 200 {array} domain.Service +// @Failure 500 {object} domain.GrpcError +// @Router /service/get_service [POST] func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) { return c.service.GetByIdList(ctx, req) } // GetByDomainId godoc -// @Tags service -// @Summary Получить список сервисов по идентификатору домена -// @Description Возвращает список сервисов по идентификатору домена -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор домена" -// @Success 200 {array} domain.Service -// @Failure 500 {object} domain.GrpcError -// @Router /service/get_services_by_domain_id [POST] +// +// @Tags service +// @Summary Получить список сервисов по идентификатору домена +// @Description Возвращает список сервисов по идентификатору домена +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор домена" +// @Success 200 {array} domain.Service +// @Failure 500 {object} domain.GrpcError +// @Router /service/get_services_by_domain_id [POST] func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) { return c.service.GetByDomainId(ctx, req.Id) } // CreateUpdate godoc -// @Tags service -// @Summary Создать/обновить сервис -// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу -// @Accept json -// @Produce json -// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса" -// @Success 200 {object} domain.Service -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /service/create_update_service [POST] +// +// @Tags service +// @Summary Создать/обновить сервис +// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу +// @Accept json +// @Produce json +// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса" +// @Success 200 {object} domain.Service +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /service/create_update_service [POST] func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { result, err := c.service.CreateUpdate(ctx, req) switch { @@ -109,16 +113,17 @@ func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat } // Delete godoc -// @Tags service -// @Summary Удалить сервисы -// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов -// @Accept json -// @Produce json -// @Param body body []integer true "Массив идентификаторов сервисов" -// @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError -// @Router /service/delete_service [POST] +// +// @Tags service +// @Summary Удалить сервисы +// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов +// @Accept json +// @Produce json +// @Param body body []integer true "Массив идентификаторов сервисов" +// @Success 200 {object} domain.DeleteResponse +// @Failure 400 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /service/delete_service [POST] func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { if len(req) == 0 { return nil, status.Error(codes.InvalidArgument, "at least one id are required") diff --git a/controller/token.go b/controller/token.go index e78eca7..fdf64ab 100644 --- a/controller/token.go +++ b/controller/token.go @@ -28,29 +28,31 @@ func NewToken(service TokenService) Token { } // GetByAppId godoc -// @Tags token -// @Summary Получить токены по идентификатору приложения -// @Description Возвращает список токенов, привязанных к приложению -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор приложения" -// @Success 200 {array} entity.Token -// @Failure 500 {object} domain.GrpcError -// @Router /token/get_tokens_by_app_id [POST] +// +// @Tags token +// @Summary Получить токены по идентификатору приложения +// @Description Возвращает список токенов, привязанных к приложению +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор приложения" +// @Success 200 {array} entity.Token +// @Failure 500 {object} domain.GrpcError +// @Router /token/get_tokens_by_app_id [POST] func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) { return c.service.GetByAppId(ctx, req.Id) } // Create godoc -// @Tags token -// @Summary Создать токен -// @Description Создает токен и привязывает его к приложению -// @Accept json -// @Produce json -// @Param body body domain.TokenCreateRequest true "Объект создания токена" -// @Success 200 {object} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError -// @Router /token/create_token [POST] +// +// @Tags token +// @Summary Создать токен +// @Description Создает токен и привязывает его к приложению +// @Accept json +// @Produce json +// @Param body body domain.TokenCreateRequest true "Объект создания токена" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 500 {object} domain.GrpcError +// @Router /token/create_token [POST] func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.Create(ctx, req) switch { @@ -68,29 +70,31 @@ func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma } // Revoke godoc -// @Tags token -// @Summary Отозвать токены -// @Description Отвязывает токены от приложений и удаляет их -// @Accept json -// @Produce json -// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов" -// @Success 200 {object} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError -// @Router /token/revoke_tokens [POST] +// +// @Tags token +// @Summary Отозвать токены +// @Description Отвязывает токены от приложений и удаляет их +// @Accept json +// @Produce json +// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов" +// @Success 200 {object} domain.ApplicationWithTokens +// @Failure 500 {object} domain.GrpcError +// @Router /token/revoke_tokens [POST] func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) { return c.service.Revoke(ctx, req) } // RevokeForApp godoc -// @Tags token -// @Summary Отозвать токены для приложения -// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения -// @Accept json -// @Produce json -// @Param body body domain.Identity true "Идентификатор приложения" -// @Success 200 {object} domain.DeleteResponse -// @Failure 500 {object} domain.GrpcError -// @Router /token/revoke_tokens_for_app [POST] +// +// @Tags token +// @Summary Отозвать токены для приложения +// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения +// @Accept json +// @Produce json +// @Param body body domain.Identity true "Идентификатор приложения" +// @Success 200 {object} domain.DeleteResponse +// @Failure 500 {object} domain.GrpcError +// @Router /token/revoke_tokens_for_app [POST] func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) { return c.service.RevokeByAppId(ctx, req.Id) } diff --git a/main.go b/main.go index c1616c4..9a43ca5 100644 --- a/main.go +++ b/main.go @@ -12,14 +12,14 @@ var ( version = "1.0.0" ) -// @title isp-system-service -// @version 1.0.0 -// @description Сервис управления реестром внешних приложений и токенами аутентификации +// @title isp-system-service +// @version 1.0.0 +// @description Сервис управления реестром внешних приложений и токенами аутентификации -// @license.name GNU GPL v3.0 +// @license.name GNU GPL v3.0 -// @host localhost:9000 -// @BasePath /api/system +// @host localhost:9000 +// @BasePath /api/system //go:generate swag init --parseDependency //go:generate rm -f docs/swagger.json From 1e281280e67e6d71a7f310a5b0aba31a6ef3e685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 11:54:34 +0300 Subject: [PATCH 21/30] MSP-5186 Fix typo --- repository/application.go | 4 ++-- repository/consts.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/repository/application.go b/repository/application.go index 4f1c6f3..7ea334c 100644 --- a/repository/application.go +++ b/repository/application.go @@ -134,7 +134,7 @@ func (r Application) UpdateApplication( var pgErr *pgconn.PgError switch { case errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolationErrorCode && - pgErr.ConstraintName == applicationUniqueNameConstrainName: + pgErr.ConstraintName == applicationUniqueNameConstraintName: return nil, domain.ErrApplicationDuplicateName case errors.Is(err, sql.ErrNoRows): return nil, domain.ErrApplicationNotFound @@ -206,7 +206,7 @@ func (r Application) handleCreateError(err error, q string) error { switch pgErr.ConstraintName { case applicationPkConstrainName: return domain.ErrApplicationDuplicateId - case applicationUniqueNameConstrainName: + case applicationUniqueNameConstraintName: return domain.ErrApplicationDuplicateName } case pgErr.Code == pgFkViolationErrorCode && pgErr.ConstraintName == applicationFkAppGroupConstraintName: diff --git a/repository/consts.go b/repository/consts.go index cef95fd..6fb0245 100644 --- a/repository/consts.go +++ b/repository/consts.go @@ -5,6 +5,6 @@ const ( pgFkViolationErrorCode = "23503" applicationPkConstrainName = "application_pkey" - applicationUniqueNameConstrainName = "uq_name_application_group_id" + applicationUniqueNameConstraintName = "uq_name_application_group_id" applicationFkAppGroupConstraintName = "fk_application_group_id" ) From 59f3dc0d2f20d02fb0922d68876fa90c2c1d0fbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 11:55:47 +0300 Subject: [PATCH 22/30] MSP-5186 Simplify constraint error checks --- repository/application.go | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/repository/application.go b/repository/application.go index 7ea334c..430e61b 100644 --- a/repository/application.go +++ b/repository/application.go @@ -133,8 +133,7 @@ func (r Application) UpdateApplication( err := r.db.SelectRow(ctx, &result, q, id, name, description) var pgErr *pgconn.PgError switch { - case errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolationErrorCode && - pgErr.ConstraintName == applicationUniqueNameConstraintName: + case errors.As(err, &pgErr) && pgErr.ConstraintName == applicationUniqueNameConstraintName: return nil, domain.ErrApplicationDuplicateName case errors.Is(err, sql.ErrNoRows): return nil, domain.ErrApplicationNotFound @@ -201,15 +200,12 @@ func (r Application) handleCreateError(err error, q string) error { if !errors.As(err, &pgErr) { return errors.WithMessagef(err, "exec query %s", q) } - switch { - case pgErr.Code == pgUniqueViolationErrorCode: - switch pgErr.ConstraintName { - case applicationPkConstrainName: - return domain.ErrApplicationDuplicateId - case applicationUniqueNameConstraintName: - return domain.ErrApplicationDuplicateName - } - case pgErr.Code == pgFkViolationErrorCode && pgErr.ConstraintName == applicationFkAppGroupConstraintName: + switch pgErr.ConstraintName { + case applicationPkConstrainName: + return domain.ErrApplicationDuplicateId + case applicationUniqueNameConstraintName: + return domain.ErrApplicationDuplicateName + case applicationFkAppGroupConstraintName: return domain.ErrAppGroupNotFound } return errors.WithMessagef(err, "exec query %s", q) From cb50a6015611efb446ee39a6972888d8ea8c8c5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 12:31:00 +0300 Subject: [PATCH 23/30] MSP-5186 Implement AppGroup CRUD endpoints --- assembly/locator.go | 3 + controller/app_group.go | 108 +++++++++++++++++++ docs/swagger.yaml | 184 +++++++++++++++++++++++++++++++- domain/app_group.go | 26 +++++ repository/app_group.go | 14 ++- repository/consts.go | 5 +- routes/routes.go | 27 ++++- service/app_group.go | 69 ++++++++++++ service/service.go | 17 +-- tests/app_group_test.go | 225 ++++++++++++++++++++++++++++++++++++++++ 10 files changed, 651 insertions(+), 27 deletions(-) create mode 100644 controller/app_group.go create mode 100644 domain/app_group.go create mode 100644 service/app_group.go create mode 100644 tests/app_group_test.go diff --git a/assembly/locator.go b/assembly/locator.go index 88779ec..c191ddb 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -65,6 +65,8 @@ func (l Locator) Config(cfg conf.Remote) Config { serviceController := controller.NewService(serviceService) tokenController := controller.NewToken(tokenService) + appGroupService := service.NewAppGroup(appGroupRep) + appGroupController := controller.NewAppGroup(appGroupService) c := routes.Controllers{ Secure: secureController, AccessList: accessListController, @@ -72,6 +74,7 @@ func (l Locator) Config(cfg conf.Remote) Config { Service: serviceController, Application: applicationController, Token: tokenController, + AppGroup: appGroupController, } mapper := endpoint.DefaultWrapper(l.logger, grpclog.Log(l.logger, true)) server := routes.Handler(mapper, c) diff --git a/controller/app_group.go b/controller/app_group.go new file mode 100644 index 0000000..99a7f22 --- /dev/null +++ b/controller/app_group.go @@ -0,0 +1,108 @@ +package controller + +import ( + "context" + "isp-system-service/domain" + + "github.com/pkg/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type AppGroupService interface { + Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) + Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) + DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) + GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error) +} + +type AppGroup struct { + service AppGroupService +} + +func NewAppGroup(service AppGroupService) AppGroup { + return AppGroup{ + service: service, + } +} + +// Create godoc +// +// @Tags application_group +// @Summary Создать группу приложений +// @Description Если группа приложений таким именем существует, возвращает ошибку +// @Accept json +// @Produce json +// @Param body body domain.CreateAppGroupRequest true "Объект группы приложений" +// @Success 200 {object} domain.AppGroup +// @Failure 400 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application_group/create [POST] +func (c AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) { + result, err := c.service.Create(ctx, req) + switch { + case errors.Is(err, domain.ErrAppGroupDuplicateName): + return nil, status.Errorf(codes.AlreadyExists, "application group with name %s already exists", req.Name) + default: + return result, err + } +} + +// Update godoc +// +// @Tags application_group +// @Summary Обновить группу приложений +// @Description Если группа приложений таким именем существует или группы приложений с указанным id не существует, возвращает ошибку +// @Accept json +// @Produce json +// @Param body body domain.UpdateAppGroupRequest true "Объект группы приложений" +// @Success 200 {object} domain.AppGroup +// @Failure 400 {object} domain.GrpcError +// @Failure 404 {object} domain.GrpcError +// @Failure 409 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application_group/update [POST] +func (c AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) { + result, err := c.service.Update(ctx, req) + switch { + case errors.Is(err, domain.ErrAppGroupDuplicateName): + return nil, status.Errorf(codes.AlreadyExists, "application group with name %s already exists", req.Name) + case errors.Is(err, domain.ErrAppGroupNotFound): + return nil, status.Errorf(codes.NotFound, "application group with id %d not found", req.Id) + default: + return result, err + } +} + +// DeleteList godoc +// +// @Tags application_group +// @Summary Удалить группы приложений +// @Description Удаляет группы приложений по списку их идентификаторов, возвращает количество удаленных групп приложений +// @Accept json +// @Produce json +// @Param body body domain.IdListRequest true "список идентификаторов групп приложений" +// @Success 200 {object} domain.DeleteResponse +// @Failure 400 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application_group/delete_list [POST] +func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) { + return c.service.DeleteList(ctx, req) +} + +// GetByIdList godoc +// +// @Tags application_group +// @Summary Получить группы приложений по списку идентификаторов +// @Description Возвращает группы приложений с указанными идентификаторами +// @Accept json +// @Produce json +// @Param body body domain.IdListRequest true "список идентификаторов групп приложений" +// @Success 200 {array} domain.AppGroup +// @Failure 400 {object} domain.GrpcError +// @Failure 500 {object} domain.GrpcError +// @Router /application_group/get_by_id_list [POST] +func (c AppGroup) GetByIdList(ctx context.Context, req domain.IdListRequest) ([]domain.AppGroup, error) { + return c.service.GetByIdList(ctx, req.IdList) +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index bafbb57..6009871 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -30,6 +30,19 @@ definitions: count: type: integer type: object + domain.AppGroup: + properties: + createdAt: + type: string + description: + type: string + id: + type: integer + name: + type: string + updatedAt: + type: string + type: object domain.Application: properties: createdAt: @@ -133,6 +146,15 @@ definitions: authorized: type: boolean type: object + domain.CreateAppGroupRequest: + properties: + description: + type: string + name: + type: string + required: + - name + type: object domain.CreateApplicationRequest: properties: applicationGroupId: @@ -207,6 +229,16 @@ definitions: errorMessage: type: string type: object + domain.IdListRequest: + properties: + idList: + items: + type: integer + minItems: 1 + type: array + required: + - idList + type: object domain.Identity: properties: id: @@ -295,6 +327,18 @@ definitions: required: - appId type: object + domain.UpdateAppGroupRequest: + properties: + description: + type: string + id: + type: integer + name: + type: string + required: + - id + - name + type: object domain.UpdateApplicationRequest: properties: description: @@ -444,10 +488,6 @@ paths: description: Bad Request schema: $ref: '#/definitions/domain.GrpcError' - "404": - description: Not Found - schema: - $ref: '#/definitions/domain.GrpcError' "409": description: Conflict schema: @@ -721,6 +761,142 @@ paths: summary: Обновить приложение tags: - application + /application_group/create: + post: + consumes: + - application/json + description: Если группа приложений таким именем существует, возвращает ошибку + parameters: + - description: Объект группы приложений + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.CreateAppGroupRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.AppGroup' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.GrpcError' + "409": + description: Conflict + schema: + $ref: '#/definitions/domain.GrpcError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Создать группу приложений + tags: + - application_group + /application_group/delete_list: + post: + consumes: + - application/json + description: Удаляет группы приложений по списку их идентификаторов, возвращает + количество удаленных групп приложений + parameters: + - description: список идентификаторов групп приложений + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.IdListRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.DeleteResponse' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.GrpcError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Удалить группы приложений + tags: + - application_group + /application_group/get_by_id_list: + post: + consumes: + - application/json + description: Возвращает группы приложений с указанными идентификаторами + parameters: + - description: список идентификаторов групп приложений + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.IdListRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/domain.AppGroup' + type: array + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.GrpcError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Получить группы приложений по списку идентификаторов + tags: + - application_group + /application_group/update: + post: + consumes: + - application/json + description: Если группа приложений таким именем существует или группы приложений + с указанным id не существует, возвращает ошибку + parameters: + - description: Объект группы приложений + in: body + name: body + required: true + schema: + $ref: '#/definitions/domain.UpdateAppGroupRequest' + produces: + - application/json + responses: + "200": + description: OK + schema: + $ref: '#/definitions/domain.AppGroup' + "400": + description: Bad Request + schema: + $ref: '#/definitions/domain.GrpcError' + "404": + description: Not Found + schema: + $ref: '#/definitions/domain.GrpcError' + "409": + description: Conflict + schema: + $ref: '#/definitions/domain.GrpcError' + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/domain.GrpcError' + summary: Обновить группу приложений + tags: + - application_group /domain/create_update_domain: post: consumes: diff --git a/domain/app_group.go b/domain/app_group.go new file mode 100644 index 0000000..44c59e1 --- /dev/null +++ b/domain/app_group.go @@ -0,0 +1,26 @@ +package domain + +import "time" + +type AppGroup struct { + Id int + Name string + Description string + CreatedAt time.Time + UpdatedAt time.Time +} + +type CreateAppGroupRequest struct { + Name string `validate:"required"` + Description string +} + +type UpdateAppGroupRequest struct { + Id int `validate:"required"` + Name string `validate:"required"` + Description string +} + +type IdListRequest struct { + IdList []int `validate:"required,min=1"` +} diff --git a/repository/app_group.go b/repository/app_group.go index bd853c3..6203411 100644 --- a/repository/app_group.go +++ b/repository/app_group.go @@ -8,6 +8,7 @@ import ( "isp-system-service/entity" "github.com/Masterminds/squirrel" + "github.com/jackc/pgx/v5/pgconn" "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db/query" @@ -104,15 +105,19 @@ func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, INSERT INTO application_group (name, description, domain_id) VALUES ($1, $2, $3) + ON CONFLICT (name, domain_id) DO NOTHING RETURNING id, name, description, domain_id, created_at, updated_at ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, desc, domainId) - if err != nil { + switch { + case errors.Is(err, sql.ErrNoRows): + return nil, domain.ErrAppGroupDuplicateName + case err != nil: return nil, errors.WithMessagef(err, "exec query %s", q) + default: + return &result, nil } - - return &result, nil } func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) { @@ -124,7 +129,10 @@ func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, descr ` result := entity.AppGroup{} err := r.db.SelectRow(ctx, &result, q, name, description, id) + var pgErr *pgconn.PgError switch { + case errors.As(err, &pgErr) && pgErr.ConstraintName == applicationGroupUniqueNameConstraint: + return nil, domain.ErrAppGroupDuplicateName case errors.Is(err, sql.ErrNoRows): return nil, domain.ErrAppGroupNotFound case err != nil: diff --git a/repository/consts.go b/repository/consts.go index 6fb0245..76aa757 100644 --- a/repository/consts.go +++ b/repository/consts.go @@ -1,10 +1,9 @@ package repository const ( - pgUniqueViolationErrorCode = "23505" - pgFkViolationErrorCode = "23503" - applicationPkConstrainName = "application_pkey" applicationUniqueNameConstraintName = "uq_name_application_group_id" applicationFkAppGroupConstraintName = "fk_application_group_id" + + applicationGroupUniqueNameConstraint = "uq_name_domain_name" ) diff --git a/routes/routes.go b/routes/routes.go index 8c4fd50..5200ba5 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -12,6 +12,7 @@ type Controllers struct { Domain controller.Domain Service controller.Service Application controller.Application + AppGroup controller.AppGroup Token controller.Token Secure controller.Secure } @@ -36,7 +37,8 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { serviceCluster(c), applicationCluster(c), tokenCluster(c), - }) + applicationGroupCluster(c), + ) } func secureCluster(c Controllers) []cluster.EndpointDescriptor { @@ -99,6 +101,7 @@ func domainCluster(c Controllers) []cluster.EndpointDescriptor { } } +// deprecated func serviceCluster(c Controllers) []cluster.EndpointDescriptor { return []cluster.EndpointDescriptor{ { @@ -208,6 +211,28 @@ func tokenCluster(c Controllers) []cluster.EndpointDescriptor { } } +func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor { + return []cluster.EndpointDescriptor{ + { + Path: "system/application_group/create", + Inner: true, + Handler: c.AppGroup.Create, + }, { + Path: "system/application_group/update", + Inner: true, + Handler: c.AppGroup.Update, + }, { + Path: "system/application_group/delete_list", + Inner: true, + Handler: c.AppGroup.DeleteList, + }, { + Path: "system/application_group/get_by_id_list", + Inner: true, + Handler: c.AppGroup.GetByIdList, + }, + } +} + func concatCluster(clusters ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { var result []cluster.EndpointDescriptor for _, c := range clusters { diff --git a/service/app_group.go b/service/app_group.go new file mode 100644 index 0000000..5538f70 --- /dev/null +++ b/service/app_group.go @@ -0,0 +1,69 @@ +package service + +import ( + "context" + "isp-system-service/domain" + "isp-system-service/entity" + + "github.com/pkg/errors" +) + +type AppGroup struct { + repo AppGroupRepo +} + +func NewAppGroup(repo AppGroupRepo) AppGroup { + return AppGroup{ + repo: repo, + } +} + +func (s AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) { + appGroup, err := s.repo.CreateAppGroup(ctx, req.Name, req.Description, 1) + if err != nil { + return nil, errors.WithMessage(err, "create appGroup") + } + converted := s.convertAppGroup(*appGroup) + return &converted, nil +} + +func (s AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) { + appGroup, err := s.repo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description) + if err != nil { + return nil, errors.WithMessage(err, "update appGroup") + } + converted := s.convertAppGroup(*appGroup) + return &converted, nil +} + +func (s AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) { + deleted, err := s.repo.DeleteAppGroup(ctx, req.IdList) + if err != nil { + return nil, errors.WithMessage(err, "delete appGroup") + } + return &domain.DeleteResponse{ + Deleted: deleted, + }, nil +} + +func (s AppGroup) GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error) { + appGroups, err := s.repo.GetAppGroupByIdList(ctx, idList) + if err != nil { + return nil, errors.WithMessage(err, "get appGroups by id list") + } + result := make([]domain.AppGroup, 0, len(appGroups)) + for _, appGroup := range appGroups { + result = append(result, s.convertAppGroup(appGroup)) + } + return result, nil +} + +func (s AppGroup) convertAppGroup(appGroup entity.AppGroup) domain.AppGroup { + return domain.AppGroup{ + Id: appGroup.Id, + Name: appGroup.Name, + Description: *appGroup.Description, + CreatedAt: appGroup.CreatedAt, + UpdatedAt: appGroup.UpdatedAt, + } +} diff --git a/service/service.go b/service/service.go index fd0ac21..659746e 100644 --- a/service/service.go +++ b/service/service.go @@ -63,23 +63,12 @@ func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Serv func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { req.DomainId = 1 // temporary use only 1 domain, soon domain entity will be removed - existed, err := s.serviceRepo.GetAppGroupByNameAndDomainId(ctx, req.Name, req.DomainId) - switch { - case errors.Is(err, domain.ErrAppGroupNotFound): - case err != nil: - return nil, errors.WithMessage(err, "get service by name and domain_id") - } - - _, err = s.domainRepo.GetDomainById(ctx, req.DomainId) + _, err := s.domainRepo.GetDomainById(ctx, req.DomainId) if err != nil { return nil, errors.WithMessage(err, "get domain by id") } if req.Id == 0 { - if existed != nil { - return nil, domain.ErrDomainDuplicateName - } - serviceEntity, err := s.serviceRepo.CreateAppGroup(ctx, req.Name, req.Description, req.DomainId) if err != nil { return nil, errors.WithMessage(err, "create service") @@ -89,10 +78,6 @@ func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat return &result, nil } - if existed != nil && existed.Id != req.Id { - return nil, domain.ErrDomainDuplicateName - } - _, err = s.serviceRepo.GetAppGroupById(ctx, req.Id) if err != nil { return nil, errors.WithMessage(err, "get service by id") diff --git a/tests/app_group_test.go b/tests/app_group_test.go new file mode 100644 index 0000000..2096d54 --- /dev/null +++ b/tests/app_group_test.go @@ -0,0 +1,225 @@ +package tests_test + +import ( + "isp-system-service/assembly" + "isp-system-service/conf" + "isp-system-service/domain" + "isp-system-service/entity" + "isp-system-service/repository" + "testing" + "time" + + "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" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +func TestApplicationGroupSuite(t *testing.T) { + t.Parallel() + suite.Run(t, &AppGroupSuite{}) +} + +type AppGroupSuite struct { + suite.Suite + test *test.Test + testDb *dbt.TestDb + domainRepo repository.Domain + appGroupRepo repository.AppGroup + api *client.Client +} + +func (s *AppGroupSuite) SetupTest() { + 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{}) + _, s.api = grpct.TestServer(s.test, config.Handler) + s.domainRepo = repository.NewDomain(s.testDb) + s.appGroupRepo = repository.NewAppGroup(s.testDb) + + q := ` + INSERT INTO domain + (id, name, description, system_id) + VALUES ($1, $2, $3, $4) + RETURNING id, name, description, system_id, created_at, updated_at + ` + _, err := s.testDb.Exec(s.T().Context(), q, 1, fake.It[string](), fake.It[string](), 1) + s.Require().NoError(err) +} + +func (s *AppGroupSuite) TestGetByIdList() { + toGenerate := 10 + appGroups := make([]domain.AppGroup, 0, toGenerate) + ids := make([]int, 0, toGenerate) + for range 10 { + appGroup := s.createAppGroup() + appGroups = append(appGroups, domain.AppGroup{ + Id: appGroup.Id, + Name: appGroup.Name, + Description: *appGroup.Description, + CreatedAt: time.Time{}, + UpdatedAt: time.Time{}, + }) + ids = append(ids, appGroup.Id) + } + result := []domain.AppGroup{} + apiReq := domain.IdListRequest{IdList: ids} + err := s.api.Invoke("system/application_group/get_by_id_list"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + for i := range result { + s.Require().NotEmpty(result[i].CreatedAt) + result[i].CreatedAt = time.Time{} + + s.Require().NotEmpty(result[i].UpdatedAt) + result[i].UpdatedAt = time.Time{} + } + s.Require().ElementsMatch(appGroups, result) +} + +func (s *AppGroupSuite) TestGetByIdList_NotFoundAppGroups() { + appGroup := s.createAppGroup() + result := []domain.AppGroup{} + + apiReq := domain.IdListRequest{IdList: []int{appGroup.Id + 1}} + err := s.api.Invoke("system/application_group/get_by_id_list"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + s.Require().Empty(result) +} + +func (s *AppGroupSuite) TestCreate_HappyPath() { + apiReq := domain.CreateAppGroupRequest{ + Name: fake.It[string](), + Description: fake.It[string](), + } + var result domain.AppGroup + err := s.api.Invoke("system/application_group/create"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + + s.Require().Equal(apiReq.Name, result.Name) + s.Require().Equal(apiReq.Description, result.Description) + + appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), result.Id) + s.Require().NoError(err) + s.Require().Equal(apiReq.Name, appGroup.Name) + s.Require().Equal(apiReq.Description, *appGroup.Description) +} + +func (s *AppGroupSuite) TestCreate_AppGroupNameNotUnique() { + appGroup := s.createAppGroup() + + apiReq := domain.CreateAppGroupRequest{ + Name: appGroup.Name, + Description: fake.It[string](), + } + var result domain.AppGroup + err := s.api.Invoke("system/application_group/create"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.AlreadyExists, statusErr.Code()) +} + +func (s *AppGroupSuite) TestUpdate_HappyPath() { + appGroupToUpdate := s.createAppGroup() + + apiReq := domain.UpdateAppGroupRequest{ + Id: appGroupToUpdate.Id, + Name: fake.It[string](), + Description: fake.It[string](), + } + var result domain.AppGroup + err := s.api.Invoke("system/application_group/update"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + + s.Require().Equal(apiReq.Name, result.Name) + s.Require().Equal(apiReq.Description, result.Description) + + appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), apiReq.Id) + s.Require().NoError(err) + s.Require().Equal(apiReq.Name, appGroup.Name) + s.Require().Equal(apiReq.Description, *appGroup.Description) +} + +func (s *AppGroupSuite) TestUpdate_AppGroupNameNotUnique() { + appGroupToUpdate := s.createAppGroup() + appGroup := s.createAppGroup() + + apiReq := domain.UpdateAppGroupRequest{ + Id: appGroupToUpdate.Id, + Name: appGroup.Name, + Description: fake.It[string](), + } + err := s.api.Invoke("system/application_group/update"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.AlreadyExists, statusErr.Code()) +} + +func (s *AppGroupSuite) TestUpdate_AppGroupNotFound() { + apiReq := domain.UpdateAppGroupRequest{ + Id: fake.It[int](), + Name: fake.It[string](), + Description: fake.It[string](), + } + err := s.api.Invoke("system/application_group/update"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.NotFound, statusErr.Code()) +} + +func (s *AppGroupSuite) TestDeleteList() { + appGroupToDelete := s.createAppGroup() + appGroup := s.createAppGroup() + + var result domain.DeleteResponse + apiReq := domain.IdListRequest{IdList: []int{appGroupToDelete.Id}} + err := s.api.Invoke("system/application_group/delete_list"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + s.Require().Equal(1, result.Deleted) + + _, err = s.appGroupRepo.GetAppGroupById(s.T().Context(), appGroup.Id) + s.Require().NoError(err) +} + +func (s *AppGroupSuite) createAppGroup() *entity.AppGroup { + appGroup, err := s.appGroupRepo.CreateAppGroup( + s.T().Context(), + fake.It[string](), + fake.It[string](), + 1, + ) + s.Require().NoError(err) + return appGroup +} From a047fb23dd0ba712eda58753146f9df411d1c68a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 12:54:58 +0300 Subject: [PATCH 24/30] MSP-5186 Simplify CreateUpdate --- service/application.go | 5 ----- 1 file changed, 5 deletions(-) diff --git a/service/application.go b/service/application.go index 590d694..ae4002c 100644 --- a/service/application.go +++ b/service/application.go @@ -173,11 +173,6 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre return result[0], nil } - _, err := s.appRepo.GetApplicationById(ctx, req.Id) - if err != nil { - return nil, errors.WithMessage(err, "get application by id") - } - app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update application") From 9a1e8a7cd452a383e0ddfe6febb177878168443a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 3 Apr 2025 12:26:16 +0300 Subject: [PATCH 25/30] MSP-5186 Use sql.NullString for description --- entity/app_group.go | 3 ++- entity/application.go | 3 ++- service/app_group.go | 2 +- service/application.go | 19 +++-------------- service/service.go | 6 +----- tests/app_group_test.go | 44 ++++++++++++++++++++++++++++++++++++--- tests/application_test.go | 5 ++--- 7 files changed, 52 insertions(+), 30 deletions(-) diff --git a/entity/app_group.go b/entity/app_group.go index 82e7d92..9638e77 100644 --- a/entity/app_group.go +++ b/entity/app_group.go @@ -1,13 +1,14 @@ package entity import ( + "database/sql" "time" ) type AppGroup struct { Id int Name string - Description *string + Description sql.NullString DomainId int CreatedAt time.Time UpdatedAt time.Time diff --git a/entity/application.go b/entity/application.go index 1fcf51d..119ed67 100644 --- a/entity/application.go +++ b/entity/application.go @@ -1,13 +1,14 @@ package entity import ( + "database/sql" "time" ) type Application struct { Id int Name string - Description *string + Description sql.NullString ApplicationGroupId int Type string CreatedAt time.Time diff --git a/service/app_group.go b/service/app_group.go index 5538f70..03a8992 100644 --- a/service/app_group.go +++ b/service/app_group.go @@ -62,7 +62,7 @@ func (s AppGroup) convertAppGroup(appGroup entity.AppGroup) domain.AppGroup { return domain.AppGroup{ Id: appGroup.Id, Name: appGroup.Name, - Description: *appGroup.Description, + Description: appGroup.Description.String, CreatedAt: appGroup.CreatedAt, UpdatedAt: appGroup.UpdatedAt, } diff --git a/service/application.go b/service/application.go index ae4002c..deab679 100644 --- a/service/application.go +++ b/service/application.go @@ -110,14 +110,10 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do resultServiceByServiceId := make(map[int]*domain.ServiceWithApps, len(serviceEntityList)) for i, serviceEntity := range serviceEntityList { serviceIdList[i] = serviceEntity.Id - description := "" - if serviceEntity.Description != nil { - description = *serviceEntity.Description - } resultService := &domain.ServiceWithApps{ Id: serviceEntity.Id, Name: serviceEntity.Name, - Description: description, + Description: serviceEntity.Description.String, Apps: make([]*domain.ApplicationSimple, 0), } r := resultByDomainId[serviceEntity.DomainId] @@ -132,15 +128,11 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do for _, applicationEntity := range applicationEntityList { resultService := resultServiceByServiceId[applicationEntity.ApplicationGroupId] - description := "" - if applicationEntity.Description != nil { - description = *applicationEntity.Description - } resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{ Id: applicationEntity.Id, Name: applicationEntity.Name, Type: applicationEntity.Type, - Description: description, + Description: applicationEntity.Description.String, Tokens: make([]domain.Token, 0), }) } @@ -291,15 +283,10 @@ func (s Application) Update(ctx context.Context, req domain.UpdateApplicationReq } func (s Application) convertApplication(req entity.Application) domain.Application { - desc := "" - if req.Description != nil { - desc = *req.Description - } - return domain.Application{ Id: req.Id, Name: req.Name, - Description: desc, + Description: req.Description.String, ServiceId: req.ApplicationGroupId, Type: req.Type, CreatedAt: req.CreatedAt, diff --git a/service/service.go b/service/service.go index 659746e..a16c69c 100644 --- a/service/service.go +++ b/service/service.go @@ -102,14 +102,10 @@ func (s Service) Delete(ctx context.Context, idList []int) (int, error) { } func (s Service) convertService(req entity.AppGroup) domain.Service { - desc := "" - if req.Description != nil { - desc = *req.Description - } result := domain.Service{ Id: req.Id, Name: req.Name, - Description: desc, + Description: req.Description.String, DomainId: req.DomainId, CreatedAt: req.CreatedAt, UpdatedAt: req.UpdatedAt, diff --git a/tests/app_group_test.go b/tests/app_group_test.go index 2096d54..775f8e2 100644 --- a/tests/app_group_test.go +++ b/tests/app_group_test.go @@ -64,7 +64,45 @@ func (s *AppGroupSuite) TestGetByIdList() { appGroups = append(appGroups, domain.AppGroup{ Id: appGroup.Id, Name: appGroup.Name, - Description: *appGroup.Description, + Description: appGroup.Description.String, + CreatedAt: time.Time{}, + UpdatedAt: time.Time{}, + }) + ids = append(ids, appGroup.Id) + } + result := []domain.AppGroup{} + apiReq := domain.IdListRequest{IdList: ids} + err := s.api.Invoke("system/application_group/get_by_id_list"). + JsonRequestBody(apiReq). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + for i := range result { + s.Require().NotEmpty(result[i].CreatedAt) + result[i].CreatedAt = time.Time{} + + s.Require().NotEmpty(result[i].UpdatedAt) + result[i].UpdatedAt = time.Time{} + } + s.Require().ElementsMatch(appGroups, result) +} + +func (s *AppGroupSuite) TestGetByIdList_EmptyDescription() { + toGenerate := 10 + appGroups := make([]domain.AppGroup, 0, toGenerate) + ids := make([]int, 0, toGenerate) + for range 10 { + appGroup, err := s.appGroupRepo.CreateAppGroup( + s.T().Context(), + fake.It[string](), + "", + 1, + ) + s.Require().NoError(err) + appGroups = append(appGroups, domain.AppGroup{ + Id: appGroup.Id, + Name: appGroup.Name, + Description: "", CreatedAt: time.Time{}, UpdatedAt: time.Time{}, }) @@ -118,7 +156,7 @@ func (s *AppGroupSuite) TestCreate_HappyPath() { appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), result.Id) s.Require().NoError(err) s.Require().Equal(apiReq.Name, appGroup.Name) - s.Require().Equal(apiReq.Description, *appGroup.Description) + s.Require().Equal(apiReq.Description, appGroup.Description.String) } func (s *AppGroupSuite) TestCreate_AppGroupNameNotUnique() { @@ -160,7 +198,7 @@ func (s *AppGroupSuite) TestUpdate_HappyPath() { appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), apiReq.Id) s.Require().NoError(err) s.Require().Equal(apiReq.Name, appGroup.Name) - s.Require().Equal(apiReq.Description, *appGroup.Description) + s.Require().Equal(apiReq.Description, appGroup.Description.String) } func (s *AppGroupSuite) TestUpdate_AppGroupNameNotUnique() { diff --git a/tests/application_test.go b/tests/application_test.go index a2f1b81..8292a1a 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -217,11 +217,10 @@ func (s *ApplicationSuite) TestUpdate_HappyPath() { expectedDbApp := entity.Application{ Id: apiReq.Id, Name: apiReq.Name, + Description: app.Description, Type: inserted[0].Type, ApplicationGroupId: inserted[0].ServiceId, } - s.Require().Equal(apiReq.Description, *app.Description) - app.Description = nil s.Require().NotEmpty(app.CreatedAt) app.CreatedAt = time.Time{} @@ -302,7 +301,7 @@ func (s *ApplicationSuite) insertApps(toInsert []domain.Application) []domain.Ap toExpect = append(toExpect, domain.Application{ Id: createdApp.Id, Name: createdApp.Name, - Description: *createdApp.Description, + Description: createdApp.Description.String, ServiceId: createdApp.ApplicationGroupId, Type: createdApp.Type, CreatedAt: time.Time{}, From 1d4c81c42565bde4c27b25e52397f444f3acd14f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 3 Apr 2025 12:48:01 +0300 Subject: [PATCH 26/30] MSP-5186 Make application id required --- domain/application.go | 2 +- service/application.go | 10 +--------- tests/application_test.go | 34 ---------------------------------- 3 files changed, 2 insertions(+), 44 deletions(-) diff --git a/domain/application.go b/domain/application.go index b66e3af..482ac07 100644 --- a/domain/application.go +++ b/domain/application.go @@ -41,7 +41,7 @@ type ApplicationSimple struct { } type CreateApplicationRequest struct { - Id int + Id int `validate:"required"` Name string `validate:"required"` Description string ApplicationGroupId int `validate:"required"` diff --git a/service/application.go b/service/application.go index deab679..5c17144 100644 --- a/service/application.go +++ b/service/application.go @@ -249,15 +249,7 @@ func (s Application) GetAll(ctx context.Context) ([]domain.Application, error) { } func (s Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { - appId := req.Id - var err error - if appId == 0 { - appId, err = s.appRepo.NextApplicationId(ctx) - if err != nil { - return nil, errors.WithMessage(err, "next application id") - } - } - app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ApplicationGroupId, req.Type) + app, err := s.appRepo.CreateApplication(ctx, req.Id, req.Name, req.Description, req.ApplicationGroupId, req.Type) if err != nil { return nil, errors.WithMessage(err, "create application") } diff --git a/tests/application_test.go b/tests/application_test.go index 8292a1a..4e8532d 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -97,40 +97,6 @@ func (s *ApplicationSuite) TestCreate_HappyPath() { s.Require().Empty(result.Tokens) } -func (s *ApplicationSuite) TestCreate_WithEmptyAppId_HappyPath() { - nextAppId, err := s.appRepo.NextApplicationId(s.T().Context()) - s.Require().NoError(err) - - result := domain.ApplicationWithTokens{} - apiReq := fake.It[domain.CreateApplicationRequest]() - apiReq.Type = domain.ApplicationMobileType - appGroup := s.createAppGroup() - apiReq.ApplicationGroupId = appGroup.Id - apiReq.Id = 0 - - err = s.api.Invoke("system/application/create_application"). - JsonRequestBody(apiReq). - JsonResponseBody(&result). - Do(s.T().Context()) - s.Require().NoError(err) - - s.Require().NotEmpty(result.App.CreatedAt) - result.App.CreatedAt = time.Time{} - - s.Require().NotEmpty(result.App.UpdatedAt) - result.App.UpdatedAt = time.Time{} - - expectedApp := domain.Application{ - Id: nextAppId, - Name: apiReq.Name, - Description: apiReq.Description, - Type: apiReq.Type, - ServiceId: apiReq.ApplicationGroupId, - } - s.Require().Equal(expectedApp, result.App) - s.Require().Empty(result.Tokens) -} - func (s *ApplicationSuite) TestCreate_AppGroupNotFound() { apiReq := fake.It[domain.CreateApplicationRequest]() apiReq.Type = domain.ApplicationSystemType From 3b43e7875de6a4712154aeade6b89dc7bde135a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 3 Apr 2025 13:22:22 +0300 Subject: [PATCH 27/30] MSP-5186 Add update app id for update application endpoint --- controller/application.go | 31 ++++++++++++++++----- domain/application.go | 3 +- domain/error.go | 8 ++++++ repository/application.go | 58 +++++++++++++++++++++++++++++++-------- repository/consts.go | 2 +- service/application.go | 2 +- service/interfaces.go | 1 + tests/application_test.go | 33 ++++++++++++++++++---- 8 files changed, 111 insertions(+), 27 deletions(-) diff --git a/controller/application.go b/controller/application.go index c91ab89..1a4fe50 100644 --- a/controller/application.go +++ b/controller/application.go @@ -223,18 +223,35 @@ func (c Application) Create(ctx context.Context, req domain.CreateApplicationReq // @Produce json // @Param body body domain.UpdateApplicationRequest true "Объект приложения" // @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 404 {object} apierrors.Error +// @Failure 409 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application/update_application [POST] func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.Update(ctx, req) switch { - case errors.Is(err, domain.ErrApplicationDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.OldId), + err, + ) + case errors.Is(err, domain.ErrApplicationDuplicateName): + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeApplicationDuplicateName, + fmt.Sprintf("application with name %s already exists", req.Name), + err, + ) + case errors.Is(err, domain.ErrApplicationDuplicateId): + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeApplicationDuplicateId, + fmt.Sprintf("application with id %d already exists", req.NewId), + err, + ) default: return result, err } diff --git a/domain/application.go b/domain/application.go index 482ac07..7296013 100644 --- a/domain/application.go +++ b/domain/application.go @@ -49,7 +49,8 @@ type CreateApplicationRequest struct { } type UpdateApplicationRequest struct { - Id int `validate:"required"` + OldId int `validate:"required"` + NewId int `validate:"required"` Name string `validate:"required"` Description string } diff --git a/domain/error.go b/domain/error.go index eb64a99..04c6a1c 100644 --- a/domain/error.go +++ b/domain/error.go @@ -4,6 +4,14 @@ import ( "github.com/pkg/errors" ) +const ( + ErrCodeInvalidRequest = 600 + ErrCodeAppGroupNotFound = 601 + ErrCodeApplicationNotFound = 602 + ErrCodeApplicationDuplicateName = 603 + ErrCodeApplicationDuplicateId = 604 +) + var ( ErrDomainNotFound = errors.New("domain not found") ErrDomainDuplicateName = errors.New("domain name already exist") diff --git a/repository/application.go b/repository/application.go index 430e61b..32c94f7 100644 --- a/repository/application.go +++ b/repository/application.go @@ -131,17 +131,33 @@ func (r Application) UpdateApplication( ` result := entity.Application{} err := r.db.SelectRow(ctx, &result, q, id, name, description) - var pgErr *pgconn.PgError - switch { - case errors.As(err, &pgErr) && pgErr.ConstraintName == applicationUniqueNameConstraintName: - return nil, domain.ErrApplicationDuplicateName - case errors.Is(err, sql.ErrNoRows): - return nil, domain.ErrApplicationNotFound - case err != nil: - return nil, errors.WithMessagef(err, "exec query %s", q) - default: - return &result, nil + if err != nil { + return nil, r.handleUpdateError(err, q) } + return &result, nil +} + +func (r Application) UpdateApplicationWithNewId( + ctx context.Context, + oldId int, + newId int, + name string, + description string, +) (*entity.Application, error) { + q := ` + UPDATE application + SET id = $2, + name = $3, + description = $4 + WHERE id = $1 + RETURNING id, name, description, application_group_id, type, created_at, updated_at +` + result := entity.Application{} + err := r.db.SelectRow(ctx, &result, q, oldId, newId, name, description) + if err != nil { + return nil, r.handleUpdateError(err, q) + } + return &result, nil } func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) { @@ -201,7 +217,7 @@ func (r Application) handleCreateError(err error, q string) error { return errors.WithMessagef(err, "exec query %s", q) } switch pgErr.ConstraintName { - case applicationPkConstrainName: + case applicationPkConstraintName: return domain.ErrApplicationDuplicateId case applicationUniqueNameConstraintName: return domain.ErrApplicationDuplicateName @@ -210,3 +226,23 @@ func (r Application) handleCreateError(err error, q string) error { } return errors.WithMessagef(err, "exec query %s", q) } + +func (r Application) handleUpdateError(err error, q string) error { + if errors.Is(err, sql.ErrNoRows) { + return domain.ErrApplicationNotFound + } + + var pgErr *pgconn.PgError + if !errors.As(err, &pgErr) { + return errors.WithMessagef(err, "exec query %s", q) + } + + switch pgErr.ConstraintName { + case applicationPkConstraintName: + return domain.ErrApplicationDuplicateId + case applicationUniqueNameConstraintName: + return domain.ErrApplicationDuplicateName + default: + return errors.WithMessagef(err, "exec query %s", q) + } +} diff --git a/repository/consts.go b/repository/consts.go index 76aa757..fec1087 100644 --- a/repository/consts.go +++ b/repository/consts.go @@ -1,7 +1,7 @@ package repository const ( - applicationPkConstrainName = "application_pkey" + applicationPkConstraintName = "application_pkey" applicationUniqueNameConstraintName = "uq_name_application_group_id" applicationFkAppGroupConstraintName = "fk_application_group_id" diff --git a/service/application.go b/service/application.go index 5c17144..19987a0 100644 --- a/service/application.go +++ b/service/application.go @@ -261,7 +261,7 @@ func (s Application) Create(ctx context.Context, req domain.CreateApplicationReq } func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) { - app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description) + app, err := s.appRepo.UpdateApplicationWithNewId(ctx, req.OldId, req.NewId, req.Name, req.Description) if err != nil { return nil, errors.WithMessage(err, "update application") } diff --git a/service/interfaces.go b/service/interfaces.go index 5d3773c..2303026 100644 --- a/service/interfaces.go +++ b/service/interfaces.go @@ -25,6 +25,7 @@ type ApplicationRepo interface { GetApplicationByNameAndAppGroupId(ctx context.Context, name string, appGroupId int) (*entity.Application, error) CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) + UpdateApplicationWithNewId(ctx context.Context, oldId int, newId int, name string, description string) (*entity.Application, error) NextApplicationId(ctx context.Context) (int, error) GetAllApplications(ctx context.Context) ([]entity.Application, error) } diff --git a/tests/application_test.go b/tests/application_test.go index 4e8532d..0e96a4f 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -149,7 +149,8 @@ func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() { func (s *ApplicationSuite) TestUpdate_HappyPath() { inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(1), fake.MaxSliceSize(1))) apiReq := domain.UpdateApplicationRequest{ - Id: inserted[0].Id, + OldId: inserted[0].Id, + NewId: fake.It[int](), Name: fake.It[string](), Description: fake.It[string](), } @@ -168,7 +169,7 @@ func (s *ApplicationSuite) TestUpdate_HappyPath() { result.App.UpdatedAt = time.Time{} expectedApp := domain.Application{ - Id: apiReq.Id, + Id: apiReq.NewId, Name: apiReq.Name, Description: apiReq.Description, Type: inserted[0].Type, @@ -177,11 +178,11 @@ func (s *ApplicationSuite) TestUpdate_HappyPath() { s.Require().Equal(expectedApp, result.App) s.Require().Empty(result.Tokens) - app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.Id) + app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.NewId) s.Require().NoError(err) expectedDbApp := entity.Application{ - Id: apiReq.Id, + Id: apiReq.NewId, Name: apiReq.Name, Description: app.Description, Type: inserted[0].Type, @@ -199,7 +200,8 @@ func (s *ApplicationSuite) TestUpdate_HappyPath() { func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() { inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(2), fake.MaxSliceSize(2))) apiReq := domain.UpdateApplicationRequest{ - Id: inserted[0].Id, + NewId: inserted[0].Id, + OldId: inserted[0].Id, Name: inserted[1].Name, Description: fake.It[string](), } @@ -213,9 +215,28 @@ func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() { s.Require().Equal(codes.AlreadyExists, statusErr.Code()) } +func (s *ApplicationSuite) TestUpdate_AppIdNotUnique() { + inserted := s.insertApps(fake.It[[]domain.Application](fake.MinSliceSize(2), fake.MaxSliceSize(2))) + apiReq := domain.UpdateApplicationRequest{ + OldId: inserted[0].Id, + NewId: inserted[1].Id, + Name: fake.It[string](), + Description: fake.It[string](), + } + + err := s.api.Invoke("system/application/update_application"). + JsonRequestBody(apiReq). + Do(s.T().Context()) + statusErr, ok := status.FromError(err) + s.Require().True(ok) + s.Require().NotNil(statusErr) + s.Require().Equal(codes.AlreadyExists, statusErr.Code()) +} + func (s *ApplicationSuite) TestUpdate_AppNotFound() { apiReq := domain.UpdateApplicationRequest{ - Id: fake.It[int](), + OldId: fake.It[int](), + NewId: fake.It[int](), Name: fake.It[string](), Description: fake.It[string](), } From 199d576956288b4ee66e7d0f7320abe76b2c08ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 3 Apr 2025 13:49:40 +0300 Subject: [PATCH 28/30] MSP-5186 Use apierrrors.Error --- controller/access_list.go | 39 +++++++--- controller/app_group.go | 46 ++++++++---- controller/application.go | 87 +++++++++++++++------- controller/domain.go | 48 ++++++++---- controller/secure.go | 4 +- controller/service.go | 53 ++++++++++---- controller/token.go | 32 ++++++-- docs/swagger.yaml | 150 +++++++++++++++++++------------------- domain/error.go | 11 ++- domain/grpc_error.go | 7 -- tests/app_group_test.go | 24 +++--- tests/application_test.go | 45 +++++------- 12 files changed, 333 insertions(+), 213 deletions(-) delete mode 100644 domain/grpc_error.go diff --git a/controller/access_list.go b/controller/access_list.go index ba53652..6ee48e1 100644 --- a/controller/access_list.go +++ b/controller/access_list.go @@ -2,11 +2,13 @@ package controller import ( "context" + "fmt" + + "isp-system-service/domain" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "isp-system-service/domain" ) type AccessListService interface { @@ -34,14 +36,19 @@ func NewAccessList(service AccessListService) AccessList { // @Produce json // @Param body body domain.Identity false "идентификатор приложения" // @Success 200 {array} domain.MethodInfo "список доступности методов" -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /access_list/get_by_id [POST] func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) { result, err := c.service.GetById(ctx, req.Id) switch { case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application not found") + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.Id), + err, + ) case err != nil: return nil, err default: @@ -58,14 +65,19 @@ func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain. // @Produce json // @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа" // @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк" -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /access_list/set_one [POST] func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) { result, err := c.service.SetOne(ctx, req) switch { case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application not found") + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.AppId), + err, + ) case err != nil: return nil, err default: @@ -82,14 +94,19 @@ func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneReque // @Produce json // @Param body body domain.AccessListSetListRequest false "объект настройки доступа" // @Success 200 {array} domain.MethodInfo "список доступности методов" -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /access_list/set_list [POST] func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) { result, err := c.service.SetList(ctx, req) switch { case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application not found") + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.AppId), + err, + ) case err != nil: return nil, err default: diff --git a/controller/app_group.go b/controller/app_group.go index 99a7f22..171fcf0 100644 --- a/controller/app_group.go +++ b/controller/app_group.go @@ -2,11 +2,12 @@ package controller import ( "context" + "fmt" "isp-system-service/domain" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type AppGroupService interface { @@ -35,15 +36,20 @@ func NewAppGroup(service AppGroupService) AppGroup { // @Produce json // @Param body body domain.CreateAppGroupRequest true "Объект группы приложений" // @Success 200 {object} domain.AppGroup -// @Failure 400 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 409 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application_group/create [POST] func (c AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) { result, err := c.service.Create(ctx, req) switch { case errors.Is(err, domain.ErrAppGroupDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "application group with name %s already exists", req.Name) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeAppGroupDuplicateName, + fmt.Sprintf("application group with name %s already exists", req.Name), + err, + ) default: return result, err } @@ -58,18 +64,28 @@ func (c AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) // @Produce json // @Param body body domain.UpdateAppGroupRequest true "Объект группы приложений" // @Success 200 {object} domain.AppGroup -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 404 {object} apierrors.Error +// @Failure 409 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application_group/update [POST] func (c AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) { result, err := c.service.Update(ctx, req) switch { case errors.Is(err, domain.ErrAppGroupDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "application group with name %s already exists", req.Name) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeAppGroupDuplicateName, + fmt.Sprintf("application group with name %s already exists", req.Name), + err, + ) case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, status.Errorf(codes.NotFound, "application group with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("application group with id %d not found", req.Id), + err, + ) default: return result, err } @@ -84,8 +100,8 @@ func (c AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) // @Produce json // @Param body body domain.IdListRequest true "список идентификаторов групп приложений" // @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application_group/delete_list [POST] func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) { return c.service.DeleteList(ctx, req) @@ -100,8 +116,8 @@ func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*do // @Produce json // @Param body body domain.IdListRequest true "список идентификаторов групп приложений" // @Success 200 {array} domain.AppGroup -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application_group/get_by_id_list [POST] func (c AppGroup) GetByIdList(ctx context.Context, req domain.IdListRequest) ([]domain.AppGroup, error) { return c.service.GetByIdList(ctx, req.IdList) diff --git a/controller/application.go b/controller/application.go index 1a4fe50..aad3bb8 100644 --- a/controller/application.go +++ b/controller/application.go @@ -2,12 +2,13 @@ package controller import ( "context" + "fmt" "isp-system-service/domain" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type ApplicationService interface { @@ -42,15 +43,20 @@ func NewApplication(service ApplicationService) Application { // @Produce json // @Param body body domain.Identity true "Идентификатор приложения" // @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application/get_application_by_id [POST] func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) { result, err := c.service.GetById(ctx, req.Id) switch { case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.Id), + err, + ) case err != nil: return nil, err default: @@ -67,7 +73,7 @@ func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain. // @Produce json // @Param body body []integer false "Массив идентификаторов приложений" // @Success 200 {array} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /application/get_applications [POST] func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) { return c.service.GetByIdList(ctx, req) @@ -82,7 +88,7 @@ func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.Appl // @Produce json // @Param body body domain.Identity true "Идентификатор сервиса" // @Success 200 {array} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /application/get_applications_by_service_id [POST] func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) { return c.service.GetByServiceId(ctx, req.Id) @@ -96,7 +102,7 @@ func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([ // @Accept json // @Produce json // @Success 200 {array} domain.DomainWithService -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /application/get_system_tree [POST] func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) { return c.service.SystemTree(ctx, domain.DefaultSystemId) @@ -111,20 +117,34 @@ func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithSer // @Produce json // @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения" // @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 404 {object} apierrors.Error +// @Failure 409 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application/create_update_application [POST] func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.CreateUpdate(ctx, req) switch { case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, status.Errorf(codes.InvalidArgument, "service with id %d not found", req.ServiceId) + return nil, apierrors.NewBusinessError( + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("service with id %d not found", req.ServiceId), + err, + ) case errors.Is(err, domain.ErrApplicationDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeApplicationDuplicateName, + fmt.Sprintf("application with name %s already exists", req.Name), + err, + ) case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.Id), + err, + ) case err != nil: return nil, err default: @@ -141,12 +161,13 @@ func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre // @Produce json // @Param body body []integer false "Массив идентификаторов приложений" // @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application/delete_applications [POST] func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { if len(req) == 0 { - return nil, status.Errorf(codes.InvalidArgument, "At least one id are required") + return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest, + "At least one id are required", errors.New("invalid id count")) } result, err := c.service.Delete(ctx, req) @@ -167,7 +188,7 @@ func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteRespo // @Accept json // @Produce json // @Success 200 {object} integer -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /application/next_id [POST] func (c Application) NextId(ctx context.Context) (int, error) { return c.service.NextId(ctx) @@ -181,7 +202,7 @@ func (c Application) NextId(ctx context.Context) (int, error) { // @Accept json // @Produce json // @Success 200 {array} domain.Application -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /application/get_all [POST] func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { return c.service.GetAll(ctx) @@ -196,19 +217,33 @@ func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) { // @Produce json // @Param body body domain.CreateApplicationRequest true "Объект приложения" // @Success 200 {object} domain.ApplicationWithTokens -// @Failure 400 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 409 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /application/create_application [POST] func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.Create(ctx, req) switch { case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, status.Errorf(codes.InvalidArgument, "application group with id %d not found", req.ApplicationGroupId) + return nil, apierrors.NewBusinessError( + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("application group with id %d not found", req.ApplicationGroupId), + err, + ) case errors.Is(err, domain.ErrApplicationDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeApplicationDuplicateName, + fmt.Sprintf("application with name %s already exists", req.Name), + err, + ) case errors.Is(err, domain.ErrApplicationDuplicateId): - return nil, status.Errorf(codes.AlreadyExists, "application with id %d already exists", req.Id) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeApplicationDuplicateId, + fmt.Sprintf("application with id %d already exists", req.Id), + err, + ) default: return result, err } diff --git a/controller/domain.go b/controller/domain.go index 4e479f9..7e40923 100644 --- a/controller/domain.go +++ b/controller/domain.go @@ -2,11 +2,13 @@ package controller import ( "context" + "fmt" + + "isp-system-service/domain" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "isp-system-service/domain" ) type DomainService interface { @@ -35,14 +37,19 @@ func NewDomain(service DomainService) Domain { // @Produce json // @Param body body domain.Identity true "Идентификатор домена" // @Success 200 {object} domain.Domain -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /domain/get_domain_by_id [POST] func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) { result, err := c.service.GetById(ctx, req.Id) switch { case errors.Is(err, domain.ErrDomainNotFound): - return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeDomainNotFound, + fmt.Sprintf("domain with id %d not found", req.Id), + err, + ) case err != nil: return nil, err default: @@ -59,7 +66,7 @@ func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domai // @Produce json // @Param body body integer false "Идентификатор системы" // @Success 200 {array} domain.Domain -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /domain/get_domains_by_system_id [POST] func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) { return c.service.GetBySystemId(ctx, domain.DefaultSystemId) @@ -74,17 +81,31 @@ func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) { // @Produce json // @Param body body domain.DomainCreateUpdateRequest true "Объект домена" // @Success 200 {object} domain.Domain -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /domain/create_update_domain [POST] func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) { result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId) switch { case errors.Is(err, domain.ErrSystemNotFound): - return nil, status.Errorf(codes.InvalidArgument, "system with id %d not found", domain.DefaultSystemId) + return nil, apierrors.NewBusinessError( + domain.ErrCodeSystemNotFound, + fmt.Sprintf("system with id %d not found", domain.DefaultSystemId), + err, + ) case errors.Is(err, domain.ErrDomainNotFound): - return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeDomainNotFound, + fmt.Sprintf("domain with id %d not found", req.Id), + err, + ) case errors.Is(err, domain.ErrDomainDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "domain with name %s already exists", req.Name) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeDomainDuplicateName, + fmt.Sprintf("domain with name %s already exists", req.Name), + err, + ) case err != nil: return nil, err default: @@ -101,12 +122,13 @@ func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR // @Produce json // @Param body body []integer false "Массив идентификаторов доменов" // @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /domain/delete_domains [POST] func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { if len(req) == 0 { - return nil, status.Errorf(codes.InvalidArgument, "at least one id are required") + return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest, + "At least one id are required", errors.New("invalid id count")) } result, err := c.service.Delete(ctx, req) diff --git a/controller/secure.go b/controller/secure.go index f0eb07b..02b0144 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -31,7 +31,7 @@ func NewSecure(service SecureService) Secure { // @Produce json // @Param body body domain.AuthenticateRequest true "Тело запроса" // @Success 200 {array} domain.AuthenticateResponse -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /secure/authenticate [POST] func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) { result, err := c.service.Authenticate(ctx, req.Token) @@ -65,7 +65,7 @@ func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest // @Produce json // @Param body body domain.AuthorizeRequest true "Тело запрос" // @Success 200 {array} domain.AuthorizeResponse -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /secure/authorize [POST] func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) { result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint) diff --git a/controller/service.go b/controller/service.go index 6117153..f081369 100644 --- a/controller/service.go +++ b/controller/service.go @@ -2,12 +2,13 @@ package controller import ( "context" + "fmt" "isp-system-service/domain" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type ServiceService interface { @@ -37,14 +38,19 @@ func NewService(service ServiceService) Service { // @Produce json // @Param body body domain.Identity true "Идентификатор сервиса" // @Success 200 {object} domain.Service -// @Failure 404 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 404 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /service/get_service_by_id [POST] func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) { result, err := c.service.GetById(ctx, req.Id) switch { case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("service with id %d not found", req.Id), + err, + ) case err != nil: return nil, err default: @@ -61,7 +67,7 @@ func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Serv // @Produce json // @Param body body []integer false "Массив идентификаторов сервисов" // @Success 200 {array} domain.Service -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /service/get_service [POST] func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) { return c.service.GetByIdList(ctx, req) @@ -76,7 +82,7 @@ func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) { // @Produce json // @Param body body domain.Identity true "Идентификатор домена" // @Success 200 {array} domain.Service -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /service/get_services_by_domain_id [POST] func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) { return c.service.GetByDomainId(ctx, req.Id) @@ -91,20 +97,34 @@ func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]doma // @Produce json // @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса" // @Success 200 {object} domain.Service -// @Failure 400 {object} domain.GrpcError -// @Failure 404 {object} domain.GrpcError -// @Failure 409 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 404 {object} apierrors.Error +// @Failure 409 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /service/create_update_service [POST] func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) { result, err := c.service.CreateUpdate(ctx, req) switch { case errors.Is(err, domain.ErrDomainNotFound): - return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId) + return nil, apierrors.NewBusinessError( + domain.ErrCodeDomainNotFound, + fmt.Sprintf("domain with id %d not found", req.DomainId), + err, + ) case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("service with id %d not found", req.Id), + err, + ) case errors.Is(err, domain.ErrAppGroupDuplicateName): - return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name) + return nil, apierrors.New( + codes.AlreadyExists, + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("service with name %s already exists", req.Name), + err, + ) case err != nil: return nil, err default: @@ -121,12 +141,13 @@ func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat // @Produce json // @Param body body []integer true "Массив идентификаторов сервисов" // @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /service/delete_service [POST] func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) { if len(req) == 0 { - return nil, status.Error(codes.InvalidArgument, "at least one id are required") + return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest, + "At least one id are required", errors.New("invalid id count")) } result, err := c.service.Delete(ctx, req) diff --git a/controller/token.go b/controller/token.go index fdf64ab..63f65fc 100644 --- a/controller/token.go +++ b/controller/token.go @@ -2,12 +2,13 @@ package controller import ( "context" + "fmt" "isp-system-service/domain" "github.com/pkg/errors" + "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type TokenService interface { @@ -36,7 +37,7 @@ func NewToken(service TokenService) Token { // @Produce json // @Param body body domain.Identity true "Идентификатор приложения" // @Success 200 {array} entity.Token -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /token/get_tokens_by_app_id [POST] func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) { return c.service.GetByAppId(ctx, req.Id) @@ -51,17 +52,32 @@ func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.To // @Produce json // @Param body body domain.TokenCreateRequest true "Объект создания токена" // @Success 200 {object} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /token/create_token [POST] func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) { result, err := c.service.Create(ctx, req) switch { case errors.Is(err, domain.ErrApplicationNotFound): - return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeApplicationNotFound, + fmt.Sprintf("application with id %d not found", req.AppId), + err, + ) case errors.Is(err, domain.ErrAppGroupNotFound): - return nil, status.Errorf(codes.NotFound, "service for app_id id %d not found", req.AppId) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeAppGroupNotFound, + fmt.Sprintf("service for app_id id %d not found", req.AppId), + err, + ) case errors.Is(err, domain.ErrDomainNotFound): - return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId) + return nil, apierrors.New( + codes.NotFound, + domain.ErrCodeDomainNotFound, + fmt.Sprintf("domain for app_id id %d not found", req.AppId), + err, + ) case err != nil: return nil, err default: @@ -78,7 +94,7 @@ func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma // @Produce json // @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов" // @Success 200 {object} domain.ApplicationWithTokens -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /token/revoke_tokens [POST] func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) { return c.service.Revoke(ctx, req) @@ -93,7 +109,7 @@ func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*doma // @Produce json // @Param body body domain.Identity true "Идентификатор приложения" // @Success 200 {object} domain.DeleteResponse -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /token/revoke_tokens_for_app [POST] func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) { return c.service.RevokeByAppId(ctx, req.Id) diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 6009871..534432b 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1,5 +1,15 @@ basePath: /api/system definitions: + apierrors.Error: + properties: + details: + additionalProperties: true + type: object + errorCode: + type: integer + errorMessage: + type: string + type: object domain.AccessListSetListRequest: properties: appId: @@ -172,6 +182,7 @@ definitions: type: string required: - applicationGroupId + - id - name - type type: object @@ -219,16 +230,6 @@ definitions: $ref: '#/definitions/domain.ServiceWithApps' type: array type: object - domain.GrpcError: - properties: - details: - items: {} - type: array - errorCode: - type: string - errorMessage: - type: string - type: object domain.IdListRequest: properties: idList: @@ -343,13 +344,16 @@ definitions: properties: description: type: string - id: - type: integer name: type: string + newId: + type: integer + oldId: + type: integer required: - - id - name + - newId + - oldId type: object entity.Token: properties: @@ -395,11 +399,11 @@ paths: "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить список доступности методов для приложения tags: - accessList @@ -427,11 +431,11 @@ paths: "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Настроить доступность списка методов для приложения tags: - accessList @@ -456,11 +460,11 @@ paths: "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Настроить доступность метода для приложения tags: - accessList @@ -487,15 +491,15 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "409": description: Conflict schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Создать приложение tags: - application @@ -522,19 +526,19 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "409": description: Conflict schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Создать/обновить приложение tags: - application @@ -562,11 +566,11 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Удалить приложения tags: - application @@ -587,7 +591,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить список приложений tags: - application @@ -613,15 +617,15 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить приложение по идентификатору tags: - application @@ -650,7 +654,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить список приложений tags: - application @@ -678,7 +682,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить список приложений по идентификатору сервиса tags: - application @@ -699,7 +703,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Метод получения системного дерева tags: - application @@ -718,7 +722,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить следующий идентификатор приложения tags: - application @@ -745,19 +749,19 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "409": description: Conflict schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Обновить приложение tags: - application @@ -783,15 +787,15 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "409": description: Conflict schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Создать группу приложений tags: - application_group @@ -818,11 +822,11 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Удалить группы приложений tags: - application_group @@ -850,11 +854,11 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить группы приложений по списку идентификаторов tags: - application_group @@ -881,19 +885,19 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "409": description: Conflict schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Обновить группу приложений tags: - application_group @@ -920,7 +924,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Создать/обновить домен tags: - domain @@ -948,11 +952,11 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Удаление доменов tags: - domain @@ -978,11 +982,11 @@ paths: "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить домен по идентификатору tags: - domain @@ -1009,7 +1013,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить домены по идентификатору системы tags: - domain @@ -1037,7 +1041,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Метод аутентификации токена tags: - secure @@ -1065,7 +1069,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Метод авторизации приложения tags: - secure @@ -1092,19 +1096,19 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "409": description: Conflict schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Создать/обновить сервис tags: - service @@ -1133,11 +1137,11 @@ paths: "400": description: Bad Request schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Удалить сервисы tags: - service @@ -1166,7 +1170,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить список сервисов tags: - service @@ -1192,11 +1196,11 @@ paths: "404": description: Not Found schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить сервис по идентификатору tags: - service @@ -1224,7 +1228,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить список сервисов по идентификатору домена tags: - service @@ -1250,7 +1254,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Создать токен tags: - token @@ -1278,7 +1282,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Получить токены по идентификатору приложения tags: - token @@ -1304,7 +1308,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Отозвать токены tags: - token @@ -1331,7 +1335,7 @@ paths: "500": description: Internal Server Error schema: - $ref: '#/definitions/domain.GrpcError' + $ref: '#/definitions/apierrors.Error' summary: Отозвать токены для приложения tags: - token diff --git a/domain/error.go b/domain/error.go index 04c6a1c..5cf7fc9 100644 --- a/domain/error.go +++ b/domain/error.go @@ -5,11 +5,18 @@ import ( ) const ( - ErrCodeInvalidRequest = 600 - ErrCodeAppGroupNotFound = 601 + ErrCodeInvalidRequest = 600 + ErrCodeApplicationNotFound = 602 ErrCodeApplicationDuplicateName = 603 ErrCodeApplicationDuplicateId = 604 + + ErrCodeAppGroupNotFound = 605 + ErrCodeAppGroupDuplicateName = 606 + + ErrCodeSystemNotFound = 607 + ErrCodeDomainNotFound = 608 + ErrCodeDomainDuplicateName = 609 ) var ( diff --git a/domain/grpc_error.go b/domain/grpc_error.go deleted file mode 100644 index 7bb2cfa..0000000 --- a/domain/grpc_error.go +++ /dev/null @@ -1,7 +0,0 @@ -package domain - -type GrpcError struct { - ErrorMessage string `json:"errorMessage"` - ErrorCode string `json:"errorCode"` - Details []interface{} `json:"details"` -} diff --git a/tests/app_group_test.go b/tests/app_group_test.go index 775f8e2..06fd16e 100644 --- a/tests/app_group_test.go +++ b/tests/app_group_test.go @@ -11,13 +11,12 @@ import ( "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/grpc/apierrors" "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" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) func TestApplicationGroupSuite(t *testing.T) { @@ -171,10 +170,9 @@ func (s *AppGroupSuite) TestCreate_AppGroupNameNotUnique() { JsonRequestBody(apiReq). JsonResponseBody(&result). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.AlreadyExists, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode) } func (s *AppGroupSuite) TestUpdate_HappyPath() { @@ -213,10 +211,9 @@ func (s *AppGroupSuite) TestUpdate_AppGroupNameNotUnique() { err := s.api.Invoke("system/application_group/update"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.AlreadyExists, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode) } func (s *AppGroupSuite) TestUpdate_AppGroupNotFound() { @@ -228,10 +225,9 @@ func (s *AppGroupSuite) TestUpdate_AppGroupNotFound() { err := s.api.Invoke("system/application_group/update"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.NotFound, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode) } func (s *AppGroupSuite) TestDeleteList() { diff --git a/tests/application_test.go b/tests/application_test.go index 0e96a4f..15cc1f7 100644 --- a/tests/application_test.go +++ b/tests/application_test.go @@ -11,13 +11,12 @@ import ( "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/grpc/apierrors" "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" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) func TestApplicationSuite(t *testing.T) { @@ -104,10 +103,9 @@ func (s *ApplicationSuite) TestCreate_AppGroupNotFound() { err := s.api.Invoke("system/application/create_application"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.InvalidArgument, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode) } func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() { @@ -122,10 +120,9 @@ func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() { err := s.api.Invoke("system/application/create_application"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.AlreadyExists, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode) } func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() { @@ -140,10 +137,9 @@ func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() { err := s.api.Invoke("system/application/create_application"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.AlreadyExists, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode) } func (s *ApplicationSuite) TestUpdate_HappyPath() { @@ -209,10 +205,9 @@ func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() { err := s.api.Invoke("system/application/update_application"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.AlreadyExists, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode) } func (s *ApplicationSuite) TestUpdate_AppIdNotUnique() { @@ -227,10 +222,9 @@ func (s *ApplicationSuite) TestUpdate_AppIdNotUnique() { err := s.api.Invoke("system/application/update_application"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.AlreadyExists, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode) } func (s *ApplicationSuite) TestUpdate_AppNotFound() { @@ -244,10 +238,9 @@ func (s *ApplicationSuite) TestUpdate_AppNotFound() { err := s.api.Invoke("system/application/update_application"). JsonRequestBody(apiReq). Do(s.T().Context()) - statusErr, ok := status.FromError(err) - s.Require().True(ok) - s.Require().NotNil(statusErr) - s.Require().Equal(codes.NotFound, statusErr.Code()) + apiError := apierrors.FromError(err) + s.Require().NotNil(apiError) + s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode) } func (s *ApplicationSuite) createAppGroup() *entity.AppGroup { From 4e85278a63fe5a070f639ce2e23814cced85893a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Thu, 3 Apr 2025 14:01:16 +0300 Subject: [PATCH 29/30] MSP-5186 Add /application_group/get_all endpoint --- controller/app_group.go | 15 +++++++++++++++ docs/swagger.yaml | 21 +++++++++++++++++++++ repository/app_group.go | 19 +++++++++++++++++++ routes/routes.go | 4 ++++ service/app_group.go | 12 ++++++++++++ service/interfaces.go | 1 + tests/app_group_test.go | 28 ++++++++++++++++++++++++++++ 7 files changed, 100 insertions(+) diff --git a/controller/app_group.go b/controller/app_group.go index 171fcf0..9b50c28 100644 --- a/controller/app_group.go +++ b/controller/app_group.go @@ -15,6 +15,7 @@ type AppGroupService interface { Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error) + GetAll(ctx context.Context) ([]domain.AppGroup, error) } type AppGroup struct { @@ -122,3 +123,17 @@ func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*do func (c AppGroup) GetByIdList(ctx context.Context, req domain.IdListRequest) ([]domain.AppGroup, error) { return c.service.GetByIdList(ctx, req.IdList) } + +// GetAll godoc +// +// @Tags application_group +// @Summary Получить группы приложений +// @Description Возвращает все группы приложений +// @Accept json +// @Produce json +// @Success 200 {array} domain.AppGroup +// @Failure 500 {object} apierrors.Error +// @Router /application_group/get_all [POST] +func (c AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) { + return c.service.GetAll(ctx) +} diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 534432b..59d2f99 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -830,6 +830,27 @@ paths: summary: Удалить группы приложений tags: - application_group + /application_group/get_all: + post: + consumes: + - application/json + description: Возвращает все группы приложений + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/domain.AppGroup' + type: array + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/apierrors.Error' + summary: Получить группы приложений + tags: + - application_group /application_group/get_by_id_list: post: consumes: diff --git a/repository/app_group.go b/repository/app_group.go index 6203411..5ce5e30 100644 --- a/repository/app_group.go +++ b/repository/app_group.go @@ -163,3 +163,22 @@ func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) return int(rowsAffected), nil } + +func (r AppGroup) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) { + q, arg, err := query.New(). + Select("id", "name", "description", "domain_id", "created_at", "updated_at"). + From("application_group"). + OrderBy("created_at DESC"). + ToSql() + if err != nil { + return nil, errors.WithMessage(err, "build query") + } + + result := make([]entity.AppGroup, 0) + err = r.db.Select(ctx, &result, q, arg...) + if err != nil { + return nil, errors.WithMessagef(err, "exec query %s", q) + } + + return result, nil +} diff --git a/routes/routes.go b/routes/routes.go index 5200ba5..79f6d36 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -229,6 +229,10 @@ func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor { Path: "system/application_group/get_by_id_list", Inner: true, Handler: c.AppGroup.GetByIdList, + }, { + Path: "system/application_group/get_all", + Inner: true, + Handler: c.AppGroup.GetAll, }, } } diff --git a/service/app_group.go b/service/app_group.go index 03a8992..685770e 100644 --- a/service/app_group.go +++ b/service/app_group.go @@ -58,6 +58,18 @@ func (s AppGroup) GetByIdList(ctx context.Context, idList []int) ([]domain.AppGr return result, nil } +func (s AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) { + appGroups, err := s.repo.GetAllAppGroups(ctx) + if err != nil { + return nil, errors.WithMessage(err, "get all appGroups") + } + result := make([]domain.AppGroup, 0, len(appGroups)) + for _, appGroup := range appGroups { + result = append(result, s.convertAppGroup(appGroup)) + } + return result, nil +} + func (s AppGroup) convertAppGroup(appGroup entity.AppGroup) domain.AppGroup { return domain.AppGroup{ Id: appGroup.Id, diff --git a/service/interfaces.go b/service/interfaces.go index 2303026..ee8a5a6 100644 --- a/service/interfaces.go +++ b/service/interfaces.go @@ -34,6 +34,7 @@ type AppGroupRepo interface { GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) + GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) diff --git a/tests/app_group_test.go b/tests/app_group_test.go index 06fd16e..bc4eab0 100644 --- a/tests/app_group_test.go +++ b/tests/app_group_test.go @@ -247,6 +247,34 @@ func (s *AppGroupSuite) TestDeleteList() { s.Require().NoError(err) } +func (s *AppGroupSuite) TestGetAll() { + toGenerate := 10 + appGroups := make([]domain.AppGroup, 0, toGenerate) + for range 10 { + appGroup := s.createAppGroup() + appGroups = append(appGroups, domain.AppGroup{ + Id: appGroup.Id, + Name: appGroup.Name, + Description: appGroup.Description.String, + CreatedAt: time.Time{}, + UpdatedAt: time.Time{}, + }) + } + result := []domain.AppGroup{} + err := s.api.Invoke("system/application_group/get_all"). + JsonResponseBody(&result). + Do(s.T().Context()) + s.Require().NoError(err) + for i := range result { + s.Require().NotEmpty(result[i].CreatedAt) + result[i].CreatedAt = time.Time{} + + s.Require().NotEmpty(result[i].UpdatedAt) + result[i].UpdatedAt = time.Time{} + } + s.Require().ElementsMatch(appGroups, result) +} + func (s *AppGroupSuite) createAppGroup() *entity.AppGroup { appGroup, err := s.appGroupRepo.CreateAppGroup( s.T().Context(), From aaecace6dfb2a4e303a9b649cdb7b5ca95c96c37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=B8=D0=BD=D0=B5=D0=BB=D1=8C=D0=BD=D0=B8=D0=BA=20?= =?UTF-8?q?=D0=A2=D0=B8=D0=BC=D1=83=D1=80=20=D0=A0=D0=BE=D0=BC=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=B8=D1=87?= Date: Wed, 2 Apr 2025 12:34:53 +0300 Subject: [PATCH 30/30] MSP-5186 Bump version to 5.2.0 --- .version | 2 +- CHANGELOG.md | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.version b/.version index 3bff059..7cbea07 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -5.1.1 \ No newline at end of file +5.2.0 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index cad6e20..6df381e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +### v5.2.0 +* Обновлены зависимости +* Добавлены новые endpoint'ы: `/application/update_application`, `/application/create_application`, `/application_group/create`, `/application_group/update`, `/application_group/delete_list`, `/application_group/get_by_id_list`, `/application_group/get_all` ### v5.1.1 * обновлены зависимости ### v5.1.0