2024-11-15 13:12:14: merge [master:93f2a5ed50211ee88fbdb241f4dbaa4af50d1d38];
This commit is contained in:
1 parent
1badb6b931
commit
12b71a1777
141 files changed
+6933
-7042
No files matched your search
+121
-95
@@ -1,117 +1,143 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc/status"
|
||||
"isp-config-service/cluster"
|
||||
"isp-config-service/domain"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/service"
|
||||
"isp-config-service/store"
|
||||
"isp-config-service/store/state"
|
||||
"time"
|
||||
"context"
|
||||
"github.com/txix-open/etp/v4"
|
||||
|
||||
"github.com/integration-system/isp-lib/v2/utils"
|
||||
"google.golang.org/grpc/codes"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v4/msg"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/helpers"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEventLifetime = 5 * time.Second
|
||||
var (
|
||||
ok = []byte("ok") //nolint:gochecknoglobals
|
||||
)
|
||||
|
||||
var Module *module
|
||||
|
||||
type module struct {
|
||||
rstore *store.Store
|
||||
type ModuleService interface {
|
||||
OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error
|
||||
OnDisconnect(ctx context.Context, conn *etp.Conn, moduleName string, isNormalClose bool, err error) error
|
||||
OnError(ctx context.Context, conn *etp.Conn, err error)
|
||||
OnModuleReady(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
backend cluster.BackendDeclaration,
|
||||
) error
|
||||
OnModuleRequirements(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
requirements cluster.ModuleRequirements,
|
||||
) error
|
||||
OnModuleConfigSchema(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
data cluster.ConfigData,
|
||||
) error
|
||||
}
|
||||
|
||||
// @Summary Метод получения полной информации о состоянии модуля
|
||||
// @Description Возвращает полное состояние всех модулей в кластере (конфигурация, схема конфигурации, подключенные экземпляры)
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.ModuleInfo
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /module/get_modules_info [POST]
|
||||
func (c *module) GetModulesAggregatedInfo() ([]domain.ModuleInfo, error) {
|
||||
var response []domain.ModuleInfo
|
||||
c.rstore.VisitReadonlyState(func(state state.ReadonlyState) {
|
||||
response = service.ModuleRegistry.GetAggregatedModuleInfo(state)
|
||||
})
|
||||
return response, nil
|
||||
type Module struct {
|
||||
service ModuleService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// @Summary Метод удаления объектов модулей по идентификаторам
|
||||
// @Description Возвращает количество удаленных модулей
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body []string true "массив идентификаторов модулей"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /module/delete_module [POST]
|
||||
func (*module) DeleteModules(identities []string) (*domain.DeleteResponse, error) {
|
||||
if len(identities) == 0 {
|
||||
validationErrors := map[string]string{
|
||||
"ids": "Required",
|
||||
}
|
||||
return nil, utils.CreateValidationErrorDetails(codes.InvalidArgument, utils.ValidationError, validationErrors)
|
||||
func NewModule(service ModuleService, logger log.Logger) Module {
|
||||
return Module{
|
||||
service: service,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var deleteResponse domain.DeleteResponse
|
||||
command := cluster.PrepareDeleteModulesCommand(identities)
|
||||
err := PerformSyncApply(command, &deleteResponse)
|
||||
func (m Module) OnConnect(conn *etp.Conn) {
|
||||
ctx := conn.HttpRequest().Context()
|
||||
err := conn.HttpRequest().ParseForm()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
m.handleError(ctx, errors.WithMessage(err, "parse form"))
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
return &deleteResponse, err
|
||||
}
|
||||
|
||||
// @Summary Метод получения модуля по имени
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.GetByModuleNameRequest true "название модуля"
|
||||
// @Success 200 {object} entity.Module
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Failure 404 {object} structure.GrpcError "модуль с указанным названием не найден"
|
||||
// @Router /module/get_by_name [POST]
|
||||
func (c *module) GetModuleByName(req domain.GetByModuleNameRequest) (*entity.Module, error) {
|
||||
var module *entity.Module
|
||||
c.rstore.VisitReadonlyState(func(readonlyState state.ReadonlyState) {
|
||||
module = readonlyState.Modules().GetByName(req.ModuleName)
|
||||
})
|
||||
if module == nil {
|
||||
return nil, status.Errorf(codes.NotFound, "module with name '%s' not found", req.ModuleName)
|
||||
moduleName := helpers.ModuleName(conn)
|
||||
if moduleName == "" {
|
||||
m.handleError(ctx, errors.New("module_name is required query param"))
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
return module, nil
|
||||
}
|
||||
|
||||
// @Summary Метод отправки события всем подключенным модулям
|
||||
// @Tags Модули
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.BroadcastEventRequest true "событие"
|
||||
// @Success 200 "OK"
|
||||
// @Failure 500 {object} structure.GrpcError
|
||||
// @Router /module/broadcast_event [POST]
|
||||
func (c *module) BroadcastEvent(req domain.BroadcastEventRequest) error {
|
||||
cmd := cluster.BroadcastEvent{
|
||||
Event: req.Event,
|
||||
ModuleNames: req.ModuleNames,
|
||||
Payload: req.Payload,
|
||||
PerformUntil: time.Now().UTC().Add(defaultEventLifetime),
|
||||
}
|
||||
command := cluster.PrepareBroadcastEventCommand(cmd)
|
||||
err := PerformSyncApply(command, nil)
|
||||
err = m.service.OnConnect(ctx, conn, moduleName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewModule(rstore *store.Store) *module {
|
||||
return &module{
|
||||
rstore: rstore,
|
||||
m.handleError(ctx, errors.WithMessage(err, "handle onConnect"))
|
||||
}
|
||||
}
|
||||
|
||||
func (m Module) OnDisconnect(conn *etp.Conn, err error) {
|
||||
ctx := conn.HttpRequest().Context()
|
||||
handleDisconnectErr := m.service.OnDisconnect(
|
||||
ctx,
|
||||
conn,
|
||||
helpers.ModuleName(conn),
|
||||
etp.IsNormalClose(err),
|
||||
err,
|
||||
)
|
||||
if handleDisconnectErr != nil {
|
||||
m.handleError(ctx, errors.WithMessage(handleDisconnectErr, "handle onDisconnect"))
|
||||
}
|
||||
}
|
||||
|
||||
func (m Module) OnError(conn *etp.Conn, err error) {
|
||||
m.service.OnError(conn.HttpRequest().Context(), conn, err)
|
||||
}
|
||||
|
||||
func (m Module) OnModuleReady(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
backend := cluster.BackendDeclaration{}
|
||||
err := json.Unmarshal(event.Data, &backend)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
|
||||
}
|
||||
|
||||
err = m.service.OnModuleReady(ctx, conn, backend)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleReady"))
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m Module) OnModuleRequirements(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
requirements := cluster.ModuleRequirements{}
|
||||
err := json.Unmarshal(event.Data, &requirements)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
|
||||
}
|
||||
|
||||
err = m.service.OnModuleRequirements(ctx, conn, requirements)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleRequirements"))
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m Module) OnModuleConfigSchema(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
configData := cluster.ConfigData{}
|
||||
err := json.Unmarshal(event.Data, &configData)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
|
||||
}
|
||||
|
||||
err = m.service.OnModuleConfigSchema(ctx, conn, configData)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleConfigSchema"))
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m Module) handleError(
|
||||
ctx context.Context,
|
||||
err error,
|
||||
) []byte {
|
||||
m.logger.Error(ctx, err)
|
||||
return []byte(err.Error())
|
||||
}
|
||||
Reference in new issue
Block a user