From 2228e02770769b214d7be1cc77e6ed22e3d630db Mon Sep 17 00:00:00 2001 From: d1slike Date: Thu, 16 May 2024 20:27:40 +0300 Subject: [PATCH] Implement missing endpoint --- controller/api/module.go | 22 ++++++++++++-- docs/swagger.yaml | 48 +++++++++++++++++++---------- domain/response.go | 15 +++++++-- repository/config.go | 2 +- routes/routes.go | 6 +++- service/api/module.go | 62 ++++++++++++++++++++++++++++++++------ service/module/service.go | 6 ++-- service/startup/service.go | 3 +- 8 files changed, 128 insertions(+), 36 deletions(-) diff --git a/controller/api/module.go b/controller/api/module.go index d494e0e..ab8e6e8 100644 --- a/controller/api/module.go +++ b/controller/api/module.go @@ -10,6 +10,7 @@ import ( type ModuleService interface { Status(ctx context.Context) ([]domain.ModuleInfo, error) Delete(ctx context.Context, id string) error + Connections(ctx context.Context) ([]domain.Connection, error) } type Module struct { @@ -22,7 +23,7 @@ func NewModule(service ModuleService) Module { } } -// GetModulesAggregatedInfo +// Status // @Summary Метод полчения полной информации о состоянии модулей // @Description Возвращает полное состояние всех модулей в кластере (схема конфигурации, подключенные экземпляры) // @Tags Модули @@ -31,7 +32,7 @@ func NewModule(service ModuleService) Module { // @Success 200 {array} domain.ModuleInfo // @Failure 500 {object} apierrors.Error // @Router /module/get_modules_info [POST] -func (c Module) GetModulesAggregatedInfo(ctx context.Context) ([]domain.ModuleInfo, error) { +func (c Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) { modulesInfo, err := c.service.Status(ctx) if err != nil { return nil, apierrors.NewInternalServiceError(err) @@ -64,6 +65,23 @@ func (c Module) DeleteModule(ctx context.Context, identities []string) (*domain. }, nil } +// Connections +// @Summary Метод получения маршрутов +// @Description Возвращает все доступные роуты +// @Tags Модули +// @Accept json +// @Produce json +// @Success 200 {array} domain.Connection +// @Failure 500 {object} apierrors.Error +// @Router /routing/get_routes [POST] +func (c Module) Connections(ctx context.Context) ([]domain.Connection, error) { + connections, err := c.service.Connections(ctx) + if err != nil { + return nil, apierrors.NewInternalServiceError(err) + } + return connections, nil +} + func getSingleId(identities []string) (string, error) { if len(identities) == 0 { return "", apierrors.NewBusinessError(domain.ErrorCodeBadRequest, "at least one id is required", nil) diff --git a/docs/swagger.yaml b/docs/swagger.yaml index 6ccf683..b87c30c 100644 --- a/docs/swagger.yaml +++ b/docs/swagger.yaml @@ -1,24 +1,12 @@ basePath: /api/config definitions: - cluster.AddressConfiguration: + domain.Address: properties: ip: type: string port: type: string type: object - cluster.EndpointDescriptor: - properties: - extra: - additionalProperties: {} - type: object - inner: - type: boolean - path: - type: string - userAuthRequired: - type: boolean - type: object domain.Config: properties: active: @@ -78,10 +66,10 @@ definitions: domain.Connection: properties: address: - $ref: '#/definitions/cluster.AddressConfiguration' + $ref: '#/definitions/domain.Address' endpoints: items: - $ref: '#/definitions/cluster.EndpointDescriptor' + $ref: '#/definitions/domain.EndpointDescriptor' type: array establishedAt: type: string @@ -113,6 +101,13 @@ definitions: deleted: type: integer type: object + domain.EndpointDescriptor: + properties: + inner: + type: boolean + path: + type: string + type: object domain.GetByModuleIdRequest: properties: moduleId: @@ -165,7 +160,7 @@ info: license: name: GNU GPL v3.0 title: isp-config-service - version: 1.0.0 + version: 3.0.0 paths: /config/create_update_config: post: @@ -466,6 +461,27 @@ paths: summary: Метод полчения полной информации о состоянии модулей tags: - Модули + /routing/get_routes: + post: + consumes: + - application/json + description: Возвращает все доступные роуты + produces: + - application/json + responses: + "200": + description: OK + schema: + items: + $ref: '#/definitions/domain.Connection' + type: array + "500": + description: Internal Server Error + schema: + $ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error' + summary: Метод получения маршрутов + tags: + - Модули /schema/get_by_module_id: post: consumes: diff --git a/domain/response.go b/domain/response.go index bc92cfe..c8ffe37 100644 --- a/domain/response.go +++ b/domain/response.go @@ -3,7 +3,6 @@ package domain import ( "time" - "github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/json" ) @@ -25,11 +24,21 @@ type ModuleInfo struct { type Connection struct { LibVersion string Version string - Address cluster.AddressConfiguration - Endpoints []cluster.EndpointDescriptor + Address Address + Endpoints []EndpointDescriptor EstablishedAt time.Time } +type Address struct { + Ip string + Port string +} + +type EndpointDescriptor struct { + Path string + Inner bool +} + type Config struct { Id string Name string diff --git a/repository/config.go b/repository/config.go index 97e9d5d..0192a91 100644 --- a/repository/config.go +++ b/repository/config.go @@ -48,7 +48,7 @@ func (r Config) GetActive(ctx context.Context, moduleId string) (*entity.Config, From(Table("config")). Where(squirrel.Eq{ "module_id": moduleId, - "active": "1", + "active": xtypes.Bool(true), }).OrderBy("version DESC"). Limit(1). ToSql() diff --git a/routes/routes.go b/routes/routes.go index cf459fa..c631c0e 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -61,11 +61,15 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { return []cluster.EndpointDescriptor{{ Path: "config/module/get_modules_info", Inner: true, - Handler: c.ModuleApi.GetModulesAggregatedInfo, + Handler: c.ModuleApi.Status, }, { Path: "config/module/delete_module", Inner: true, Handler: c.ModuleApi.DeleteModule, + }, { + Path: "config/routing/get_routes", + Inner: true, + Handler: c.ModuleApi.Connections, }, { Path: "config/config/get_active_config_by_module_name", Inner: true, diff --git a/service/api/module.go b/service/api/module.go index 3e16139..b5966cb 100644 --- a/service/api/module.go +++ b/service/api/module.go @@ -1,7 +1,9 @@ package api import ( + "cmp" "context" + "slices" "time" "github.com/pkg/errors" @@ -74,16 +76,9 @@ func (s Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) { connections := make(map[string][]domain.Connection, len(modules)) for _, backend := range backends { - addr, err := helpers.SplitAddress(backend) + conn, err := s.backendToDto(backend) if err != nil { - return nil, errors.WithMessage(err, "split address") - } - conn := domain.Connection{ - LibVersion: backend.LibVersion, - Version: backend.Version, - Address: addr, - Endpoints: backend.Endpoints.Value, - EstablishedAt: time.Time(backend.UpdatedAt), + return nil, errors.WithMessage(err, "backend to dto") } connections[backend.ModuleId] = append(connections[backend.ModuleId], conn) } @@ -118,3 +113,52 @@ func (s Module) Delete(ctx context.Context, id string) error { } return nil } + +func (s Module) Connections(ctx context.Context) ([]domain.Connection, error) { + backends, err := s.backendsRepo.All(ctx) + if err != nil { + return nil, errors.WithMessage(err, "get all backends") + } + + connections := make([]domain.Connection, 0, len(backends)) + for _, backend := range backends { + conn, err := s.backendToDto(backend) + if err != nil { + return nil, errors.WithMessage(err, "backend to dto") + } + connections = append(connections, conn) + } + + return connections, nil +} + +func (s Module) backendToDto(backend entity.Backend) (domain.Connection, error) { + addr, err := helpers.SplitAddress(backend) + if err != nil { + return domain.Connection{}, errors.WithMessage(err, "split address") + } + + endpointsDescriptors := make([]domain.EndpointDescriptor, 0) + for _, desc := range backend.Endpoints.Value { + endpointsDescriptors = append(endpointsDescriptors, domain.EndpointDescriptor{ + Path: desc.Path, + Inner: desc.Inner, + }) + } + slices.SortFunc(endpointsDescriptors, func(a, b domain.EndpointDescriptor) int { + return cmp.Compare(a.Path, b.Path) + }) + + conn := domain.Connection{ + LibVersion: backend.LibVersion, + Version: backend.Version, + Address: domain.Address{ + Ip: addr.IP, + Port: addr.Port, + }, + Endpoints: endpointsDescriptors, + EstablishedAt: time.Time(backend.UpdatedAt), + } + + return conn, nil +} diff --git a/service/module/service.go b/service/module/service.go index 94434fc..722ea61 100644 --- a/service/module/service.go +++ b/service/module/service.go @@ -234,6 +234,9 @@ func (s Service) OnModuleConfigSchema( } config, err := s.configRepo.GetActive(ctx, moduleId) + if err != nil { + return errors.WithMessage(err, "get active config") + } if config == nil { hash := sha256.Sum256([]byte(moduleId)) initialConfigId := hex.EncodeToString(hash[:]) @@ -251,9 +254,6 @@ func (s Service) OnModuleConfigSchema( } config = &initialConfig } - if err != nil { - return errors.WithMessage(err, "get active config") - } s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigWhenConnected, config.Data) diff --git a/service/startup/service.go b/service/startup/service.go index f7a1866..b2924dd 100644 --- a/service/startup/service.go +++ b/service/startup/service.go @@ -17,6 +17,7 @@ import ( "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/httpclix" "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/observability/sentry" "github.com/txix-open/isp-kit/worker" "isp-config-service/assembly" "isp-config-service/conf" @@ -52,7 +53,7 @@ func New(boot *bootstrap.Bootstrap) *Service { grpcSrv: grpc.DefaultServer(), httpSrv: http.NewServer(boot.App.Logger()), clusterCli: boot.ClusterCli, - logger: boot.App.Logger(), + logger: sentry.WrapErrorLogger(boot.App.Logger(), boot.SentryHub), } }