Implement api

This commit is contained in:
d1slike committed 2024-05-08 15:40:14 +03:00
1 parent 80a99c425b
commit b2e34c00a4
30 files changed
+708 -69

No files matched your search

+15 -1
View File
@@ -10,8 +10,10 @@ import (
"github.com/txix-open/isp-kit/log"
"github.com/txix-open/isp-kit/worker"
"isp-config-service/controller"
"isp-config-service/controller/api"
"isp-config-service/repository"
"isp-config-service/routes"
apisvs "isp-config-service/service/api"
"isp-config-service/service/event"
"isp-config-service/service/module"
"isp-config-service/service/rqlite/db"
@@ -76,8 +78,20 @@ func (l Locator) Config() Config {
l.logger,
)
moduleController := controller.NewModule(moduleService, l.logger)
moduleApiService := apisvs.NewModule(moduleRepo, backendRepo, configSchemaRepo)
moduleApiController := api.NewModule(moduleApiService)
configApiController := api.NewConfig(nil)
configHistoryController := api.NewConfigHistory(nil)
configSchemaController := api.NewConfigSchema(nil)
controllers := routes.Controllers{
Module: moduleController,
Module: moduleController,
ModuleApi: moduleApiController,
ConfigApi: configApiController,
ConfigHistoryApi: configHistoryController,
ConfigSchemaApi: configSchemaController,
}
mapper := endpoint.DefaultWrapper(l.logger)
grpcMux := routes.GrpcHandler(mapper, controllers)
+1
View File
@@ -18,4 +18,5 @@ rqlite:
RaftAddr: "127.0.0.1:9003"
JoinAddrs: "127.0.0.1:9003"
FKConstraints: true
AutoVacInterval: 12h
+118
View File
@@ -0,0 +1,118 @@
package api
import (
"context"
"isp-config-service/domain"
)
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, moduleId string) (*domain.Config, error)
GetConfigById(ctx context.Context, configId string) (*domain.Config, error)
MarkConfigAsActive(ctx context.Context, configId string) error
DeleteConfigs(ctx context.Context, idList []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 404 {object} apierrors.Error "если конфигурация не найдена"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_active_config_by_module_name [POST]
func (c Config) GetActiveConfigByModuleName(ctx context.Context, request domain.GetByModuleNameRequest) (*domain.Config, error) {
}
// 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 404 {object} apierrors.Error "если конфигурация не найдена"
// @Failure 500 {object} apierrors.Error
// @Router /config/get_configs_by_module_id [POST]
func (c Config) GetConfigsByModuleId(ctx context.Context, request domain.GetByModuleIdRequest) ([]domain.Config, error) {
}
// CreateUpdateConfig
// @Summary Метод обновления конфигурации
// @Description Если конфиг с таким id существует, то обновляет данные, если нет, то добавляет данные в базу
// @Description В случае обновления рассылает всем подключенным модулям актуальную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.CreateUpdateConfigRequest true "объект для сохранения"
// @Success 200 {object} domain.Config
// @Failure 404 {object} apierrors.Error "если конфигурация не найдена"
// @Failure 500 {object} apierrors.Error
// @Router /config/create_update_config [POST]
func (c Config) CreateUpdateConfig(ctx context.Context, config domain.CreateUpdateConfigRequest) (*domain.Config, error) {
}
// GetConfigById
// @Summary Метод получение актуальной конфигурации конфигурации
// @Description Возвращает актуальную версию конфигурации без дополнительного содержимого (ConfigData)
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "если не указан идентификатор конфигурации"
// @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) {
}
// MarkConfigAsActive
// @Summary Метод активации конфигурации для модуля
// @Description Активирует указанную конфигурацию и деактивирует остальные, возвращает активированную конфигурацию
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.ConfigIdRequest true "id конфигурации для изменения"
// @Success 200 {object} domain.Config "активированная конфигурация"
// @Failure 404 {object} apierrors.Error "если конфигурация не найдена"
// @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) {
}
// 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) {
}
+52
View File
@@ -0,0 +1,52 @@
package api
import (
"context"
"isp-config-service/domain"
)
type ConfigHistoryService interface {
GetAllVersion(ctx context.Context, configId string) ([]domain.ConfigVersion, error)
DeleteConfigVersion(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) {
}
// 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) {
}
+36
View File
@@ -0,0 +1,36 @@
package api
import (
"context"
"isp-config-service/domain"
)
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 404 {object} apierrors.Error "если схема для модуля не найдена"
// @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) {
}
+65
View File
@@ -0,0 +1,65 @@
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, idList []string) error
}
type Module struct {
service ModuleService
}
func NewModule(service ModuleService) Module {
return Module{
service: service,
}
}
// GetModulesAggregatedInfo
// @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) GetModulesAggregatedInfo(ctx context.Context) ([]domain.ModuleInfo, error) {
modulesInfo, err := c.service.Status(ctx)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return modulesInfo, nil
}
// DeleteModules
// @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) DeleteModules(ctx context.Context, identities []string) (*domain.DeleteResponse, error) {
if len(identities) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrorCodeBadRequest, "at least one id is required", nil)
}
err := c.service.Delete(ctx, identities)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return &domain.DeleteResponse{
Deleted: len(identities),
}, nil
}
+8 -1
View File
@@ -58,7 +58,14 @@ func (m Module) OnConnect(conn *etp.Conn) {
return
}
err = m.service.OnConnect(ctx, conn, helpers.ModuleName(conn))
moduleName := helpers.ModuleName(conn)
if moduleName == "" {
m.handleError(ctx, errors.New("module_name is required query param"))
_ = conn.Close()
return
}
err = m.service.OnConnect(ctx, conn, moduleName)
if err != nil {
m.handleError(ctx, errors.WithMessage(err, "handle onConnect"))
}
+5
View File
@@ -0,0 +1,5 @@
package domain
const (
ErrorCodeBadRequest = 400
)
+26
View File
@@ -0,0 +1,26 @@
package domain
import (
"github.com/txix-open/isp-kit/json"
)
type ConfigIdRequest struct {
Id string `validate:"required"`
}
type GetByModuleIdRequest struct {
ModuleId string `validate:"required"`
}
type GetByModuleNameRequest struct {
ModuleName string `validate:"required"`
}
type CreateUpdateConfigRequest struct {
Id string
Name string `validate:"required"`
ModuleId string `validate:"required"`
Version int
Data json.RawMessage
Unsafe bool
}
+61
View File
@@ -0,0 +1,61 @@
package domain
import (
"time"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/rc/schema"
)
type DeleteResponse struct {
Deleted int
}
type ModuleInfo struct {
Id string
Name string
Active bool
LastConnectedAt *time.Time
LastDisconnectedAt *time.Time
ConfigSchema json.RawMessage
Status []Connection
CreatedAt time.Time
}
type Connection struct {
LibVersion string
Version string
Address cluster.AddressConfiguration
Endpoints []cluster.EndpointDescriptor
EstablishedAt time.Time
}
type Config struct {
Id string
Name string
ModuleId string
Valid bool
Data json.RawMessage
Version int
Active bool
CreatedAt time.Time
UpdatedAt time.Time
}
type ConfigVersion struct {
Id string
ConfigId string
ConfigVersion int32
Data json.RawMessage
CreatedAt time.Time
}
type ConfigSchema struct {
Id string
Version string
ModuleId string
Schema schema.Schema
CreatedAt time.Time
UpdatedAt time.Time
}
+1 -10
View File
@@ -6,17 +6,8 @@ import (
"isp-config-service/entity/xtypes"
)
type EventType int
const (
Unknown EventType = iota
ConfigUpdated
ModuleReady
ModuleDisconnected
)
type Event struct {
RowId int `json:"rowid"`
Id int `json:"id"`
Payload xtypes.Json[EventPayload] `json:"payload"`
}
+3 -5
View File
@@ -1,8 +1,6 @@
package xtypes
type Bool struct {
Value bool
}
type Bool bool
func (l Bool) MarshalJSON() ([]byte, error) {
return l.MarshalText()
@@ -13,13 +11,13 @@ func (l *Bool) UnmarshalJSON(data []byte) error {
}
func (l Bool) MarshalText() ([]byte, error) {
if l.Value {
if l {
return []byte("1"), nil
}
return []byte("0"), nil
}
func (l *Bool) UnmarshalText(data []byte) error {
l.Value = string(data) == "1"
*l = string(data) == "1"
return nil
}
+7 -5
View File
@@ -5,9 +5,7 @@ import (
"time"
)
type Time struct {
Value time.Time
}
type Time time.Time
func (l Time) MarshalJSON() ([]byte, error) {
return l.MarshalText()
@@ -18,15 +16,19 @@ func (l *Time) UnmarshalJSON(data []byte) error {
}
func (l Time) MarshalText() ([]byte, error) {
value := strconv.Itoa(int(l.Value.Unix()))
t := time.Time(l)
value := strconv.Itoa(int(t.Unix()))
return []byte(value), nil
}
func (l *Time) UnmarshalText(data []byte) error {
if string(data) == "null" {
return nil
}
value, err := strconv.Atoi(string(data))
if err != nil {
return err
}
l.Value = time.Unix(int64(value), 0)
*l = Time(time.Unix(int64(value), 0))
return nil
}
+16
View File
@@ -1,9 +1,25 @@
package helpers
import (
"net"
"github.com/pkg/errors"
"github.com/txix-open/etp/v3"
"github.com/txix-open/isp-kit/cluster"
"isp-config-service/entity"
)
func ModuleName(conn *etp.Conn) string {
return conn.HttpRequest().Form.Get("module_name")
}
func SplitAddress(backend entity.Backend) (cluster.AddressConfiguration, error) {
host, port, err := net.SplitHostPort(backend.Address)
if err != nil {
return cluster.AddressConfiguration{}, errors.WithMessagef(err, "split backend %s address: %s", backend.ModuleId, backend.Address)
}
return cluster.AddressConfiguration{
IP: host,
Port: port,
}, nil
}
+1 -2
View File
@@ -19,11 +19,10 @@ var (
// @license.name GNU GPL v3.0
// @host localhost:9000
// @BasePath /api/isp-config-service
// @BasePath /api/config
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.json docs/docs.go
func main() {
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
app := boot.App
+3 -1
View File
@@ -65,8 +65,10 @@ create table isp_config_service__backend
create table isp_config_service__event
(
id integer,
payload blob not null,
created_at integer not null default (unixepoch())
created_at integer not null default (unixepoch()),
primary key (id desc)
);
-- +goose Down
+11
View File
@@ -2,6 +2,7 @@ package repository
import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
@@ -37,3 +38,13 @@ func (r ConfigSchema) Upsert(ctx context.Context, schema entity.ConfigSchema) er
return nil
}
func (r ConfigSchema) All(ctx context.Context) ([]entity.ConfigSchema, error) {
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)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
+3 -3
View File
@@ -29,10 +29,10 @@ func (r Event) Insert(ctx context.Context, event entity.Event) error {
return nil
}
func (r Event) Get(ctx context.Context, lastRowId int, limit int) ([]entity.Event, error) {
query := fmt.Sprintf("select * from %s where rowid > ? order by rowid desc limit ?", Table("event"))
func (r Event) Get(ctx context.Context, lastEventId int, limit int) ([]entity.Event, error) {
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, lastRowId, limit)
err := r.db.Select(ctx, &result, query, lastEventId, limit)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
+29 -7
View File
@@ -7,7 +7,6 @@ import (
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/service/rqlite/db"
)
@@ -24,9 +23,8 @@ func NewModule(db db.DB) Module {
func (r Module) Upsert(ctx context.Context, module entity.Module) (string, error) {
query, args, err := squirrel.Insert(Table("module")).
Columns("id", "name", "last_connected_at").
Values(module.Id, module.Name, module.LastConnectedAt).
Suffix(`on conflict (name) do update
set last_connected_at = excluded.last_connected_at`).
Values(module.Id, module.Name, squirrel.Expr("unixepoch()")).
Suffix(`on conflict (name) do update set last_connected_at = unixepoch()`).
Suffix("returning id").
ToSql()
if err != nil {
@@ -41,13 +39,12 @@ func (r Module) Upsert(ctx context.Context, module entity.Module) (string, error
return result["id"], nil
}
func (r Module) SetDisconnectedAt(
func (r Module) SetDisconnectedAtNow(
ctx context.Context,
moduleId string,
disconnected xtypes.Time,
) error {
query, args, err := squirrel.Update(Table("module")).
Set("last_disconnected_at", disconnected).
Set("last_disconnected_at", squirrel.Expr("unixepoch()")).
Where(squirrel.Eq{"id": moduleId}).
ToSql()
if err != nil {
@@ -92,6 +89,31 @@ func (r Module) GetById(ctx context.Context, id string) (*entity.Module, error)
return &result, nil
}
func (r Module) All(ctx context.Context) ([]entity.Module, error) {
result := make([]entity.Module, 0)
query := fmt.Sprintf("select * from %s order by name", Table("module"))
err := r.db.Select(ctx, &result, query)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Module) Delete(ctx context.Context, idList []string) error {
query, args, err := squirrel.Delete(Table("module")).
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
_, err = r.db.Exec(ctx, query, args...)
if err != nil {
return errors.WithMessagef(err, "exec: %s", query)
}
return nil
}
func Table(table string) string {
return fmt.Sprintf("isp_config_service__%s", table)
}
+51 -2
View File
@@ -8,10 +8,15 @@ import (
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"isp-config-service/controller"
"isp-config-service/controller/api"
)
type Controllers struct {
Module controller.Module
Module controller.Module
ModuleApi api.Module
ConfigApi api.Config
ConfigHistoryApi api.ConfigHistory
ConfigSchemaApi api.ConfigSchema
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
@@ -42,5 +47,49 @@ func HttpHandler(etpSrv *etp.Server) http.Handler {
}
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{}
return []cluster.EndpointDescriptor{{
Path: "module/get_modules_info",
Inner: true,
Handler: c.ModuleApi.GetModulesAggregatedInfo,
}, {
Path: "module/delete_module",
Inner: true,
Handler: c.ModuleApi.DeleteModules,
}, {
Path: "config/get_active_config_by_module_name",
Inner: true,
Handler: c.ConfigApi.GetActiveConfigByModuleName,
}, {
Path: "config/get_configs_by_module_id",
Inner: true,
Handler: c.ConfigApi.GetConfigsByModuleId,
}, {
Path: "config/create_update_config",
Inner: true,
Handler: c.ConfigApi.CreateUpdateConfig,
}, {
Path: "config/get_config_by_id",
Inner: true,
Handler: c.ConfigApi.GetConfigById,
}, {
Path: "config/mark_config_as_active",
Inner: true,
Handler: c.ConfigApi.MarkConfigAsActive,
}, {
Path: "config/delete_config",
Inner: true,
Handler: c.ConfigApi.DeleteConfigs,
}, {
Path: "config/get_all_version",
Inner: true,
Handler: c.ConfigHistoryApi.GetAllVersion,
}, {
Path: "config/delete_version",
Inner: true,
Handler: c.ConfigHistoryApi.DeleteConfigVersion,
}, {
Path: "schema/get_by_module_id",
Inner: true,
Handler: c.ConfigSchemaApi.SchemaByModuleId,
}}
}
+34
View File
@@ -0,0 +1,34 @@
package api
import (
"context"
"isp-config-service/domain"
)
type Config struct {
}
func (c Config) GetActiveConfigByModuleName(ctx context.Context, moduleName string) (*domain.Config, error) {
}
func (c Config) GetConfigsByModuleId(ctx context.Context, moduleId string) ([]domain.Config, error) {
}
func (c Config) CreateUpdateConfig(ctx context.Context, moduleId string) (*domain.Config, error) {
}
func (c Config) GetConfigById(ctx context.Context, configId string) (*domain.Config, error) {
}
func (c Config) MarkConfigAsActive(ctx context.Context, configId string) error {
}
func (c Config) DeleteConfigs(ctx context.Context, idList []string) error {
}
+18
View File
@@ -0,0 +1,18 @@
package api
import (
"context"
"isp-config-service/domain"
)
type ConfigHistory struct {
}
func (c ConfigHistory) GetAllVersion(ctx context.Context, configId string) ([]domain.ConfigVersion, error) {
}
func (c ConfigHistory) DeleteConfigVersion(ctx context.Context, id string) error {
}
+14
View File
@@ -0,0 +1,14 @@
package api
import (
"context"
"isp-config-service/domain"
)
type ConfigSchema struct {
}
func (c ConfigSchema) SchemaByModuleId(ctx context.Context, moduleId string) (*domain.ConfigSchema, error) {
}
+116
View File
@@ -0,0 +1,116 @@
package api
import (
"context"
"time"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/json"
"golang.org/x/sync/errgroup"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/helpers"
)
type ModuleRepo interface {
All(ctx context.Context) ([]entity.Module, error)
Delete(ctx context.Context, idList []string) error
}
type BackendsRepo interface {
All(ctx context.Context) ([]entity.Backend, error)
}
type SchemaRepo interface {
All(ctx context.Context) ([]entity.ConfigSchema, error)
}
type Module struct {
moduleRepo ModuleRepo
backendsRepo BackendsRepo
schemaRepo SchemaRepo
}
func NewModule(
moduleRepo ModuleRepo,
backendsRepo BackendsRepo,
schemaRepo SchemaRepo,
) Module {
return Module{
moduleRepo: moduleRepo,
backendsRepo: backendsRepo,
schemaRepo: schemaRepo,
}
}
func (s Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) {
var (
modules []entity.Module
backends []entity.Backend
schemas []entity.ConfigSchema
err error
)
group, ctx := errgroup.WithContext(ctx)
group.Go(func() error {
modules, err = s.moduleRepo.All(ctx)
return errors.WithMessage(err, "get all modules")
})
group.Go(func() error {
backends, err = s.backendsRepo.All(ctx)
return errors.WithMessage(err, "get all backends")
})
group.Go(func() error {
schemas, err = s.schemaRepo.All(ctx)
return errors.WithMessage(err, "get all schemas")
})
err = group.Wait()
if err != nil {
return nil, errors.WithMessage(err, "wait")
}
connections := make(map[string][]domain.Connection, len(modules))
for _, backend := range backends {
addr, err := helpers.SplitAddress(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),
}
connections[backend.ModuleId] = append(connections[backend.ModuleId], conn)
}
schemasMap := make(map[string]json.RawMessage)
for _, schema := range schemas {
schemasMap[schema.ModuleId] = schema.Data
}
moduleInfos := make([]domain.ModuleInfo, 0, len(modules))
for _, module := range modules {
info := domain.ModuleInfo{
Id: module.Id,
Name: module.Name,
Active: len(connections[module.Id]) > 0,
LastConnectedAt: (*time.Time)(module.LastConnectedAt),
LastDisconnectedAt: (*time.Time)(module.LastDisconnectedAt),
ConfigSchema: schemasMap[module.Id],
Status: connections[module.Id],
CreatedAt: time.Time(module.CreatedAt),
}
moduleInfos = append(moduleInfos, info)
}
return moduleInfos, nil
}
func (s Module) Delete(ctx context.Context, idList []string) error {
err := s.moduleRepo.Delete(ctx, idList)
if err != nil {
return errors.WithMessage(err, "delete modules")
}
return nil
}
+1 -1
View File
@@ -26,7 +26,7 @@ func NewCleaner(repo Repo, eventTtl time.Duration, logger log.Logger) Cleaner {
func (c Cleaner) Do(ctx context.Context) {
deleteBefore := time.Now().Add(-c.eventTtl)
deleted, err := c.repo.DeleteByCreatedAt(ctx, xtypes.Time{Value: deleteBefore})
deleted, err := c.repo.DeleteByCreatedAt(ctx, xtypes.Time(deleteBefore))
if err != nil {
c.logger.Error(ctx, errors.WithMessage(err, "delete old events"))
return
+3
View File
@@ -1,6 +1,8 @@
package event
import (
"slices"
"isp-config-service/entity"
)
@@ -23,5 +25,6 @@ func (c Compactor) Compact(events []entity.Event) []entity.Event {
uniqueEvents = append(uniqueEvents, event)
uniqueEventKeys[key] = true
}
slices.Reverse(uniqueEvents)
return uniqueEvents
}
+1 -1
View File
@@ -60,7 +60,7 @@ func (w *Worker) do(ctx context.Context) error {
events = w.compactor.Compact(events)
w.handler.Handle(ctx, events)
w.lastEventId = events[len(events)-1].RowId
w.lastEventId = events[len(events)-1].Id
return nil
}
+5 -14
View File
@@ -5,7 +5,6 @@ import (
"crypto/md5"
"encoding/hex"
"fmt"
"time"
"github.com/google/uuid"
"github.com/pkg/errors"
@@ -25,10 +24,9 @@ const (
type Repo interface {
Upsert(ctx context.Context, module entity.Module) (string, error)
SetDisconnectedAt(
SetDisconnectedAtNow(
ctx context.Context,
moduleId string,
disconnected xtypes.Time,
) error
}
@@ -87,11 +85,9 @@ func NewService(
}
func (s Service) OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error {
now := now()
module := entity.Module{
Id: uuid.NewString(),
Name: moduleName,
LastConnectedAt: &xtypes.Time{Value: now},
Id: uuid.NewString(),
Name: moduleName,
}
moduleId, err := s.moduleRepo.Upsert(ctx, module)
if err != nil {
@@ -121,10 +117,9 @@ func (s Service) OnDisconnect(
s.logger.Error(ctx, message)
}
now := now()
moduleId, _ := store.Get[string](conn.Data(), moduleIdKey)
if moduleId != "" {
err = s.moduleRepo.SetDisconnectedAt(ctx, moduleName, xtypes.Time{Value: now})
err = s.moduleRepo.SetDisconnectedAtNow(ctx, moduleName)
if err != nil {
return errors.WithMessage(err, "update disconnected time in store")
}
@@ -241,7 +236,7 @@ func (s Service) OnModuleConfigSchema(
ModuleId: moduleId,
Data: data.Config,
Version: 1,
Active: xtypes.Bool{Value: true},
Active: xtypes.Bool(true),
}
err := s.configRepo.Insert(ctx, initialConfig)
if err != nil {
@@ -273,7 +268,3 @@ func (s Service) OnModuleConfigSchema(
return nil
}
func now() time.Time {
return time.Now().UTC()
}
+1 -1
View File
@@ -43,7 +43,7 @@ func (d Adapter) Select(ctx context.Context, ptr any, query string, args ...any)
consistencyFromContext(ctx).appendParams(params)
err := d.cli.Post("/db/query").
QueryParams(params).
JsonRequestBody(request(query, args...)).
JsonRequestBody(requests(request(query, args...))).
JsonResponseBody(&resp).
StatusCodeToError().
DoWithoutResponse(ctx)
+3 -15
View File
@@ -2,7 +2,6 @@ package subscription
import (
"context"
"net"
"time"
"github.com/pkg/errors"
@@ -126,7 +125,7 @@ func (s Service) notifyBackendsChanged(
addresses := make([]cluster.AddressConfiguration, 0)
for _, backend := range backends {
addr, err := splitAddress(backend)
addr, err := helpers.SplitAddress(backend)
if err != nil {
return errors.WithMessage(err, "split address")
}
@@ -173,7 +172,7 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
routingConfig := cluster.RoutingConfig{}
for _, backend := range backends {
addr, err := splitAddress(backend)
addr, err := helpers.SplitAddress(backend)
if err != nil {
return errors.WithMessage(err, "split address")
}
@@ -217,20 +216,9 @@ func (s Service) emitEvent(
if err != nil {
err := errors.WithMessagef(
err,
"emit event %s, to %s module, connId: %d",
"emit event '%s', to %s module, connId: %d",
event, helpers.ModuleName(conn), conn.Id(),
)
s.logger.Error(ctx, err)
}
}
func splitAddress(backend entity.Backend) (cluster.AddressConfiguration, error) {
host, port, err := net.SplitHostPort(backend.Address)
if err != nil {
return cluster.AddressConfiguration{}, errors.WithMessagef(err, "split backend %s address: %s", backend.ModuleId, backend.Address)
}
return cluster.AddressConfiguration{
IP: host,
Port: port,
}, nil
}