Implement lifecycle
This commit is contained in:
1 parent
8a2a65d8ed
commit
c4abdaa54b
21 files changed
+582
-173
No files matched your search
+20
-1
@@ -8,7 +8,10 @@ import (
|
||||
"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/repository"
|
||||
"isp-config-service/routes"
|
||||
"isp-config-service/service"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -34,7 +37,23 @@ type Config struct {
|
||||
}
|
||||
|
||||
func (l Locator) Config() Config {
|
||||
controllers := routes.Controllers{}
|
||||
moduleRepo := repository.NewModule(l.db)
|
||||
backendRepo := repository.NewBackend(l.db)
|
||||
eventRepo := repository.NewEvent(l.db)
|
||||
configRepo := repository.NewConfig(l.db)
|
||||
configSchemaRepo := repository.NewConfigSchema(l.db)
|
||||
moduleService := service.NewModule(
|
||||
moduleRepo,
|
||||
backendRepo,
|
||||
eventRepo,
|
||||
configRepo,
|
||||
configSchemaRepo,
|
||||
l.logger,
|
||||
)
|
||||
moduleController := controller.NewModule(moduleService, l.logger)
|
||||
controllers := routes.Controllers{
|
||||
Module: moduleController,
|
||||
}
|
||||
mapper := endpoint.DefaultWrapper(l.logger)
|
||||
grpcMux := routes.GrpcHandler(mapper, controllers)
|
||||
|
||||
|
||||
+15
-15
@@ -9,6 +9,7 @@ import (
|
||||
"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"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -16,9 +17,9 @@ var (
|
||||
)
|
||||
|
||||
type ModuleService interface {
|
||||
OnConnect(conn *etp.Conn, moduleName string) error
|
||||
OnDisconnect(conn *etp.Conn, moduleName string, isNormalClose bool, err error) error
|
||||
OnError(conn *etp.Conn, moduleName string, err error)
|
||||
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)
|
||||
OnModuleReady(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
@@ -49,26 +50,29 @@ func NewModule(service ModuleService, logger log.Logger) Module {
|
||||
}
|
||||
|
||||
func (m Module) OnConnect(conn *etp.Conn) {
|
||||
err := m.service.OnConnect(conn, moduleName(conn))
|
||||
ctx := conn.HttpRequest().Context()
|
||||
err := m.service.OnConnect(ctx, conn, helpers.ModuleName(conn))
|
||||
if err != nil {
|
||||
m.handleError(context.Background(), err)
|
||||
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,
|
||||
moduleName(conn),
|
||||
helpers.ModuleName(conn),
|
||||
etp.IsNormalClose(err),
|
||||
err,
|
||||
)
|
||||
if handleDisconnectErr != nil {
|
||||
m.handleError(context.Background(), handleDisconnectErr)
|
||||
m.handleError(ctx, errors.WithMessage(handleDisconnectErr, "handle onDisconnect"))
|
||||
}
|
||||
}
|
||||
|
||||
func (m Module) OnError(conn *etp.Conn, err error) {
|
||||
m.service.OnError(conn, moduleName(conn), err)
|
||||
m.service.OnError(conn.HttpRequest().Context(), conn, helpers.ModuleName(conn), err)
|
||||
}
|
||||
|
||||
func (m Module) OnModuleReady(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
@@ -80,7 +84,7 @@ func (m Module) OnModuleReady(ctx context.Context, conn *etp.Conn, event msg.Eve
|
||||
|
||||
err = m.service.OnModuleReady(ctx, conn, backend)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, err)
|
||||
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleReady"))
|
||||
}
|
||||
|
||||
return ok
|
||||
@@ -95,7 +99,7 @@ func (m Module) OnModuleRequirements(ctx context.Context, conn *etp.Conn, event
|
||||
|
||||
err = m.service.OnModuleRequirements(ctx, conn, requirements)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, err)
|
||||
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleRequirements"))
|
||||
}
|
||||
|
||||
return ok
|
||||
@@ -110,7 +114,7 @@ func (m Module) OnModuleConfigSchema(ctx context.Context, conn *etp.Conn, event
|
||||
|
||||
err = m.service.OnModuleConfigSchema(ctx, conn, configData)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, err)
|
||||
return m.handleError(ctx, errors.WithMessage(err, "handle onModuleConfigSchema"))
|
||||
}
|
||||
|
||||
return ok
|
||||
@@ -123,7 +127,3 @@ func (m Module) handleError(
|
||||
m.logger.Error(ctx, err)
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
func moduleName(conn *etp.Conn) string {
|
||||
return conn.HttpRequest().Form.Get("module_name")
|
||||
}
|
||||
+9
-8
@@ -2,15 +2,16 @@ package entity
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
type Backend struct {
|
||||
ModuleId string `json:"module_id"`
|
||||
Address string `json:"address"`
|
||||
Version string `json:"version"`
|
||||
LibVersion string `json:"lib_version"`
|
||||
Endpoints JsonValue[[]cluster.EndpointDescriptor] `json:"endpoints"`
|
||||
RequiredModules JsonValue[cluster.ModuleRequirements] `json:"required_modules"`
|
||||
//CreatedAt time.Time `json:"created_at"`
|
||||
//UpdatedAt time.Time `json:"updated_at"`
|
||||
ModuleId string `json:"module_id"`
|
||||
Address string `json:"address"`
|
||||
Version string `json:"version"`
|
||||
LibVersion string `json:"lib_version"`
|
||||
Endpoints xtypes.Json[[]cluster.EndpointDescriptor] `json:"endpoints"`
|
||||
RequiredModules xtypes.Json[[]cluster.ModuleDependency] `json:"required_modules"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
UpdatedAt xtypes.Time `json:"updated_at"`
|
||||
}
|
||||
+26
-21
@@ -1,34 +1,39 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
"github.com/pkg/errors"
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNoActiveConfig = errors.New("no active config")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ModuleId string `json:"module_id"`
|
||||
Data []byte `json:"data"`
|
||||
Version int `json:"version"`
|
||||
Active int `json:"active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
ModuleId string `json:"module_id"`
|
||||
Data []byte `json:"data"`
|
||||
Version int `json:"version"`
|
||||
Active xtypes.Bool `json:"active"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
UpdatedAt xtypes.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type ConfigHistory struct {
|
||||
Id string `json:"id"`
|
||||
ConfigId string `json:"config_id"`
|
||||
Data []byte `json:"data"`
|
||||
Version int `json:"version"`
|
||||
AdminId int `json:"admin_id"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Id string `json:"id"`
|
||||
ConfigId string `json:"config_id"`
|
||||
Data []byte `json:"data"`
|
||||
Version int `json:"version"`
|
||||
AdminId int `json:"admin_id"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type ConfigSchema struct {
|
||||
Id string `json:"id"`
|
||||
ModuleId string `json:"module_id"`
|
||||
Data []byte `json:"data"`
|
||||
ModuleVersion string `json:"module_version"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Id string `json:"id"`
|
||||
ModuleId string `json:"module_id"`
|
||||
Data []byte `json:"data"`
|
||||
ModuleVersion string `json:"module_version"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
UpdatedAt xtypes.Time `json:"updated_at"`
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
type EventType int
|
||||
|
||||
const (
|
||||
Unknown EventType = iota
|
||||
ConfigUpdated
|
||||
ModuleReady
|
||||
ModuleDisconnected
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
RowId int `json:"rowid"`
|
||||
Type EventType `json:"type"`
|
||||
Payload xtypes.Json[EventPayload] `json:"payload"`
|
||||
}
|
||||
|
||||
func NewEvent(t EventType, payload EventPayload) Event {
|
||||
return Event{
|
||||
Type: t,
|
||||
Payload: xtypes.Json[EventPayload]{
|
||||
Value: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type EventPayload struct {
|
||||
ConfigUpdated *PayloadConfigUpdated `json:",omitempty"`
|
||||
ModuleReady *PayloadModuleReady `json:",omitempty"`
|
||||
ModuleDisconnected *PayloadModuleDisconnected `json:",omitempty"`
|
||||
}
|
||||
|
||||
type PayloadConfigUpdated struct {
|
||||
ModuleId string
|
||||
}
|
||||
|
||||
type PayloadModuleReady struct {
|
||||
ModuleId string
|
||||
}
|
||||
|
||||
type PayloadModuleDisconnected struct {
|
||||
ModuleId string
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
type JsonValue[T any] struct {
|
||||
Value T
|
||||
}
|
||||
|
||||
func (l JsonValue[T]) MarshalJSON() ([]byte, error) {
|
||||
data, err := l.MarshalText()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte(strconv.Quote(string(data))), nil
|
||||
}
|
||||
|
||||
func (l *JsonValue[T]) UnmarshalJSON(data []byte) error {
|
||||
s, err := strconv.Unquote(string(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.UnmarshalText([]byte(s))
|
||||
}
|
||||
|
||||
func (l JsonValue[T]) MarshalText() ([]byte, error) {
|
||||
data, err := json.Marshal(l.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s := base64.StdEncoding.EncodeToString(data)
|
||||
return []byte(s), nil
|
||||
}
|
||||
|
||||
func (l *JsonValue[T]) UnmarshalText(data []byte) error {
|
||||
arr, err := base64.StdEncoding.DecodeString(string(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(arr, &l.Value)
|
||||
}
|
||||
+6
-6
@@ -1,13 +1,13 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
type Module struct {
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
LastConnectedAt *time.Time `json:"last_connected_at"`
|
||||
LastDisconnectedAt *time.Time `json:"last_disconnected_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
LastConnectedAt *xtypes.Time `json:"last_connected_at"`
|
||||
LastDisconnectedAt *xtypes.Time `json:"last_disconnected_at"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package xtypes
|
||||
|
||||
type Bool struct {
|
||||
Value bool
|
||||
}
|
||||
|
||||
func (l Bool) MarshalJSON() ([]byte, error) {
|
||||
return l.MarshalText()
|
||||
}
|
||||
|
||||
func (l *Bool) UnmarshalJSON(data []byte) error {
|
||||
return l.UnmarshalText(data)
|
||||
}
|
||||
|
||||
func (l Bool) MarshalText() ([]byte, error) {
|
||||
if l.Value {
|
||||
return []byte("1"), nil
|
||||
}
|
||||
return []byte("0"), nil
|
||||
}
|
||||
|
||||
func (l *Bool) UnmarshalText(data []byte) error {
|
||||
l.Value = string(data) == "1"
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package xtypes
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
type Json[T any] struct {
|
||||
Value T
|
||||
}
|
||||
|
||||
func (l Json[T]) MarshalJSON() ([]byte, error) {
|
||||
data, err := l.MarshalText()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []byte(strconv.Quote(string(data))), nil
|
||||
}
|
||||
|
||||
func (l *Json[T]) UnmarshalJSON(data []byte) error {
|
||||
s, err := strconv.Unquote(string(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.UnmarshalText([]byte(s))
|
||||
}
|
||||
|
||||
func (l Json[T]) MarshalText() ([]byte, error) {
|
||||
data, err := json.Marshal(l.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (l *Json[T]) UnmarshalText(data []byte) error {
|
||||
return json.Unmarshal(data, &l.Value)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package xtypes
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Time struct {
|
||||
Value time.Time
|
||||
}
|
||||
|
||||
func (l Time) MarshalJSON() ([]byte, error) {
|
||||
return l.MarshalText()
|
||||
}
|
||||
|
||||
func (l *Time) UnmarshalJSON(data []byte) error {
|
||||
return l.UnmarshalText(data)
|
||||
}
|
||||
|
||||
func (l Time) MarshalText() ([]byte, error) {
|
||||
value := strconv.Itoa(int(l.Value.Unix()))
|
||||
return []byte(value), nil
|
||||
}
|
||||
|
||||
func (l *Time) UnmarshalText(data []byte) error {
|
||||
value, err := strconv.Atoi(string(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
l.Value = time.Unix(int64(value), 0)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"github.com/txix-open/etp/v3"
|
||||
)
|
||||
|
||||
func ModuleName(conn *etp.Conn) string {
|
||||
_ = conn.HttpRequest().ParseForm()
|
||||
return conn.HttpRequest().Form.Get("module_name")
|
||||
}
|
||||
@@ -2,23 +2,23 @@
|
||||
-- +goose NO TRANSACTION
|
||||
create table isp_config_service__module
|
||||
(
|
||||
id text not null primary key,
|
||||
name text not null unique,
|
||||
last_connected_at text,
|
||||
last_disconnected_at text,
|
||||
created_at text not null default (datetime('now'))
|
||||
id text not null primary key,
|
||||
name text not null unique,
|
||||
last_connected_at integer,
|
||||
last_disconnected_at integer,
|
||||
created_at integer not null default (unixepoch())
|
||||
);
|
||||
|
||||
create table isp_config_service__config
|
||||
(
|
||||
id text not null primary key,
|
||||
name text not null,
|
||||
module_id text not null,
|
||||
data blob not null,
|
||||
version int not null default 1,
|
||||
active int not null default 0,
|
||||
created_at text not null default (datetime('now')),
|
||||
updated_at text not null default (datetime('now')),
|
||||
id text not null primary key,
|
||||
name text not null,
|
||||
module_id text not null,
|
||||
data blob not null,
|
||||
version int not null default 1,
|
||||
active 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
|
||||
);
|
||||
|
||||
@@ -26,12 +26,12 @@ create index IX_isp_config_service__config__module_id on isp_config_service__con
|
||||
|
||||
create table isp_config_service__config_history
|
||||
(
|
||||
id text not null primary key,
|
||||
config_id text not null,
|
||||
data blob not null,
|
||||
version int not null default 1,
|
||||
admin_id int not null,
|
||||
created_at text not null default (datetime('now')),
|
||||
id text not null primary key,
|
||||
config_id text not null,
|
||||
data blob not null,
|
||||
version int not null default 1,
|
||||
admin_id int not null,
|
||||
created_at integer not null default (unixepoch()),
|
||||
foreign key (config_id) references isp_config_service__config (id) on delete cascade on update cascade
|
||||
);
|
||||
|
||||
@@ -39,32 +39,40 @@ create index IX_isp_config_service__config_history__config_id on isp_config_serv
|
||||
|
||||
create table isp_config_service__config_schema
|
||||
(
|
||||
id text not null primary key,
|
||||
module_id text not null unique,
|
||||
data blob not null,
|
||||
module_version text not null default 1,
|
||||
created_at text not null default (datetime('now')),
|
||||
updated_at text not null default (datetime('now')),
|
||||
id text not null primary key,
|
||||
module_id text not null unique,
|
||||
data blob not null,
|
||||
module_version text not null default 1,
|
||||
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
|
||||
);
|
||||
|
||||
create table isp_config_service__backend
|
||||
(
|
||||
module_id text not null,
|
||||
address text not null,
|
||||
version text not null,
|
||||
lib_version text not null,
|
||||
endpoints blob not null,
|
||||
required_modules blob not null,
|
||||
created_at text not null default (datetime('now')),
|
||||
updated_at text not null default (datetime('now')),
|
||||
module_id text not null,
|
||||
address text not null,
|
||||
version text not null,
|
||||
lib_version text not null,
|
||||
endpoints blob not null,
|
||||
required_modules blob not null,
|
||||
created_at integer not null default (unixepoch()),
|
||||
updated_at integer not null default (unixepoch()),
|
||||
primary key (module_id, address),
|
||||
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
|
||||
);
|
||||
|
||||
create table isp_config_service__event
|
||||
(
|
||||
type integer not null,
|
||||
payload blob not null,
|
||||
created_at integer not null default (unixepoch())
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
drop table isp_config_service__module;
|
||||
drop table isp_config_service__config;
|
||||
drop table isp_config_service__config_history;
|
||||
drop table isp_config_service__config_schema;
|
||||
drop table isp_config_service__backend;
|
||||
drop table isp_config_service__event;
|
||||
@@ -30,7 +30,7 @@ func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
|
||||
).Suffix(`on conflict (module_id, address) do update
|
||||
set version = excluded.version, lib_version = excluded.lib_version,
|
||||
endpoints = excluded.endpoints, required_modules = excluded.required_modules,
|
||||
updated_at = datetime('now')
|
||||
updated_at = unixepoch()
|
||||
`).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewConfig(db db.DB) Config {
|
||||
return Config{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r Config) Insert(ctx context.Context, cfg entity.Config) error {
|
||||
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).
|
||||
Suffix("on conflict (id) do nothing").
|
||||
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 (r Config) GetActive(ctx context.Context, moduleId string) (*entity.Config, error) {
|
||||
query, args, err := squirrel.Select("*").
|
||||
From(Table("config")).
|
||||
Where(squirrel.Eq{
|
||||
"module_id": moduleId,
|
||||
"active": "1",
|
||||
}).OrderBy("version DESC").
|
||||
Limit(1).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result := entity.Config{}
|
||||
err = r.db.SelectRow(ctx, &result, query, args...)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, entity.ErrNoActiveConfig
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
|
||||
return &result, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type ConfigSchema struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewConfigSchema(db db.DB) ConfigSchema {
|
||||
return ConfigSchema{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r ConfigSchema) Upsert(ctx context.Context, schema entity.ConfigSchema) error {
|
||||
query, args, err := squirrel.Insert(Table("config_schema")).
|
||||
Columns("id", "module_id", "data", "module_version").
|
||||
Values(schema.Id, schema.ModuleId, schema.Data, schema.ModuleVersion).
|
||||
Suffix(`on conflict (module_id) do update
|
||||
set data = excluded.data, module_version = excluded.module_version, updated_at = unixepoch()`).
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewEvent(db db.DB) Event {
|
||||
return Event{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
func (r Event) Insert(ctx context.Context, event entity.Event) error {
|
||||
query := fmt.Sprintf("insert into %s (type, payload) values (?, ?)", Table("event"))
|
||||
_, err := r.db.Exec(ctx, query, event.Type, event.Payload)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "exec: %s", query)
|
||||
}
|
||||
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"))
|
||||
result := make([]entity.Event, 0)
|
||||
err := r.db.Select(ctx, &result, query, lastRowId, limit)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r Event) DeleteByCreatedAt(ctx context.Context, before int) (int, error) {
|
||||
query := fmt.Sprintf("delete from %s where created_at < ?", Table("event"))
|
||||
result, err := r.db.Exec(ctx, query, before)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "exec: %s", query)
|
||||
}
|
||||
|
||||
affected, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, errors.WithMessage(err, "get affected rows")
|
||||
}
|
||||
|
||||
return int(affected), nil
|
||||
}
|
||||
@@ -3,12 +3,12 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
type Module struct {
|
||||
@@ -25,7 +25,8 @@ 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").
|
||||
Suffix(`on conflict (name) do update
|
||||
set last_connected_at = excluded.last_connected_at`).
|
||||
Suffix("returning id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
@@ -43,7 +44,7 @@ func (r Module) Upsert(ctx context.Context, module entity.Module) (string, error
|
||||
func (r Module) SetDisconnectedAt(
|
||||
ctx context.Context,
|
||||
moduleId string,
|
||||
disconnected time.Time,
|
||||
disconnected xtypes.Time,
|
||||
) error {
|
||||
query, args, err := squirrel.Update(Table("module")).
|
||||
Set("last_disconnected_at", disconnected).
|
||||
|
||||
+126
-26
@@ -2,6 +2,8 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -12,6 +14,8 @@ import (
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
"isp-config-service/helpers"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -24,7 +28,7 @@ type ModuleRepo interface {
|
||||
SetDisconnectedAt(
|
||||
ctx context.Context,
|
||||
moduleId string,
|
||||
disconnected time.Time,
|
||||
disconnected xtypes.Time,
|
||||
) error
|
||||
}
|
||||
|
||||
@@ -33,33 +37,54 @@ type BackendRepo interface {
|
||||
Delete(ctx context.Context, moduleId string, address string) error
|
||||
}
|
||||
|
||||
type EventRepo interface {
|
||||
Insert(ctx context.Context, event entity.Event) error
|
||||
}
|
||||
|
||||
type ConfigSchemaRepo interface {
|
||||
Upsert(ctx context.Context, schema entity.ConfigSchema) error
|
||||
}
|
||||
|
||||
type ConfigRepo interface {
|
||||
Insert(ctx context.Context, cfg entity.Config) error
|
||||
GetActive(ctx context.Context, moduleId string) (*entity.Config, error)
|
||||
}
|
||||
|
||||
type Module struct {
|
||||
moduleRepo ModuleRepo
|
||||
backendRepo BackendRepo
|
||||
logger log.Logger
|
||||
moduleRepo ModuleRepo
|
||||
backendRepo BackendRepo
|
||||
eventRepo EventRepo
|
||||
configRepo ConfigRepo
|
||||
configSchemaRepo ConfigSchemaRepo
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewModule(
|
||||
moduleRepo ModuleRepo,
|
||||
backendRepo BackendRepo,
|
||||
eventRepo EventRepo,
|
||||
configRepo ConfigRepo,
|
||||
configSchemaRepo ConfigSchemaRepo,
|
||||
logger log.Logger,
|
||||
) Module {
|
||||
return Module{
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
logger: logger,
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
eventRepo: eventRepo,
|
||||
configRepo: configRepo,
|
||||
configSchemaRepo: configSchemaRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Module) OnConnect(conn *etp.Conn, moduleName string) error {
|
||||
now := time.Now().UTC()
|
||||
func (s Module) OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error {
|
||||
now := now()
|
||||
module := entity.Module{
|
||||
Id: uuid.NewString(),
|
||||
Name: moduleName,
|
||||
LastConnectedAt: &now,
|
||||
CreatedAt: now,
|
||||
LastConnectedAt: &xtypes.Time{Value: now},
|
||||
}
|
||||
moduleId, err := s.moduleRepo.Upsert(context.Background(), module)
|
||||
moduleId, err := s.moduleRepo.Upsert(ctx, module)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert module in store")
|
||||
}
|
||||
@@ -70,25 +95,27 @@ func (s Module) OnConnect(conn *etp.Conn, moduleName string) error {
|
||||
}
|
||||
|
||||
func (s Module) OnDisconnect(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
moduleName string,
|
||||
isNormalClose bool,
|
||||
err error,
|
||||
) error {
|
||||
if isNormalClose {
|
||||
s.logger.Info(context.Background(), fmt.Sprintf("module '%s' disconnected", moduleName))
|
||||
s.logger.Info(ctx, fmt.Sprintf("module '%s' disconnected", moduleName))
|
||||
} else {
|
||||
message := errors.WithMessagef(
|
||||
err,
|
||||
"module '%s' unexpectedly disconnected",
|
||||
moduleName,
|
||||
)
|
||||
s.logger.Error(context.Background(), message)
|
||||
s.logger.Error(ctx, message)
|
||||
}
|
||||
|
||||
now := now()
|
||||
moduleId, _ := store.Get[string](conn.Data(), moduleIdKey)
|
||||
if moduleId != "" {
|
||||
err = s.moduleRepo.SetDisconnectedAt(context.Background(), moduleName, time.Now().UTC())
|
||||
err = s.moduleRepo.SetDisconnectedAt(ctx, moduleName, xtypes.Time{Value: now})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update disconnected time in store")
|
||||
}
|
||||
@@ -96,28 +123,38 @@ func (s Module) OnDisconnect(
|
||||
|
||||
backend, _ := store.Get[entity.Backend](conn.Data(), backendKey)
|
||||
if backend.ModuleId != "" {
|
||||
err = s.backendRepo.Delete(context.Background(), backend.ModuleId, backend.Address)
|
||||
err = s.backendRepo.Delete(ctx, backend.ModuleId, backend.Address)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "delete backend in store")
|
||||
}
|
||||
|
||||
event := entity.NewEvent(entity.ModuleDisconnected, entity.EventPayload{
|
||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
})
|
||||
err = s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnError(conn *etp.Conn, moduleName string, err error) {
|
||||
func (s Module) OnError(ctx context.Context, conn *etp.Conn, moduleName string, err error) {
|
||||
err = errors.WithMessagef(
|
||||
err,
|
||||
"unexpected error in communication, module: '%s'",
|
||||
moduleName,
|
||||
)
|
||||
s.logger.Error(context.Background(), err)
|
||||
s.logger.Error(ctx, err)
|
||||
}
|
||||
|
||||
func (s Module) OnModuleReady(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
backend cluster.BackendDeclaration,
|
||||
declaration cluster.BackendDeclaration,
|
||||
) error {
|
||||
moduleId, err := store.Get[string](conn.Data(), moduleIdKey)
|
||||
if err != nil {
|
||||
@@ -126,14 +163,30 @@ func (s Module) OnModuleReady(
|
||||
|
||||
backend := entity.Backend{
|
||||
ModuleId: moduleId,
|
||||
Address: fmt.Sprintf("%s:%s", backend.Address.IP, backend.Address.Port),
|
||||
Version: backend.Version,
|
||||
LibVersion: backend.LibVersion,
|
||||
Endpoints: nil,
|
||||
RequiredModules: nil,
|
||||
CreatedAt: time.Time{},
|
||||
UpdatedAt: time.Time{},
|
||||
Address: fmt.Sprintf("%s:%s", declaration.Address.IP, declaration.Address.Port),
|
||||
Version: declaration.Version,
|
||||
LibVersion: declaration.LibVersion,
|
||||
Endpoints: xtypes.Json[[]cluster.EndpointDescriptor]{Value: declaration.Endpoints},
|
||||
RequiredModules: xtypes.Json[[]cluster.ModuleDependency]{Value: declaration.RequiredModules},
|
||||
}
|
||||
err = s.backendRepo.Upsert(ctx, backend)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert backend in store")
|
||||
}
|
||||
|
||||
conn.Data().Set(backendKey, backend)
|
||||
|
||||
event := entity.NewEvent(entity.ModuleReady, entity.EventPayload{
|
||||
ModuleReady: &entity.PayloadModuleReady{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
})
|
||||
err = s.eventRepo.Insert(ctx, event)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert event in store")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnModuleRequirements(
|
||||
@@ -149,5 +202,52 @@ func (s Module) OnModuleConfigSchema(
|
||||
conn *etp.Conn,
|
||||
data cluster.ConfigData,
|
||||
) error {
|
||||
moduleId, err := store.Get[string](conn.Data(), moduleIdKey)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "resolve module id")
|
||||
}
|
||||
|
||||
config, err := s.configRepo.GetActive(ctx, moduleId)
|
||||
if errors.Is(err, entity.ErrNoActiveConfig) {
|
||||
md5Sum := md5.Sum([]byte(moduleId))
|
||||
initialConfigId := hex.EncodeToString(md5Sum[:])
|
||||
initialConfig := entity.Config{
|
||||
Id: initialConfigId,
|
||||
Name: helpers.ModuleName(conn),
|
||||
ModuleId: moduleId,
|
||||
Data: data.Config,
|
||||
Version: 1,
|
||||
Active: xtypes.Bool{Value: true},
|
||||
}
|
||||
err := s.configRepo.Insert(ctx, initialConfig)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "insert config in store")
|
||||
}
|
||||
config = &initialConfig
|
||||
}
|
||||
if err != nil {
|
||||
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")
|
||||
}
|
||||
|
||||
configSchema := entity.ConfigSchema{
|
||||
Id: uuid.NewString(),
|
||||
ModuleId: moduleId,
|
||||
Data: data.Schema,
|
||||
ModuleVersion: data.Version,
|
||||
}
|
||||
err = s.configSchemaRepo.Upsert(ctx, configSchema)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert config schema in store")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func now() time.Time {
|
||||
return time.Now().UTC()
|
||||
}
|
||||
@@ -11,7 +11,7 @@ var (
|
||||
consistencyCtxValue = consistencyCtxKey{}
|
||||
)
|
||||
|
||||
func ConsistencyFromContext(ctx context.Context) Consistency {
|
||||
func consistencyFromContext(ctx context.Context) Consistency {
|
||||
c, ok := ctx.Value(consistencyCtxValue).(Consistency)
|
||||
if !ok {
|
||||
return Consistency{}
|
||||
|
||||
@@ -46,7 +46,7 @@ func (d DB) Select(ctx context.Context, ptr any, query string, args ...any) erro
|
||||
"timings": true,
|
||||
"associative": true,
|
||||
}
|
||||
ConsistencyFromContext(ctx).appendParams(params)
|
||||
consistencyFromContext(ctx).appendParams(params)
|
||||
err := d.cli.Post("/db/query").
|
||||
QueryParams(params).
|
||||
JsonRequestBody(request(query, args...)).
|
||||
@@ -71,7 +71,7 @@ func (d DB) SelectRow(ctx context.Context, ptr any, query string, args ...any) e
|
||||
"timings": true,
|
||||
"associative": true,
|
||||
}
|
||||
ConsistencyFromContext(ctx).appendParams(params)
|
||||
consistencyFromContext(ctx).appendParams(params)
|
||||
httpResp, err := d.cli.Post("/db/request").
|
||||
QueryParams(params).
|
||||
JsonRequestBody(requests(request(query, args...))).
|
||||
|
||||
+21
-11
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/dbx/migration"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
@@ -28,11 +29,12 @@ const (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
rqlite *rqlite.Rqlite
|
||||
grpcSrv *grpc.Server
|
||||
httpSrv *http.Server
|
||||
logger log.Logger
|
||||
boot *bootstrap.Bootstrap
|
||||
rqlite *rqlite.Rqlite
|
||||
grpcSrv *grpc.Server
|
||||
httpSrv *http.Server
|
||||
clusterCli *cluster.Client
|
||||
logger log.Logger
|
||||
|
||||
//initialized in Run
|
||||
etpSrv *etp.Server
|
||||
@@ -41,11 +43,12 @@ type Service struct {
|
||||
func New(boot *bootstrap.Bootstrap) Service {
|
||||
rqlite := rqlite.New(boot.App.Config())
|
||||
return Service{
|
||||
boot: boot,
|
||||
rqlite: rqlite,
|
||||
logger: boot.App.Logger(),
|
||||
httpSrv: http.NewServer(boot.App.Logger()),
|
||||
grpcSrv: grpc.DefaultServer(),
|
||||
boot: boot,
|
||||
rqlite: rqlite,
|
||||
grpcSrv: grpc.DefaultServer(),
|
||||
httpSrv: http.NewServer(boot.App.Logger()),
|
||||
clusterCli: boot.ClusterCli,
|
||||
logger: boot.App.Logger(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +110,14 @@ func (s Service) Run(ctx context.Context) error {
|
||||
s.boot.Fatal(errors.WithMessage(err, "start http server"))
|
||||
}
|
||||
}()
|
||||
time.Sleep(1 * time.Second)
|
||||
time.Sleep(1 * time.Second) //wait for http start
|
||||
|
||||
go func() {
|
||||
err = s.clusterCli.Run(ctx, cluster.NewEventHandler())
|
||||
if err != nil {
|
||||
s.boot.Fatal(errors.WithMessage(err, "connect to it's self"))
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user