Improve logging

This commit is contained in:
d1slike committed 2024-05-14 14:34:13 +03:00
1 parent cddd3383e8
commit 3b34468842
27 files changed
+908 -82

No files matched your search

+4 -1
View File
@@ -61,11 +61,13 @@ func (l Locator) Config() Config {
InsecureSkipVerify: true,
}),
)
emitter := module.NewEmitter(l.logger)
subscriptionService := subscription.NewService(
moduleRepo,
backendRepo,
configRepo,
etpSrv.Rooms(),
emitter,
l.logger,
)
@@ -76,6 +78,7 @@ func (l Locator) Config() Config {
configRepo,
configSchemaRepo,
subscriptionService,
emitter,
l.logger,
)
moduleController := controller.NewModule(moduleService, l.logger)
@@ -108,7 +111,7 @@ func (l Locator) Config() Config {
mapper := endpoint.DefaultWrapper(l.logger)
grpcMux := routes.GrpcHandler(mapper, controllers)
routes.BindEtp(etpSrv, controllers)
routes.BindEtp(etpSrv, controllers, l.logger)
httpMux := routes.HttpHandler(etpSrv)
+111 -15
View File
@@ -2,9 +2,12 @@ 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"
)
@@ -36,7 +39,7 @@ func NewConfig(service ConfigService) Config {
// @Produce json
// @Param body body domain.GetByModuleNameRequest true "название модуля"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "если конфигурация не найдена"
// @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) {
@@ -50,7 +53,7 @@ func (c Config) GetActiveConfigByModuleName(ctx context.Context, req domain.GetB
)
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
domain.ErrorCodeConfigNotFound,
"active config not found",
err,
)
@@ -70,11 +73,16 @@ func (c Config) GetActiveConfigByModuleName(ctx context.Context, req domain.GetB
// @Param body body domain.GetByModuleIdRequest true "ID модуля"
// @Success 200 {array} domain.Config
// @Failure 400 {object} apierrors.Error "если идентификатор не указан"
// @Failure 404 {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) {
c.service.GetConfigsByModuleId(, re)
configs, err := c.service.GetConfigsByModuleId(ctx, req.ModuleId)
switch {
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return configs, nil
}
}
// CreateUpdateConfig
@@ -86,26 +94,83 @@ func (c Config) GetConfigsByModuleId(ctx context.Context, req domain.GetByModule
// @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.Config
// @Failure 404 {object} apierrors.Error "если конфигурация не найдена"
// @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, config domain.CreateUpdateConfigRequest) (*domain.Config, error) {
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 Метод получение актуальной конфигурации конфигурации
// @Description Возвращает актуальную версию конфигурации без дополнительного содержимого (ConfigData)
// @Summary Метод получение конфигурации по id
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "если не указан идентификатор конфигурации"
// @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) {
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
@@ -115,12 +180,24 @@ func (c Config) GetConfigById(ctx context.Context, req domain.ConfigIdRequest) (
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200 {object} domain.Config "активированная конфигурация"
// @Failure 404 {object} apierrors.Error "если конфигурация не найдена"
// @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) (*domain.Config, error) {
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
@@ -135,5 +212,24 @@ func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.ConfigId
// @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
}
}
+2 -2
View File
@@ -19,7 +19,7 @@ var (
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, moduleName string, err error)
OnError(ctx context.Context, conn *etp.Conn, err error)
OnModuleReady(
ctx context.Context,
conn *etp.Conn,
@@ -86,7 +86,7 @@ func (m Module) OnDisconnect(conn *etp.Conn, err error) {
}
func (m Module) OnError(conn *etp.Conn, err error) {
m.service.OnError(conn.HttpRequest().Context(), conn, helpers.ModuleName(conn), err)
m.service.OnError(conn.HttpRequest().Context(), conn, err)
}
func (m Module) OnModuleReady(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
+499
View File
@@ -0,0 +1,499 @@
basePath: /api/config
definitions:
cluster.AddressConfiguration:
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:
type: boolean
createdAt:
type: string
data:
type: object
id:
type: string
moduleId:
type: string
name:
type: string
updatedAt:
type: string
valid:
type: boolean
version:
type: integer
type: object
domain.ConfigIdRequest:
properties:
id:
type: string
required:
- id
type: object
domain.ConfigSchema:
properties:
createdAt:
type: string
id:
type: string
moduleId:
type: string
schema:
type: object
updatedAt:
type: string
version:
type: string
type: object
domain.ConfigVersion:
properties:
configId:
type: string
configVersion:
type: integer
createdAt:
type: string
data:
type: object
id:
type: string
type: object
domain.Connection:
properties:
address:
$ref: '#/definitions/cluster.AddressConfiguration'
endpoints:
items:
$ref: '#/definitions/cluster.EndpointDescriptor'
type: array
establishedAt:
type: string
libVersion:
type: string
version:
type: string
type: object
domain.CreateUpdateConfigRequest:
properties:
data:
type: object
id:
type: string
moduleId:
type: string
name:
type: string
unsafe:
type: boolean
version:
type: integer
required:
- moduleId
- name
type: object
domain.DeleteResponse:
properties:
deleted:
type: integer
type: object
domain.GetByModuleIdRequest:
properties:
moduleId:
type: string
required:
- moduleId
type: object
domain.GetByModuleNameRequest:
properties:
moduleName:
type: string
required:
- moduleName
type: object
domain.ModuleInfo:
properties:
active:
type: boolean
configSchema:
type: object
createdAt:
type: string
id:
type: string
lastConnectedAt:
type: string
lastDisconnectedAt:
type: string
name:
type: string
status:
items:
$ref: '#/definitions/domain.Connection'
type: array
type: object
github_com_txix-open_isp-kit_grpc_apierrors.Error:
properties:
details:
additionalProperties: true
type: object
errorCode:
type: integer
errorMessage:
type: string
type: object
host: localhost:9000
info:
contact: {}
description: Модуль управления конфигурациями
license:
name: GNU GPL v3.0
title: isp-config-service
version: 1.0.0
paths:
/config/create_update_config:
post:
consumes:
- application/json
description: |-
Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
parameters:
- description: объект для сохранения
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.CreateUpdateConfigRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.Config'
"400":
description: '`errorCode: 2003` - конфиг не соотвествует текущей схеме<br/>`errorCode:
2002` - указанного id не сущесвует<br/>`errorCode: 2004` - кто-то уже
обновил конфигурацию<br/>`errorCode: 2005` - схема конфигурации не найдена<br/>'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод обновления конфигурации
tags:
- Конфигурация
/config/delete_config:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов конфигураций
in: body
name: body
required: true
schema:
items:
type: string
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: если не указан массив идентификаторов
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод удаления объектов конфигурации по идентификаторам
tags:
- Конфигурация
/config/delete_version:
post:
consumes:
- application/json
description: Возвращает количество удаленных версий
parameters:
- description: id версии конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"400":
description: не указан массив идентификаторов
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод удаления версии конфигурации
tags:
- Конфигурация
/config/get_active_config_by_module_name:
post:
consumes:
- application/json
description: Возвращает активную конфиграцию по названию модуля
parameters:
- description: название модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleNameRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.Config'
"400":
description: '`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002`
- конфиг не найден'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод получения объекта конфигурации по названию модуля
tags:
- Конфигурация
/config/get_all_version:
post:
consumes:
- application/json
description: Возвращает предыдущие версии конфигураций
parameters:
- description: id конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/domain.ConfigVersion'
type: array
"400":
description: если не указан массив идентификаторов
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод получение старых версий конфигурации
tags:
- Конфигурация
/config/get_config_by_id:
post:
consumes:
- application/json
parameters:
- description: id конфигурации
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.Config'
"400":
description: '`errorCode: 2002` - конфиг не найден<br/>'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод получение конфигурации по id
tags:
- Конфигурация
/config/get_configs_by_module_id:
post:
consumes:
- application/json
description: Возвращает список конфиграции по ID модуля
parameters:
- description: ID модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/domain.Config'
type: array
"400":
description: если идентификатор не указан
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод получения списка конфигураций по ID модуля
tags:
- Конфигурация
/config/mark_config_as_active:
post:
consumes:
- application/json
description: Активирует указанную конфигурацию и деактивирует остальные, возвращает
активированную конфигурацию
parameters:
- description: id конфигурации для изменения
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.ConfigIdRequest'
produces:
- application/json
responses:
"200":
description: OK
"400":
description: '`errorCode: 2002` - конфиг не найден<br/>'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод активации конфигурации для модуля
tags:
- Конфигурация
/module/delete_module:
post:
consumes:
- application/json
description: Возвращает количество удаленных модулей
parameters:
- description: массив идентификаторов модулей
in: body
name: body
required: true
schema:
items:
type: string
type: array
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.DeleteResponse'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод удаления объектов модулей по идентификаторам
tags:
- Модули
/module/get_modules_info:
post:
consumes:
- application/json
description: Возвращает полное состояние всех модулей в кластере (схема конфигурации,
подключенные экземпляры)
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/domain.ModuleInfo'
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:
- application/json
description: Возвращает текущую json схему конфигурации модуля
parameters:
- description: идентификатор модуля
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.GetByModuleIdRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/domain.ConfigSchema'
"400":
description: '`errorCode: 2005` - схема для модуля не найдена'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод получения схемы конфигурации модуля
tags:
- Схема
swagger: "2.0"
+1 -1
View File
@@ -21,6 +21,6 @@ type CreateUpdateConfigRequest struct {
Name string `validate:"required"`
ModuleId string `validate:"required"`
Version int
Data json.RawMessage
Data json.RawMessage `swaggertype:"object"`
Unsafe bool
}
+4 -4
View File
@@ -17,7 +17,7 @@ type ModuleInfo struct {
Active bool
LastConnectedAt *time.Time
LastDisconnectedAt *time.Time
ConfigSchema json.RawMessage
ConfigSchema json.RawMessage `swaggertype:"object"`
Status []Connection
CreatedAt time.Time
}
@@ -35,7 +35,7 @@ type Config struct {
Name string
ModuleId string
Valid bool
Data json.RawMessage
Data json.RawMessage `swaggertype:"object"`
Version int
Active bool
CreatedAt time.Time
@@ -46,7 +46,7 @@ type ConfigVersion struct {
Id string
ConfigId string
ConfigVersion int
Data json.RawMessage
Data json.RawMessage `swaggertype:"object"`
CreatedAt time.Time
}
@@ -54,7 +54,7 @@ type ConfigSchema struct {
Id string
Version string
ModuleId string
Schema json.RawMessage
Schema json.RawMessage `swaggertype:"object"`
CreatedAt time.Time
UpdatedAt time.Time
}
+1
View File
@@ -11,6 +11,7 @@ type Config struct {
Data []byte `json:"data"`
Version int `json:"version"`
Active xtypes.Bool `json:"active"`
AdminId int `json:"admin_id"`
CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"`
}
+6 -3
View File
@@ -7,11 +7,15 @@ require (
github.com/google/uuid v1.6.0
github.com/pkg/errors v0.9.1
github.com/pressly/goose/v3 v3.20.0
github.com/prometheus/client_golang v1.19.0
github.com/rqlite/gorqlite v0.0.0-20240227123050-397b03f02418
github.com/rqlite/rqlite/v8 v8.23.4
github.com/tidwall/gjson v1.17.1
github.com/txix-open/etp/v3 v3.1.0
github.com/txix-open/isp-kit v1.31.2
github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/sync v0.7.0
google.golang.org/grpc v1.63.2
)
require (
@@ -49,7 +53,6 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.19.0 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.53.0 // indirect
github.com/prometheus/procfs v0.14.0 // indirect
@@ -63,6 +66,8 @@ require (
github.com/txix-open/jsonschema v1.2.0 // indirect
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
go.etcd.io/bbolt v1.3.9 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.51.0 // indirect
go.opentelemetry.io/otel v1.26.0 // indirect
@@ -76,12 +81,10 @@ require (
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be // indirect
google.golang.org/grpc v1.63.2 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
+7
View File
@@ -237,6 +237,13 @@ github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99/go.mod h1:pA0NYmhL0uEkkxj55S+S7MZU4e2QIt46x9XSrzrWc3c=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
go.etcd.io/bbolt v1.3.9 h1:8x7aARPEXiXbHmtUwAIv7eV2fQFHrLLavdiJ3uzJXoI=
+9
View File
@@ -2,10 +2,12 @@ package helpers
import (
"net"
"strconv"
"github.com/pkg/errors"
"github.com/txix-open/etp/v3"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity"
)
@@ -23,3 +25,10 @@ func SplitAddress(backend entity.Backend) (cluster.AddressConfiguration, error)
Port: port,
}, nil
}
func LogFields(conn *etp.Conn) []log.Field {
return []log.Field{
log.String("moduleName", ModuleName(conn)),
log.String("connId", strconv.FormatUint(conn.Id(), 10)),
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ var (
)
// @title isp-config-service
// @version 1.0.0
// @version 3.0.0
// @description Модуль управления конфигурациями
// @license.name GNU GPL v3.0
+32
View File
@@ -0,0 +1,32 @@
package middlewares
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/metrics"
"isp-config-service/middlewares/sql_metrics"
)
func SqlOperationMiddleware() httpcli.Middleware {
sqlQueryDuration := metrics.GetOrRegister(metrics.DefaultRegistry, prometheus.NewSummaryVec(prometheus.SummaryOpts{
Subsystem: "sql",
Name: "query_duration_ms",
Help: "The latencies of sql query",
Objectives: metrics.DefaultObjectives,
}, []string{"operation"}))
return func(next httpcli.RoundTripper) httpcli.RoundTripper {
return httpcli.RoundTripperFunc(func(ctx context.Context, request *httpcli.Request) (*httpcli.Response, error) {
label := sql_metrics.OperationLabelFromContext(ctx)
now := time.Now()
resp, err := next.RoundTrip(ctx, request)
if label != "" {
duration := time.Since(now)
sqlQueryDuration.WithLabelValues(label).Observe(metrics.Milliseconds(duration))
}
return resp, err
})
}
}
+20
View File
@@ -0,0 +1,20 @@
package sql_metrics
import (
"context"
)
type tracerContextKey int
const (
labelContextKey = tracerContextKey(2)
)
func OperationLabelToContext(ctx context.Context, label string) context.Context {
return context.WithValue(ctx, labelContextKey, label)
}
func OperationLabelFromContext(ctx context.Context) string {
value, _ := ctx.Value(labelContextKey).(string)
return value
}
+32
View File
@@ -0,0 +1,32 @@
package middlewares
import (
"context"
"github.com/txix-open/etp/v3"
"github.com/txix-open/etp/v3/msg"
"github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
)
type EtpMiddleware func(next etp.Handler) etp.Handler
func EtpLogger(logger log.Logger) EtpMiddleware {
return func(next etp.Handler) etp.Handler {
return etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fields := append(
helpers.LogFields(conn),
log.String("event", event.Name),
)
logger.Debug(ctx, "event received", fields...)
return next.Handle(ctx, conn, event)
})
}
}
func EtpChain(root etp.Handler, middlewares ...EtpMiddleware) etp.Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
root = middlewares[i](root)
}
return root
}
+3 -2
View File
@@ -17,6 +17,7 @@ create table isp_config_service__config
data blob not null,
version int not null default 1,
active int not null default 0,
admin_id int not null default 0,
created_at integer not null default (unixepoch()),
updated_at integer not null default (unixepoch()),
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
@@ -30,7 +31,7 @@ create table isp_config_service__config_history
config_id text not null,
data blob not null,
version int not null default 1,
admin_id int not null,
admin_id int not null default 0,
created_at integer not null default (unixepoch()),
foreign key (config_id) references isp_config_service__config (id) on delete cascade on update cascade
);
@@ -65,7 +66,7 @@ create table isp_config_service__backend
create table isp_config_service__event
(
id integer,
id integer,
payload blob not null,
created_at integer not null default (unixepoch()),
primary key (id desc)
+9
View File
@@ -7,6 +7,7 @@ import (
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
@@ -21,6 +22,8 @@ func NewBackend(db db.DB) Backend {
}
func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Upsert")
query, args, err := squirrel.Insert(Table("backend")).
Columns("module_id", "address",
"version", "lib_version", "module_name",
@@ -47,6 +50,8 @@ func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
}
func (r Backend) Delete(ctx context.Context, moduleId string, address string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Delete")
query, args, err := squirrel.Delete(Table("backend")).
Where(squirrel.Eq{
"module_id": moduleId,
@@ -65,6 +70,8 @@ func (r Backend) Delete(ctx context.Context, moduleId string, address string) er
}
func (r Backend) All(ctx context.Context) ([]entity.Backend, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.All")
result := make([]entity.Backend, 0)
query := fmt.Sprintf("SELECT * FROM %s order by created_at desc", Table("backend"))
err := r.db.Select(ctx, &result, query)
@@ -75,6 +82,8 @@ func (r Backend) All(ctx context.Context) ([]entity.Backend, error) {
}
func (r Backend) GetByModuleId(ctx context.Context, moduleId string) ([]entity.Backend, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.GetByModuleId")
query, args, err := squirrel.Select("*").
From(Table("backend")).
Where(squirrel.Eq{
+20 -4
View File
@@ -7,6 +7,7 @@ import (
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
@@ -21,9 +22,11 @@ func NewConfig(db db.DB) Config {
}
func (r Config) Insert(ctx context.Context, cfg entity.Config) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.Insert")
query, args, err := squirrel.Insert(Table("config")).
Columns("id", "name", "module_id", "data", "version", "active").
Values(cfg.Id, cfg.Name, cfg.ModuleId, cfg.Data, cfg.Version, cfg.Active).
Columns("id", "name", "module_id", "data", "version", "active", "admin_id").
Values(cfg.Id, cfg.Name, cfg.ModuleId, cfg.Data, cfg.Version, cfg.Active, cfg.AdminId).
Suffix("on conflict (id) do nothing").
ToSql()
if err != nil {
@@ -39,6 +42,8 @@ func (r Config) Insert(ctx context.Context, cfg entity.Config) error {
}
func (r Config) GetActive(ctx context.Context, moduleId string) (*entity.Config, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetActive")
query, args, err := squirrel.Select("*").
From(Table("config")).
Where(squirrel.Eq{
@@ -55,6 +60,8 @@ func (r Config) GetActive(ctx context.Context, moduleId string) (*entity.Config,
}
func (r Config) GetByModuleId(ctx context.Context, moduleId string) ([]entity.Config, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetByModuleId")
query, args, err := squirrel.Select("*").
From(Table("config")).
Where(squirrel.Eq{
@@ -75,6 +82,8 @@ func (r Config) GetByModuleId(ctx context.Context, moduleId string) ([]entity.Co
}
func (r Config) GetById(ctx context.Context, id string) (*entity.Config, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.GetById")
query, args, err := squirrel.Select("*").
From(Table("config")).
Where(squirrel.Eq{
@@ -88,10 +97,12 @@ func (r Config) GetById(ctx context.Context, id string) (*entity.Config, error)
}
func (r Config) DeleteNonActiveById(ctx context.Context, id string) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.DeleteNonActiveById")
query, args, err := squirrel.Delete(Table("config")).
Where(squirrel.Eq{
"id": id,
"active": "0",
"active": xtypes.Bool(false),
}).ToSql()
if err != nil {
return false, errors.WithMessage(err, "build query")
@@ -110,12 +121,15 @@ func (r Config) DeleteNonActiveById(ctx context.Context, id string) (bool, error
}
func (r Config) UpdateByVersion(ctx context.Context, cfg entity.Config) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.UpdateByVersion")
query, args, err := squirrel.Update(Table("config")).
SetMap(map[string]interface{}{
SetMap(map[string]any{
"name": cfg.Name,
"data": cfg.Data,
"version": squirrel.Expr("version + 1"),
"updated_at": squirrel.Expr("unixepoch()"),
"admin_id": cfg.AdminId,
}).Where(squirrel.Eq{
"id": cfg.Id,
"version": cfg.Version,
@@ -137,6 +151,8 @@ func (r Config) UpdateByVersion(ctx context.Context, cfg entity.Config) (bool, e
}
func (r Config) SetActive(ctx context.Context, configId string, active xtypes.Bool) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Config.SetActive")
query, args, err := squirrel.Update(Table("config")).
Set("active", active).
Set("updated_at", squirrel.Expr("unixepoch()")).
+7
View File
@@ -7,6 +7,7 @@ import (
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
@@ -21,6 +22,8 @@ func NewConfigHistory(db db.DB) ConfigHistory {
}
func (r ConfigHistory) GetByConfigId(ctx context.Context, configId string) ([]entity.ConfigHistory, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.GetByConfigId")
query := fmt.Sprintf(`select * from %s where config_id = ? order by version desc`, Table("config_history"))
result := make([]entity.ConfigHistory, 0)
err := r.db.Select(ctx, &result, query, configId)
@@ -31,6 +34,8 @@ func (r ConfigHistory) GetByConfigId(ctx context.Context, configId string) ([]en
}
func (r ConfigHistory) Delete(ctx context.Context, id string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.Delete")
query := fmt.Sprintf(`delete from %s where id = ?`, Table("config_history"))
_, err := r.db.Exec(ctx, query, id)
if err != nil {
@@ -40,6 +45,8 @@ func (r ConfigHistory) Delete(ctx context.Context, id string) error {
}
func (r ConfigHistory) Insert(ctx context.Context, history entity.ConfigHistory) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigHistory.Insert")
query, args, err := squirrel.Insert(Table("config_history")).
Columns("id", "config_id", "data", "version", "admin_id").
Values(history.Id, history.ConfigId, history.Data, history.Version, history.AdminId).
+7
View File
@@ -8,6 +8,7 @@ import (
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
@@ -22,6 +23,8 @@ func NewConfigSchema(db db.DB) ConfigSchema {
}
func (r ConfigSchema) Upsert(ctx context.Context, schema entity.ConfigSchema) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.Upsert")
query, args, err := squirrel.Insert(Table("config_schema")).
Columns("id", "module_id", "data", "module_version").
Values(schema.Id, schema.ModuleId, schema.Data, schema.ModuleVersion).
@@ -41,6 +44,8 @@ func (r ConfigSchema) Upsert(ctx context.Context, schema entity.ConfigSchema) er
}
func (r ConfigSchema) All(ctx context.Context) ([]entity.ConfigSchema, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.All")
result := make([]entity.ConfigSchema, 0)
query := fmt.Sprintf("select * from %s order by created_at", Table("config_schema"))
err := r.db.Select(ctx, &result, query)
@@ -51,6 +56,8 @@ func (r ConfigSchema) All(ctx context.Context) ([]entity.ConfigSchema, error) {
}
func (r ConfigSchema) GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "ConfigSchema.GetByModuleId")
query, args, err := squirrel.Select("*").
From(Table("config_schema")).
Where(squirrel.Eq{"module_id": moduleId}).
+7
View File
@@ -7,6 +7,7 @@ import (
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
@@ -21,6 +22,8 @@ func NewEvent(db db.DB) Event {
}
func (r Event) Insert(ctx context.Context, event entity.Event) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Event.Insert")
query := fmt.Sprintf("insert into %s (payload) values (?)", Table("event"))
_, err := r.db.Exec(ctx, query, event.Payload)
if err != nil {
@@ -30,6 +33,8 @@ func (r Event) Insert(ctx context.Context, event entity.Event) error {
}
func (r Event) Get(ctx context.Context, lastEventId int, limit int) ([]entity.Event, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Event.Get")
query := fmt.Sprintf("select * from %s where id > ? order by id desc limit ?", Table("event"))
result := make([]entity.Event, 0)
err := r.db.Select(ctx, &result, query, lastEventId, limit)
@@ -40,6 +45,8 @@ func (r Event) Get(ctx context.Context, lastEventId int, limit int) ([]entity.Ev
}
func (r Event) DeleteByCreatedAt(ctx context.Context, before xtypes.Time) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Event.DeleteByCreatedAt")
query := fmt.Sprintf("delete from %s where created_at < ?", Table("event"))
result, err := r.db.Exec(ctx, query, before)
if err != nil {
+13
View File
@@ -7,6 +7,7 @@ import (
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
)
@@ -21,6 +22,8 @@ func NewModule(db db.DB) Module {
}
func (r Module) Upsert(ctx context.Context, module entity.Module) (string, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.Upsert")
query, args, err := squirrel.Insert(Table("module")).
Columns("id", "name", "last_connected_at").
Values(module.Id, module.Name, squirrel.Expr("unixepoch()")).
@@ -43,6 +46,8 @@ func (r Module) SetDisconnectedAtNow(
ctx context.Context,
moduleId string,
) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.SetDisconnectedAtNow")
query, args, err := squirrel.Update(Table("module")).
Set("last_disconnected_at", squirrel.Expr("unixepoch()")).
Where(squirrel.Eq{"id": moduleId}).
@@ -60,6 +65,8 @@ func (r Module) SetDisconnectedAtNow(
}
func (r Module) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.GetByNames")
query, args, err := squirrel.Select("*").
From(Table("module")).
Where(squirrel.Eq{
@@ -80,11 +87,15 @@ func (r Module) GetByNames(ctx context.Context, names []string) ([]entity.Module
}
func (r Module) GetById(ctx context.Context, id string) (*entity.Module, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.GetById")
query := fmt.Sprintf("select * from %s where id = ?", Table("module"))
return selectRow[entity.Module](ctx, r.db, query, id)
}
func (r Module) All(ctx context.Context) ([]entity.Module, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.All")
result := make([]entity.Module, 0)
query := fmt.Sprintf("select * from %s order by name", Table("module"))
err := r.db.Select(ctx, &result, query)
@@ -95,6 +106,8 @@ func (r Module) All(ctx context.Context) ([]entity.Module, error) {
}
func (r Module) Delete(ctx context.Context, id string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Module.Delete")
query, args, err := squirrel.Delete(Table("module")).
Where(squirrel.Eq{"id": id}).
ToSql()
+15 -4
View File
@@ -7,8 +7,10 @@ import (
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/log"
"isp-config-service/controller"
"isp-config-service/controller/api"
mws "isp-config-service/middlewares"
)
type Controllers struct {
@@ -31,13 +33,22 @@ func GrpcHandler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
return muxer
}
func BindEtp(etpSrv *etp.Server, c Controllers) {
func BindEtp(etpSrv *etp.Server, c Controllers, logger log.Logger) {
middlewares := []mws.EtpMiddleware{
mws.EtpLogger(logger),
}
etpSrv.OnConnect(c.Module.OnConnect)
etpSrv.OnDisconnect(c.Module.OnDisconnect)
etpSrv.OnError(c.Module.OnError)
etpSrv.On(cluster.ModuleSendConfigSchema, etp.HandlerFunc(c.Module.OnModuleConfigSchema))
etpSrv.On(cluster.ModuleSendRequirements, etp.HandlerFunc(c.Module.OnModuleRequirements))
etpSrv.On(cluster.ModuleReady, etp.HandlerFunc(c.Module.OnModuleReady))
onConfigSchema := mws.EtpChain(etp.HandlerFunc(c.Module.OnModuleConfigSchema), middlewares...)
etpSrv.On(cluster.ModuleSendConfigSchema, onConfigSchema)
onRequirements := mws.EtpChain(etp.HandlerFunc(c.Module.OnModuleRequirements), middlewares...)
etpSrv.On(cluster.ModuleSendRequirements, onRequirements)
onModuleReady := mws.EtpChain(etp.HandlerFunc(c.Module.OnModuleReady), middlewares...)
etpSrv.On(cluster.ModuleReady, onModuleReady)
}
func HttpHandler(etpSrv *etp.Server) http.Handler {
+3 -1
View File
@@ -118,6 +118,7 @@ func (c Config) CreateUpdateConfig(
Data: req.Data,
Version: 1,
Active: false,
AdminId: adminId,
}
err := c.configRepo.Insert(ctx, config)
if err != nil {
@@ -140,6 +141,7 @@ func (c Config) CreateUpdateConfig(
Name: req.Name,
Data: req.Data,
Version: req.Version,
AdminId: adminId,
}
updated, err := c.configRepo.UpdateByVersion(ctx, config)
if err != nil {
@@ -154,7 +156,7 @@ func (c Config) CreateUpdateConfig(
ConfigId: req.Id,
Data: oldConfig.Data,
Version: oldConfig.Version,
AdminId: adminId,
AdminId: oldConfig.AdminId,
}
err = c.configHistoryRepo.Insert(ctx, history)
if err != nil {
+59
View File
@@ -0,0 +1,59 @@
package module
import (
"context"
"strings"
"time"
"github.com/pkg/errors"
"github.com/txix-open/etp/v3"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
)
const (
emitEventTimeout = 5 * time.Second
)
type Emitter struct {
logger log.Logger
}
func NewEmitter(logger log.Logger) Emitter {
return Emitter{
logger: logger,
}
}
func (s Emitter) Emit(
ctx context.Context,
conn *etp.Conn,
event string,
data []byte,
) {
ctx, cancel := context.WithTimeout(ctx, emitEventTimeout)
defer cancel()
fields := append(helpers.LogFields(conn), log.String("event", event))
if strings.HasSuffix(event, cluster.ModuleConnectionSuffix) {
fields = append(fields, log.ByteString("data", data))
}
s.logger.Debug(
ctx,
"emit event",
fields...,
)
err := conn.Emit(ctx, event, data)
if err != nil {
err := errors.WithMessagef(
err,
"emit event '%s', to %s module, connId: %d",
event, helpers.ModuleName(conn), conn.Id(),
)
s.logger.Error(ctx, err)
}
}
+20 -16
View File
@@ -61,6 +61,7 @@ type Service struct {
configRepo ConfigRepo
configSchemaRepo ConfigSchemaRepo
subscriptionService SubscriptionService
emitter Emitter
logger log.Logger
}
@@ -71,6 +72,7 @@ func NewService(
configRepo ConfigRepo,
configSchemaRepo ConfigSchemaRepo,
subscriptionService SubscriptionService,
emitter Emitter,
logger log.Logger,
) Service {
return Service{
@@ -80,11 +82,14 @@ func NewService(
configRepo: configRepo,
configSchemaRepo: configSchemaRepo,
subscriptionService: subscriptionService,
emitter: emitter,
logger: logger,
}
}
func (s Service) OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error {
s.logger.Info(ctx, "module connected", helpers.LogFields(conn)...)
module := entity.Module{
Id: uuid.NewString(),
Name: moduleName,
@@ -107,14 +112,17 @@ func (s Service) OnDisconnect(
err error,
) error {
if isNormalClose {
s.logger.Info(ctx, fmt.Sprintf("module '%s' disconnected", moduleName))
} else {
message := errors.WithMessagef(
err,
"module '%s' unexpectedly disconnected",
moduleName,
s.logger.Info(
ctx,
"module disconnected",
helpers.LogFields(conn)...,
)
s.logger.Error(ctx, message)
} else {
message := errors.WithMessage(
err,
"module unexpectedly disconnected",
)
s.logger.Error(ctx, message, helpers.LogFields(conn)...)
}
moduleId, _ := store.Get[string](conn.Data(), moduleIdKey)
@@ -146,13 +154,12 @@ func (s Service) OnDisconnect(
return nil
}
func (s Service) OnError(ctx context.Context, conn *etp.Conn, moduleName string, err error) {
err = errors.WithMessagef(
func (s Service) OnError(ctx context.Context, conn *etp.Conn, err error) {
err = errors.WithMessage(
err,
"unexpected error in communication, module: '%s'",
moduleName,
"unexpected error in communication",
)
s.logger.Error(ctx, err)
s.logger.Error(ctx, err, helpers.LogFields(conn)...)
}
func (s Service) OnModuleReady(
@@ -248,10 +255,7 @@ func (s Service) OnModuleConfigSchema(
return errors.WithMessage(err, "get active config")
}
err = conn.Emit(ctx, cluster.ConfigSendConfigWhenConnected, config.Data)
if err != nil {
return errors.WithMessage(err, "send event with config")
}
s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigWhenConnected, config.Data)
s.subscriptionService.SubscribeToConfigChanges(conn, moduleId)
+6 -1
View File
@@ -20,6 +20,7 @@ import (
"github.com/txix-open/isp-kit/worker"
"isp-config-service/assembly"
"isp-config-service/conf"
"isp-config-service/middlewares"
"isp-config-service/service/rqlite"
"isp-config-service/service/rqlite/db"
"isp-config-service/service/rqlite/goose_store"
@@ -87,7 +88,11 @@ func (s *Service) Run(ctx context.Context) error {
s.logger.Debug(ctx, "is not a leader")
}
db, err := db.Open(ctx, s.rqlite.Dsn(), httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(s.logger))))
db, err := db.Open(
ctx,
s.rqlite.Dsn(),
httpclix.Default(httpcli.WithMiddlewares(middlewares.SqlOperationMiddleware())),
)
if err != nil {
return errors.WithMessage(err, "dial to embedded rqlite")
}
+10 -27
View File
@@ -2,7 +2,6 @@ package subscription
import (
"context"
"time"
"github.com/pkg/errors"
"github.com/txix-open/etp/v3"
@@ -28,11 +27,16 @@ type ConfigRepo interface {
GetActive(ctx context.Context, moduleId string) (*entity.Config, error)
}
type Emitter interface {
Emit(ctx context.Context, conn *etp.Conn, event string, data []byte)
}
type Service struct {
moduleRepo ModuleRepo
backendRepo BackendRepo
configRepo ConfigRepo
rooms *etp.Rooms
emitter Emitter
logger log.Logger
}
@@ -41,6 +45,7 @@ func NewService(
backendRepo BackendRepo,
configRepo ConfigRepo,
rooms *etp.Rooms,
emitter Emitter,
logger log.Logger,
) Service {
return Service{
@@ -48,6 +53,7 @@ func NewService(
backendRepo: backendRepo,
configRepo: configRepo,
rooms: rooms,
emitter: emitter,
logger: logger,
}
}
@@ -70,7 +76,7 @@ func (s Service) NotifyConfigChanged(ctx context.Context, moduleId string) error
for _, conn := range conns {
go func() {
s.emitEvent(ctx, conn, cluster.ConfigSendConfigChanged, config.Data)
s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigChanged, config.Data)
}()
}
@@ -141,7 +147,7 @@ func (s Service) notifyBackendsChanged(
for _, conn := range conns {
go func() {
s.emitEvent(ctx, conn, cluster.ModuleConnectedEvent(module.Name), data)
s.emitter.Emit(ctx, conn, cluster.ModuleConnectedEvent(module.Name), data)
}()
}
@@ -196,32 +202,9 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
for _, conn := range conns {
go func() {
s.emitEvent(ctx, conn, event, data)
s.emitter.Emit(ctx, conn, event, data)
}()
}
return nil
}
const (
emitEventTimeout = 5 * time.Second
)
func (s Service) emitEvent(
ctx context.Context,
conn *etp.Conn,
event string,
data []byte,
) {
ctx, cancel := context.WithTimeout(ctx, emitEventTimeout)
defer cancel()
err := conn.Emit(ctx, event, data)
if err != nil {
err := errors.WithMessagef(
err,
"emit event '%s', to %s module, connId: %d",
event, helpers.ModuleName(conn), conn.Id(),
)
s.logger.Error(ctx, err)
}
}