2024-11-15 13:12:14: merge [master:93f2a5ed50211ee88fbdb241f4dbaa4af50d1d38];

This commit is contained in:
txix committed 2024-11-15 13:12:14 +03:00
1 parent 1badb6b931
commit 12b71a1777
141 files changed
+6933 -7042

No files matched your search

+236
View File
@@ -0,0 +1,236 @@
//nolint:lll
package api
import (
"context"
"strconv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/metadata"
"isp-config-service/domain"
"isp-config-service/entity"
)
type ConfigService interface {
GetActiveConfigByModuleName(ctx context.Context, moduleName string) (*domain.Config, error)
GetConfigsByModuleId(ctx context.Context, moduleId string) ([]domain.Config, error)
CreateUpdateConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (*domain.Config, error)
GetConfigById(ctx context.Context, configId string) (*domain.Config, error)
MarkConfigAsActive(ctx context.Context, configId string) error
DeleteConfig(ctx context.Context, id string) error
}
type Config struct {
service ConfigService
}
func NewConfig(service ConfigService) Config {
return Config{
service: service,
}
}
// GetActiveConfigByModuleName
// @Summary Метод получения объекта конфигурации по названию модуля
// @Description Возвращает активную конфиграцию по названию модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_active_config_by_module_name [POST]
func (c Config) GetActiveConfigByModuleName(ctx context.Context, req domain.GetByModuleNameRequest) (*domain.Config, error) {
config, err := c.service.GetActiveConfigByModuleName(ctx, req.ModuleName)
switch {
case errors.Is(err, entity.ErrModuleNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"active config not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return config, nil
}
}
// GetConfigsByModuleId
// @Summary Метод получения списка конфигураций по ID модуля
// @Description Возвращает список конфиграции по ID модуля
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "ID модуля"
// @Success 200 {array} domain.Config
// @Failure 400 {object} apierrors.Error "если идентификатор не указан"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_configs_by_module_id [POST]
func (c Config) GetConfigsByModuleId(ctx context.Context, req domain.GetByModuleIdRequest) ([]domain.Config, error) {
configs, err := c.service.GetConfigsByModuleId(ctx, req.ModuleId)
switch {
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return configs, nil
}
}
// CreateUpdateConfig
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2003` - конфиг не соотвествует текущей схеме<br/>`errorCode: 2002` - указанного id не сущесвует<br/>`errorCode: 2004` - кто-то уже обновил конфигурацию<br/>`errorCode: 2005` - схема конфигурации не найдена<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/create_update_config [POST]
func (c Config) CreateUpdateConfig(
ctx context.Context,
authData grpc.AuthData,
req domain.CreateUpdateConfigRequest,
) (*domain.Config, error) {
adminIdValue, _ := grpc.StringFromMd("x-admin-id", metadata.MD(authData))
var adminId int
if adminIdValue != "" {
adminId, _ = strconv.Atoi(adminIdValue)
}
config, err := c.service.CreateUpdateConfig(ctx, adminId, req)
var validationError domain.ConfigValidationError
switch {
case errors.As(err, &validationError):
details := map[string]any{}
for key, value := range validationError.Details {
details[key] = value
}
return nil, apierrors.NewBusinessError(
domain.ErrorCodeInvalidConfig,
"invalid config",
err,
).WithDetails(details)
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case errors.Is(err, entity.ErrConfigConflictUpdate):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigVersionConflict,
"someone has updated the config",
err,
)
case errors.Is(err, entity.ErrSchemaNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeSchemaNotFound,
"config schema not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return config, nil
}
}
// GetConfigById
// @Summary Метод получение конфигурации по id
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_config_by_id [POST]
func (c Config) GetConfigById(ctx context.Context, req domain.ConfigIdRequest) (*domain.Config, error) {
config, err := c.service.GetConfigById(ctx, req.Id)
switch {
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return config, nil
}
}
// MarkConfigAsActive
// @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/mark_config_as_active [POST]
func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.ConfigIdRequest) error {
err := c.service.MarkConfigAsActive(ctx, identity.Id)
switch {
case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
return nil
}
}
// DeleteConfigs
// @Summary Метод удаления объектов конфигурации по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов конфигураций"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error "если не указан массив идентификаторов"
// @Failure 500 {object} apierrors.Error
// @Router /config/delete_config [POST]
func (c Config) DeleteConfigs(ctx context.Context, identities []string) (*domain.DeleteResponse, error) {
configId, err := getSingleId(identities)
if err != nil {
return nil, err
}
err = c.service.DeleteConfig(ctx, configId)
switch {
case errors.Is(err, entity.ErrConfigNotFoundOrActive):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found or is active",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return &domain.DeleteResponse{
Deleted: 1,
}, nil
}
}
+63
View File
@@ -0,0 +1,63 @@
package api
import (
"context"
"github.com/txix-open/isp-kit/grpc/apierrors"
"isp-config-service/domain"
)
type ConfigHistoryService interface {
GetAllVersions(ctx context.Context, configId string) ([]domain.ConfigVersion, error)
Delete(ctx context.Context, id string) error
}
type ConfigHistory struct {
service ConfigHistoryService
}
func NewConfigHistory(service ConfigHistoryService) ConfigHistory {
return ConfigHistory{
service: service,
}
}
// GetAllVersion
// @Summary Метод получение старых версий конфигурации
// @Description Возвращает предыдущие версии конфигураций
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {array} domain.ConfigVersion
// @Failure 400 {object} apierrors.Error "если не указан массив идентификаторов"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_all_version [POST]
func (c ConfigHistory) GetAllVersion(ctx context.Context, req domain.ConfigIdRequest) ([]domain.ConfigVersion, error) {
versions, err := c.service.GetAllVersions(ctx, req.Id)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return versions, nil
}
// DeleteConfigVersion
// @Summary Метод удаления версии конфигурации
// @Description Возвращает количество удаленных версий
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id версии конфигурации"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error "не указан массив идентификаторов"
// @Failure 500 {object} apierrors.Error
// @Router /config/delete_version [POST]
func (c ConfigHistory) DeleteConfigVersion(ctx context.Context, req domain.ConfigIdRequest) (*domain.DeleteResponse, error) {
err := c.service.Delete(ctx, req.Id)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return &domain.DeleteResponse{
Deleted: 1,
}, nil
}
+51
View File
@@ -0,0 +1,51 @@
package api
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"isp-config-service/domain"
"isp-config-service/entity"
)
type ConfigSchemaService interface {
SchemaByModuleId(ctx context.Context, moduleId string) (*domain.ConfigSchema, error)
}
type ConfigSchema struct {
service ConfigSchemaService
}
func NewConfigSchema(service ConfigSchemaService) ConfigSchema {
return ConfigSchema{
service: service,
}
}
// SchemaByModuleId
// @Summary Метод получения схемы конфигурации модуля
// @Description Возвращает текущую json схему конфигурации модуля
// @Tags Схема
// @Accept json
// @Produce json
// @Param body body domain.GetByModuleIdRequest true "идентификатор модуля"
// @Success 200 {object} domain.ConfigSchema
// @Failure 400 {object} apierrors.Error "`errorCode: 2005` - схема для модуля не найдена"
// @Failure 500 {object} apierrors.Error
// @Router /schema/get_by_module_id [POST]
func (c ConfigSchema) SchemaByModuleId(ctx context.Context, request domain.GetByModuleIdRequest) (*domain.ConfigSchema, error) {
schema, err := c.service.SchemaByModuleId(ctx, request.ModuleId)
switch {
case errors.Is(err, entity.ErrSchemaNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeSchemaNotFound,
"config schema not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return schema, nil
}
}
+93
View File
@@ -0,0 +1,93 @@
package api
import (
"context"
"github.com/txix-open/isp-kit/grpc/apierrors"
"isp-config-service/domain"
)
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 {
service ModuleService
}
func NewModule(service ModuleService) Module {
return Module{
service: service,
}
}
// Status
// @Summary Метод полчения полной информации о состоянии модулей
// @Description Возвращает полное состояние всех модулей в кластере (схема конфигурации, подключенные экземпляры)
// @Tags Модули
// @Accept json
// @Produce json
// @Success 200 {array} domain.ModuleInfo
// @Failure 500 {object} apierrors.Error
// @Router /module/get_modules_info [POST]
func (c Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) {
modulesInfo, err := c.service.Status(ctx)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return modulesInfo, nil
}
// DeleteModule
// @Summary Метод удаления объектов модулей по идентификаторам
// @Description Возвращает количество удаленных модулей
// @Tags Модули
// @Accept json
// @Produce json
// @Param body body []string true "массив идентификаторов модулей"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} apierrors.Error
// @Router /module/delete_module [POST]
func (c Module) DeleteModule(ctx context.Context, identities []string) (*domain.DeleteResponse, error) {
id, err := getSingleId(identities)
if err != nil {
return nil, err
}
err = c.service.Delete(ctx, id)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return &domain.DeleteResponse{
Deleted: len(identities),
}, 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)
}
if len(identities) > 1 {
return "", apierrors.NewBusinessError(domain.ErrorCodeBadRequest, "accept only single identity", nil)
}
return identities[0], nil
}