MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+157
@@ -0,0 +1,157 @@
|
||||
# Package `cluster`
|
||||
|
||||
Пакет `cluster` предназначен для управления кластером микросервисов с возможностями:
|
||||
|
||||
- Регистрация модулей в кластере
|
||||
- Динамическое обновление конфигурации
|
||||
- Обмен маршрутами между сервисами
|
||||
- Обработка событий кластера
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Структура `Client` представляет собой клиент кластера с функциональностью установки и поддержки соединения с
|
||||
конфигурационным сервисом, регистрации модуля в кластере, обработки жизненного цикла соединения с отправкой метаданных
|
||||
модуля (версия, эндпоинты)
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewClient(moduleInfo ModuleInfo, configData ConfigData, hosts []string, handleConfigTimeout time.Duration, logger log.Logger) *Client`
|
||||
|
||||
Конструктор клиента кластера.
|
||||
|
||||
#### `(c *Client) Run(ctx context.Context, eventHandler *EventHandler) error`
|
||||
|
||||
Запустить клиент кластера с указанным обработчиком событий.
|
||||
|
||||
#### `(c *Client) Close() error`
|
||||
|
||||
Завершить работу клиента.
|
||||
|
||||
#### `(c *Client) Healthcheck(ctx context.Context) error`
|
||||
|
||||
Проверить активна ли текущая сессия.
|
||||
|
||||
### EventHandler
|
||||
|
||||
Структура `EventHandler` представляет собой компоновку обработчиков основных событий в кластере микросервисов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewEventHandler() *EventHandler`
|
||||
|
||||
Конструктор.
|
||||
|
||||
#### `(h *EventHandler) RemoteConfigReceiver(receiver RemoteConfigReceiver) *EventHandler`
|
||||
|
||||
Установить обработчик на получение обновленной динамической-конфигурации текущего модуля. Обработчик должен реализовывать интерфейс `RemoteConfigReceiver`.
|
||||
По умолчанию выставляет timeout на обработку конфига в 5 секунд.
|
||||
|
||||
#### `(h *EventHandler) RoutesReceiver(receiver RoutesReceiver) *EventHandler`
|
||||
|
||||
Установить обработчик на получение актуальных эндпоинтов, зависимостях и прочей информации о сервисах в кластере. Обработчик должен реализовывать интерфейс `RoutesReceiver`.
|
||||
|
||||
#### `(h *EventHandler) RequireModule(moduleName string, upgrader HostsUpgrader) *EventHandler`
|
||||
|
||||
Установить обработчик на получение списка адресов модулей, от которых зависит текущий сервис. Обработчик должен реализовывать интерфейс `HostsUpgrader`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/rc"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type remoteConfigUpdater struct{}
|
||||
|
||||
func (r remoteConfigUpdater) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
|
||||
/* handle & update new remote config */
|
||||
return nil
|
||||
}
|
||||
|
||||
type routesHandler struct{}
|
||||
|
||||
func (r routesHandler) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error {
|
||||
for _, module := range routes {
|
||||
/* handle each module's info */
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func noopHandler() {}
|
||||
|
||||
func main() {
|
||||
application, err := app.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
moduleInfo := cluster.ModuleInfo{
|
||||
ModuleName: "noop-service",
|
||||
Version: "1.0.0",
|
||||
Endpoints: []cluster.EndpointDescriptor{{
|
||||
Path: "/api/foo",
|
||||
Inner: false,
|
||||
Handler: noopHandler,
|
||||
}},
|
||||
}
|
||||
defaultRemoteConfig := []byte{...}
|
||||
configData := cluster.ConfigData{
|
||||
Version: "1.0.0",
|
||||
Schema: rc.GenerateConfigSchema(defaultRemoteConfig),
|
||||
Config: defaultRemoteConfig,
|
||||
}
|
||||
clusterCli := cluster.NewClient(
|
||||
moduleInfo,
|
||||
configData,
|
||||
[]string{"config-service:8080"},
|
||||
application.Config().Optional().Duration("remoteConfigReceiverTimeout", 5*time.Second),
|
||||
application.Logger(),
|
||||
)
|
||||
|
||||
/* client implements HostsUpgrader interface & will have auth-service's addresses */
|
||||
authServiceCli, err := client.Default()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
eventHandler := cluster.NewEventHandler(). /* Настройка обработчиков */
|
||||
RemoteConfigReceiver(remoteConfigUpdater{}).
|
||||
RoutesReceiver(routesHandler{}).
|
||||
RequireModule("auth-service", authServiceCli)
|
||||
application.AddRunners(app.RunnerFunc(func(ctx context.Context) error {
|
||||
err := clusterCli.Run(ctx, eventHandler)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
application.AddClosers(clusterCli, authServiceCli)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
application.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = application.Run() /* blocking here */
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
// Package cluster provides client-side functionality for connecting to a isp-config-service
|
||||
// in a distributed system. It handles session management, event-driven configuration updates,
|
||||
// and module dependency management.
|
||||
//
|
||||
// The package uses the ETP (Event Transport Protocol) for communication and supports
|
||||
// automatic load balancing, liveness probing, and graceful reconnection.
|
||||
//
|
||||
// Basic usage:
|
||||
//
|
||||
// client := cluster.NewClient(moduleInfo, configData, hosts, timeout, logger)
|
||||
// eventHandler := cluster.NewEventHandler().
|
||||
// RemoteConfigReceiver(myReceiver).
|
||||
// RoutesReceiver(myRoutesReceiver)
|
||||
// err := client.Run(ctx, eventHandler)
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/lb"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
livenessProbeFrequency = 5 * time.Second
|
||||
livenessProbeTimeout = 3 * time.Second
|
||||
|
||||
awaitEventTimeout = 1 * time.Second
|
||||
awaitConfigWhenConnectedBaseTimeout = 5 * time.Second
|
||||
|
||||
restartSessionWaitTime = 1 * time.Second
|
||||
|
||||
etpClientReadLimit = 4 * 1024 * 1024
|
||||
)
|
||||
|
||||
// Client manages the connection to a isp-config-service, handling session lifecycle,
|
||||
// event processing, and automatic reconnection.
|
||||
type Client struct {
|
||||
moduleInfo ModuleInfo
|
||||
configData ConfigData
|
||||
lb *lb.RoundRobin
|
||||
eventHandler *EventHandler
|
||||
handleConfigTimeout time.Duration
|
||||
logger log.Logger
|
||||
sessionIsActive *atomic.Bool
|
||||
closed *atomic.Bool
|
||||
applyConfigLock sync.Mutex
|
||||
|
||||
cli *atomic.Pointer[clientWrapper]
|
||||
}
|
||||
|
||||
// NewClient creates a new Client with the provided module information, configuration data,
|
||||
// list of hosts, timeout duration, and logger.
|
||||
func NewClient(
|
||||
moduleInfo ModuleInfo,
|
||||
configData ConfigData,
|
||||
hosts []string,
|
||||
handleConfigTimeout time.Duration,
|
||||
logger log.Logger,
|
||||
) *Client {
|
||||
return &Client{
|
||||
moduleInfo: moduleInfo,
|
||||
configData: configData,
|
||||
lb: lb.NewRoundRobin(hosts),
|
||||
handleConfigTimeout: handleConfigTimeout,
|
||||
sessionIsActive: &atomic.Bool{},
|
||||
closed: &atomic.Bool{},
|
||||
cli: &atomic.Pointer[clientWrapper]{},
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Run starts the client's main loop, establishing a connection to the isp-config-service
|
||||
// and handling events through the provided event handler. It blocks until the context is
|
||||
// canceled or the client is closed.
|
||||
func (c *Client) Run(ctx context.Context, eventHandler *EventHandler) error {
|
||||
if c.handleConfigTimeout != 0 {
|
||||
eventHandler.handleConfigTimeout = c.handleConfigTimeout
|
||||
}
|
||||
c.eventHandler = eventHandler
|
||||
c.closed.Store(false)
|
||||
|
||||
for {
|
||||
if c.closed.Load() {
|
||||
return nil
|
||||
}
|
||||
|
||||
host, err := c.lb.Next()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "peek config service host")
|
||||
}
|
||||
|
||||
sessionId := requestid.Next()
|
||||
sessionCtx := log.ToContext(ctx, log.String("sessionId", sessionId), log.String("configService", host))
|
||||
c.logger.Info(sessionCtx, "run config service session")
|
||||
|
||||
err = c.runSession(sessionCtx, host)
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return nil
|
||||
}
|
||||
cli := c.cli.Load()
|
||||
if cli != nil {
|
||||
_ = cli.Close()
|
||||
}
|
||||
if err != nil && !etp.IsNormalClose(err) {
|
||||
c.logger.Error(sessionCtx, "run config service session", log.String("error", err.Error()))
|
||||
}
|
||||
c.logger.Info(sessionCtx, "config service session stopped")
|
||||
|
||||
select {
|
||||
case <-sessionCtx.Done():
|
||||
return nil
|
||||
case <-time.After(restartSessionWaitTime):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close terminates the client and releases associated resources.
|
||||
func (c *Client) Close() error {
|
||||
c.closed.Store(true)
|
||||
cli := c.cli.Load()
|
||||
if cli != nil {
|
||||
return cli.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Healthcheck returns an error if the session is inactive, otherwise returns nil.
|
||||
func (c *Client) Healthcheck(ctx context.Context) error {
|
||||
if c.sessionIsActive.Load() {
|
||||
return nil
|
||||
}
|
||||
return errors.New("session inactive")
|
||||
}
|
||||
|
||||
// runSession establishes and manages a single session with the isp-config-service.
|
||||
func (c *Client) runSession(ctx context.Context, host string) error {
|
||||
defer c.sessionIsActive.Store(false)
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
requiredModules := make([]string, 0, len(c.eventHandler.requiredModules))
|
||||
for moduleName := range c.eventHandler.requiredModules {
|
||||
requiredModules = append(requiredModules, moduleName)
|
||||
}
|
||||
requirements := ModuleRequirements{
|
||||
RequiredModules: requiredModules,
|
||||
RequireRoutes: c.eventHandler.routesReceiver != nil,
|
||||
}
|
||||
|
||||
etpCli := etp.NewClient(etp.WithClientReadLimit(etpClientReadLimit))
|
||||
cli := newClientWrapper(ctx, etpCli, c.logger)
|
||||
c.cli.Store(cli)
|
||||
|
||||
disconnectCh := c.subscribeToEvents(cli)
|
||||
|
||||
err := c.dialClientWrapper(ctx, cli, host)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "dial client wrapper")
|
||||
}
|
||||
|
||||
_, err = cli.EmitJsonWithAck(ctx, ModuleSendConfigSchema, c.configData)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "emit module config schema")
|
||||
}
|
||||
|
||||
_, err = cli.EmitJsonWithAck(ctx, ModuleSendRequirements, requirements)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "emit module requirements")
|
||||
}
|
||||
|
||||
err = c.waitModuleReady(ctx, cli, requirements)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "wait module ready")
|
||||
}
|
||||
err = c.notifyModuleReady(ctx, cli, requirements)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "notify module ready")
|
||||
}
|
||||
|
||||
c.sessionIsActive.Store(true)
|
||||
go c.livenessProbeLoop(ctx)
|
||||
err = <-disconnectCh
|
||||
return err
|
||||
}
|
||||
|
||||
// subscribeToEvents registers handlers for configuration and routing events.
|
||||
func (c *Client) subscribeToEvents(cli *clientWrapper) chan error {
|
||||
for moduleName, upgrader := range c.eventHandler.requiredModules {
|
||||
event := ModuleConnectedEvent(moduleName)
|
||||
cli.RegisterEvent(event, func(eventId string, data []byte) error {
|
||||
hosts, err := readHosts(data)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "read hosts")
|
||||
}
|
||||
upgrader.Upgrade(hosts)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if c.eventHandler.remoteConfigReceiver != nil {
|
||||
cli.RegisterEvent(ConfigSendConfigChanged, c.remoteConfigEventHandler)
|
||||
cli.RegisterEvent(ConfigSendConfigWhenConnected, c.remoteConfigEventHandler)
|
||||
}
|
||||
if c.eventHandler.routesReceiver != nil {
|
||||
cli.RegisterEvent(ConfigSendRoutesChanged, c.routesEventHandler)
|
||||
cli.RegisterEvent(ConfigSendRoutesWhenConnected, c.routesEventHandler)
|
||||
}
|
||||
|
||||
disconnectCh := make(chan error, 1)
|
||||
cli.OnDisconnect(func(conn *etp.Conn, err error) {
|
||||
disconnectCh <- err
|
||||
})
|
||||
|
||||
return disconnectCh
|
||||
}
|
||||
|
||||
// dialClientWrapper establishes a WebSocket connection to the isp-config-service.
|
||||
func (c *Client) dialClientWrapper(ctx context.Context, cli *clientWrapper, host string) error {
|
||||
connUrl, err := url.Parse(fmt.Sprintf("ws://%s/isp-etp/", host))
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "parse conn url")
|
||||
}
|
||||
params := url.Values{}
|
||||
params.Add("module_name", c.moduleInfo.ModuleName)
|
||||
connUrl.RawQuery = params.Encode()
|
||||
|
||||
err = cli.Dial(ctx, connUrl.String())
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "connect to config service %s", host)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// remoteConfigEventHandler processes incoming remote configuration updates.
|
||||
func (c *Client) remoteConfigEventHandler(eventId string, data []byte) error {
|
||||
c.applyConfigLock.Lock()
|
||||
defer c.applyConfigLock.Unlock()
|
||||
|
||||
cli := c.cli.Load()
|
||||
ctx := log.ToContext(cli.ctx, log.String(EventIdContextKey, eventId))
|
||||
|
||||
c.logger.Info(ctx, "remote config applying...")
|
||||
err := c.applyRemoteConfig(ctx, data)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "apply remote config")
|
||||
}
|
||||
c.logger.Info(ctx, "remote config successfully applied")
|
||||
return nil
|
||||
}
|
||||
|
||||
// routesEventHandler processes incoming routing configuration updates.
|
||||
func (c *Client) routesEventHandler(eventId string, data []byte) error {
|
||||
cli := c.cli.Load()
|
||||
|
||||
routes, err := readRoutes(data)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "read route")
|
||||
}
|
||||
err = c.eventHandler.routesReceiver.ReceiveRoutes(cli.ctx, routes)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "handle routes")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitModuleReady waits for all required modules and optional events (routes, config)
|
||||
// to be ready, with individual timeouts for each.
|
||||
func (c *Client) waitModuleReady(ctx context.Context, cli *clientWrapper, requirements ModuleRequirements) error {
|
||||
awaitEvents := make(map[string]time.Duration, len(requirements.RequiredModules)+1)
|
||||
if requirements.RequireRoutes {
|
||||
awaitEvents[ConfigSendRoutesWhenConnected] = awaitEventTimeout
|
||||
}
|
||||
if c.eventHandler.remoteConfigReceiver != nil {
|
||||
awaitEvents[ConfigSendConfigWhenConnected] = awaitConfigWhenConnectedBaseTimeout + c.eventHandler.handleConfigTimeout
|
||||
}
|
||||
for _, module := range requirements.RequiredModules {
|
||||
event := ModuleConnectedEvent(module)
|
||||
awaitEvents[event] = awaitEventTimeout
|
||||
}
|
||||
|
||||
for event, timeout := range awaitEvents {
|
||||
err := cli.AwaitEvent(ctx, event, timeout)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "await '%s' event", event)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyModuleReady sends a ModuleReady event to the isp-config-service, announcing
|
||||
// the module's availability and its dependencies.
|
||||
func (c *Client) notifyModuleReady(ctx context.Context, cli *clientWrapper, requirements ModuleRequirements) error {
|
||||
moduleDependencies := make([]ModuleDependency, 0, len(requirements.RequiredModules))
|
||||
for _, module := range requirements.RequiredModules {
|
||||
dep := ModuleDependency{
|
||||
Name: module,
|
||||
Required: true,
|
||||
}
|
||||
moduleDependencies = append(moduleDependencies, dep)
|
||||
}
|
||||
declaration := BackendDeclaration{
|
||||
ModuleName: c.moduleInfo.ModuleName,
|
||||
Version: c.moduleInfo.ModuleVersion,
|
||||
LibVersion: c.moduleInfo.LibVersion,
|
||||
Endpoints: c.moduleInfo.Endpoints,
|
||||
Transport: c.moduleInfo.Transport,
|
||||
RequiredModules: moduleDependencies,
|
||||
Address: c.moduleInfo.GrpcOuterAddress,
|
||||
MetricsAutodiscovery: c.moduleInfo.MetricsAutodiscovery,
|
||||
}
|
||||
_, err := cli.EmitJsonWithAck(ctx, ModuleReady, declaration)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "emit module ready")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyRemoteConfig applies a remote configuration update with the configured timeout.
|
||||
func (c *Client) applyRemoteConfig(ctx context.Context, config []byte) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, c.eventHandler.handleConfigTimeout)
|
||||
defer cancel()
|
||||
|
||||
errChan := make(chan error, 1)
|
||||
go func() {
|
||||
errChan <- c.eventHandler.remoteConfigReceiver.ReceiveConfig(ctx, config)
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-errChan:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// livenessProbeLoop periodically sends ping requests to verify the connection to the
|
||||
// isp-config-service is still alive.
|
||||
func (c *Client) livenessProbeLoop(ctx context.Context) {
|
||||
for {
|
||||
cli := c.cli.Load()
|
||||
if cli == nil {
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(livenessProbeFrequency):
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, livenessProbeTimeout)
|
||||
err := cli.Ping(ctx)
|
||||
cancel()
|
||||
|
||||
if err != nil {
|
||||
c.logger.Warn(ctx, "ping config service", log.String("error", err.Error()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readRoutes unmarshals JSON data into a RoutingConfig.
|
||||
func readRoutes(data []byte) (RoutingConfig, error) {
|
||||
var routes RoutingConfig
|
||||
err := json.Unmarshal(data, &routes)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal routes")
|
||||
}
|
||||
return routes, nil
|
||||
}
|
||||
|
||||
// readHosts unmarshals JSON data into a list of host addresses.
|
||||
func readHosts(data []byte) ([]string, error) {
|
||||
addresses := make([]AddressConfiguration, 0)
|
||||
err := json.Unmarshal(data, &addresses)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "unmarshal to address")
|
||||
}
|
||||
hosts := make([]string, 0, len(addresses))
|
||||
for _, addr := range addresses {
|
||||
host := net.JoinHostPort(addr.IP, addr.Port)
|
||||
hosts = append(hosts, host)
|
||||
}
|
||||
return hosts, nil
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
const (
|
||||
RequiredAdminPermission = "reqAdminPerm"
|
||||
|
||||
GrpcTransport = "grpc"
|
||||
HttpTransport = "http"
|
||||
EmptyTransport = "empty"
|
||||
)
|
||||
|
||||
// AddressConfiguration represents the IP address and port for a service endpoint.
|
||||
type AddressConfiguration struct {
|
||||
IP string `json:"ip"`
|
||||
Port string `json:"port"`
|
||||
}
|
||||
|
||||
// ConfigData contains configuration data for a module, including version information
|
||||
// and JSON-encoded schema and configuration payloads.
|
||||
type ConfigData struct {
|
||||
Version string
|
||||
Schema json.RawMessage
|
||||
Config json.RawMessage
|
||||
}
|
||||
|
||||
// ModuleInfo describes a module's metadata, including its name, version, transport
|
||||
// configuration, exposed endpoints, and metrics autodiscovery settings.
|
||||
type ModuleInfo struct {
|
||||
ModuleName string
|
||||
ModuleVersion string
|
||||
LibVersion string
|
||||
Transport string
|
||||
GrpcOuterAddress AddressConfiguration
|
||||
Endpoints []EndpointDescriptor
|
||||
MetricsAutodiscovery *MetricsAutodiscovery
|
||||
}
|
||||
|
||||
// RoutingConfig represents a list of backend declarations for routing configuration.
|
||||
type RoutingConfig []BackendDeclaration
|
||||
|
||||
// BackendDeclaration describes a backend service, including its metadata, endpoints,
|
||||
// dependencies, and network configuration.
|
||||
type BackendDeclaration struct {
|
||||
ModuleName string
|
||||
Version string
|
||||
LibVersion string
|
||||
Transport string
|
||||
Endpoints []EndpointDescriptor
|
||||
RequiredModules []ModuleDependency
|
||||
Address AddressConfiguration
|
||||
MetricsAutodiscovery *MetricsAutodiscovery
|
||||
}
|
||||
|
||||
// EndpointDescriptor describes an HTTP endpoint, including its path, method, authentication
|
||||
// requirements, and optional metadata. The Handler field is excluded from JSON serialization.
|
||||
type EndpointDescriptor struct {
|
||||
Path string
|
||||
Inner bool
|
||||
UserAuthRequired bool
|
||||
HttpMethod string
|
||||
Extra map[string]any
|
||||
Handler any `json:"-"`
|
||||
}
|
||||
|
||||
// ModuleRequirements specifies the modules and routes that a module depends on.
|
||||
type ModuleRequirements struct {
|
||||
RequiredModules []string
|
||||
RequireRoutes bool
|
||||
}
|
||||
|
||||
// ModuleDependency represents a dependency on another module, indicating whether
|
||||
// the dependency is required for operation.
|
||||
type ModuleDependency struct {
|
||||
Name string
|
||||
Required bool
|
||||
}
|
||||
|
||||
// MetricsAutodiscovery configuration for automatic metrics endpoint discovery,
|
||||
// including the address and optional Prometheus labels.
|
||||
type MetricsAutodiscovery struct {
|
||||
Address string
|
||||
Labels map[string]string
|
||||
}
|
||||
|
||||
// RequireAdminPermission creates endpoint metadata that specifies an admin permission
|
||||
// requirement for the endpoint. The permission string is stored under the RequiredAdminPermission key.
|
||||
func RequireAdminPermission(perm string) map[string]any {
|
||||
return map[string]any{
|
||||
RequiredAdminPermission: perm,
|
||||
}
|
||||
}
|
||||
|
||||
// GetRequiredAdminPermission extracts the admin permission requirement from an
|
||||
// EndpointDescriptor. Returns the permission string and a boolean indicating whether
|
||||
// the permission requirement was found.
|
||||
func GetRequiredAdminPermission(desc EndpointDescriptor) (string, bool) {
|
||||
if len(desc.Extra) == 0 {
|
||||
return "", false
|
||||
}
|
||||
value, ok := desc.Extra[RequiredAdminPermission].(string)
|
||||
return value, ok
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RemoteConfigReceiver is an interface for receiving and processing remote configuration updates.
|
||||
type RemoteConfigReceiver interface {
|
||||
// ReceiveConfig processes the remote configuration.
|
||||
ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
}
|
||||
|
||||
// RoutesReceiver is an interface for receiving and processing routing configuration updates.
|
||||
type RoutesReceiver interface {
|
||||
// ReceiveRoutes processes the routing configuration.
|
||||
ReceiveRoutes(ctx context.Context, routes RoutingConfig) error
|
||||
}
|
||||
|
||||
// HostsUpgrader is an interface for upgrading or updating host lists.
|
||||
type HostsUpgrader interface {
|
||||
// Upgrade updates the list of hosts.
|
||||
Upgrade(hosts []string)
|
||||
}
|
||||
|
||||
const (
|
||||
defaultRemoteConfigReceiverTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
// EventHandler manages event handling for remote configuration, routes, and module dependencies.
|
||||
type EventHandler struct {
|
||||
remoteConfigReceiver RemoteConfigReceiver
|
||||
handleConfigTimeout time.Duration
|
||||
routesReceiver RoutesReceiver
|
||||
requiredModules map[string]HostsUpgrader
|
||||
}
|
||||
|
||||
// NewEventHandler creates a new EventHandler with default settings.
|
||||
func NewEventHandler() *EventHandler {
|
||||
return &EventHandler{
|
||||
requiredModules: make(map[string]HostsUpgrader),
|
||||
handleConfigTimeout: defaultRemoteConfigReceiverTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
// RemoteConfigReceiver sets the receiver for remote configuration updates and returns
|
||||
// the EventHandler for method chaining.
|
||||
func (h *EventHandler) RemoteConfigReceiver(receiver RemoteConfigReceiver) *EventHandler {
|
||||
h.remoteConfigReceiver = receiver
|
||||
return h
|
||||
}
|
||||
|
||||
// RoutesReceiver sets the receiver for routing configuration updates and returns
|
||||
// the EventHandler for method chaining.
|
||||
func (h *EventHandler) RoutesReceiver(receiver RoutesReceiver) *EventHandler {
|
||||
h.routesReceiver = receiver
|
||||
return h
|
||||
}
|
||||
|
||||
// RequireModule registers a module dependency with its corresponding hosts upgrader
|
||||
// and returns the EventHandler for method chaining.
|
||||
func (h *EventHandler) RequireModule(moduleName string, upgrader HostsUpgrader) *EventHandler {
|
||||
h.requiredModules[moduleName] = upgrader
|
||||
return h
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package cluster
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
// ErrorConnection is the event name for connection errors.
|
||||
ErrorConnection = "ERROR_CONNECTION"
|
||||
// ConfigError is the event name for configuration errors.
|
||||
ConfigError = "ERROR_CONFIG"
|
||||
|
||||
// ConfigSendConfigWhenConnected is the event for sending config when connected.
|
||||
ConfigSendConfigWhenConnected = "CONFIG:SEND_CONFIG_WHEN_CONNECTED"
|
||||
// ConfigSendConfigChanged is the event for config change notifications.
|
||||
ConfigSendConfigChanged = "CONFIG:SEND_CONFIG_CHANGED"
|
||||
|
||||
// ConfigSendRoutesWhenConnected is the event for sending routes when connected.
|
||||
ConfigSendRoutesWhenConnected = "CONFIG:SEND_ROUTES_WHEN_CONNECTED"
|
||||
// ConfigSendRoutesChanged is the event for route change notifications.
|
||||
ConfigSendRoutesChanged = "CONFIG:SEND_ROUTES_CHANGED"
|
||||
|
||||
// ModuleReady is the event sent when a module is ready.
|
||||
ModuleReady = "MODULE:READY"
|
||||
// ModuleSendRequirements is the event for sending module requirements.
|
||||
ModuleSendRequirements = "MODULE:SEND_REQUIREMENTS"
|
||||
// ModuleSendConfigSchema is the event for sending configuration schema.
|
||||
ModuleSendConfigSchema = "MODULE:SEND_CONFIG_SCHEMA"
|
||||
|
||||
// ModuleConnectionSuffix is the suffix appended to module names for connection events.
|
||||
ModuleConnectionSuffix = "MODULE_CONNECTED"
|
||||
)
|
||||
|
||||
// ModuleConnectedEvent generates the event name for a module connection event
|
||||
// by combining the module name with the ModuleConnectionSuffix.
|
||||
func ModuleConnectedEvent(moduleName string) string {
|
||||
return fmt.Sprintf("%s_%s", moduleName, ModuleConnectionSuffix)
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bellows"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
var (
|
||||
// secretFieldSubstrings contains field name substrings that indicate sensitive data.
|
||||
secretFieldSubstrings = map[string]bool{
|
||||
"password": true,
|
||||
"secret": true,
|
||||
"token": true,
|
||||
"credentials": true,
|
||||
}
|
||||
// hidingSecretsEvents contains event names that require secret masking in logs.
|
||||
hidingSecretsEvents = map[string]bool{
|
||||
ConfigSendConfigWhenConnected: true,
|
||||
ConfigSendConfigChanged: true,
|
||||
ModuleSendConfigSchema: true,
|
||||
}
|
||||
)
|
||||
|
||||
// HideSecrets masks sensitive data (passwords, secrets, tokens) in JSON configuration
|
||||
// by replacing their values with "***". Returns the masked JSON or an error.
|
||||
func HideSecrets(data []byte) ([]byte, error) {
|
||||
config := make(map[string]any)
|
||||
err := json.Unmarshal(data, &config)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal config for replacement secret")
|
||||
}
|
||||
|
||||
flattenConf := bellows.Flatten(config)
|
||||
|
||||
for key := range flattenConf {
|
||||
if flattenConf[key] == "" {
|
||||
continue
|
||||
}
|
||||
for tag := range secretFieldSubstrings {
|
||||
if strings.Contains(strings.ToLower(key), tag) {
|
||||
flattenConf[key] = "***"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expandConf := bellows.Expand(flattenConf)
|
||||
if expandConf == nil {
|
||||
expandConf = make(map[string]any)
|
||||
}
|
||||
|
||||
config, ok := expandConf.(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.WithMessagef(err, "unexpected type from bellows, expected map, got %T", config)
|
||||
}
|
||||
|
||||
data, err = json.Marshal(config)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "marshal config for replacement secret")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// RegisterSecretSubstrings adds custom field name substrings to the list of patterns
|
||||
// that indicate sensitive data.
|
||||
func RegisterSecretSubstrings(substrings []string) {
|
||||
for _, substring := range substrings {
|
||||
secretFieldSubstrings[strings.ToLower(substring)] = true
|
||||
}
|
||||
}
|
||||
|
||||
// UnregisterSecretSubstrings removes custom field name substrings from the list of
|
||||
// patterns that indicate sensitive data.
|
||||
func UnregisterSecretSubstrings(substrings []string) {
|
||||
for _, substring := range substrings {
|
||||
delete(secretFieldSubstrings, strings.ToLower(substring))
|
||||
}
|
||||
}
|
||||
|
||||
// hideSecrets masks sensitive data in logs for events that contain configuration data.
|
||||
func hideSecrets(event string, data []byte) []byte {
|
||||
if hidingSecretsEvents[event] {
|
||||
dataToLog, err := HideSecrets(data)
|
||||
if err != nil {
|
||||
return data
|
||||
}
|
||||
return dataToLog
|
||||
}
|
||||
return data
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// OfflineClient provides configuration loading from a local file instead of a remote
|
||||
// isp-config-service. It is useful for offline or testing scenarios.
|
||||
type OfflineClient struct {
|
||||
configPath string
|
||||
}
|
||||
|
||||
// NewOfflineClient creates a new OfflineClient that reads configuration from the specified path.
|
||||
func NewOfflineClient(configPath string) OfflineClient {
|
||||
return OfflineClient{
|
||||
configPath: configPath,
|
||||
}
|
||||
}
|
||||
|
||||
// Run loads the configuration from the local file and applies it using the provided
|
||||
// event handler. Returns nil if the handler is nil.
|
||||
func (d OfflineClient) Run(ctx context.Context, handler *EventHandler) error {
|
||||
if handler == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
err := d.receiveConfig(ctx, handler)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "receive config")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close releases resources associated with the offline client.
|
||||
func (d OfflineClient) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// receiveConfig reads the configuration file and applies it using the event handler.
|
||||
func (d OfflineClient) receiveConfig(ctx context.Context, handler *EventHandler) error {
|
||||
if handler.remoteConfigReceiver == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, handler.handleConfigTimeout)
|
||||
defer cancel()
|
||||
|
||||
cfg, err := os.ReadFile(d.configPath)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "read file %s", d.configPath)
|
||||
}
|
||||
|
||||
err = handler.remoteConfigReceiver.ReceiveConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "receive config")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
package cluster
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/etp/v4"
|
||||
"github.com/txix-open/etp/v4/msg"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
// EventIdContextKey is the context key used for event IDs.
|
||||
EventIdContextKey = "eventId"
|
||||
// emitWithAckTimeout is the default timeout for emit-with-ack operations.
|
||||
emitWithAckTimeout = 1 * time.Second
|
||||
)
|
||||
|
||||
// eventFuture tracks pending event responses.
|
||||
type eventFuture struct {
|
||||
responseCh chan []byte
|
||||
errorCh chan error
|
||||
}
|
||||
|
||||
// clientWrapper wraps an ETP client with additional functionality for event handling,
|
||||
// logging, and secret masking.
|
||||
type clientWrapper struct {
|
||||
cli *etp.Client
|
||||
errorConnChan chan []byte
|
||||
configErrorChan chan []byte
|
||||
ctx context.Context
|
||||
eventFutures sync.Map // map[eventName]eventFuture
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// newClientWrapper creates a new clientWrapper with the provided context, ETP client, and logger.
|
||||
func newClientWrapper(ctx context.Context, cli *etp.Client, logger log.Logger) *clientWrapper {
|
||||
w := &clientWrapper{
|
||||
cli: cli,
|
||||
ctx: ctx,
|
||||
logger: logger,
|
||||
}
|
||||
w.errorConnChan = w.eventChan(ErrorConnection)
|
||||
w.configErrorChan = w.eventChan(ConfigError)
|
||||
cli.OnUnknownEvent(etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
logger.Error(
|
||||
ctx,
|
||||
"unexpected event from config service",
|
||||
log.String("event", event.Name),
|
||||
log.ByteString("data", event.Data),
|
||||
)
|
||||
return nil
|
||||
}))
|
||||
return w
|
||||
}
|
||||
|
||||
// EmitJsonWithAck marshals data to JSON and emits an event with acknowledgment, returning
|
||||
// the response or an error.
|
||||
func (w *clientWrapper) EmitJsonWithAck(ctx context.Context, event string, data any) ([]byte, error) {
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "marshal '%s' data", event)
|
||||
}
|
||||
|
||||
resp, err := w.EmitWithAck(ctx, event, jsonData)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "emit with ask")
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// EmitWithAck sends an event and waits for an acknowledgment, logging the event and response.
|
||||
func (w *clientWrapper) EmitWithAck(ctx context.Context, event string, data []byte) ([]byte, error) {
|
||||
ctx = log.ToContext(ctx, log.String("event", event))
|
||||
w.logger.Info(
|
||||
ctx,
|
||||
"send event",
|
||||
log.ByteString("data", hideSecrets(event, data)),
|
||||
)
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, emitWithAckTimeout)
|
||||
defer cancel()
|
||||
|
||||
resp, err := w.cli.EmitWithAck(ctx, event, data)
|
||||
if err != nil {
|
||||
w.logger.Error(ctx, "error", log.Any("error", err))
|
||||
return resp, err
|
||||
}
|
||||
|
||||
w.logger.Info(ctx, "event acknowledged", log.ByteString("response", resp))
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// RegisterEvent registers a handler for a specific event. The handler will be called
|
||||
// when the event is received, and the event future is used to track the response.
|
||||
func (w *clientWrapper) RegisterEvent(event string, handler func(string, []byte) error) {
|
||||
future := eventFuture{
|
||||
errorCh: make(chan error, 1),
|
||||
responseCh: make(chan []byte, 1),
|
||||
}
|
||||
w.eventFutures.Store(event, future)
|
||||
|
||||
w.on(event, func(eventId string, data []byte) {
|
||||
err := handler(eventId, data)
|
||||
if err != nil {
|
||||
sendNonBlocking(future.errorCh, err)
|
||||
w.logger.Error(w.ctx, "handle event",
|
||||
log.String(EventIdContextKey, eventId),
|
||||
log.String("event", event),
|
||||
log.String("error", err.Error()),
|
||||
)
|
||||
return
|
||||
}
|
||||
sendNonBlocking(future.responseCh, data)
|
||||
})
|
||||
}
|
||||
|
||||
// AwaitEvent waits for a registered event to be received within the specified timeout.
|
||||
// Returns an error if the event is not registered or the timeout is exceeded.
|
||||
func (w *clientWrapper) AwaitEvent(ctx context.Context, event string, timeout time.Duration) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
futureVal, ok := w.eventFutures.Load(event)
|
||||
if !ok {
|
||||
return errors.Errorf("event %s not registered", event)
|
||||
}
|
||||
future := futureVal.(eventFuture) // nolint:forcetypeassert
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case data := <-w.errorConnChan:
|
||||
return errors.New(string(data))
|
||||
case data := <-w.configErrorChan:
|
||||
return errors.New(string(data))
|
||||
case err := <-future.errorCh:
|
||||
return err
|
||||
case <-future.responseCh:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Ping sends a ping request to verify the connection is alive.
|
||||
func (w *clientWrapper) Ping(ctx context.Context) error {
|
||||
return w.cli.Ping(ctx)
|
||||
}
|
||||
|
||||
// Close closes the underlying ETP connection.
|
||||
func (w *clientWrapper) Close() error {
|
||||
return w.cli.Close()
|
||||
}
|
||||
|
||||
// Dial establishes a WebSocket connection to the specified URL.
|
||||
func (w *clientWrapper) Dial(ctx context.Context, url string) error {
|
||||
return w.cli.Dial(ctx, url)
|
||||
}
|
||||
|
||||
// OnDisconnect registers a handler for disconnection events.
|
||||
func (w *clientWrapper) OnDisconnect(handler etp.DisconnectHandler) {
|
||||
w.cli.OnDisconnect(handler)
|
||||
}
|
||||
|
||||
// eventChan creates a channel for a specific event and registers a handler to forward
|
||||
// event data to the channel.
|
||||
func (w *clientWrapper) eventChan(event string) chan []byte {
|
||||
ch := make(chan []byte, 1)
|
||||
w.on(event, func(_ string, data []byte) {
|
||||
select {
|
||||
case <-w.ctx.Done():
|
||||
case ch <- data:
|
||||
}
|
||||
})
|
||||
return ch
|
||||
}
|
||||
|
||||
// on registers a low-level event handler that forwards events to the provided handler function.
|
||||
func (w *clientWrapper) on(event string, handler func(eventId string, data []byte)) {
|
||||
w.cli.On(event, etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
|
||||
eventId := requestid.Next()
|
||||
w.logger.Info(
|
||||
w.ctx,
|
||||
"event received",
|
||||
log.String(EventIdContextKey, eventId),
|
||||
log.String("event", event.Name),
|
||||
log.ByteString("data", hideSecrets(event.Name, event.Data)),
|
||||
)
|
||||
handler(eventId, event.Data)
|
||||
return nil
|
||||
}))
|
||||
}
|
||||
|
||||
// sendNonBlocking attempts to send data on a channel without blocking.
|
||||
func sendNonBlocking[T any](ch chan T, data T) {
|
||||
select {
|
||||
case ch <- data:
|
||||
default:
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user