Implement lifecycle
This commit is contained in:
1 parent
2e23e882bb
commit
8a2a65d8ed
14 files changed
+594
-38
No files matched your search
+100
-10
@@ -3,37 +3,127 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v3"
|
||||
"github.com/txix-open/etp/v3/msg"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type Module struct {
|
||||
var (
|
||||
ok = []byte("ok")
|
||||
)
|
||||
|
||||
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)
|
||||
OnModuleReady(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
backend cluster.BackendDeclaration,
|
||||
) error
|
||||
OnModuleRequirements(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
requirements cluster.ModuleRequirements,
|
||||
) error
|
||||
OnModuleConfigSchema(
|
||||
ctx context.Context,
|
||||
conn *etp.Conn,
|
||||
data cluster.ConfigData,
|
||||
) error
|
||||
}
|
||||
|
||||
func NewModule() Module {
|
||||
return Module{}
|
||||
type Module struct {
|
||||
service ModuleService
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewModule(service ModuleService, logger log.Logger) Module {
|
||||
return Module{
|
||||
service: service,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (m Module) OnConnect(conn *etp.Conn) {
|
||||
|
||||
err := m.service.OnConnect(conn, moduleName(conn))
|
||||
if err != nil {
|
||||
m.handleError(context.Background(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func (m Module) OnDisconnect(ctx *etp.Conn, conn error) {
|
||||
|
||||
func (m Module) OnDisconnect(conn *etp.Conn, err error) {
|
||||
handleDisconnectErr := m.service.OnDisconnect(
|
||||
conn,
|
||||
moduleName(conn),
|
||||
etp.IsNormalClose(err),
|
||||
err,
|
||||
)
|
||||
if handleDisconnectErr != nil {
|
||||
m.handleError(context.Background(), handleDisconnectErr)
|
||||
}
|
||||
}
|
||||
|
||||
func (m Module) OnError(conn *etp.Conn, err error) {
|
||||
|
||||
m.service.OnError(conn, moduleName(conn), err)
|
||||
}
|
||||
|
||||
func (m Module) OnModuleReady(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
return nil
|
||||
backend := cluster.BackendDeclaration{}
|
||||
err := json.Unmarshal(event.Data, &backend)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
|
||||
}
|
||||
|
||||
err = m.service.OnModuleReady(ctx, conn, backend)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, err)
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m Module) OnModuleRequirements(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
return nil
|
||||
requirements := cluster.ModuleRequirements{}
|
||||
err := json.Unmarshal(event.Data, &requirements)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
|
||||
}
|
||||
|
||||
err = m.service.OnModuleRequirements(ctx, conn, requirements)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, err)
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m Module) OnModuleConfigSchema(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
return nil
|
||||
configData := cluster.ConfigData{}
|
||||
err := json.Unmarshal(event.Data, &configData)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, errors.WithMessage(err, "unmarshal event data"))
|
||||
}
|
||||
|
||||
err = m.service.OnModuleConfigSchema(ctx, conn, configData)
|
||||
if err != nil {
|
||||
return m.handleError(ctx, err)
|
||||
}
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
func (m Module) handleError(
|
||||
ctx context.Context,
|
||||
err error,
|
||||
) []byte {
|
||||
m.logger.Error(ctx, err)
|
||||
return []byte(err.Error())
|
||||
}
|
||||
|
||||
func moduleName(conn *etp.Conn) string {
|
||||
return conn.HttpRequest().Form.Get("module_name")
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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)
|
||||
}
|
||||
+5
-5
@@ -5,9 +5,9 @@ import (
|
||||
)
|
||||
|
||||
type Module struct {
|
||||
Id string
|
||||
Name string
|
||||
LastConnectedAt time.Time
|
||||
LastDisconnectedAt time.Time
|
||||
Created time.Time
|
||||
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"`
|
||||
}
|
||||
@@ -3,13 +3,16 @@ module isp-config-service
|
||||
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
|
||||
github.com/rqlite/rqlite/v8 v8.23.4
|
||||
github.com/tidwall/gjson v1.17.1
|
||||
github.com/txix-open/etp/v3 v3.0.0
|
||||
github.com/txix-open/etp/v3 v3.1.0
|
||||
github.com/txix-open/isp-kit v1.31.2
|
||||
)
|
||||
|
||||
@@ -36,12 +39,13 @@ 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/iancoleman/strcase v0.3.0 // 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
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
|
||||
@@ -39,20 +39,32 @@ 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,
|
||||
name text not null,
|
||||
module_id text not null,
|
||||
data blob not null,
|
||||
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 text not null default (datetime('now')),
|
||||
updated_at text not null default (datetime('now')),
|
||||
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
|
||||
);
|
||||
|
||||
create index IX_isp_config_service__config_schema__module_id on isp_config_service__config_schema (module_id);
|
||||
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')),
|
||||
primary key (module_id, address),
|
||||
foreign key (module_id) references isp_config_service__module (id) on delete cascade on update cascade
|
||||
);
|
||||
|
||||
-- +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;
|
||||
@@ -0,0 +1,64 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"isp-config-service/entity"
|
||||
)
|
||||
|
||||
type Backend struct {
|
||||
db db.DB
|
||||
}
|
||||
|
||||
func NewBackend(db db.DB) Backend {
|
||||
return Backend{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
"endpoints", "required_modules").
|
||||
Values(backend.ModuleId, backend.Address,
|
||||
backend.Version, backend.LibVersion,
|
||||
backend.Endpoints, backend.RequiredModules,
|
||||
).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')
|
||||
`).
|
||||
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 Backend) Delete(ctx context.Context, moduleId string, address string) error {
|
||||
query, args, err := squirrel.Delete(Table("backend")).
|
||||
Where(squirrel.Eq{
|
||||
"module_id": moduleId,
|
||||
"address": address,
|
||||
}).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
|
||||
}
|
||||
+45
-1
@@ -2,7 +2,11 @@ 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"
|
||||
)
|
||||
@@ -17,6 +21,46 @@ func NewModule(db db.DB) Module {
|
||||
}
|
||||
}
|
||||
|
||||
func (r Module) Upsert(ctx context.Context, module entity.Module) error {
|
||||
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("returning id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return "", errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
result := make(map[string]string)
|
||||
err = r.db.SelectRow(ctx, &result, query, args...)
|
||||
if err != nil {
|
||||
return "", errors.WithMessagef(err, "select : %s", query)
|
||||
}
|
||||
return result["id"], nil
|
||||
}
|
||||
|
||||
func (r Module) SetDisconnectedAt(
|
||||
ctx context.Context,
|
||||
moduleId string,
|
||||
disconnected time.Time,
|
||||
) error {
|
||||
query, args, err := squirrel.Update(Table("module")).
|
||||
Set("last_disconnected_at", disconnected).
|
||||
Where(squirrel.Eq{"id": moduleId}).
|
||||
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)
|
||||
}
|
||||
@@ -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