Implement lifecycle
This commit is contained in:
1 parent
2e23e882bb
commit
8a2a65d8ed
14 files changed
+594
-38
No files matched your search
@@ -1,4 +1,153 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v3/store"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
const (
|
||||
moduleIdKey = "moduleId"
|
||||
backendKey = "backend"
|
||||
)
|
||||
|
||||
type ModuleRepo interface {
|
||||
Upsert(ctx context.Context, module entity.Module) (string, error)
|
||||
SetDisconnectedAt(
|
||||
ctx context.Context,
|
||||
moduleId string,
|
||||
disconnected time.Time,
|
||||
) error
|
||||
}
|
||||
|
||||
type BackendRepo interface {
|
||||
Upsert(ctx context.Context, backend entity.Backend) error
|
||||
Delete(ctx context.Context, moduleId string, address string) error
|
||||
}
|
||||
|
||||
type Module struct {
|
||||
moduleRepo ModuleRepo
|
||||
backendRepo BackendRepo
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewModule(
|
||||
moduleRepo ModuleRepo,
|
||||
backendRepo BackendRepo,
|
||||
logger log.Logger,
|
||||
) Module {
|
||||
return Module{
|
||||
moduleRepo: moduleRepo,
|
||||
backendRepo: backendRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Module) OnConnect(conn *etp.Conn, moduleName string) error {
|
||||
now := time.Now().UTC()
|
||||
module := entity.Module{
|
||||
Id: uuid.NewString(),
|
||||
Name: moduleName,
|
||||
LastConnectedAt: &now,
|
||||
CreatedAt: now,
|
||||
}
|
||||
moduleId, err := s.moduleRepo.Upsert(context.Background(), module)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert module in store")
|
||||
}
|
||||
|
||||
conn.Data().Set(moduleIdKey, moduleId)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnDisconnect(
|
||||
conn *etp.Conn,
|
||||
moduleName string,
|
||||
isNormalClose bool,
|
||||
err error,
|
||||
) error {
|
||||
if isNormalClose {
|
||||
s.logger.Info(context.Background(), fmt.Sprintf("module '%s' disconnected", moduleName))
|
||||
} else {
|
||||
message := errors.WithMessagef(
|
||||
err,
|
||||
"module '%s' unexpectedly disconnected",
|
||||
moduleName,
|
||||
)
|
||||
s.logger.Error(context.Background(), message)
|
||||
}
|
||||
|
||||
moduleId, _ := store.Get[string](conn.Data(), moduleIdKey)
|
||||
if moduleId != "" {
|
||||
err = s.moduleRepo.SetDisconnectedAt(context.Background(), moduleName, time.Now().UTC())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update disconnected time in store")
|
||||
}
|
||||
}
|
||||
|
||||
backend, _ := store.Get[entity.Backend](conn.Data(), backendKey)
|
||||
if backend.ModuleId != "" {
|
||||
err = s.backendRepo.Delete(context.Background(), backend.ModuleId, backend.Address)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "delete backend in store")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnError(conn *etp.Conn, moduleName string, err error) {
|
||||
err = errors.WithMessagef(
|
||||
err,
|
||||
"unexpected error in communication, module: '%s'",
|
||||
moduleName,
|
||||
)
|
||||
s.logger.Error(context.Background(), err)
|
||||
}
|
||||
|
||||
func (s Module) OnModuleReady(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
backend cluster.BackendDeclaration,
|
||||
) error {
|
||||
moduleId, err := store.Get[string](conn.Data(), moduleIdKey)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "resolve module id")
|
||||
}
|
||||
|
||||
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{},
|
||||
}
|
||||
}
|
||||
|
||||
func (s Module) OnModuleRequirements(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
requirements cluster.ModuleRequirements,
|
||||
) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Module) OnModuleConfigSchema(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
data cluster.ConfigData,
|
||||
) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type consistencyCtxKey struct{}
|
||||
|
||||
var (
|
||||
consistencyCtxValue = consistencyCtxKey{}
|
||||
)
|
||||
|
||||
func ConsistencyFromContext(ctx context.Context) Consistency {
|
||||
c, ok := ctx.Value(consistencyCtxValue).(Consistency)
|
||||
if !ok {
|
||||
return Consistency{}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
type ConsistencyLevel string
|
||||
|
||||
const (
|
||||
ConsistencyLevelNone ConsistencyLevel = "none"
|
||||
ConsistencyLevelWeak ConsistencyLevel = "weak"
|
||||
ConsistencyLevelStrong ConsistencyLevel = "strong"
|
||||
)
|
||||
|
||||
type Consistency struct {
|
||||
level ConsistencyLevel
|
||||
freshness time.Duration
|
||||
freshnessStrict bool
|
||||
}
|
||||
|
||||
func (c Consistency) WithLevel(level ConsistencyLevel) Consistency {
|
||||
c.level = level
|
||||
return c
|
||||
}
|
||||
|
||||
func (c Consistency) WithFreshness(freshness time.Duration) Consistency {
|
||||
c.freshness = freshness
|
||||
return c
|
||||
}
|
||||
|
||||
func (c Consistency) WithFreshnessStrict(freshnessStrict bool) Consistency {
|
||||
c.freshnessStrict = freshnessStrict
|
||||
return c
|
||||
}
|
||||
func (c Consistency) ToContext(ctx context.Context) context.Context {
|
||||
return context.WithValue(ctx, consistencyCtxValue, c)
|
||||
}
|
||||
|
||||
func (c Consistency) appendParams(params map[string]any) {
|
||||
if c.level != "" {
|
||||
params["level"] = c.level
|
||||
}
|
||||
if c.freshness > 0 {
|
||||
params["freshness"] = c.freshness.String()
|
||||
}
|
||||
if c.freshnessStrict {
|
||||
params["freshness_strict"] = c.freshnessStrict
|
||||
}
|
||||
}
|
||||
|
||||
func NoneConsistency() Consistency {
|
||||
return Consistency{
|
||||
level: ConsistencyLevelNone,
|
||||
}
|
||||
}
|
||||
|
||||
func WeakConsistency() Consistency {
|
||||
return Consistency{
|
||||
level: ConsistencyLevelWeak,
|
||||
}
|
||||
}
|
||||
|
||||
func StrongConsistency() Consistency {
|
||||
return Consistency{
|
||||
level: ConsistencyLevelStrong,
|
||||
}
|
||||
}
|
||||
+21
-10
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/iancoleman/strcase"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -11,6 +12,10 @@ import (
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
func init() {
|
||||
sqlx.NameMapper = strcase.ToSnake
|
||||
}
|
||||
|
||||
type DB struct {
|
||||
cli *httpcli.Client
|
||||
}
|
||||
@@ -37,11 +42,14 @@ func (d DB) Select(ctx context.Context, ptr any, query string, args ...any) erro
|
||||
resp := Response{
|
||||
Results: []*Result{result},
|
||||
}
|
||||
params := map[string]any{
|
||||
"timings": true,
|
||||
"associative": true,
|
||||
}
|
||||
ConsistencyFromContext(ctx).appendParams(params)
|
||||
err := d.cli.Post("/db/query").
|
||||
QueryParams(map[string]any{
|
||||
"timings": true,
|
||||
"associative": true,
|
||||
}).JsonRequestBody(Request(query, args...)).
|
||||
QueryParams(params).
|
||||
JsonRequestBody(request(query, args...)).
|
||||
JsonResponseBody(&resp).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
@@ -59,11 +67,14 @@ func (d DB) SelectRow(ctx context.Context, ptr any, query string, args ...any) e
|
||||
resp := Response{
|
||||
Results: []*Result{result},
|
||||
}
|
||||
httpResp, err := d.cli.Post("/db/query").
|
||||
QueryParams(map[string]any{
|
||||
"timings": true,
|
||||
"associative": true,
|
||||
}).JsonRequestBody(Request(query, args...)).
|
||||
params := map[string]any{
|
||||
"timings": true,
|
||||
"associative": true,
|
||||
}
|
||||
ConsistencyFromContext(ctx).appendParams(params)
|
||||
httpResp, err := d.cli.Post("/db/request").
|
||||
QueryParams(params).
|
||||
JsonRequestBody(requests(request(query, args...))).
|
||||
JsonResponseBody(&resp).
|
||||
StatusCodeToError().
|
||||
Do(ctx)
|
||||
@@ -98,7 +109,7 @@ func (d DB) Exec(ctx context.Context, query string, args ...any) (sql.Result, er
|
||||
err := d.cli.Post("/db/execute").
|
||||
QueryParams(map[string]any{
|
||||
"timings": true,
|
||||
}).JsonRequestBody(Request(query, args...)).
|
||||
}).JsonRequestBody(requests(request(query, args...))).
|
||||
JsonResponseBody(&resp).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
package db
|
||||
|
||||
func Request(query string, args ...any) []any {
|
||||
func request(query string, args ...any) []any {
|
||||
return append([]any{query}, args...)
|
||||
}
|
||||
|
||||
func requests(requests ...[]any) [][]any {
|
||||
return requests
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/txix-open/isp-kit/dbx/migration"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"isp-config-service/assembly"
|
||||
@@ -80,7 +81,7 @@ func (s Service) Run(ctx context.Context) error {
|
||||
s.logger.Debug(ctx, "is not a leader")
|
||||
}
|
||||
|
||||
db, err := db.Open(ctx, s.rqlite.Dsn(), httpclix.Default())
|
||||
db, err := db.Open(ctx, s.rqlite.Dsn(), httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(s.logger))))
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "dial to embedded rqlite")
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user