Implement event stream
This commit is contained in:
1 parent
f90063cb03
commit
80a99c425b
24 files changed
+697
-113
No files matched your search
+44
-16
@@ -2,20 +2,27 @@ package assembly
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/worker"
|
||||
"isp-config-service/controller"
|
||||
"isp-config-service/repository"
|
||||
"isp-config-service/routes"
|
||||
"isp-config-service/service"
|
||||
"isp-config-service/service/event"
|
||||
"isp-config-service/service/module"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
"isp-config-service/service/subscription"
|
||||
)
|
||||
|
||||
const (
|
||||
wsReadLimit = 4 * 1024 * 1024
|
||||
wsReadLimit = 4 * 1024 * 1024
|
||||
handleEventsInterval = 500 * time.Millisecond
|
||||
cleanEventInterval = 60 * time.Second
|
||||
eventTtl = 60 * time.Second
|
||||
)
|
||||
|
||||
type Locator struct {
|
||||
@@ -31,9 +38,11 @@ func NewLocator(logger log.Logger, db db.DB) Locator {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
GrpcMux *grpc.Mux
|
||||
HttpMux http.Handler
|
||||
EtpSrv *etp.Server
|
||||
GrpcMux *grpc.Mux
|
||||
HttpMux http.Handler
|
||||
EtpSrv *etp.Server
|
||||
HandleEventWorker *worker.Worker
|
||||
CleanEventWorker *worker.Worker
|
||||
}
|
||||
|
||||
func (l Locator) Config() Config {
|
||||
@@ -42,12 +51,28 @@ func (l Locator) Config() Config {
|
||||
eventRepo := repository.NewEvent(l.db)
|
||||
configRepo := repository.NewConfig(l.db)
|
||||
configSchemaRepo := repository.NewConfigSchema(l.db)
|
||||
moduleService := service.NewModule(
|
||||
|
||||
etpSrv := etp.NewServer(
|
||||
etp.WithServerReadLimit(wsReadLimit),
|
||||
etp.WithServerAcceptOptions(&etp.AcceptOptions{
|
||||
InsecureSkipVerify: true,
|
||||
}),
|
||||
)
|
||||
subscriptionService := subscription.NewService(
|
||||
moduleRepo,
|
||||
backendRepo,
|
||||
configRepo,
|
||||
etpSrv.Rooms(),
|
||||
l.logger,
|
||||
)
|
||||
|
||||
moduleService := module.NewService(
|
||||
moduleRepo,
|
||||
backendRepo,
|
||||
eventRepo,
|
||||
configRepo,
|
||||
configSchemaRepo,
|
||||
subscriptionService,
|
||||
l.logger,
|
||||
)
|
||||
moduleController := controller.NewModule(moduleService, l.logger)
|
||||
@@ -57,19 +82,22 @@ func (l Locator) Config() Config {
|
||||
mapper := endpoint.DefaultWrapper(l.logger)
|
||||
grpcMux := routes.GrpcHandler(mapper, controllers)
|
||||
|
||||
etpSrv := etp.NewServer(
|
||||
etp.WithServerReadLimit(wsReadLimit),
|
||||
etp.WithServerAcceptOptions(&etp.AcceptOptions{
|
||||
InsecureSkipVerify: true,
|
||||
}),
|
||||
)
|
||||
routes.BindEtp(etpSrv, controllers)
|
||||
|
||||
httpMux := routes.HttpHandler(etpSrv)
|
||||
|
||||
eventHandler := event.NewHandler(subscriptionService, l.logger)
|
||||
handleEventJob := event.NewWorker(eventRepo, eventHandler, l.logger)
|
||||
handleEventWorker := worker.New(handleEventJob, worker.WithInterval(handleEventsInterval))
|
||||
|
||||
cleanerJob := event.NewCleaner(eventRepo, eventTtl, l.logger)
|
||||
cleanEventWorker := worker.New(cleanerJob, worker.WithInterval(cleanEventInterval))
|
||||
|
||||
return Config{
|
||||
GrpcMux: grpcMux,
|
||||
EtpSrv: etpSrv,
|
||||
HttpMux: httpMux,
|
||||
GrpcMux: grpcMux,
|
||||
EtpSrv: etpSrv,
|
||||
HttpMux: httpMux,
|
||||
HandleEventWorker: handleEventWorker,
|
||||
CleanEventWorker: cleanEventWorker,
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,14 @@ func NewModule(service ModuleService, logger log.Logger) Module {
|
||||
|
||||
func (m Module) OnConnect(conn *etp.Conn) {
|
||||
ctx := conn.HttpRequest().Context()
|
||||
err := m.service.OnConnect(ctx, conn, helpers.ModuleName(conn))
|
||||
err := conn.HttpRequest().ParseForm()
|
||||
if err != nil {
|
||||
m.handleError(ctx, errors.WithMessage(err, "parse form"))
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
err = m.service.OnConnect(ctx, conn, helpers.ModuleName(conn))
|
||||
if err != nil {
|
||||
m.handleError(ctx, errors.WithMessage(err, "handle onConnect"))
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ type Backend struct {
|
||||
Address string `json:"address"`
|
||||
Version string `json:"version"`
|
||||
LibVersion string `json:"lib_version"`
|
||||
ModuleName string `json:"module_name"`
|
||||
Endpoints xtypes.Json[[]cluster.EndpointDescriptor] `json:"endpoints"`
|
||||
RequiredModules xtypes.Json[[]cluster.ModuleDependency] `json:"required_modules"`
|
||||
CreatedAt xtypes.Time `json:"created_at"`
|
||||
|
||||
+16
-3
@@ -1,6 +1,8 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
@@ -15,19 +17,30 @@ const (
|
||||
|
||||
type Event struct {
|
||||
RowId int `json:"rowid"`
|
||||
Type EventType `json:"type"`
|
||||
Payload xtypes.Json[EventPayload] `json:"payload"`
|
||||
}
|
||||
|
||||
func NewEvent(t EventType, payload EventPayload) Event {
|
||||
func NewEvent(payload EventPayload) Event {
|
||||
return Event{
|
||||
Type: t,
|
||||
Payload: xtypes.Json[EventPayload]{
|
||||
Value: payload,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (e Event) Key() string {
|
||||
switch {
|
||||
case e.Payload.Value.ConfigUpdated != nil:
|
||||
return fmt.Sprintf("config_updated_%s", e.Payload.Value.ConfigUpdated.ModuleId)
|
||||
case e.Payload.Value.ModuleReady != nil:
|
||||
return fmt.Sprintf("module_lifecycle_%s", e.Payload.Value.ModuleReady.ModuleId)
|
||||
case e.Payload.Value.ModuleDisconnected != nil:
|
||||
return fmt.Sprintf("module_lifecycle_%s", e.Payload.Value.ModuleDisconnected.ModuleId)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type EventPayload struct {
|
||||
ConfigUpdated *PayloadConfigUpdated `json:",omitempty"`
|
||||
ModuleReady *PayloadModuleReady `json:",omitempty"`
|
||||
|
||||
@@ -5,8 +5,6 @@ go 1.22
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/iancoleman/strcase v0.3.0
|
||||
github.com/jmoiron/sqlx v1.4.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pressly/goose/v3 v3.20.0
|
||||
github.com/rqlite/gorqlite v0.0.0-20240227123050-397b03f02418
|
||||
@@ -39,10 +37,6 @@ require (
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/hashicorp/golang-lru v1.0.2 // indirect
|
||||
github.com/hashicorp/raft v1.6.1 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
|
||||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||
@@ -59,8 +57,6 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-resty/resty/v2 v2.12.0 h1:rsVL8P90LFvkUYq/V5BTVe203WfRIU4gvcf+yfzJzGA=
|
||||
github.com/go-resty/resty/v2 v2.12.0/go.mod h1:o0yGPrkS3lOe1+eFajk6kBW8ScXzwU3hD69/gt2yB/0=
|
||||
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
|
||||
github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
|
||||
@@ -104,18 +100,6 @@ github.com/hashicorp/raft v1.1.0/go.mod h1:4Ak7FSPnuvmb0GV6vgIAJ4vYT4bek9bb6Q+7H
|
||||
github.com/hashicorp/raft v1.6.1 h1:v/jm5fcYHvVkL0akByAp+IDdDSzCNCGhdO6VdB56HIM=
|
||||
github.com/hashicorp/raft v1.6.1/go.mod h1:N1sKh6Vn47mrWvEArQgILTyng8GoDRNYlgKyK7PMjs0=
|
||||
github.com/hashicorp/raft-boltdb v0.0.0-20210409134258-03c10cc3d4ea/go.mod h1:qRd6nFJYYS6Iqnc/8HcUmko2/2Gw8qTFEmxDLii6W5I=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA=
|
||||
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
|
||||
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
|
||||
@@ -139,8 +123,6 @@ github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhR
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
@@ -152,8 +134,6 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
@@ -229,7 +209,6 @@ github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
|
||||
@@ -5,6 +5,5 @@ import (
|
||||
)
|
||||
|
||||
func ModuleName(conn *etp.Conn) string {
|
||||
_ = conn.HttpRequest().ParseForm()
|
||||
return conn.HttpRequest().Form.Get("module_name")
|
||||
}
|
||||
@@ -54,6 +54,7 @@ create table isp_config_service__backend
|
||||
address text not null,
|
||||
version text not null,
|
||||
lib_version text not null,
|
||||
module_name text not null,
|
||||
endpoints blob not null,
|
||||
required_modules blob not null,
|
||||
created_at integer not null default (unixepoch()),
|
||||
@@ -64,7 +65,6 @@ create table isp_config_service__backend
|
||||
|
||||
create table isp_config_service__event
|
||||
(
|
||||
type integer not null,
|
||||
payload blob not null,
|
||||
created_at integer not null default (unixepoch())
|
||||
);
|
||||
|
||||
+35
-4
@@ -2,11 +2,12 @@ package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
type Backend struct {
|
||||
@@ -22,13 +23,13 @@ func NewBackend(db db.DB) Backend {
|
||||
func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
|
||||
query, args, err := squirrel.Insert(Table("backend")).
|
||||
Columns("module_id", "address",
|
||||
"version", "lib_version",
|
||||
"version", "lib_version", "module_name",
|
||||
"endpoints", "required_modules").
|
||||
Values(backend.ModuleId, backend.Address,
|
||||
backend.Version, backend.LibVersion,
|
||||
backend.Version, backend.LibVersion, backend.ModuleName,
|
||||
backend.Endpoints, backend.RequiredModules,
|
||||
).Suffix(`on conflict (module_id, address) do update
|
||||
set version = excluded.version, lib_version = excluded.lib_version,
|
||||
set version = excluded.version, lib_version = excluded.lib_version, module_name = excluded.module_name,
|
||||
endpoints = excluded.endpoints, required_modules = excluded.required_modules,
|
||||
updated_at = unixepoch()
|
||||
`).
|
||||
@@ -62,3 +63,33 @@ func (r Backend) Delete(ctx context.Context, moduleId string, address string) er
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Backend) All(ctx context.Context) ([]entity.Backend, error) {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r Backend) GetByModuleId(ctx context.Context, moduleId string) ([]entity.Backend, error) {
|
||||
query, args, err := squirrel.Select("*").
|
||||
From(Table("backend")).
|
||||
Where(squirrel.Eq{
|
||||
"module_id": moduleId,
|
||||
}).OrderBy("created_at desc").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result := make([]entity.Backend, 0)
|
||||
err = r.db.Select(ctx, &result, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
type ConfigSchema struct {
|
||||
|
||||
+5
-4
@@ -5,8 +5,9 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
@@ -20,8 +21,8 @@ func NewEvent(db db.DB) Event {
|
||||
}
|
||||
|
||||
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)
|
||||
query := fmt.Sprintf("insert into %s (payload) values (?)", Table("event"))
|
||||
_, err := r.db.Exec(ctx, query, event.Payload)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "exec: %s", query)
|
||||
}
|
||||
@@ -38,7 +39,7 @@ func (r Event) Get(ctx context.Context, lastRowId int, limit int) ([]entity.Even
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r Event) DeleteByCreatedAt(ctx context.Context, before int) (int, error) {
|
||||
func (r Event) DeleteByCreatedAt(ctx context.Context, before xtypes.Time) (int, error) {
|
||||
query := fmt.Sprintf("delete from %s where created_at < ?", Table("event"))
|
||||
result, err := r.db.Exec(ctx, query, before)
|
||||
if err != nil {
|
||||
|
||||
+32
-2
@@ -6,9 +6,9 @@ import (
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
type Module struct {
|
||||
@@ -36,7 +36,7 @@ func (r Module) Upsert(ctx context.Context, module entity.Module) (string, error
|
||||
result := make(map[string]string)
|
||||
err = r.db.SelectRow(ctx, &result, query, args...)
|
||||
if err != nil {
|
||||
return "", errors.WithMessagef(err, "select : %s", query)
|
||||
return "", errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
return result["id"], nil
|
||||
}
|
||||
@@ -62,6 +62,36 @@ func (r Module) SetDisconnectedAt(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Module) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) {
|
||||
query, args, err := squirrel.Select("*").
|
||||
From(Table("module")).
|
||||
Where(squirrel.Eq{
|
||||
"name": names,
|
||||
}).OrderBy("created_at desc").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result := make([]entity.Module, 0)
|
||||
err = r.db.Select(ctx, &result, query, args...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select: %s", query)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r Module) GetById(ctx context.Context, id string) (*entity.Module, error) {
|
||||
result := entity.Module{}
|
||||
query := fmt.Sprintf("select * from %s where id = ?", Table("module"))
|
||||
err := r.db.SelectRow(ctx, &result, query, id)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
func Table(table string) string {
|
||||
return fmt.Sprintf("isp_config_service__%s", table)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity/xtypes"
|
||||
)
|
||||
|
||||
type Cleaner struct {
|
||||
repo Repo
|
||||
eventTtl time.Duration
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewCleaner(repo Repo, eventTtl time.Duration, logger log.Logger) Cleaner {
|
||||
return Cleaner{
|
||||
repo: repo,
|
||||
eventTtl: eventTtl,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Cleaner) Do(ctx context.Context) {
|
||||
deleteBefore := time.Now().Add(-c.eventTtl)
|
||||
deleted, err := c.repo.DeleteByCreatedAt(ctx, xtypes.Time{Value: deleteBefore})
|
||||
if err != nil {
|
||||
c.logger.Error(ctx, errors.WithMessage(err, "delete old events"))
|
||||
return
|
||||
}
|
||||
c.logger.Debug(ctx, fmt.Sprintf("delete %d old events", deleted))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type Compactor struct {
|
||||
}
|
||||
|
||||
func NewCompactor() Compactor {
|
||||
return Compactor{}
|
||||
}
|
||||
|
||||
func (c Compactor) Compact(events []entity.Event) []entity.Event {
|
||||
uniqueEvents := make([]entity.Event, 0, len(events))
|
||||
uniqueEventKeys := make(map[string]bool, len(events))
|
||||
for i := len(events) - 1; i >= 0; i-- {
|
||||
event := events[i]
|
||||
key := event.Key()
|
||||
if uniqueEventKeys[key] {
|
||||
continue
|
||||
}
|
||||
uniqueEvents = append(uniqueEvents, event)
|
||||
uniqueEventKeys[key] = true
|
||||
}
|
||||
return uniqueEvents
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type SubscriptionService interface {
|
||||
NotifyConfigChanged(ctx context.Context, moduleId string) error
|
||||
NotifyBackendsChanged(ctx context.Context, moduleId string) error
|
||||
NotifyRoutingChanged(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
subscriptionService SubscriptionService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
subscriptionService SubscriptionService,
|
||||
logger log.Logger,
|
||||
) Handler {
|
||||
return Handler{
|
||||
subscriptionService: subscriptionService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (h Handler) Handle(ctx context.Context, events []entity.Event) {
|
||||
routingChanged := false
|
||||
for _, event := range events {
|
||||
payload := event.Payload.Value
|
||||
routingChanged = routingChanged || payload.ModuleReady != nil || payload.ModuleDisconnected != nil
|
||||
err := h.handleEvent(ctx, event)
|
||||
if err != nil {
|
||||
h.logger.Error(ctx, errors.WithMessagef(err, "handle event: %s", event.Key()))
|
||||
}
|
||||
}
|
||||
|
||||
if routingChanged {
|
||||
err := h.subscriptionService.NotifyRoutingChanged(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error(ctx, errors.WithMessage(err, "handle routing changed"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h Handler) handleEvent(ctx context.Context, event entity.Event) error {
|
||||
payload := event.Payload.Value
|
||||
switch {
|
||||
case payload.ConfigUpdated != nil:
|
||||
err := h.subscriptionService.NotifyConfigChanged(ctx, payload.ConfigUpdated.ModuleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "handle config changed event")
|
||||
}
|
||||
case payload.ModuleReady != nil:
|
||||
err := h.subscriptionService.NotifyBackendsChanged(ctx, payload.ModuleReady.ModuleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "handle module ready event")
|
||||
}
|
||||
case payload.ModuleDisconnected != nil:
|
||||
err := h.subscriptionService.NotifyBackendsChanged(ctx, payload.ModuleDisconnected.ModuleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "handle module disconnected event")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unknown event: %v", payload)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package event
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/entity/xtypes"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
const (
|
||||
limit = 100
|
||||
)
|
||||
|
||||
type HandlerRepo interface {
|
||||
Handle(ctx context.Context, events []entity.Event)
|
||||
}
|
||||
|
||||
type Repo interface {
|
||||
Get(ctx context.Context, lastRowId int, limit int) ([]entity.Event, error)
|
||||
DeleteByCreatedAt(ctx context.Context, before xtypes.Time) (int, error)
|
||||
}
|
||||
|
||||
type Worker struct {
|
||||
repo Repo
|
||||
compactor Compactor
|
||||
handler HandlerRepo
|
||||
lastEventId int
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewWorker(repo Repo, handler HandlerRepo, logger log.Logger) *Worker {
|
||||
return &Worker{
|
||||
repo: repo,
|
||||
handler: handler,
|
||||
compactor: NewCompactor(),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) Do(ctx context.Context) {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "eventReader"))
|
||||
err := w.do(ctx)
|
||||
if err != nil {
|
||||
w.logger.Error(ctx, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) do(ctx context.Context) error {
|
||||
getEventCtx := db.NoneConsistency().ToContext(ctx)
|
||||
events, err := w.repo.Get(getEventCtx, w.lastEventId, limit)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get new events")
|
||||
}
|
||||
if len(events) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
events = w.compactor.Compact(events)
|
||||
w.handler.Handle(ctx, events)
|
||||
w.lastEventId = events[len(events)-1].RowId
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -23,7 +23,7 @@ const (
|
||||
backendKey = "backend"
|
||||
)
|
||||
|
||||
type ModuleRepo interface {
|
||||
type Repo interface {
|
||||
Upsert(ctx context.Context, module entity.Module) (string, error)
|
||||
SetDisconnectedAt(
|
||||
ctx context.Context,
|
||||
@@ -50,34 +50,43 @@ type ConfigRepo interface {
|
||||
GetActive(ctx context.Context, moduleId string) (*entity.Config, error)
|
||||
}
|
||||
|
||||
type Module struct {
|
||||
moduleRepo ModuleRepo
|
||||
backendRepo BackendRepo
|
||||
eventRepo EventRepo
|
||||
configRepo ConfigRepo
|
||||
configSchemaRepo ConfigSchemaRepo
|
||||
logger log.Logger
|
||||
type SubscriptionService interface {
|
||||
SubscribeToConfigChanges(conn *etp.Conn, moduleId string)
|
||||
SubscribeToBackendsChanges(ctx context.Context, conn *etp.Conn, requiredModuleNames []string) error
|
||||
SubscribeToRoutingChanges(ctx context.Context, conn *etp.Conn) error
|
||||
}
|
||||
|
||||
func NewModule(
|
||||
moduleRepo ModuleRepo,
|
||||
type Service struct {
|
||||
moduleRepo Repo
|
||||
backendRepo BackendRepo
|
||||
eventRepo EventRepo
|
||||
configRepo ConfigRepo
|
||||
configSchemaRepo ConfigSchemaRepo
|
||||
subscriptionService SubscriptionService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewService(
|
||||
moduleRepo Repo,
|
||||
backendRepo BackendRepo,
|
||||
eventRepo EventRepo,
|
||||
configRepo ConfigRepo,
|
||||
configSchemaRepo ConfigSchemaRepo,
|
||||
subscriptionService SubscriptionService,
|
||||
logger log.Logger,
|
||||
) Module {
|
||||
return Module{
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
eventRepo: eventRepo,
|
||||
configRepo: configRepo,
|
||||
configSchemaRepo: configSchemaRepo,
|
||||
logger: logger,
|
||||
) Service {
|
||||
return Service{
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
eventRepo: eventRepo,
|
||||
configRepo: configRepo,
|
||||
configSchemaRepo: configSchemaRepo,
|
||||
subscriptionService: subscriptionService,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Module) OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error {
|
||||
func (s Service) OnConnect(ctx context.Context, conn *etp.Conn, moduleName string) error {
|
||||
now := now()
|
||||
module := entity.Module{
|
||||
Id: uuid.NewString(),
|
||||
@@ -94,7 +103,7 @@ func (s Module) OnConnect(ctx context.Context, conn *etp.Conn, moduleName string
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnDisconnect(
|
||||
func (s Service) OnDisconnect(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
moduleName string,
|
||||
@@ -128,7 +137,7 @@ func (s Module) OnDisconnect(
|
||||
return errors.WithMessage(err, "delete backend in store")
|
||||
}
|
||||
|
||||
event := entity.NewEvent(entity.ModuleDisconnected, entity.EventPayload{
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
@@ -142,7 +151,7 @@ func (s Module) OnDisconnect(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnError(ctx context.Context, conn *etp.Conn, moduleName string, err error) {
|
||||
func (s Service) OnError(ctx context.Context, conn *etp.Conn, moduleName string, err error) {
|
||||
err = errors.WithMessagef(
|
||||
err,
|
||||
"unexpected error in communication, module: '%s'",
|
||||
@@ -151,7 +160,7 @@ func (s Module) OnError(ctx context.Context, conn *etp.Conn, moduleName string,
|
||||
s.logger.Error(ctx, err)
|
||||
}
|
||||
|
||||
func (s Module) OnModuleReady(
|
||||
func (s Service) OnModuleReady(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
declaration cluster.BackendDeclaration,
|
||||
@@ -166,6 +175,7 @@ func (s Module) OnModuleReady(
|
||||
Address: fmt.Sprintf("%s:%s", declaration.Address.IP, declaration.Address.Port),
|
||||
Version: declaration.Version,
|
||||
LibVersion: declaration.LibVersion,
|
||||
ModuleName: declaration.ModuleName,
|
||||
Endpoints: xtypes.Json[[]cluster.EndpointDescriptor]{Value: declaration.Endpoints},
|
||||
RequiredModules: xtypes.Json[[]cluster.ModuleDependency]{Value: declaration.RequiredModules},
|
||||
}
|
||||
@@ -176,7 +186,7 @@ func (s Module) OnModuleReady(
|
||||
|
||||
conn.Data().Set(backendKey, backend)
|
||||
|
||||
event := entity.NewEvent(entity.ModuleReady, entity.EventPayload{
|
||||
event := entity.NewEvent(entity.EventPayload{
|
||||
ModuleReady: &entity.PayloadModuleReady{
|
||||
ModuleId: moduleId,
|
||||
},
|
||||
@@ -189,15 +199,29 @@ func (s Module) OnModuleReady(
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnModuleRequirements(
|
||||
func (s Service) OnModuleRequirements(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
requirements cluster.ModuleRequirements,
|
||||
) error {
|
||||
if len(requirements.RequiredModules) > 0 {
|
||||
err := s.subscriptionService.SubscribeToBackendsChanges(ctx, conn, requirements.RequiredModules)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "subscribe to required modules")
|
||||
}
|
||||
}
|
||||
|
||||
if requirements.RequireRoutes {
|
||||
err := s.subscriptionService.SubscribeToRoutingChanges(ctx, conn)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "subscribe to routing changes")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnModuleConfigSchema(
|
||||
func (s Service) OnModuleConfigSchema(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
data cluster.ConfigData,
|
||||
@@ -234,6 +258,8 @@ func (s Module) OnModuleConfigSchema(
|
||||
return errors.WithMessage(err, "send event with config")
|
||||
}
|
||||
|
||||
s.subscriptionService.SubscribeToConfigChanges(conn, moduleId)
|
||||
|
||||
configSchema := entity.ConfigSchema{
|
||||
Id: uuid.NewString(),
|
||||
ModuleId: moduleId,
|
||||
+8
-18
@@ -4,25 +4,19 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/iancoleman/strcase"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
func init() {
|
||||
sqlx.NameMapper = strcase.ToSnake
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
type Adapter struct {
|
||||
cli *httpcli.Client
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, dsn string, client *httpcli.Client) (*DB, error) {
|
||||
func Open(ctx context.Context, dsn string, client *httpcli.Client) (*Adapter, error) {
|
||||
client.GlobalRequestConfig().BaseUrl = dsn
|
||||
db := &DB{
|
||||
db := &Adapter{
|
||||
cli: client,
|
||||
}
|
||||
|
||||
@@ -35,7 +29,7 @@ func Open(ctx context.Context, dsn string, client *httpcli.Client) (*DB, error)
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func (d DB) Select(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
func (d Adapter) Select(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
result := &Result{
|
||||
Rows: ptr,
|
||||
}
|
||||
@@ -62,7 +56,7 @@ func (d DB) Select(ctx context.Context, ptr any, query string, args ...any) erro
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d DB) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
func (d Adapter) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
result := &Result{}
|
||||
resp := Response{
|
||||
Results: []*Result{result},
|
||||
@@ -101,7 +95,7 @@ func (d DB) SelectRow(ctx context.Context, ptr any, query string, args ...any) e
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d DB) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
func (d Adapter) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
result := &Result{}
|
||||
resp := Response{
|
||||
Results: []*Result{result},
|
||||
@@ -122,10 +116,6 @@ func (d DB) Exec(ctx context.Context, query string, args ...any) (sql.Result, er
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d DB) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
|
||||
query, args, err := sqlx.Named(query, arg)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "map to unnamed query")
|
||||
}
|
||||
return d.Exec(ctx, query, args...)
|
||||
func (d Adapter) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
|
||||
return d.Exec(ctx, query, arg)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
type DB interface {
|
||||
Select(ctx context.Context, ptr any, query string, args ...any) error
|
||||
SelectRow(ctx context.Context, ptr any, query string, args ...any) error
|
||||
Exec(ctx context.Context, query string, args ...any) (sql.Result, error)
|
||||
ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/pressly/goose/v3/database"
|
||||
"isp-config-service/repository"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
@@ -18,7 +19,7 @@ type Store struct {
|
||||
func NewStore(db *sql.DB) Store {
|
||||
return Store{
|
||||
db: db,
|
||||
tablename: "isp_config_service__goose_db_version",
|
||||
tablename: repository.Table("goose_db_version"),
|
||||
querier: &Rqlite{},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/worker"
|
||||
"isp-config-service/assembly"
|
||||
"isp-config-service/conf"
|
||||
"isp-config-service/service/rqlite"
|
||||
@@ -37,12 +38,14 @@ type Service struct {
|
||||
logger log.Logger
|
||||
|
||||
//initialized in Run
|
||||
etpSrv *etp.Server
|
||||
etpSrv *etp.Server
|
||||
handleEventWorker *worker.Worker
|
||||
cleanEventWorker *worker.Worker
|
||||
}
|
||||
|
||||
func New(boot *bootstrap.Bootstrap) Service {
|
||||
func New(boot *bootstrap.Bootstrap) *Service {
|
||||
rqlite := rqlite.New(boot.App.Config())
|
||||
return Service{
|
||||
return &Service{
|
||||
boot: boot,
|
||||
rqlite: rqlite,
|
||||
grpcSrv: grpc.DefaultServer(),
|
||||
@@ -52,7 +55,7 @@ func New(boot *bootstrap.Bootstrap) Service {
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) Run(ctx context.Context) error {
|
||||
func (s *Service) Run(ctx context.Context) error {
|
||||
localConfig := conf.Local{}
|
||||
err := s.boot.App.Config().Read(&localConfig)
|
||||
if err != nil {
|
||||
@@ -91,9 +94,14 @@ func (s Service) Run(ctx context.Context) error {
|
||||
|
||||
config := assembly.NewLocator(s.logger, db).Config()
|
||||
s.etpSrv = config.EtpSrv
|
||||
s.handleEventWorker = config.HandleEventWorker
|
||||
s.cleanEventWorker = config.CleanEventWorker
|
||||
s.grpcSrv.Upgrade(config.GrpcMux)
|
||||
s.httpSrv.Upgrade(config.HttpMux)
|
||||
|
||||
s.handleEventWorker.Run(ctx)
|
||||
s.cleanEventWorker.Run(ctx)
|
||||
|
||||
go func() {
|
||||
s.logger.Debug(ctx, fmt.Sprintf("starting grpc server on %s", s.boot.BindingAddress))
|
||||
err := s.grpcSrv.ListenAndServe(s.boot.BindingAddress)
|
||||
@@ -122,7 +130,7 @@ func (s Service) Run(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) Closers() []app.Closer {
|
||||
func (s *Service) Closers() []app.Closer {
|
||||
return []app.Closer{
|
||||
app.CloserFunc(func() error {
|
||||
s.grpcSrv.Shutdown()
|
||||
@@ -133,6 +141,15 @@ func (s Service) Closers() []app.Closer {
|
||||
defer cancel()
|
||||
return s.httpSrv.Shutdown(ctx)
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
if s.handleEventWorker != nil {
|
||||
s.handleEventWorker.Shutdown()
|
||||
}
|
||||
if s.cleanEventWorker != nil {
|
||||
s.cleanEventWorker.Shutdown()
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
if s.etpSrv == nil {
|
||||
return nil
|
||||
@@ -145,7 +162,7 @@ func (s Service) Closers() []app.Closer {
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) leaderStartup(ctx context.Context) error {
|
||||
func (s *Service) leaderStartup(ctx context.Context) error {
|
||||
db, err := s.rqlite.SqlDB()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "open sql db")
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package subscription
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func ConfigChangingRoom(moduleId string) string {
|
||||
return fmt.Sprintf("config_changing_room.%s", moduleId)
|
||||
}
|
||||
|
||||
func BackendsChangingRoom(moduleId string) string {
|
||||
return fmt.Sprintf("backends_changing_room.%s", moduleId)
|
||||
}
|
||||
|
||||
func RoutingChangingRoom() string {
|
||||
return "routing_changing_room"
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package subscription
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
"isp-config-service/helpers"
|
||||
"isp-config-service/service/rqlite/db"
|
||||
)
|
||||
|
||||
type ModuleRepo interface {
|
||||
GetByNames(ctx context.Context, names []string) ([]entity.Module, error)
|
||||
GetById(ctx context.Context, id string) (*entity.Module, error)
|
||||
}
|
||||
|
||||
type BackendRepo interface {
|
||||
GetByModuleId(ctx context.Context, moduleId string) ([]entity.Backend, error)
|
||||
All(ctx context.Context) ([]entity.Backend, error)
|
||||
}
|
||||
|
||||
type ConfigRepo interface {
|
||||
GetActive(ctx context.Context, moduleId string) (*entity.Config, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
moduleRepo ModuleRepo
|
||||
backendRepo BackendRepo
|
||||
configRepo ConfigRepo
|
||||
rooms *etp.Rooms
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewService(
|
||||
moduleRepo ModuleRepo,
|
||||
backendRepo BackendRepo,
|
||||
configRepo ConfigRepo,
|
||||
rooms *etp.Rooms,
|
||||
logger log.Logger,
|
||||
) Service {
|
||||
return Service{
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
configRepo: configRepo,
|
||||
rooms: rooms,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) SubscribeToConfigChanges(conn *etp.Conn, moduleId string) {
|
||||
s.rooms.Join(conn, ConfigChangingRoom(moduleId))
|
||||
}
|
||||
|
||||
func (s Service) NotifyConfigChanged(ctx context.Context, moduleId string) error {
|
||||
conns := s.rooms.ToBroadcast(ConfigChangingRoom(moduleId))
|
||||
if len(conns) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx = db.NoneConsistency().ToContext(ctx)
|
||||
config, err := s.configRepo.GetActive(ctx, moduleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get active config")
|
||||
}
|
||||
|
||||
for _, conn := range conns {
|
||||
go func() {
|
||||
s.emitEvent(ctx, conn, cluster.ConfigSendConfigChanged, config.Data)
|
||||
}()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) SubscribeToBackendsChanges(ctx context.Context, conn *etp.Conn, requiredModuleNames []string) error {
|
||||
ctx = db.NoneConsistency().ToContext(ctx)
|
||||
modules, err := s.moduleRepo.GetByNames(ctx, requiredModuleNames)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get modules by names")
|
||||
}
|
||||
|
||||
roomsToJoin := make([]string, 0)
|
||||
for _, module := range modules {
|
||||
roomsToJoin = append(roomsToJoin, BackendsChangingRoom(module.Id))
|
||||
go func() {
|
||||
err := s.notifyBackendsChanged(ctx, module.Id, []*etp.Conn{conn})
|
||||
if err != nil {
|
||||
s.logger.Error(ctx, errors.WithMessage(err, "notify backends changed"))
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
s.rooms.Join(conn, roomsToJoin...)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) NotifyBackendsChanged(ctx context.Context, moduleId string) error {
|
||||
conns := s.rooms.ToBroadcast(BackendsChangingRoom(moduleId))
|
||||
if len(conns) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.notifyBackendsChanged(ctx, moduleId, conns)
|
||||
}
|
||||
|
||||
func (s Service) notifyBackendsChanged(
|
||||
ctx context.Context,
|
||||
moduleId string,
|
||||
conns []*etp.Conn,
|
||||
) error {
|
||||
ctx = db.NoneConsistency().ToContext(ctx)
|
||||
module, err := s.moduleRepo.GetById(ctx, moduleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get module by id")
|
||||
}
|
||||
backends, err := s.backendRepo.GetByModuleId(ctx, moduleId)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get backends by module id")
|
||||
}
|
||||
|
||||
addresses := make([]cluster.AddressConfiguration, 0)
|
||||
for _, backend := range backends {
|
||||
addr, err := splitAddress(backend)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "split address")
|
||||
}
|
||||
addresses = append(addresses, addr)
|
||||
}
|
||||
data, err := json.Marshal(addresses)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal addresses")
|
||||
}
|
||||
|
||||
for _, conn := range conns {
|
||||
go func() {
|
||||
s.emitEvent(ctx, conn, cluster.ModuleConnectedEvent(module.Name), data)
|
||||
}()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) SubscribeToRoutingChanges(ctx context.Context, conn *etp.Conn) error {
|
||||
err := s.notifyRoutingChanged(ctx, cluster.ConfigSendRoutesWhenConnected, []*etp.Conn{conn})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "notify routing changed")
|
||||
}
|
||||
|
||||
s.rooms.Join(conn, RoutingChangingRoom())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) NotifyRoutingChanged(ctx context.Context) error {
|
||||
conns := s.rooms.ToBroadcast(RoutingChangingRoom())
|
||||
if len(conns) == 0 {
|
||||
return nil
|
||||
}
|
||||
return s.notifyRoutingChanged(ctx, cluster.ConfigSendRoutesChanged, conns)
|
||||
}
|
||||
|
||||
func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns []*etp.Conn) error {
|
||||
backends, err := s.backendRepo.All(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get all backends")
|
||||
}
|
||||
|
||||
routingConfig := cluster.RoutingConfig{}
|
||||
for _, backend := range backends {
|
||||
addr, err := splitAddress(backend)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "split address")
|
||||
}
|
||||
declaration := cluster.BackendDeclaration{
|
||||
ModuleName: backend.ModuleName,
|
||||
Version: backend.Version,
|
||||
LibVersion: backend.LibVersion,
|
||||
Endpoints: backend.Endpoints.Value,
|
||||
RequiredModules: backend.RequiredModules.Value,
|
||||
Address: addr,
|
||||
}
|
||||
routingConfig = append(routingConfig, declaration)
|
||||
}
|
||||
data, err := json.Marshal(routingConfig)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal routing config")
|
||||
}
|
||||
|
||||
for _, conn := range conns {
|
||||
go func() {
|
||||
s.emitEvent(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)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user