MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 txix-open
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# Package `app`
|
||||
|
||||
Пакет `app` предназначен для создания приложений с простым и гибким управлением жизненным циклом.
|
||||
|
||||
## Types
|
||||
|
||||
### Application
|
||||
|
||||
Структура `Application` представляет собой абстракцию, которая содержит в себе основные необходимые компоненты
|
||||
приложения (logger, config, context), а также позволяет простым и гибким способом управлять жизненным циклом компонент
|
||||
приложения реализующих интерфейсы `Runner` и `Closer`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(a *Application) Context() context.Context`
|
||||
|
||||
Получить контекст приложения.
|
||||
|
||||
#### `(a *Application) Config() *config.Config`
|
||||
|
||||
Получить конфигурацию приложения.
|
||||
|
||||
#### `(a *Application) Logger() *log.Adapter`
|
||||
|
||||
Получить логгер.
|
||||
|
||||
#### `(a *Application) AddRunners(runners ...Runner)`
|
||||
|
||||
Добавить компоненты приложения, реализующих интерфейс `Runner`.
|
||||
|
||||
#### `(a *Application) AddClosers(closers ...Closer)`
|
||||
|
||||
Добавить компоненты приложения, реализующих интерфейс `Closer`.
|
||||
|
||||
#### `(a *Application) Run() error`
|
||||
|
||||
Вызывает у каждой `Runner` компоненты приложения метод `Run`. Блокирующая операция. Если хотя бы одна компонента при
|
||||
запуске вернула ошибку, то метод `Run` завершается с ошибкой.
|
||||
|
||||
#### `(a *Application) Close()`
|
||||
|
||||
Вызывает у каждой `Closer` компоненты приложения метод `Close`.
|
||||
|
||||
#### `(a *Application) Shutdown()`
|
||||
|
||||
То же самое, что и метод `Close`, но в конце дополнительно завершает контекст.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
func noopRunnerFn(_ context.Context) error { return nil }
|
||||
|
||||
func noopCloserFn() error { return nil }
|
||||
|
||||
type noopRunner struct{}
|
||||
|
||||
func (r noopRunner) Run(_ context.Context) error { return nil }
|
||||
|
||||
type noopCloser struct{}
|
||||
|
||||
func (c noopCloser) Close() error { return nil }
|
||||
|
||||
func main() {
|
||||
application, err := app.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
application.AddRunners(app.RunnerFunc(noopRunnerFn), noopRunner{})
|
||||
application.AddClosers(app.CloserFunc(noopCloserFn), noopCloser{})
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Construct `Application` instance with options
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
func main() {
|
||||
application, err := app.New(
|
||||
app.WithConfigOptions(
|
||||
config.WithValidator(validator.Default),
|
||||
/* pass the config options you want */
|
||||
),
|
||||
app.WithLoggerConfigSupplier(func(cfg *config.Config) log2.Config {
|
||||
var loggerCfg log2.Config
|
||||
/* form the logger config the way you want */
|
||||
return loggerCfg
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
...
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Construct `Application` instance with config
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
func main() {
|
||||
config := app.Config{
|
||||
ConfigOptions: []config.Option{
|
||||
config.WithValidator(validator.Default),
|
||||
/* pass the config options you want */
|
||||
},
|
||||
}
|
||||
application, err := app.NewFromConfig(config)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
...
|
||||
}
|
||||
|
||||
```
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
// Package app provides a lightweight application lifecycle management framework.
|
||||
//
|
||||
// The Application struct orchestrates the startup and shutdown of multiple
|
||||
// Runner components, handling graceful lifecycle transitions and resource cleanup.
|
||||
//
|
||||
// # Usage
|
||||
//
|
||||
// Create a new application with optional configuration:
|
||||
//
|
||||
// app, err := app.New(
|
||||
// app.WithConfigOptions(config.WithExtraSource(config.NewYamlConfig("config.yaml"))),
|
||||
// app.WithLoggerConfigSupplier(func(cfg *config.Config) log.Config {
|
||||
// return *log.DefaultConfig()
|
||||
// }),
|
||||
// )
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
//
|
||||
// Add runners and closers:
|
||||
//
|
||||
// app.AddRunners(myRunner)
|
||||
// app.AddClosers(myCloser)
|
||||
//
|
||||
// Start the application:
|
||||
//
|
||||
// if err := app.Run(); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
//
|
||||
// Shutdown when needed:
|
||||
//
|
||||
// app.Shutdown()
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// Application manages the lifecycle of long-running services.
|
||||
// It coordinates the startup and graceful shutdown of multiple Runner components,
|
||||
// providing context propagation and resource cleanup through Closers.
|
||||
//
|
||||
// Application is not safe for concurrent modification. All AddRunners and AddClosers
|
||||
// calls should be made before calling Run.
|
||||
type Application struct {
|
||||
ctx context.Context
|
||||
cfg *config.Config
|
||||
logger *log.Adapter
|
||||
|
||||
cancel context.CancelFunc
|
||||
runners []Runner
|
||||
closers []Closer
|
||||
}
|
||||
|
||||
// New creates a new Application instance with the provided options.
|
||||
// It applies the options to a DefaultConfig and then creates
|
||||
// the application from the resulting configuration.
|
||||
//
|
||||
// Returns an error if the configuration or logger cannot be initialized.
|
||||
func New(opts ...Option) (*Application, error) {
|
||||
appConfig := DefaultConfig()
|
||||
for _, opt := range opts {
|
||||
opt(appConfig)
|
||||
}
|
||||
return NewFromConfig(*appConfig)
|
||||
}
|
||||
|
||||
// NewFromConfig creates a new Application from the provided configuration.
|
||||
// It initializes the configuration, logger, and context, setting up the
|
||||
// application with a default closer that syncs the logger on shutdown.
|
||||
//
|
||||
// Returns an error if the configuration or logger cannot be initialized.
|
||||
func NewFromConfig(appConfig Config) (*Application, error) {
|
||||
cfg, err := config.New(appConfig.ConfigOptions...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create config")
|
||||
}
|
||||
|
||||
loggerConfig := appConfig.LoggerConfigSupplier(cfg)
|
||||
logger, err := log.NewFromConfig(loggerConfig)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create logger")
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
return &Application{
|
||||
ctx: ctx,
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
closers: []Closer{CloserFunc(func() error {
|
||||
_ = logger.Sync()
|
||||
return nil
|
||||
})},
|
||||
cancel: cancel,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Context returns the application's context.
|
||||
// The context is cancelled when Shutdown is called.
|
||||
func (a *Application) Context() context.Context {
|
||||
return a.ctx
|
||||
}
|
||||
|
||||
// Config returns the application's configuration.
|
||||
func (a *Application) Config() *config.Config {
|
||||
return a.cfg
|
||||
}
|
||||
|
||||
// Logger returns the application's logger.
|
||||
func (a *Application) Logger() *log.Adapter {
|
||||
return a.logger
|
||||
}
|
||||
|
||||
// AddRunners appends the provided runners to the application.
|
||||
// Runners are started as goroutines when Run is called.
|
||||
//
|
||||
// AddRunners should be called before Run to ensure proper initialization.
|
||||
func (a *Application) AddRunners(runners ...Runner) {
|
||||
a.runners = append(a.runners, runners...)
|
||||
}
|
||||
|
||||
// AddClosers appends the provided closers to the application.
|
||||
// Closers are invoked during shutdown to release resources.
|
||||
//
|
||||
// AddClosers should be called before Run to ensure proper cleanup.
|
||||
func (a *Application) AddClosers(closers ...Closer) {
|
||||
a.closers = append(a.closers, closers...)
|
||||
}
|
||||
|
||||
// Run starts all registered runners and blocks until one of them returns an error
|
||||
// or the application context is cancelled.
|
||||
//
|
||||
// Each runner executes in its own goroutine. If any runner fails, Run returns
|
||||
// the first error encountered. If the context is cancelled via Shutdown,
|
||||
// Run returns nil.
|
||||
//
|
||||
// Run is safe to call only once per Application instance.
|
||||
func (a *Application) Run() error {
|
||||
errChan := make(chan error)
|
||||
|
||||
for i := range a.runners {
|
||||
go func(index int, runner Runner) {
|
||||
err := runner.Run(a.ctx)
|
||||
if err != nil {
|
||||
select {
|
||||
case errChan <- errors.WithMessagef(err, "start runner[%d] -> %T", index, runner):
|
||||
default:
|
||||
a.logger.Error(a.ctx, errors.WithMessagef(err, "start runner[%d] -> %T", index, runner))
|
||||
}
|
||||
}
|
||||
}(i, a.runners[i])
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-errChan:
|
||||
return err
|
||||
case <-a.ctx.Done():
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown initiates graceful shutdown by closing all resources and cancelling
|
||||
// the application context.
|
||||
//
|
||||
// Shutdown should be called to terminate running services and release resources.
|
||||
func (a *Application) Shutdown() {
|
||||
a.Close()
|
||||
a.cancel()
|
||||
}
|
||||
|
||||
// Close invokes all registered closers to release resources.
|
||||
// Errors from individual closers are logged but do not halt the shutdown process.
|
||||
func (a *Application) Close() {
|
||||
for i := range a.closers {
|
||||
closer := a.closers[i]
|
||||
err := closer.Close()
|
||||
if err != nil {
|
||||
a.logger.Error(a.ctx, errors.WithMessagef(err, "closers[%d] -> %T", i, closer))
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package app
|
||||
|
||||
// Closer represents a resource that needs to be cleaned up.
|
||||
// Implementations should release resources and return an error if cleanup fails.
|
||||
type Closer interface {
|
||||
Close() error
|
||||
}
|
||||
|
||||
// CloserFunc is a function adapter that implements the Closer interface.
|
||||
// It allows using simple functions as closers without defining a new type.
|
||||
//
|
||||
// Example usage:
|
||||
//
|
||||
// closer := app.CloserFunc(func() error {
|
||||
// // close database connection
|
||||
// return nil
|
||||
// })
|
||||
type CloserFunc func() error
|
||||
|
||||
// Close executes the underlying function to release resources.
|
||||
func (c CloserFunc) Close() error {
|
||||
return c()
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// LoggerConfigSupplier is a function that generates a logger configuration
|
||||
// based on the application configuration.
|
||||
type LoggerConfigSupplier func(cfg *config.Config) log.Config
|
||||
|
||||
// Option is a function that configures an Application configuration.
|
||||
// Options follow the functional options pattern for flexible configuration.
|
||||
type Option func(c *Config)
|
||||
|
||||
// Config holds the configuration for creating an Application.
|
||||
type Config struct {
|
||||
// LoggerConfigSupplier generates the logger configuration from app config.
|
||||
LoggerConfigSupplier LoggerConfigSupplier
|
||||
// ConfigOptions are passed to the underlying configuration system.
|
||||
ConfigOptions []config.Option
|
||||
}
|
||||
|
||||
// DefaultConfig returns a new Config with sensible defaults.
|
||||
// The default logger configuration supplier returns a standard log.Config.
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
LoggerConfigSupplier: func(cfg *config.Config) log.Config {
|
||||
return *log.DefaultConfig()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// WithConfigOptions creates an Option that appends configuration options
|
||||
// to the Application's config.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// app, err := app.New(
|
||||
// app.WithConfigOptions(
|
||||
// config.WithExtraSource(config.NewYamlConfig("config.yaml")),
|
||||
// config.WithEnvPrefix("APP"),
|
||||
// ),
|
||||
// )
|
||||
func WithConfigOptions(opts ...config.Option) Option {
|
||||
return func(c *Config) {
|
||||
c.ConfigOptions = append(c.ConfigOptions, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithLoggerConfigSupplier creates an Option that sets the logger configuration
|
||||
// supplier function.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// app, err := app.New(
|
||||
// app.WithLoggerConfigSupplier(func(cfg *config.Config) log.Config {
|
||||
// logCfg := *log.DefaultConfig()
|
||||
// logCfg.Level = log.DebugLevel
|
||||
// return logCfg
|
||||
// }),
|
||||
// )
|
||||
func WithLoggerConfigSupplier(supplier LoggerConfigSupplier) Option {
|
||||
return func(c *Config) {
|
||||
c.LoggerConfigSupplier = supplier
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Runner represents a long-running service or task.
|
||||
// Implementations should block while running and return an error on failure.
|
||||
// The context is cancelled when the application shuts down.
|
||||
type Runner interface {
|
||||
Run(ctx context.Context) error
|
||||
}
|
||||
|
||||
// RunnerFunc is a function adapter that implements the Runner interface.
|
||||
// It allows using simple functions as runners without defining a new type.
|
||||
//
|
||||
// Example usage:
|
||||
//
|
||||
// run := app.RunnerFunc(func(ctx context.Context) error {
|
||||
// for {
|
||||
// select {
|
||||
// case <-ctx.Done():
|
||||
// return nil
|
||||
// // process work
|
||||
// }
|
||||
// }
|
||||
// })
|
||||
type RunnerFunc func(ctx context.Context) error
|
||||
|
||||
// Run executes the underlying function with the provided context.
|
||||
func (r RunnerFunc) Run(ctx context.Context) error {
|
||||
return r(ctx)
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
# Package `bgjobx`
|
||||
|
||||
Пакет `bgjobx` предоставляет инструменты для работы с фоновыми задачами. Основные компоненты: клиент для работы с
|
||||
задачами, конфигурация воркеров, сбор метрик и логирование.
|
||||
|
||||
Данный пакет использует PostgreSQL для организации очередей задач. Для работы клиента необходимо применить к БД [sql-файл](./migration/20220705201051_bgjob.sql).
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Клиент для взаимодействия с фоновыми задачами. Воркер обнаруживает новую задачу и вызывает функцию-обработчик. При
|
||||
успехе – задание помечается выполненным. При ошибке – ретраи с экспоненциальной задержкой. После исчерпания попыток –
|
||||
перемещение в DLQ.
|
||||
|
||||
**Методы:**
|
||||
|
||||
#### `NewClient(db DBProvider, logger log.Logger) *Client`
|
||||
|
||||
Конструктор клиента
|
||||
|
||||
#### `Upgrade(ctx context.Context, workerConfigs []WorkerConfig) error`
|
||||
|
||||
Обновить конфигурацию воркеров. Остановить старые воркеры и запустить новые согласно переданным конфигурациям
|
||||
|
||||
#### `Enqueue(ctx context.Context, req bgjob.EnqueueRequest) error`
|
||||
|
||||
Добавить задачу в очередь
|
||||
|
||||
#### `BulkEnqueue(ctx context.Context, list []bgjob.EnqueueRequest) error`
|
||||
|
||||
Добавить список задач в очередь
|
||||
|
||||
#### `Close()`
|
||||
|
||||
Остановить все воркеры
|
||||
|
||||
### WorkerConfig
|
||||
|
||||
Конфигурация обработчика задач
|
||||
|
||||
**Поля:**
|
||||
|
||||
- `Queue` - имя очереди
|
||||
- `Concurrency` - количество параллельных обработчиков
|
||||
- `PollInterval` - интервал опроса очереди
|
||||
- `Handle` - функция-обработчик задачи
|
||||
|
||||
## Метрики
|
||||
|
||||
- Время выполнения задачи
|
||||
- Количество успешных выполнений
|
||||
- Количество ретраев
|
||||
- Количество перемещений в DLQ
|
||||
- Количество ошибок воркеров
|
||||
|
||||
## Стандартный обработчик
|
||||
|
||||
#### `NewDefaultHandler(adapter handler.SyncHandlerAdapter, metricStorage handler.MetricStorage) handler.Sync`
|
||||
|
||||
Используется для добавления стандартных middleware в функцию-обработчик каждого воркера при создании воркеров.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
)
|
||||
|
||||
func main() {
|
||||
application, err := app.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
db := dbrx.New(application.Logger())
|
||||
err = db.Upgrade(application.Context(), dbx.Config{
|
||||
Host: "127.0.0.1",
|
||||
Port: 5432,
|
||||
Database: "test",
|
||||
Username: "test",
|
||||
Password: "test",
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli := bgjobx.NewClient(db, application.Logger())
|
||||
worker := bgjobx.WorkerConfig{
|
||||
Queue: "test",
|
||||
Concurrency: 5,
|
||||
PollInterval: 1 * time.Second,
|
||||
Handle: handler.SyncHandlerAdapterFunc(func(ctx context.Context, job bgjob.Job) handler.Result {
|
||||
/* do some work */
|
||||
return handler.Complete()
|
||||
}),
|
||||
}
|
||||
err = cli.Upgrade(application.Context(), []bgjobx.WorkerConfig{worker})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
/* enqueue task */
|
||||
err = cli.Enqueue(application.Context(), bgjob.EnqueueRequest{
|
||||
Queue: "test",
|
||||
Type: "some-type",
|
||||
Arg: []byte(`{"hello": "world"}`),
|
||||
})
|
||||
}
|
||||
|
||||
```
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package bgjobx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/bgjob_metrics"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
// DBProvider defines an interface for obtaining a database client.
|
||||
type DBProvider interface {
|
||||
DB() (*dbx.Client, error)
|
||||
}
|
||||
|
||||
// Client manages background job workers and provides functionality for
|
||||
// enqueuing and processing jobs. It handles worker lifecycle, including
|
||||
// startup, graceful shutdown, and configuration updates.
|
||||
//
|
||||
// The Client is safe for concurrent use by multiple goroutines.
|
||||
type Client struct {
|
||||
db DBProvider
|
||||
logger log.Logger
|
||||
lock sync.Locker
|
||||
workers []*bgjob.Worker
|
||||
}
|
||||
|
||||
// NewClient creates a new Client instance with the provided database provider
|
||||
// and logger. The client is ready to be configured with workers via Upgrade.
|
||||
func NewClient(db DBProvider, logger log.Logger) *Client {
|
||||
return &Client{
|
||||
db: db,
|
||||
logger: logger,
|
||||
lock: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade configures and starts workers based on the provided worker configurations.
|
||||
// It gracefully stops any previously running workers before starting the new ones.
|
||||
// Each worker polls its designated queue for jobs and processes them using the
|
||||
// configured handler.
|
||||
//
|
||||
// Returns an error if the database connection cannot be established or if the
|
||||
// job store cannot be created.
|
||||
func (c *Client) Upgrade(ctx context.Context, workerConfigs []WorkerConfig) error {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.shutdownAllWorkers()
|
||||
|
||||
db, err := c.db.DB()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get db")
|
||||
}
|
||||
store, err := bgjob.NewPgStoreV2(ctx, db.DB.DB)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "create bgjob store")
|
||||
}
|
||||
cli := bgjob.NewClient(store)
|
||||
|
||||
workers := make([]*bgjob.Worker, 0)
|
||||
metricStorage := bgjob_metrics.NewStorage(metrics.DefaultRegistry)
|
||||
for _, config := range workerConfigs {
|
||||
worker := bgjob.NewWorker(
|
||||
cli,
|
||||
config.Queue,
|
||||
NewDefaultHandler(config.Handle, metricStorage),
|
||||
bgjob.WithConcurrency(config.GetConcurrency()),
|
||||
bgjob.WithPollInterval(config.GetPollInterval()),
|
||||
bgjob.WithObserver(Observer{log: c.logger, metricStorage: metricStorage}),
|
||||
)
|
||||
workers = append(workers, worker)
|
||||
}
|
||||
c.workers = workers
|
||||
|
||||
for _, worker := range c.workers {
|
||||
worker.Run(ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Enqueue adds a single job to the background job queue.
|
||||
// If the request does not contain a RequestId, it attempts to extract one from
|
||||
// the context, or generates a new one if none is present.
|
||||
//
|
||||
// Returns an error if the database connection cannot be established.
|
||||
func (c *Client) Enqueue(ctx context.Context, req bgjob.EnqueueRequest) error {
|
||||
db, err := c.db.DB()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get db")
|
||||
}
|
||||
|
||||
requestId := req.RequestId
|
||||
|
||||
if requestId == "" {
|
||||
requestId = requestid.FromContext(ctx)
|
||||
}
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
req.RequestId = requestId
|
||||
|
||||
return bgjob.Enqueue(ctx, db, req)
|
||||
}
|
||||
|
||||
// BulkEnqueue adds multiple jobs to the background job queue in a single operation.
|
||||
// If any request in the list does not contain a RequestId, it inherits the main
|
||||
// RequestId from the context (or generates one if not present).
|
||||
//
|
||||
// Returns an error if the database connection cannot be established.
|
||||
func (c *Client) BulkEnqueue(ctx context.Context, list []bgjob.EnqueueRequest) error {
|
||||
db, err := c.db.DB()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get db")
|
||||
}
|
||||
|
||||
mainRequestId := requestid.FromContext(ctx)
|
||||
if mainRequestId == "" {
|
||||
mainRequestId = requestid.Next()
|
||||
}
|
||||
|
||||
for i := range list {
|
||||
if list[i].RequestId == "" {
|
||||
list[i].RequestId = mainRequestId
|
||||
}
|
||||
}
|
||||
return bgjob.BulkEnqueue(ctx, db, list)
|
||||
}
|
||||
|
||||
// Close gracefully shuts down all running workers.
|
||||
// This method should be called when the application is stopping to ensure
|
||||
// in-flight jobs are properly handled.
|
||||
func (c *Client) Close() {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.shutdownAllWorkers()
|
||||
}
|
||||
|
||||
// shutdownAllWorkers stops all registered workers by calling their Shutdown method.
|
||||
// This method assumes the caller holds the lock.
|
||||
func (c *Client) shutdownAllWorkers() {
|
||||
for _, worker := range c.workers {
|
||||
worker.Shutdown()
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package bgjobx
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
)
|
||||
|
||||
// WorkerConfig defines the configuration for a background job worker.
|
||||
// It specifies the queue to poll, concurrency level, polling interval,
|
||||
// and the handler that processes jobs.
|
||||
type WorkerConfig struct {
|
||||
Queue string
|
||||
Concurrency int
|
||||
PollInterval time.Duration
|
||||
Handle handler.SyncHandlerAdapter
|
||||
}
|
||||
|
||||
// GetConcurrency returns the configured concurrency level.
|
||||
// If Concurrency is not set or is less than or equal to zero, it returns 1.
|
||||
func (c WorkerConfig) GetConcurrency() int {
|
||||
if c.Concurrency <= 0 {
|
||||
return 1
|
||||
}
|
||||
return c.Concurrency
|
||||
}
|
||||
|
||||
// GetPollInterval returns the configured polling interval.
|
||||
// If PollInterval is not set or is less than or equal to zero, it returns 1 second.
|
||||
func (c WorkerConfig) GetPollInterval() time.Duration {
|
||||
if c.PollInterval <= 0 {
|
||||
return 1 * time.Second
|
||||
}
|
||||
return c.PollInterval
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package bgjobx
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
)
|
||||
|
||||
// NewDefaultHandler creates a handler with standard middleware applied.
|
||||
// It wraps the provided adapter with metrics collection, panic recovery,
|
||||
// and request ID propagation middleware.
|
||||
//
|
||||
// The middleware stack is applied in the following order:
|
||||
// 1. RequestId - propagates request IDs to the context
|
||||
// 2. Recovery - catches panics and moves jobs to DLQ
|
||||
// 3. Metrics - records execution duration and job outcomes
|
||||
//
|
||||
// Returns a Sync handler ready to be used with workers.
|
||||
func NewDefaultHandler(adapter handler.SyncHandlerAdapter, metricStorage handler.MetricStorage) handler.Sync {
|
||||
return handler.NewSync(
|
||||
adapter,
|
||||
handler.Metrics(metricStorage),
|
||||
handler.Recovery(),
|
||||
handler.RequestId(),
|
||||
)
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
# Package `handler`
|
||||
|
||||
Пакет `handler` предоставляет инструменты для обработки результатов выполнения bgjob с использованием middleware.
|
||||
|
||||
## Types
|
||||
|
||||
### Sync
|
||||
|
||||
Структура `Sync` реализует обработчик фоновых задач с поддержкой middleware.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewSync(adapter SyncHandlerAdapter, middlewares ...Middleware) Sync`
|
||||
|
||||
Конструктор синхронного обработчика, принимающий на вход адаптер бизнес-логики, который должен реализовывать интерфейс
|
||||
`SyncHandlerAdapter`
|
||||
или быть преобразованным к `SyncHandlerAdapterFunc`, если это функция-обработчик.
|
||||
|
||||
Стандартные Middleware:
|
||||
|
||||
- `Metrics(storage MetricStorage) Middleware` – middleware для сбора метрик, регистрирующая время
|
||||
обработки. Принимает на вход хранилище метрик, реализующее интерфейс `MetricStorage`.
|
||||
- `Recovery() Middleware` – предотвращает падение сервиса при панике в обработчике, преобразуя ее в ошибку.
|
||||
- `RequestId() Middleware` – обеспечивает трассировку, берёт `requestId` из `job.RequestId`.
|
||||
#### `(r Sync) Handle(ctx context.Context, job bgjob.Job) bgjob.Result`
|
||||
|
||||
Выполняет обработку сообщения.
|
||||
|
||||
### Mux
|
||||
|
||||
Структура `Mux` реализует мультиплексор фоновых задач.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMux() *Mux`
|
||||
|
||||
Конструктор мультиплексора.
|
||||
|
||||
#### `(m *Mux) Register(jobType string, handler SyncHandlerAdapter) *Mux`
|
||||
|
||||
Выполняет регистрацию обработчика задачи по ее типу в мультиплексоре.
|
||||
|
||||
#### `(m *Mux) Handle(ctx context.Context, job bgjob.Job) Result`
|
||||
|
||||
Выполняет вызов обработчика задачи в зависимости от типа задачи. Если обработчик не зарегистрирован, отправляет задачу в DLQ с ошибкой `bgjob.ErrUnknownType`.
|
||||
|
||||
## Functions
|
||||
|
||||
### Reschedule(by RescheduleBy, opts ...RescheduleOption) Result
|
||||
|
||||
Отдает результат перепланировки задачи:
|
||||
|
||||
**Методы перепланировки задач:**
|
||||
|
||||
#### ByAfterTime(after time.Duration, currentTime time.Time) AfterTime
|
||||
|
||||
Перепланировка задачи на дату спустя указанное время.
|
||||
|
||||
#### ByCron(cronExpression string, currentTime time.Time) Cron
|
||||
|
||||
Перепланировка задачи по cron-выражению.
|
||||
|
||||
**Опции перепланирования:**
|
||||
|
||||
#### WithArg(arg []byte) RescheduleOption
|
||||
|
||||
Опция для указания аргумента при перепланировании.
|
||||
|
||||
## Usage
|
||||
|
||||
### Custom handler
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
)
|
||||
|
||||
type customHandler struct{}
|
||||
|
||||
func (h customHandler) Handle(ctx context.Context, job bgjob.Job) handler.Result {
|
||||
/* put here business logic */
|
||||
return handler.Reschedule(handler.ByAfterTime(10*time.Minutes, time.Now()))
|
||||
}
|
||||
|
||||
func main() {
|
||||
var (
|
||||
metricStorage = NewMetricStorage() /* MetricStorage interface implementation */
|
||||
adapter customHandler
|
||||
)
|
||||
|
||||
syncHandler := handler.NewSync(adapter, []handler.Middleware{
|
||||
handler.Metrics(metricStorage),
|
||||
handler.Recovery(),
|
||||
handler.RequestId(),
|
||||
}...)
|
||||
|
||||
/* handler's call for example */
|
||||
job := new(bgjob.Job) /* placeholder for example */
|
||||
syncHandler.Handle(context.Background(), job)
|
||||
}
|
||||
|
||||
```
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/panic_recovery"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
// MetricStorage defines the interface for recording job execution metrics.
|
||||
// Implementations should track job performance and outcome statistics.
|
||||
type MetricStorage interface {
|
||||
// ObserveExecuteDuration records the time taken to execute a job.
|
||||
ObserveExecuteDuration(queue string, jobType string, t time.Duration)
|
||||
// IncRetryCount increments the retry counter for a job type.
|
||||
IncRetryCount(queue string, jobType string)
|
||||
// IncDlqCount increments the dead letter queue counter for a job type.
|
||||
IncDlqCount(queue string, jobType string)
|
||||
// IncSuccessCount increments the success counter for a job type.
|
||||
IncSuccessCount(queue string, jobType string)
|
||||
// IncInternalErrorCount increments the internal worker error counter.
|
||||
IncInternalErrorCount()
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that records execution metrics.
|
||||
// It measures the duration of job execution and reports success, retry,
|
||||
// and DLQ events to the provided MetricStorage.
|
||||
func Metrics(storage MetricStorage) Middleware {
|
||||
return func(next SyncHandlerAdapter) SyncHandlerAdapter {
|
||||
return SyncHandlerAdapterFunc(func(ctx context.Context, job bgjob.Job) Result {
|
||||
start := time.Now()
|
||||
result := next.Handle(ctx, job)
|
||||
storage.ObserveExecuteDuration(job.Queue, job.Type, time.Since(start))
|
||||
return result
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Recovery creates a middleware that catches panics during job execution.
|
||||
// When a panic occurs, the job is moved to the dead letter queue with
|
||||
// the panic error. This prevents worker crashes from unhandled panics.
|
||||
func Recovery() Middleware {
|
||||
return func(next SyncHandlerAdapter) SyncHandlerAdapter {
|
||||
return SyncHandlerAdapterFunc(func(ctx context.Context, job bgjob.Job) (res Result) {
|
||||
defer panic_recovery.Recover(func(err error) {
|
||||
res.MoveToDlq = true
|
||||
res.Err = err
|
||||
})
|
||||
return next.Handle(ctx, job)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// RequestId creates a middleware that ensures request IDs are available
|
||||
// in the handler context. If the job does not have a RequestId, it
|
||||
// generates a new one. The request ID is added to the context for
|
||||
// downstream logging and tracing.
|
||||
func RequestId() Middleware {
|
||||
return func(next SyncHandlerAdapter) SyncHandlerAdapter {
|
||||
return SyncHandlerAdapterFunc(func(ctx context.Context, job bgjob.Job) Result {
|
||||
requestId := job.RequestId
|
||||
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
job.RequestId = requestId
|
||||
}
|
||||
|
||||
ctx = requestid.ToContext(ctx, requestId)
|
||||
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
|
||||
|
||||
return next.Handle(ctx, job)
|
||||
})
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/robfig/cron/v3"
|
||||
)
|
||||
|
||||
// Result defines the outcome of job processing.
|
||||
// One of the boolean flags (Complete, Retry, MoveToDlq, Reschedule, RescheduleWithArg)
|
||||
// should be set to indicate the desired action.
|
||||
type Result struct {
|
||||
// Complete indicates the job was successfully processed.
|
||||
Complete bool
|
||||
// Err contains the error that occurred during processing.
|
||||
Err error
|
||||
// MoveToDlq indicates the job should be moved to the dead letter queue.
|
||||
MoveToDlq bool
|
||||
// Retry indicates the job should be retried.
|
||||
Retry bool
|
||||
// RetryDelay specifies the delay before retrying the job.
|
||||
RetryDelay time.Duration
|
||||
|
||||
// Reschedule indicates the job should be rescheduled.
|
||||
Reschedule bool
|
||||
// RescheduleDelay specifies when to reschedule the job.
|
||||
RescheduleDelay time.Duration
|
||||
// RescheduleWithArg indicates the job should be rescheduled with a new argument.
|
||||
RescheduleWithArg bool
|
||||
// Arg contains the new payload for rescheduled jobs.
|
||||
Arg []byte
|
||||
}
|
||||
|
||||
// RescheduleBy is an interface for types that can calculate a rescheduling delay.
|
||||
type RescheduleBy interface {
|
||||
Reschedule() (time.Duration, error)
|
||||
}
|
||||
|
||||
// Complete returns a Result indicating successful job completion.
|
||||
func Complete() Result {
|
||||
return Result{Complete: true}
|
||||
}
|
||||
|
||||
// Retry returns a Result indicating the job should be retried after the specified delay.
|
||||
func Retry(after time.Duration, err error) Result {
|
||||
return Result{Retry: true, RetryDelay: after, Err: err}
|
||||
}
|
||||
|
||||
// MoveToDlq returns a Result indicating the job should be moved to the dead letter queue.
|
||||
func MoveToDlq(err error) Result {
|
||||
return Result{MoveToDlq: true, Err: err}
|
||||
}
|
||||
|
||||
// Cron implements RescheduleBy using a cron expression to calculate the next run time.
|
||||
type Cron struct {
|
||||
cronExpression string
|
||||
currentTime time.Time
|
||||
}
|
||||
|
||||
// ByCron creates a Cron reschedule option using a cron expression and current time.
|
||||
func ByCron(cronExpression string, currentTime time.Time) Cron {
|
||||
return Cron{
|
||||
cronExpression: cronExpression,
|
||||
currentTime: currentTime,
|
||||
}
|
||||
}
|
||||
|
||||
// Reschedule calculates the duration until the next scheduled time based on the cron expression.
|
||||
func (b Cron) Reschedule() (time.Duration, error) {
|
||||
return rescheduleByCron(b.cronExpression, b.currentTime)
|
||||
}
|
||||
|
||||
// rescheduleByCron parses the cron expression and returns the duration until the next run.
|
||||
func rescheduleByCron(cronExpression string, currentTime time.Time) (time.Duration, error) {
|
||||
schedule, err := cron.ParseStandard(cronExpression)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
nextRunAt := schedule.Next(currentTime)
|
||||
return nextRunAt.Sub(currentTime), nil
|
||||
}
|
||||
|
||||
// AfterTime implements RescheduleBy for rescheduling after a fixed duration.
|
||||
type AfterTime struct {
|
||||
after time.Duration
|
||||
currentTime time.Time
|
||||
}
|
||||
|
||||
// ByAfterTime creates an AfterTime reschedule option.
|
||||
func ByAfterTime(after time.Duration, currentTime time.Time) AfterTime {
|
||||
return AfterTime{
|
||||
after: after,
|
||||
currentTime: currentTime,
|
||||
}
|
||||
}
|
||||
|
||||
// Reschedule returns the fixed duration for rescheduling.
|
||||
func (b AfterTime) Reschedule() (time.Duration, error) {
|
||||
return b.after, nil
|
||||
}
|
||||
|
||||
// RescheduleOption is a function type for configuring reschedule options.
|
||||
type RescheduleOption func(opt *rescheduleOptions)
|
||||
|
||||
type rescheduleOptions struct {
|
||||
Arg []byte
|
||||
RescheduleWithArg bool
|
||||
}
|
||||
|
||||
// WithArg configures a reschedule to include a new payload.
|
||||
func WithArg(arg []byte) RescheduleOption {
|
||||
return func(opt *rescheduleOptions) {
|
||||
if len(arg) > 0 {
|
||||
opt.Arg = arg
|
||||
opt.RescheduleWithArg = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reschedule creates a Result for rescheduling a job at a future time.
|
||||
// It uses the provided RescheduleBy implementation to calculate the delay.
|
||||
// Optional RescheduleOption functions can be used to include a new payload.
|
||||
// If the reschedule calculation fails, the job is moved to the DLQ.
|
||||
func Reschedule(by RescheduleBy, opts ...RescheduleOption) Result {
|
||||
options := &rescheduleOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
|
||||
rescheduleDelay, err := by.Reschedule()
|
||||
if err != nil {
|
||||
return MoveToDlq(errors.WithMessage(err, "failed to reschedule"))
|
||||
}
|
||||
|
||||
return Result{
|
||||
Reschedule: !options.RescheduleWithArg,
|
||||
RescheduleWithArg: options.RescheduleWithArg,
|
||||
Arg: options.Arg,
|
||||
RescheduleDelay: rescheduleDelay,
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/bgjob"
|
||||
)
|
||||
|
||||
// SyncHandlerAdapter defines the interface for synchronous job handlers.
|
||||
// Implementations must process a job and return a Result indicating the
|
||||
// desired action (complete, retry, reschedule, or move to DLQ).
|
||||
type SyncHandlerAdapter interface {
|
||||
Handle(ctx context.Context, job bgjob.Job) Result
|
||||
}
|
||||
|
||||
// Middleware is a function that wraps a SyncHandlerAdapter with additional
|
||||
// functionality. Middleware components can log, measure metrics, recover from
|
||||
// panics, or modify the context before/after calling the next handler.
|
||||
type Middleware func(next SyncHandlerAdapter) SyncHandlerAdapter
|
||||
|
||||
// SyncHandlerAdapterFunc is an adapter type that allows regular functions
|
||||
// to be used as SyncHandlerAdapter implementations.
|
||||
type SyncHandlerAdapterFunc func(ctx context.Context, job bgjob.Job) Result
|
||||
|
||||
// Handle calls the underlying function.
|
||||
func (a SyncHandlerAdapterFunc) Handle(ctx context.Context, job bgjob.Job) Result {
|
||||
return a(ctx, job)
|
||||
}
|
||||
|
||||
// Sync wraps a SyncHandlerAdapter with a chain of Middleware functions.
|
||||
// It ensures that middleware is applied in the correct order (last to first).
|
||||
type Sync struct {
|
||||
handler SyncHandlerAdapter
|
||||
}
|
||||
|
||||
// NewSync creates a new Sync instance with the provided adapter and middleware chain.
|
||||
// Middleware is applied in reverse order, so the first middleware in the list
|
||||
// will be the outermost wrapper.
|
||||
func NewSync(adapter SyncHandlerAdapter, middlewares ...Middleware) Sync {
|
||||
s := Sync{}
|
||||
for i := len(middlewares) - 1; i >= 0; i-- {
|
||||
adapter = middlewares[i](adapter)
|
||||
}
|
||||
s.handler = adapter
|
||||
return s
|
||||
}
|
||||
|
||||
// Handle processes the job using the wrapped handler and middleware chain.
|
||||
// It translates the Result into a bgjob.Result to control job lifecycle:
|
||||
// - Complete: marks the job as successfully processed
|
||||
// - Retry: schedules the job for retry after a delay
|
||||
// - MoveToDlq: moves the job to the dead letter queue
|
||||
// - Reschedule: reschedules the job for later execution
|
||||
func (r Sync) Handle(ctx context.Context, job bgjob.Job) bgjob.Result {
|
||||
result := r.handler.Handle(ctx, job)
|
||||
|
||||
switch {
|
||||
case result.Complete:
|
||||
return bgjob.Complete()
|
||||
case result.Retry:
|
||||
return bgjob.Retry(result.RetryDelay, result.Err)
|
||||
case result.MoveToDlq:
|
||||
return bgjob.MoveToDlq(result.Err)
|
||||
case result.Reschedule:
|
||||
return bgjob.Reschedule(result.RescheduleDelay)
|
||||
case result.RescheduleWithArg:
|
||||
return bgjob.RescheduleWithArg(result.RescheduleDelay, result.Arg)
|
||||
}
|
||||
|
||||
return bgjob.Result{}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/bgjob"
|
||||
)
|
||||
|
||||
// Mux routes jobs to different handlers based on their type.
|
||||
// It maintains a registry of job types and their corresponding handlers,
|
||||
// returning an error for unknown job types.
|
||||
type Mux struct {
|
||||
data map[string]SyncHandlerAdapter
|
||||
}
|
||||
|
||||
// NewMux creates a new empty Mux instance.
|
||||
func NewMux() *Mux {
|
||||
return &Mux{
|
||||
data: make(map[string]SyncHandlerAdapter),
|
||||
}
|
||||
}
|
||||
|
||||
// Register associates a job type with its handler.
|
||||
// Returns the Mux for method chaining.
|
||||
func (m *Mux) Register(jobType string, handler SyncHandlerAdapter) *Mux {
|
||||
m.data[jobType] = handler
|
||||
return m
|
||||
}
|
||||
|
||||
// Handle routes a job to the appropriate handler based on its type.
|
||||
// If no handler is registered for the job type, it returns MoveToDlq
|
||||
// with ErrUnknownType.
|
||||
func (m *Mux) Handle(ctx context.Context, job bgjob.Job) Result {
|
||||
handler, ok := m.data[job.Type]
|
||||
if !ok {
|
||||
return MoveToDlq(bgjob.ErrUnknownType)
|
||||
}
|
||||
return handler.Handle(ctx, job)
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package bgjobx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
)
|
||||
|
||||
// Observer implements the bgjob.Observer interface to provide logging and
|
||||
// metrics collection for job lifecycle events. It records job state changes
|
||||
// such as completion, retries, and failures to the dead letter queue.
|
||||
type Observer struct {
|
||||
bgjob.NoopObserver
|
||||
|
||||
log log.Logger
|
||||
metricStorage handler.MetricStorage
|
||||
}
|
||||
|
||||
// JobStarted is called when a job begins processing.
|
||||
// It logs the job ID, request ID, and job type at debug level.
|
||||
func (o Observer) JobStarted(ctx context.Context, job bgjob.Job) {
|
||||
o.log.Debug(ctx, "bgjob: job started", log.String("id", job.Id), log.String(requestid.LogKey, job.RequestId), log.String("type", job.Type))
|
||||
}
|
||||
|
||||
// JobCompleted is called when a job finishes successfully.
|
||||
// It logs the completion and increments the success counter for the queue and job type.
|
||||
func (o Observer) JobCompleted(ctx context.Context, job bgjob.Job) {
|
||||
o.log.Debug(ctx, "bgjob: job completed", log.String("id", job.Id), log.String(requestid.LogKey, job.RequestId))
|
||||
o.metricStorage.IncSuccessCount(job.Queue, job.Type)
|
||||
}
|
||||
|
||||
// JobWillBeRetried is called when a job fails and is scheduled for retry.
|
||||
// It logs the error and the retry delay, and increments the retry counter.
|
||||
func (o Observer) JobWillBeRetried(ctx context.Context, job bgjob.Job, after time.Duration, err error) {
|
||||
o.log.Error(ctx, "bgjob: job will be retried", log.String("id", job.Id), log.String(requestid.LogKey, job.RequestId), log.String("after", after.String()), log.Any("error", err))
|
||||
o.metricStorage.IncRetryCount(job.Queue, job.Type)
|
||||
}
|
||||
|
||||
// JobMovedToDlq is called when a job is moved to the dead letter queue
|
||||
// after exhausting all retry attempts. It logs the error and increments the DLQ counter.
|
||||
func (o Observer) JobMovedToDlq(ctx context.Context, job bgjob.Job, err error) {
|
||||
o.log.Error(ctx, "bgjob: job will be moved to dlq", log.String("id", job.Id), log.String(requestid.LogKey, job.RequestId), log.Any("error", err))
|
||||
o.metricStorage.IncDlqCount(job.Queue, job.Type)
|
||||
}
|
||||
|
||||
// JobRescheduled is called when a job is rescheduled for future execution.
|
||||
// It logs the rescheduled time for the job.
|
||||
func (o Observer) JobRescheduled(ctx context.Context, job bgjob.Job, after time.Duration) {
|
||||
o.log.Debug(ctx, "bgjob: job rescheduled", log.String("id", job.Id), log.String(requestid.LogKey, job.RequestId), log.Any("nextRunAt", after.String()))
|
||||
}
|
||||
|
||||
// WorkerError is called when an unexpected error occurs in the worker.
|
||||
// It logs the error and increments the internal error counter.
|
||||
func (o Observer) WorkerError(ctx context.Context, err error) {
|
||||
o.log.Error(ctx, "bgjob: unexpected worker error", log.Any("error", err))
|
||||
o.metricStorage.IncInternalErrorCount()
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
# Package `bootstrap`
|
||||
|
||||
Пакет `bootstrap` предназначен для инициализации инфраструктуры приложения и настройки основных компонентов.
|
||||
|
||||
## Types
|
||||
|
||||
### Bootstrap
|
||||
|
||||
Центральная структура, которая предоставляет функциональность для инициализации и настройки модуля приложения, включая
|
||||
динамическую конфигурацию, логирование, трейсинг, запуск инфраструктурного http-сервера (метрики, healthchecks),
|
||||
подключение к кластеру сервисов и интеграцию с sentry для обработки ошибок. Другими словами, объект структуры
|
||||
`Bootstrap` управляет жизненным циклом приложения.
|
||||
|
||||
**Методы:**
|
||||
|
||||
#### `(b *BaseBootstrap) Fatal(err error)`
|
||||
|
||||
Обработать критические ошибки с уведомлением в Sentry
|
||||
|
||||
#### `New(moduleVersion string, remoteConfig any, endpoints []cluster.EndpointDescriptor, transport string) *Bootstrap`
|
||||
|
||||
Конструктор с параметрами:
|
||||
|
||||
- `moduleVersion` - версия модуля
|
||||
- `remoteConfig` - структура для динамической конфигурации
|
||||
- `endpoints` - список эндпоинтов модуля, для транспорта `http` у каждого `endpoint`'а должен быть указан `HttpMethod`
|
||||
- `transport` - тип сервера, `grpc`, `http` или `empty`
|
||||
|
||||
#### `NewStandalone(moduleVersion string) *StandaloneBootstrap`
|
||||
|
||||
Конструктор с параметрами:
|
||||
|
||||
- `moduleVersion` - версия модуля
|
||||
|
||||
#### `func (b *StandaloneBootstrap) ReadConfig(destPtr any) error`
|
||||
|
||||
Прочитать локальную `json` конфигурацию, путь до конфигурации определяется настройкой в локальном конфиге `remoteConfigPath`, по умолчанию путь `./conf/config.json` (либо относительно бинарника, если запуск не в `dev` режиме)
|
||||
|
||||
## Конфигурация
|
||||
|
||||
Файлы конфигурации по умолчанию:
|
||||
|
||||
- `conf/config_dev.yml` для разработки
|
||||
- `config.yml` рядом с бинарником для `production`
|
||||
|
||||
Переменные окружения:
|
||||
|
||||
- `APP_MODE=dev` — режим разработки
|
||||
- `APP_CONFIG_PATH` — кастомный путь к конфигу
|
||||
- `APP_CONFIG_ENV_PREFIX` — префикс для env variables
|
||||
- `CLUSTER_MODE=offline` — режим, при котором будет использоваться заглушка для конфиг сервиса
|
||||
|
||||
## Инфраструктурные эндпоинты
|
||||
|
||||
По умолчанию доступны:
|
||||
|
||||
- `/internal/metrics` — prometheus метрики
|
||||
- `/internal/metrics/descriptions` — описание метрик
|
||||
- `/internal/health` — healthcheck статус
|
||||
- `/internal/debug/pprof/` — профилирование
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow for clustered
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type remoteConfig struct {
|
||||
Foo string `validate:"required"`
|
||||
Bar int
|
||||
}
|
||||
|
||||
func noopHandler() {}
|
||||
|
||||
func main() {
|
||||
endpoints := []cluster.EndpointDescriptor{{
|
||||
Path: "/api/service/private",
|
||||
Inner: true,
|
||||
Handler: noopHandler,
|
||||
}, {
|
||||
Path: "/api/service/public",
|
||||
Inner: false,
|
||||
Handler: noopHandler,
|
||||
}}
|
||||
boot := bootstrap.New("1.0.0", remoteConfig{}, endpoints, cluster.GrpcTransport)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
boot.App.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err := boot.App.Run()
|
||||
if err != nil {
|
||||
boot.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Default usage flow for standalone
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
Foo string `validate:"required"`
|
||||
Bar int
|
||||
}
|
||||
|
||||
func main() {
|
||||
boot := bootstrap.NewStandalone("1.0.0")
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
boot.App.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
cfg := config{}
|
||||
err := boot.ReadConfig(&cfg)
|
||||
if err != nil {
|
||||
boot.Fatal(err)
|
||||
}
|
||||
|
||||
err = boot.App.Run()
|
||||
if err != nil {
|
||||
boot.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+294
@@ -0,0 +1,294 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/healthcheck"
|
||||
"github.com/txix-open/isp-kit/infra"
|
||||
"github.com/txix-open/isp-kit/infra/pprof"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/file"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/app_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/observability/tracing"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
const (
|
||||
postShutdownWait = 500 * time.Millisecond
|
||||
|
||||
defaultLogFileMaxSizeMb = 512
|
||||
defaultLogFileMaxBackups = 4
|
||||
defaultLogFileCompress = true
|
||||
|
||||
defaultEnableLogSampling = false
|
||||
defaultMaxLogSamplingPerSecond = 1000
|
||||
defaulLogSamplingPassEvery = 100
|
||||
)
|
||||
|
||||
// BaseBootstrap provides the core initialization context for all application types.
|
||||
// It contains shared functionality for application lifecycle, metrics, infrastructure,
|
||||
// observability, and health checking.
|
||||
//
|
||||
// Fields:
|
||||
// - App: Application instance for lifecycle management and context
|
||||
// - MetricsRegistry: Registry for application metrics
|
||||
// - InfraServer: Infrastructure server for internal endpoints (metrics, health, pprof)
|
||||
// - HealthcheckRegistry: Registry for health check endpoints
|
||||
// - BindingAddress: inner binding address (host:port)
|
||||
// - MigrationsDir: Path to database migrations directory
|
||||
// - ModuleName: Name of the module
|
||||
// - SentryHub: Sentry error reporting hub
|
||||
// - TracingProvider: OpenTelemetry tracing provider
|
||||
//
|
||||
// Create a BaseBootstrap through New() or NewStandalone() functions.
|
||||
type BaseBootstrap struct {
|
||||
App *app.Application
|
||||
MetricsRegistry *metrics.Registry
|
||||
InfraServer *infra.Server
|
||||
HealthcheckRegistry *healthcheck.Registry
|
||||
BindingAddress string
|
||||
MigrationsDir string
|
||||
ModuleName string
|
||||
SentryHub sentry.Hub
|
||||
TracingProvider tracing.Provider
|
||||
}
|
||||
|
||||
// Fatal logs a fatal error, reports it to Sentry, and terminates the application.
|
||||
//
|
||||
// This method performs the following steps:
|
||||
// 1. Reports the error to Sentry with fatal level
|
||||
// 2. Closes the application and all registered closers
|
||||
// 3. Waits for post-shutdown operations (500ms)
|
||||
// 4. Logs the fatal error and terminates the process
|
||||
//
|
||||
// This method does not return and should only be used for unrecoverable errors.
|
||||
func (b *BaseBootstrap) Fatal(err error) {
|
||||
b.SentryHub.CatchError(b.App.Context(), err, log.FatalLevel)
|
||||
b.App.Close()
|
||||
time.Sleep(postShutdownWait)
|
||||
b.App.Logger().Fatal(context.Background(), err)
|
||||
}
|
||||
|
||||
func initApp(isDev bool) (*app.Application, error) {
|
||||
appConfig, err := appConfig(isDev)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "app config")
|
||||
}
|
||||
app, err := app.NewFromConfig(*appConfig)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create app")
|
||||
}
|
||||
return app, nil
|
||||
}
|
||||
|
||||
func bootstrap(
|
||||
isDev bool,
|
||||
application *app.Application,
|
||||
sentryHub sentry.Hub,
|
||||
localConfig LocalConfig,
|
||||
moduleVersion string,
|
||||
instanceId string,
|
||||
) (*BaseBootstrap, error) {
|
||||
bindingAddress := net.JoinHostPort(localConfig.GrpcInnerAddress.IP, strconv.Itoa(localConfig.GrpcInnerAddress.Port))
|
||||
|
||||
migrationsDir, err := migrationsDirPath(isDev, localConfig)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "resolve migrations dir path")
|
||||
}
|
||||
|
||||
infraServer, metricsRegistry, healthcheckRegistry := initInfra(application, localConfig)
|
||||
|
||||
tracingProvider := initTracing(
|
||||
application.Context(),
|
||||
sentryHub,
|
||||
localConfig,
|
||||
moduleVersion,
|
||||
instanceId,
|
||||
application.Logger(),
|
||||
)
|
||||
tracing.DefaultProvider = tracingProvider
|
||||
|
||||
application.AddClosers(
|
||||
app.CloserFunc(func() error {
|
||||
sentryHub.Flush()
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
err := tracingProvider.Shutdown(context.Background())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "shutdown tracing provider")
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
|
||||
return &BaseBootstrap{
|
||||
App: application,
|
||||
BindingAddress: bindingAddress,
|
||||
ModuleName: localConfig.ModuleName,
|
||||
MigrationsDir: migrationsDir,
|
||||
InfraServer: infraServer,
|
||||
MetricsRegistry: metricsRegistry,
|
||||
HealthcheckRegistry: healthcheckRegistry,
|
||||
SentryHub: sentryHub,
|
||||
TracingProvider: tracingProvider,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func initInfra(application *app.Application, localConfig LocalConfig) (*infra.Server, *metrics.Registry, *healthcheck.Registry) {
|
||||
infraServer := infra.NewServer()
|
||||
infraServerPort := localConfig.GrpcInnerAddress.Port + 1
|
||||
if localConfig.InfraServerPort != 0 {
|
||||
infraServerPort = localConfig.InfraServerPort
|
||||
}
|
||||
infraServerAddress := fmt.Sprintf(":%d", infraServerPort)
|
||||
application.AddRunners(
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
application.Logger().Info(ctx, "run infra server", log.String("infraServerAddress", infraServerAddress))
|
||||
err := infraServer.ListenAndServe(infraServerAddress)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "run infra server on %s", infraServerAddress)
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
)
|
||||
application.AddClosers(app.CloserFunc(func() error {
|
||||
return infraServer.Shutdown()
|
||||
}))
|
||||
|
||||
metricsReg := metrics.DefaultRegistry
|
||||
hcReg := healthcheck.NewRegistry(localConfig.HealthcheckHandlerTimeout)
|
||||
|
||||
infraServer.Handle("/internal/metrics", metricsReg.MetricsHandler())
|
||||
infraServer.Handle("/internal/metrics/descriptions", metricsReg.MetricsDescriptionHandler())
|
||||
infraServer.Handle("/internal/health", hcReg.Handler())
|
||||
pprof.RegisterHandlers("/internal", infraServer)
|
||||
|
||||
application.Logger().Info(application.Context(),
|
||||
"infra server handlers",
|
||||
log.Any("infraServerHandlers",
|
||||
append([]string{
|
||||
"/internal/metrics",
|
||||
"/internal/metrics/descriptions",
|
||||
"/internal/health",
|
||||
}, pprof.Endpoints("/internal")...),
|
||||
),
|
||||
)
|
||||
|
||||
return infraServer, metricsReg, hcReg
|
||||
}
|
||||
|
||||
// nolint:ireturn
|
||||
func initTracing(
|
||||
ctx context.Context,
|
||||
hub sentry.Hub,
|
||||
cfg LocalConfig,
|
||||
version string,
|
||||
instanceId string,
|
||||
logger log.Logger,
|
||||
) tracing.Provider {
|
||||
tracingCfg := tracing.Config{
|
||||
Enable: cfg.Observability.Tracing.Enable,
|
||||
Address: cfg.Observability.Tracing.Address,
|
||||
ModuleName: cfg.ModuleName,
|
||||
ModuleVersion: version,
|
||||
Environment: cfg.Observability.Tracing.Environment,
|
||||
InstanceId: instanceId,
|
||||
Attributes: cfg.Observability.Tracing.Attributes,
|
||||
}
|
||||
provider, err := tracing.NewProviderFromConfiguration(
|
||||
ctx,
|
||||
logger,
|
||||
tracingCfg,
|
||||
)
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "new tracing provider, tracing will be disabled")
|
||||
hub.CatchError(ctx, err, log.ErrorLevel)
|
||||
logger.Error(ctx, err)
|
||||
return tracing.NewNoopProvider()
|
||||
}
|
||||
return provider
|
||||
}
|
||||
|
||||
func appConfig(isDev bool) (*app.Config, error) {
|
||||
localConfigPath, err := configFilePath(isDev)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "resolve local config path")
|
||||
}
|
||||
configsOpts := []config.Option{
|
||||
config.WithValidator(validator.Default),
|
||||
config.WithEnvPrefix(os.Getenv("APP_CONFIG_ENV_PREFIX")),
|
||||
}
|
||||
if localConfigPath != "" {
|
||||
configsOpts = append(configsOpts, config.WithExtraSource(config.NewYamlConfig(localConfigPath)))
|
||||
}
|
||||
|
||||
logConfigSupplier := app.LoggerConfigSupplier(func(cfg *config.Config) log.Config {
|
||||
initialLevel := log.InfoLevel
|
||||
if isDev {
|
||||
initialLevel = log.DebugLevel
|
||||
}
|
||||
|
||||
var outputPaths []string
|
||||
logFilePath := cfg.Optional().String("LOGFILE.PATH", "")
|
||||
if !isDev && logFilePath != "" {
|
||||
fileOutput := file.Output{
|
||||
File: logFilePath,
|
||||
MaxSizeMb: cfg.Optional().Int("LOGFILE.MAXSIZEMB", defaultLogFileMaxSizeMb),
|
||||
MaxDays: 0,
|
||||
MaxBackups: cfg.Optional().Int("LOGFILE.MAXBACKUPS", defaultLogFileMaxBackups),
|
||||
Compress: cfg.Optional().Bool("LOGFILE.COMPRESS", defaultLogFileCompress),
|
||||
}
|
||||
outputPaths = append(outputPaths, file.ConfigToUrl(fileOutput).String())
|
||||
}
|
||||
|
||||
logCounter := app_metrics.NewLogCounter(metrics.DefaultRegistry)
|
||||
|
||||
var sampling *log.SamplingConfig
|
||||
isEnableSampling := cfg.Optional().Bool("LOGS.SAMPLING.ENABLE", defaultEnableLogSampling)
|
||||
if !isDev && isEnableSampling {
|
||||
sampling = &log.SamplingConfig{
|
||||
Initial: cfg.Optional().Int("LOGS.SAMPLING.MAXPERSECOND", defaultMaxLogSamplingPerSecond),
|
||||
Thereafter: cfg.Optional().Int("LOGS.SAMPLING.PASSEVERY", defaulLogSamplingPassEvery),
|
||||
Hook: logCounter.DroppedLogCounter(),
|
||||
}
|
||||
}
|
||||
|
||||
return log.Config{
|
||||
IsInDevMode: isDev,
|
||||
OutputPaths: outputPaths,
|
||||
Sampling: sampling,
|
||||
InitialLevel: initialLevel,
|
||||
Hooks: []func(entry zapcore.Entry) error{
|
||||
logCounter.SampledLogCounter(),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
return &app.Config{
|
||||
LoggerConfigSupplier: logConfigSupplier,
|
||||
ConfigOptions: configsOpts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func configPath(isDev bool, configPath string) (string, error) {
|
||||
if configPath != "" {
|
||||
return configPath, nil
|
||||
}
|
||||
if isDev {
|
||||
return "./conf/config.json", nil
|
||||
}
|
||||
|
||||
return relativePathFromBin("conf/config.json")
|
||||
}
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
// Package bootstrap provides a unified initialization framework for isp-kit applications.
|
||||
//
|
||||
// The bootstrap package handles application setup including configuration management,
|
||||
// logging, observability (Sentry and tracing), cluster coordination, and infrastructure
|
||||
// server initialization. It supports both clustered and standalone deployment modes.
|
||||
//
|
||||
// # Usage
|
||||
//
|
||||
// For clustered applications:
|
||||
//
|
||||
// boot := bootstrap.New(
|
||||
// "1.0.0", // module version
|
||||
// &RemoteConfig{}, // remote config struct
|
||||
// []cluster.EndpointDescriptor{}, // service endpoints
|
||||
// cluster.HttpTransport, // transport type
|
||||
// )
|
||||
//
|
||||
// For standalone applications:
|
||||
//
|
||||
// boot := bootstrap.NewStandalone("1.0.0")
|
||||
// var cfg MyConfig
|
||||
// if err := boot.ReadConfig(&cfg); err != nil {
|
||||
// // handle error
|
||||
// }
|
||||
//
|
||||
// The package automatically initializes:
|
||||
// - Application context and lifecycle management
|
||||
// - Logging with optional file output and sampling
|
||||
// - Sentry error reporting and tracing
|
||||
// - Health check endpoints
|
||||
// - Metrics endpoints
|
||||
// - Cluster client (for clustered mode)
|
||||
// - Remote configuration management (for clustered mode)
|
||||
//
|
||||
// # Environment Variables
|
||||
//
|
||||
// The following environment variables are supported:
|
||||
// - APP_MODE: Set to "dev" to enable development mode (affects logging level and file paths)
|
||||
// - CLUSTER_MODE: Set to "offline" to enable offline cluster mode
|
||||
// - APP_CONFIG_PATH: Custom path to the application configuration file
|
||||
// - APP_CONFIG_ENV_PREFIX: Prefix for environment variable configuration keys
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
json2 "encoding/json"
|
||||
stdlog "log"
|
||||
"maps"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/rc"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
// ClusterClient defines the interface for cluster coordination operations.
|
||||
type ClusterClient interface {
|
||||
Run(ctx context.Context, eventHandler *cluster.EventHandler) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
// Bootstrap represents the main initialization context for clustered applications.
|
||||
// It embeds BaseBootstrap and adds cluster-specific functionality including
|
||||
// cluster client management and remote configuration.
|
||||
//
|
||||
// The Bootstrap instance provides access to:
|
||||
// - Application lifecycle management (via BaseBootstrap)
|
||||
// - Cluster coordination through ClusterCli
|
||||
// - Remote configuration via RemoteConfig
|
||||
//
|
||||
// Create a Bootstrap instance using the New() function.
|
||||
type Bootstrap struct {
|
||||
*BaseBootstrap
|
||||
|
||||
ClusterCli ClusterClient
|
||||
RemoteConfig *rc.Config
|
||||
}
|
||||
|
||||
// New creates and initializes a new Bootstrap instance for clustered applications.
|
||||
//
|
||||
// Parameters:
|
||||
// - moduleVersion: Version string of the module (e.g., "1.0.0")
|
||||
// - remoteConfig: Pointer to a struct defining the remote configuration schema
|
||||
// - endpoints: List of service endpoint descriptors for cluster discovery
|
||||
// - transport: Transport type (e.g., cluster.HttpTransport or cluster.GrpcTransport)
|
||||
//
|
||||
// Returns a fully initialized Bootstrap instance with:
|
||||
// - Application context and logging
|
||||
// - Sentry error reporting
|
||||
// - Cluster client for coordination
|
||||
// - Remote configuration management
|
||||
// - Infrastructure server with metrics and health endpoints
|
||||
//
|
||||
// The function automatically detects the deployment mode (dev/offline) and
|
||||
// configures the application accordingly. In case of initialization errors,
|
||||
// the function logs a fatal error and terminates the application.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// boot := bootstrap.New(
|
||||
// "1.2.3",
|
||||
// &MyRemoteConfig{},
|
||||
// []cluster.EndpointDescriptor{
|
||||
// {Path: "/api/v1", HttpMethod: "GET"},
|
||||
// },
|
||||
// cluster.HttpTransport,
|
||||
// )
|
||||
func New(
|
||||
moduleVersion string,
|
||||
remoteConfig any,
|
||||
endpoints []cluster.EndpointDescriptor,
|
||||
transport string,
|
||||
) *Bootstrap {
|
||||
isDev := isOnDevMode()
|
||||
app, err := initApp(isDev)
|
||||
if err != nil {
|
||||
stdlog.Fatal(err)
|
||||
}
|
||||
|
||||
if transport == cluster.HttpTransport {
|
||||
for _, endpoint := range endpoints {
|
||||
if endpoint.HttpMethod == "" {
|
||||
app.Logger().Fatal(
|
||||
app.Context(),
|
||||
"invalid endpoint",
|
||||
log.String("reason", "empty httpMethod"),
|
||||
log.String("path", endpoint.Path),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
localCfg, err := localConfig[ClusteredLocalConfig](app.Config())
|
||||
if err != nil {
|
||||
app.Logger().Fatal(app.Context(), errors.WithMessage(err, "create local config"))
|
||||
}
|
||||
sentryHub, err := sentry.NewHubFromConfiguration(sentry.Config{
|
||||
Enable: localCfg.Observability.Sentry.Enable,
|
||||
Dsn: localCfg.Observability.Sentry.Dsn,
|
||||
ModuleName: localCfg.ModuleName,
|
||||
Environment: localCfg.Observability.Sentry.Environment,
|
||||
Tags: localCfg.Observability.Sentry.Tags,
|
||||
InstanceId: localCfg.GrpcOuterAddress.IP,
|
||||
ModuleVersion: moduleVersion,
|
||||
})
|
||||
if err != nil {
|
||||
app.Logger().Fatal(app.Context(), errors.WithMessage(err, "create sentry error reporter"))
|
||||
}
|
||||
|
||||
if isOnOfflineMode() {
|
||||
boot, err := newOfflineClustered(
|
||||
isDev,
|
||||
app,
|
||||
sentryHub,
|
||||
localCfg,
|
||||
moduleVersion,
|
||||
)
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "create offline bootstrap")
|
||||
sentryHub.CatchError(app.Context(), err, log.FatalLevel)
|
||||
app.Logger().Fatal(app.Context(), err)
|
||||
}
|
||||
return boot
|
||||
}
|
||||
|
||||
boot, err := newClustered(
|
||||
isDev,
|
||||
app,
|
||||
sentryHub,
|
||||
localCfg,
|
||||
transport,
|
||||
remoteConfig,
|
||||
moduleVersion,
|
||||
endpoints,
|
||||
)
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "create bootstrap")
|
||||
sentryHub.CatchError(app.Context(), err, log.FatalLevel)
|
||||
app.Logger().Fatal(app.Context(), err)
|
||||
}
|
||||
return boot
|
||||
}
|
||||
|
||||
func newClustered(
|
||||
isDev bool,
|
||||
application *app.Application,
|
||||
sentryHub sentry.Hub,
|
||||
localConfig ClusteredLocalConfig,
|
||||
transport string,
|
||||
remoteConfig any,
|
||||
moduleVersion string,
|
||||
endpoints []cluster.EndpointDescriptor,
|
||||
) (*Bootstrap, error) {
|
||||
broadcastHost, err := resolveBroadcastHost(localConfig)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "resolve broadcast host")
|
||||
}
|
||||
|
||||
boot, err := bootstrap(
|
||||
isDev,
|
||||
application,
|
||||
sentryHub,
|
||||
localConfig.LocalConfig,
|
||||
moduleVersion,
|
||||
broadcastHost,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create bootstrap")
|
||||
}
|
||||
|
||||
wrappedLogger := sentry.WrapErrorLogger(application.Logger(), sentryHub)
|
||||
clusterCli, err := initClusterClient(
|
||||
isDev,
|
||||
localConfig,
|
||||
remoteConfig,
|
||||
moduleVersion,
|
||||
transport,
|
||||
broadcastHost,
|
||||
endpoints,
|
||||
wrappedLogger,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "init cluster client")
|
||||
}
|
||||
boot.HealthcheckRegistry.Register("configServiceConnection", clusterCli)
|
||||
rc := rc.New(validator.Default, []byte(localConfig.RemoteConfigOverride))
|
||||
|
||||
return &Bootstrap{
|
||||
BaseBootstrap: boot,
|
||||
ClusterCli: clusterCli,
|
||||
RemoteConfig: rc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newOfflineClustered(
|
||||
isDev bool,
|
||||
application *app.Application,
|
||||
sentryHub sentry.Hub,
|
||||
localConfig ClusteredLocalConfig,
|
||||
moduleVersion string,
|
||||
) (*Bootstrap, error) {
|
||||
configPath, err := configPath(isDev, localConfig.RemoteConfigPath)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get config path")
|
||||
}
|
||||
|
||||
boot, err := bootstrap(
|
||||
isDev,
|
||||
application,
|
||||
sentryHub,
|
||||
localConfig.LocalConfig,
|
||||
moduleVersion,
|
||||
localConfig.GrpcOuterAddress.IP,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create bootstrap")
|
||||
}
|
||||
|
||||
clusterCli := cluster.NewOfflineClient(configPath)
|
||||
rc := rc.New(validator.Default, []byte(localConfig.RemoteConfigOverride))
|
||||
return &Bootstrap{
|
||||
BaseBootstrap: boot,
|
||||
ClusterCli: clusterCli,
|
||||
RemoteConfig: rc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func resolveBroadcastHost(localConfig ClusteredLocalConfig) (string, error) {
|
||||
if localConfig.GrpcOuterAddress.IP != "" {
|
||||
return localConfig.GrpcOuterAddress.IP, nil
|
||||
}
|
||||
hosts, err := parseConfigServiceHosts(localConfig.ConfigServiceAddress)
|
||||
if err != nil {
|
||||
return "", errors.WithMessage(err, "parse config service hosts")
|
||||
}
|
||||
broadcastHost, err := resolveHost(hosts[0])
|
||||
if err != nil {
|
||||
return "", errors.WithMessage(err, "resolve local host")
|
||||
}
|
||||
return broadcastHost, nil
|
||||
}
|
||||
|
||||
func initClusterClient(
|
||||
isDev bool,
|
||||
localConfig ClusteredLocalConfig,
|
||||
remoteConfig any,
|
||||
moduleVersion string,
|
||||
transport string,
|
||||
broadcastHost string,
|
||||
endpoints []cluster.EndpointDescriptor,
|
||||
logger log.Logger,
|
||||
) (*cluster.Client, error) {
|
||||
moduleInfo := cluster.ModuleInfo{
|
||||
ModuleName: localConfig.ModuleName,
|
||||
ModuleVersion: moduleVersion,
|
||||
LibVersion: kitVersion(),
|
||||
Transport: transport,
|
||||
GrpcOuterAddress: cluster.AddressConfiguration{
|
||||
IP: broadcastHost,
|
||||
Port: strconv.Itoa(localConfig.GrpcOuterAddress.Port),
|
||||
},
|
||||
Endpoints: endpoints,
|
||||
MetricsAutodiscovery: metricsServiceDiscovery(localConfig, broadcastHost),
|
||||
}
|
||||
|
||||
schema := rc.GenerateConfigSchema(remoteConfig)
|
||||
schemaData, err := json.Marshal(schema)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "marshal schema")
|
||||
}
|
||||
|
||||
path, err := defaultRemoteConfigPath(isDev, localConfig)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "resolve path")
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "read file")
|
||||
}
|
||||
|
||||
defaultConfig := json2.RawMessage{}
|
||||
err = json.Unmarshal(data, &defaultConfig)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal json")
|
||||
}
|
||||
|
||||
configData := cluster.ConfigData{
|
||||
Version: moduleVersion,
|
||||
Schema: schemaData,
|
||||
Config: defaultConfig,
|
||||
}
|
||||
|
||||
configServiceHosts, err := parseConfigServiceHosts(localConfig.ConfigServiceAddress)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse config service hosts")
|
||||
}
|
||||
|
||||
return cluster.NewClient(
|
||||
moduleInfo,
|
||||
configData,
|
||||
configServiceHosts,
|
||||
localConfig.RemoteConfigReceiverTimeout,
|
||||
logger,
|
||||
), nil
|
||||
}
|
||||
|
||||
func defaultRemoteConfigPath(isDev bool, cfg ClusteredLocalConfig) (string, error) {
|
||||
if cfg.DefaultRemoteConfigPath != "" {
|
||||
return cfg.DefaultRemoteConfigPath, nil
|
||||
}
|
||||
|
||||
if isDev {
|
||||
return "conf/default_remote_config.json", nil
|
||||
}
|
||||
|
||||
return relativePathFromBin("default_remote_config.json")
|
||||
}
|
||||
|
||||
func metricsServiceDiscovery(localConfig ClusteredLocalConfig, broadcastHost string) *cluster.MetricsAutodiscovery {
|
||||
if !localConfig.MetricsAutodiscovery.Enable {
|
||||
return nil
|
||||
}
|
||||
|
||||
labels := map[string]string{
|
||||
"__metrics_path__": "/internal/metrics",
|
||||
"app": localConfig.ModuleName,
|
||||
}
|
||||
maps.Insert(labels, maps.All(localConfig.MetricsAutodiscovery.AdditionalLabels))
|
||||
|
||||
address := localConfig.MetricsAutodiscovery.Address
|
||||
if address == "" {
|
||||
address = net.JoinHostPort(
|
||||
broadcastHost,
|
||||
strconv.Itoa(defineInfraServerPort(localConfig.LocalConfig)),
|
||||
)
|
||||
}
|
||||
|
||||
return &cluster.MetricsAutodiscovery{
|
||||
Address: address,
|
||||
Labels: labels,
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package bootstrap
|
||||
|
||||
import "time"
|
||||
|
||||
// LocalConfig defines the local configuration structure for standalone applications.
|
||||
//
|
||||
// Fields:
|
||||
// - GrpcOuterAddress: External address configuration (IP and port)
|
||||
// - GrpcInnerAddress: Internal address configuration (IP and port, required)
|
||||
// - ModuleName: Unique name of the module/application (required)
|
||||
// - MigrationsDirPath: Path to database migrations directory (optional)
|
||||
// - RemoteConfigOverride: Override content for remote configuration (optional)
|
||||
// - LogFile: File-based logging configuration
|
||||
// - Logs: Log sampling and rate limiting configuration
|
||||
// - Observability: Sentry and tracing configuration
|
||||
// - InfraServerPort: Custom port for infrastructure server (optional, defaults to GrpcInnerAddress.Port + 1)
|
||||
// - HealthcheckHandlerTimeout: Timeout for health check requests
|
||||
// - RemoteConfigPath: Path to application configuration file (optional)
|
||||
type LocalConfig struct {
|
||||
GrpcOuterAddress GrpcOuterAddr
|
||||
GrpcInnerAddress GrpcInnerAddr
|
||||
ModuleName string `validate:"required"`
|
||||
MigrationsDirPath string
|
||||
RemoteConfigOverride string
|
||||
LogFile LogFile
|
||||
Logs Logs
|
||||
Observability Observability
|
||||
InfraServerPort int
|
||||
HealthcheckHandlerTimeout time.Duration
|
||||
// Path to the application configuration
|
||||
RemoteConfigPath string
|
||||
}
|
||||
|
||||
// ClusteredLocalConfig extends LocalConfig with additional configuration for clustered applications.
|
||||
//
|
||||
// Embedded:
|
||||
// - LocalConfig: All fields from LocalConfig
|
||||
//
|
||||
// Additional fields:
|
||||
// - ConfigServiceAddress: Address of the config service for cluster coordination (IP;Port format, required)
|
||||
// - DefaultRemoteConfigPath: Custom path for default remote configuration file (optional)
|
||||
// - RemoteConfigReceiverTimeout: Timeout for receiving remote configuration updates
|
||||
// - MetricsAutodiscovery: Configuration for Prometheus metrics auto-discovery
|
||||
type ClusteredLocalConfig struct {
|
||||
LocalConfig
|
||||
|
||||
ConfigServiceAddress ConfigServiceAddr
|
||||
DefaultRemoteConfigPath string
|
||||
RemoteConfigReceiverTimeout time.Duration
|
||||
MetricsAutodiscovery MetricsAutodiscovery
|
||||
}
|
||||
|
||||
// Logs configures log sampling and rate limiting.
|
||||
//
|
||||
// Fields:
|
||||
// - Sampling.Enable: Enable log sampling to prevent log flooding
|
||||
// - Sampling.MaxPerSecond: Maximum log entries per second when sampling is enabled
|
||||
// - Sampling.PassEvery: Number of log entries to pass before sampling again
|
||||
type Logs struct {
|
||||
Sampling struct {
|
||||
Enable bool
|
||||
MaxPerSecond int
|
||||
PassEvery int
|
||||
}
|
||||
}
|
||||
|
||||
// LogFile configures file-based logging output.
|
||||
//
|
||||
// Fields:
|
||||
// - Path: Path to the log file
|
||||
// - MaxSizeMb: Maximum file size in megabytes before rotation (default: 512)
|
||||
// - MaxBackups: Maximum number of backup files to keep (default: 4)
|
||||
// - Compress: Whether to compress rotated log files (default: true)
|
||||
type LogFile struct {
|
||||
Path string
|
||||
MaxSizeMb int
|
||||
MaxBackups int
|
||||
Compress bool
|
||||
}
|
||||
|
||||
// ConfigServiceAddr defines the address configuration for the cluster config service.
|
||||
//
|
||||
// Fields:
|
||||
// - IP: Comma-separated list of config service host IPs
|
||||
// - Port: Comma-separated list of config service ports (must match length of IP)
|
||||
//
|
||||
// Multiple addresses can be specified using semicolon separation (e.g., "host1;host2" and "port1;port2")
|
||||
type ConfigServiceAddr struct {
|
||||
IP string `validate:"required"`
|
||||
Port string `validate:"required"`
|
||||
}
|
||||
|
||||
// GrpcOuterAddr defines the external gRPC address configuration.
|
||||
//
|
||||
// Fields:
|
||||
// - IP: External IP address (can be empty for standalone)
|
||||
// - Port: External gRPC port (required)
|
||||
type GrpcOuterAddr struct {
|
||||
IP string
|
||||
Port int `validate:"required"`
|
||||
}
|
||||
|
||||
// GrpcInnerAddr defines the internal gRPC address configuration.
|
||||
//
|
||||
// Fields:
|
||||
// - IP: Internal IP address (required)
|
||||
// - Port: Internal gRPC port (required)
|
||||
type GrpcInnerAddr struct {
|
||||
IP string `validate:"required"`
|
||||
Port int `validate:"required"`
|
||||
}
|
||||
|
||||
// Observability configures observability features including Sentry and tracing.
|
||||
//
|
||||
// Fields:
|
||||
// - Sentry: Error reporting configuration
|
||||
// - Tracing: Distributed tracing configuration
|
||||
type Observability struct {
|
||||
Sentry Sentry
|
||||
Tracing Tracing
|
||||
}
|
||||
|
||||
// Sentry configures Sentry error reporting.
|
||||
//
|
||||
// Fields:
|
||||
// - Enable: Enable Sentry error reporting
|
||||
// - Dsn: Sentry DSN (Data Source Name)
|
||||
// - Environment: Environment name (e.g., "production", "development")
|
||||
// - Tags: Additional tags for Sentry events
|
||||
type Sentry struct {
|
||||
Enable bool
|
||||
Dsn string
|
||||
Environment string
|
||||
Tags map[string]string
|
||||
}
|
||||
|
||||
// Tracing configures distributed tracing (OpenTelemetry).
|
||||
//
|
||||
// Fields:
|
||||
// - Enable: Enable distributed tracing
|
||||
// - Address: Tracing collector endpoint address
|
||||
// - Environment: Environment name for trace attribution
|
||||
// - Attributes: Additional attributes for trace spans
|
||||
type Tracing struct {
|
||||
Enable bool
|
||||
Address string
|
||||
Environment string
|
||||
Attributes map[string]string
|
||||
}
|
||||
|
||||
// MetricsAutodiscovery configures Prometheus metrics auto-discovery.
|
||||
//
|
||||
// Fields:
|
||||
// - Enable: Enable metrics auto-discovery
|
||||
// - Address: Metrics endpoint address (optional, defaults to infra server address)
|
||||
// - AdditionalLabels: Additional labels to attach to metrics
|
||||
type MetricsAutodiscovery struct {
|
||||
Enable bool
|
||||
Address string
|
||||
AdditionalLabels map[string]string
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
stdlog "log"
|
||||
"os"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
// StandaloneBootstrap represents the initialization context for standalone applications.
|
||||
// It embeds BaseBootstrap and provides functionality for reading application configuration
|
||||
// from a local file.
|
||||
//
|
||||
// Use this type for applications that do not require cluster coordination or remote
|
||||
// configuration. Ideal for single-instance services, batch jobs, or development environments.
|
||||
//
|
||||
// Create a StandaloneBootstrap using the NewStandalone() function.
|
||||
type StandaloneBootstrap struct {
|
||||
*BaseBootstrap
|
||||
|
||||
appConfigPath string
|
||||
}
|
||||
|
||||
// NewStandalone creates and initializes a new StandaloneBootstrap instance.
|
||||
//
|
||||
// Parameters:
|
||||
// - moduleVersion: Version string of the module (e.g., "1.0.0")
|
||||
//
|
||||
// Returns a fully initialized StandaloneBootstrap with:
|
||||
// - Application context and logging
|
||||
// - Sentry error reporting
|
||||
// - Infrastructure server with metrics and health endpoints
|
||||
// - Tracing provider (if configured)
|
||||
//
|
||||
// Unlike New(), this function does not initialize cluster client or remote
|
||||
// configuration. It is suitable for standalone applications that read their
|
||||
// configuration from local files.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// boot := bootstrap.NewStandalone("1.2.3")
|
||||
// var cfg MyConfig
|
||||
// if err := boot.ReadConfig(&cfg); err != nil {
|
||||
// // handle configuration error
|
||||
// }
|
||||
func NewStandalone(moduleVersion string) *StandaloneBootstrap {
|
||||
isDev := isOnDevMode()
|
||||
app, err := initApp(isDev)
|
||||
if err != nil {
|
||||
stdlog.Fatal(err)
|
||||
}
|
||||
|
||||
localCfg, err := localConfig[LocalConfig](app.Config())
|
||||
if err != nil {
|
||||
app.Logger().Fatal(app.Context(), errors.WithMessage(err, "create local config"))
|
||||
}
|
||||
sentryHub, err := sentry.NewHubFromConfiguration(sentry.Config{
|
||||
Enable: localCfg.Observability.Sentry.Enable,
|
||||
Dsn: localCfg.Observability.Sentry.Dsn,
|
||||
ModuleName: localCfg.ModuleName,
|
||||
Environment: localCfg.Observability.Sentry.Environment,
|
||||
Tags: localCfg.Observability.Sentry.Tags,
|
||||
InstanceId: localCfg.GrpcOuterAddress.IP,
|
||||
ModuleVersion: moduleVersion,
|
||||
})
|
||||
if err != nil {
|
||||
app.Logger().Fatal(app.Context(), errors.WithMessage(err, "create sentry error reporter"))
|
||||
}
|
||||
|
||||
appConfigPath, err := configPath(isDev, localCfg.RemoteConfigPath)
|
||||
if err != nil {
|
||||
app.Logger().Fatal(app.Context(), errors.WithMessage(err, "get config path"))
|
||||
}
|
||||
|
||||
boot, err := bootstrap(
|
||||
isDev,
|
||||
app,
|
||||
sentryHub,
|
||||
localCfg,
|
||||
moduleVersion,
|
||||
localCfg.GrpcOuterAddress.IP,
|
||||
)
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "create bootstrap")
|
||||
sentryHub.CatchError(app.Context(), err, log.FatalLevel)
|
||||
app.Logger().Fatal(app.Context(), err)
|
||||
}
|
||||
|
||||
return &StandaloneBootstrap{
|
||||
BaseBootstrap: boot,
|
||||
appConfigPath: appConfigPath,
|
||||
}
|
||||
}
|
||||
|
||||
// ReadConfig reads and validates the application configuration from a JSON file.
|
||||
//
|
||||
// Parameters:
|
||||
// - destPtr: Pointer to a struct where the configuration will be unmarshaled
|
||||
//
|
||||
// Returns an error if:
|
||||
// - The configuration file cannot be read
|
||||
// - The JSON cannot be unmarshaled into the destination struct
|
||||
// - The configuration fails validation
|
||||
//
|
||||
// The configuration file path is determined by the RemoteConfigPath field
|
||||
// in the local configuration, or defaults to "./conf/config.json" in dev mode
|
||||
// or "./conf/config.json" relative to the binary in production.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var cfg MyConfig
|
||||
// if err := boot.ReadConfig(&cfg); err != nil {
|
||||
// log.Fatalf("failed to read config: %v", err)
|
||||
// }
|
||||
func (b *StandaloneBootstrap) ReadConfig(destPtr any) error {
|
||||
rawCfg, err := os.ReadFile(b.appConfigPath)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "read file %s", b.appConfigPath)
|
||||
}
|
||||
err = json.Unmarshal(rawCfg, destPtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "unmarshal config")
|
||||
}
|
||||
err = validator.Default.ValidateToError(destPtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "validate config")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"path"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
)
|
||||
|
||||
func isOnDevMode() bool {
|
||||
return strings.ToLower(os.Getenv("APP_MODE")) == "dev"
|
||||
}
|
||||
|
||||
func isOnOfflineMode() bool {
|
||||
return strings.ToLower(os.Getenv("CLUSTER_MODE")) == "offline"
|
||||
}
|
||||
|
||||
func parseConfigServiceHosts(cfg ConfigServiceAddr) ([]string, error) {
|
||||
hosts := strings.Split(cfg.IP, ";")
|
||||
ports := strings.Split(cfg.Port, ";")
|
||||
if len(hosts) != len(ports) {
|
||||
return nil, errors.New("len(hosts) != len(ports)")
|
||||
}
|
||||
arr := make([]string, 0)
|
||||
for i, host := range hosts {
|
||||
arr = append(arr, net.JoinHostPort(host, ports[i]))
|
||||
}
|
||||
return arr, nil
|
||||
}
|
||||
|
||||
func resolveHost(target string) (string, error) {
|
||||
conn, err := net.Dial("udp", target) // nolint:noctx
|
||||
if err != nil {
|
||||
return "", errors.WithMessage(err, "net dial udp")
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
return conn.LocalAddr().(*net.UDPAddr).IP.To4().String(), nil // nolint:forcetypeassert
|
||||
}
|
||||
|
||||
func configFilePath(isDev bool) (string, error) {
|
||||
cfgPath := os.Getenv("APP_CONFIG_PATH")
|
||||
if cfgPath != "" {
|
||||
return cfgPath, nil
|
||||
}
|
||||
|
||||
if isDev {
|
||||
return "./conf/config_dev.yml", nil
|
||||
}
|
||||
|
||||
return relativePathFromBin("config.yml")
|
||||
}
|
||||
|
||||
func migrationsDirPath(isDev bool, cfg LocalConfig) (string, error) {
|
||||
if cfg.MigrationsDirPath != "" {
|
||||
return cfg.MigrationsDirPath, nil
|
||||
}
|
||||
|
||||
if isDev {
|
||||
return "./migrations", nil
|
||||
}
|
||||
|
||||
return relativePathFromBin("migrations")
|
||||
}
|
||||
|
||||
func relativePathFromBin(part string) (string, error) {
|
||||
ex, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", errors.WithMessage(err, "get executable path")
|
||||
}
|
||||
return path.Join(path.Dir(ex), part), nil
|
||||
}
|
||||
|
||||
// nolint:ireturn
|
||||
func localConfig[T any](config *config.Config) (T, error) {
|
||||
localConfig := new(T)
|
||||
err := config.Read(localConfig)
|
||||
if err != nil {
|
||||
var zero T
|
||||
return zero, errors.WithMessage(err, "read local config")
|
||||
}
|
||||
return *localConfig, nil
|
||||
}
|
||||
|
||||
func kitVersion() string {
|
||||
info, ok := debug.ReadBuildInfo()
|
||||
if !ok {
|
||||
return "0.0.0"
|
||||
}
|
||||
for _, dep := range info.Deps {
|
||||
if dep.Path == "github.com/txix-open/isp-kit" {
|
||||
return dep.Version
|
||||
}
|
||||
}
|
||||
return "0.0.0"
|
||||
}
|
||||
|
||||
func defineInfraServerPort(localConfig LocalConfig) int {
|
||||
if localConfig.InfraServerPort != 0 {
|
||||
return localConfig.InfraServerPort
|
||||
}
|
||||
return localConfig.GrpcInnerAddress.Port + 1
|
||||
}
|
||||
+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:
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
# Package `codec`
|
||||
|
||||
Пакет `codec` предоставляет реализации для кодирования и декодирования payload.
|
||||
|
||||
Поддерживаются:
|
||||
|
||||
* потоковое кодирование (`io.Writer` / `io.Reader`)
|
||||
* кодирование/декодирование в память (`[]byte`)
|
||||
* переиспользуемые реализации через pooling (для снижения аллокаций)
|
||||
|
||||
## Types
|
||||
|
||||
### Zstd
|
||||
|
||||
Реализация кодека на базе Zstandard.
|
||||
|
||||
#### `NewZstd(cfg ZstdConfig) *Zstd`
|
||||
|
||||
Создаёт новый экземпляр Zstd-кодека.
|
||||
|
||||
**ZstdConfig:**
|
||||
|
||||
* `Level` — уровень сжатия (`zstd.EncoderLevel`)
|
||||
|
||||
#### `(z *Zstd) EncodingType() string`
|
||||
|
||||
Возвращает тип кодирования:
|
||||
|
||||
```
|
||||
"zstd"
|
||||
```
|
||||
|
||||
## Encoding
|
||||
|
||||
### `(z *Zstd) Encode(w io.Writer) (io.WriteCloser, error)`
|
||||
|
||||
Создаёт потоковый энкодер.
|
||||
|
||||
Используется для записи данных в поток с последующим сжатием.
|
||||
|
||||
Пример:
|
||||
|
||||
```go
|
||||
enc, err := codec.Encode(w)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer enc.Close()
|
||||
|
||||
_, _ = enc.Write(data)
|
||||
```
|
||||
|
||||
### `(z *Zstd) EncodeBytes(data []byte) ([]byte, error)`
|
||||
|
||||
Кодирует байтовый срез в память.
|
||||
|
||||
Используется для случаев, когда не нужен streaming API.
|
||||
|
||||
## Decoding
|
||||
|
||||
### `(z *Zstd) Decode(body io.ReadCloser) (io.ReadCloser, error)`
|
||||
|
||||
Оборачивает входной поток декодером.
|
||||
|
||||
Возвращаемый `ReadCloser` автоматически декодирует данные при чтении.
|
||||
|
||||
|
||||
### `(z *Zstd) DecodeBytes(data []byte) ([]byte, error)`
|
||||
|
||||
Декодирует данные из памяти.
|
||||
|
||||
## Internals
|
||||
|
||||
Пакет использует pooling энкодеров (`sync.Pool`) для снижения нагрузки на GC.
|
||||
|
||||
Основные оптимизации:
|
||||
|
||||
* повторное использование `zstd.Encoder`
|
||||
* минимизация аллокаций при streaming encode
|
||||
* разделение streaming и byte API
|
||||
|
||||
## Usage
|
||||
|
||||
### HTTP / middleware example
|
||||
|
||||
```go
|
||||
codec := codec.Default
|
||||
|
||||
encoded, err := codec.EncodeBytes(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
|
||||
### Decode example
|
||||
|
||||
```go
|
||||
codec := codec.Default
|
||||
|
||||
decoded, err := codec.DecodeBytes(encoded)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// Package codec provides abstractions and implementations for payload
|
||||
// encoding and decoding.
|
||||
//
|
||||
// The package defines common interfaces for streaming and byte-based codecs
|
||||
// that can be used by transports such as HTTP, gRPC, and AMQP. It also
|
||||
// provides a reusable Zstandard (zstd) implementation with encoder pooling
|
||||
// for efficient compression.
|
||||
//
|
||||
// Codecs support both streaming APIs (io.Reader/io.Writer) and in-memory
|
||||
// byte slice operations, allowing the same implementation to be reused
|
||||
// across different transports and middleware.
|
||||
//
|
||||
// Example usage:
|
||||
//
|
||||
// codec := codec.Default
|
||||
//
|
||||
// // Encode bytes.
|
||||
// encoded, err := codec.EncodeBytes(data)
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
//
|
||||
// // Decode bytes.
|
||||
// plain, err := codec.DecodeBytes(encoded)
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
package codec
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package codec
|
||||
|
||||
const DefaultEncodeThreshold = 128 * 1024
|
||||
|
||||
var (
|
||||
Default Codec = NewZstd(ZstdConfig{
|
||||
Level: ZstdLevel(ZstdSpeedDefault),
|
||||
})
|
||||
)
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package codec
|
||||
|
||||
import "io"
|
||||
|
||||
type Codec interface {
|
||||
Type() string
|
||||
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
|
||||
Encode(w io.Writer) (io.WriteCloser, error)
|
||||
Decode(rc io.ReadCloser) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
type decoder interface {
|
||||
io.Reader
|
||||
Reset(r io.Reader) error
|
||||
}
|
||||
|
||||
type encoder interface {
|
||||
io.Writer
|
||||
Close() error
|
||||
Reset(w io.Writer)
|
||||
}
|
||||
|
||||
type putter interface {
|
||||
Put(x any)
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package codec
|
||||
|
||||
import "io"
|
||||
|
||||
type readCloser struct {
|
||||
decoder decoder
|
||||
pool putter
|
||||
body io.Closer
|
||||
}
|
||||
|
||||
func (rc *readCloser) Read(p []byte) (n int, err error) {
|
||||
return rc.decoder.Read(p)
|
||||
}
|
||||
|
||||
func (rc *readCloser) Close() error {
|
||||
// reset to avoid leaking state between uses
|
||||
_ = rc.decoder.Reset(nil)
|
||||
|
||||
// return to pool
|
||||
rc.pool.Put(rc.decoder)
|
||||
rc.decoder = nil
|
||||
|
||||
return rc.body.Close()
|
||||
}
|
||||
|
||||
type writeCloser struct {
|
||||
encoder encoder
|
||||
pool putter
|
||||
}
|
||||
|
||||
func (wc *writeCloser) Write(p []byte) (int, error) {
|
||||
return wc.encoder.Write(p)
|
||||
}
|
||||
|
||||
func (wc *writeCloser) Close() error {
|
||||
err := wc.encoder.Close()
|
||||
|
||||
// reset to avoid leaking state between uses
|
||||
wc.encoder.Reset(nil)
|
||||
|
||||
// return to pool
|
||||
wc.pool.Put(wc.encoder)
|
||||
wc.encoder = nil
|
||||
|
||||
return err
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package codec
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sync"
|
||||
|
||||
"github.com/klauspost/compress/zstd"
|
||||
)
|
||||
|
||||
// Level is an alias for zstd.EncoderLevel representing encoder compression levels.
|
||||
type ZstdLevel zstd.EncoderLevel
|
||||
|
||||
const (
|
||||
ZstdSpeedFastest = zstd.SpeedFastest
|
||||
ZstdSpeedDefault = zstd.SpeedDefault
|
||||
ZstdSpeedBetterCompression = zstd.SpeedBetterCompression
|
||||
ZstdSpeedBestCompression = zstd.SpeedBestCompression
|
||||
)
|
||||
|
||||
type ZstdConfig struct {
|
||||
Level ZstdLevel
|
||||
}
|
||||
|
||||
type Zstd struct {
|
||||
encoderPool sync.Pool
|
||||
decoderPool sync.Pool
|
||||
}
|
||||
|
||||
// NewZstd create instance of zstd
|
||||
func NewZstd(cfg ZstdConfig) *Zstd {
|
||||
encoderLevel := zstd.EncoderLevel(cfg.Level)
|
||||
return &Zstd{
|
||||
encoderPool: sync.Pool{
|
||||
New: func() any {
|
||||
enc, _ := zstd.NewWriter(nil, zstd.WithEncoderLevel(encoderLevel))
|
||||
return enc
|
||||
},
|
||||
},
|
||||
decoderPool: sync.Pool{
|
||||
New: func() any {
|
||||
dec, _ := zstd.NewReader(nil)
|
||||
return dec
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (*Zstd) Type() string {
|
||||
return "zstd"
|
||||
}
|
||||
|
||||
// Encode data using zstd.
|
||||
func (m *Zstd) Encode(w io.Writer) (io.WriteCloser, error) {
|
||||
encoder := m.encoderPool.Get().(*zstd.Encoder) //nolint:forcetypeassert
|
||||
|
||||
// Reset encoder to new destination
|
||||
encoder.Reset(w)
|
||||
|
||||
return &writeCloser{
|
||||
encoder: encoder,
|
||||
pool: &m.encoderPool,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// EncodeBytes encode data using zstd.
|
||||
func (m *Zstd) EncodeBytes(data []byte) ([]byte, error) {
|
||||
encoder := m.encoderPool.Get().(*zstd.Encoder) //nolint:forcetypeassert
|
||||
defer m.encoderPool.Put(encoder)
|
||||
|
||||
return encoder.EncodeAll(data, nil), nil
|
||||
}
|
||||
|
||||
// Decode wraps body with a zstd decoder.
|
||||
func (m *Zstd) Decode(body io.ReadCloser) (io.ReadCloser, error) {
|
||||
decoder := m.decoderPool.Get().(*zstd.Decoder) //nolint:forcetypeassert
|
||||
|
||||
err := decoder.Reset(body)
|
||||
if err != nil {
|
||||
m.decoderPool.Put(decoder)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &readCloser{
|
||||
decoder: decoder,
|
||||
pool: &m.decoderPool,
|
||||
body: body,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DecodeBytes decodes bytes body using zstd.
|
||||
func (m *Zstd) DecodeBytes(data []byte) ([]byte, error) {
|
||||
decoder := m.decoderPool.Get().(*zstd.Decoder) //nolint:forcetypeassert
|
||||
defer m.decoderPool.Put(decoder)
|
||||
|
||||
return decoder.DecodeAll(data, nil)
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
# Package `common_endpoints`
|
||||
|
||||
Пакет `common_endpoints` предназначен для формирования набора стандартных (общих) эндпоинтов сервиса.
|
||||
|
||||
## Types
|
||||
|
||||
### CommonEndpointOption
|
||||
|
||||
Тип `CommonEndpointOption` представляет собой функциональную опцию для конфигурации набора общих эндпоинтов.
|
||||
|
||||
Используется для модификации внутренней конфигурации `commonEndpointsCfg`.
|
||||
|
||||
```go
|
||||
type CommonEndpointOption func(cfg *commonEndpointsCfg)
|
||||
```
|
||||
|
||||
## Functions
|
||||
|
||||
### `CommonEndpoints(basePath string, opts ...CommonEndpointOption) []cluster.EndpointDescriptor`
|
||||
|
||||
Создаёт и возвращает список `cluster.EndpointDescriptor` на основе переданных опций.
|
||||
|
||||
* `basePath` — базовый путь для всех создаваемых эндпоинтов.
|
||||
* `opts` — набор опций конфигурации (например, добавление swagger-endpoint).
|
||||
|
||||
### `WithSwaggerEndpoint(swagger []byte) CommonEndpointOption`
|
||||
|
||||
Добавляет endpoint для получения Swagger-спецификации.
|
||||
|
||||
* `swagger` — содержимое swagger-файла в виде `[]byte`, если он пустой, endpoint не будет добавлен.
|
||||
* Данные автоматически кодируются в Base64 перед возвратом клиенту.
|
||||
|
||||
Endpoint будет доступен по пути:
|
||||
|
||||
```
|
||||
{basePath}/swagger
|
||||
```
|
||||
|
||||
и будет иметь параметры:
|
||||
|
||||
* HTTP метод: `GET`
|
||||
* `UserAuthRequired = false`
|
||||
* `Inner = false`
|
||||
|
||||
|
||||
## Internal behavior
|
||||
|
||||
### Swagger endpoint
|
||||
|
||||
Swagger endpoint формируется функцией `swaggerEndpoint` и возвращает `cluster.EndpointDescriptor` со следующими характеристиками:
|
||||
|
||||
* Path: `basePath + "/swagger"`
|
||||
* Handler: возвращает Base64-кодированную строку swagger-файла
|
||||
* Не требует аутентификации пользователя
|
||||
* Использует метод `GET`
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/common_endpoints"
|
||||
)
|
||||
|
||||
func main() {
|
||||
swaggerBytes, _ := os.ReadFile("swagger.json")
|
||||
|
||||
endpoints := common_endpoints.CommonEndpoints(
|
||||
"/api",
|
||||
common_endpoints.WithSwaggerEndpoint(swaggerBytes),
|
||||
)
|
||||
|
||||
var descriptors []cluster.EndpointDescriptor
|
||||
descriptors = append(descriptors, endpoints...)
|
||||
|
||||
// передаём descriptors в config сервис/router
|
||||
}
|
||||
```
|
||||
|
||||
### Without swagger endpoint
|
||||
|
||||
```go
|
||||
endpoints := common_endpoints.CommonEndpoints("/api")
|
||||
// endpoints будет пустым
|
||||
```
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package common_endpoints
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// commonEndpointsCfg holds configuration for common endpoints.
|
||||
type commonEndpointsCfg struct {
|
||||
swagger []byte
|
||||
}
|
||||
|
||||
// CommonEndpoints creates a slice of cluster.EndpointDescriptor for common service endpoints.
|
||||
// It accepts a basePath for URL path prefix and variadic CommonEndpointOption functions to configure endpoints.
|
||||
// Returns a slice of endpoint descriptors that can be registered with a cluster router.
|
||||
// Currently supports Swagger documentation endpoint when configured via WithSwaggerEndpoint.
|
||||
func CommonEndpoints(basePath string, opts ...CommonEndpointOption) []cluster.EndpointDescriptor {
|
||||
cfg := &commonEndpointsCfg{}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
endpoints := make([]cluster.EndpointDescriptor, 0)
|
||||
if len(cfg.swagger) > 0 {
|
||||
endpoints = append(endpoints, swaggerEndpoint(basePath, cfg.swagger))
|
||||
}
|
||||
|
||||
return endpoints
|
||||
}
|
||||
|
||||
// swaggerEndpoint creates an endpoint descriptor for serving Swagger documentation.
|
||||
// The endpoint is registered at basePath+"/swagger" and returns the swagger JSON on HTTP GET.
|
||||
// User authentication is not required for this endpoint.
|
||||
func swaggerEndpoint(basePath string, swaggerJson json.RawMessage) cluster.EndpointDescriptor {
|
||||
return cluster.EndpointDescriptor{
|
||||
Path: basePath + "/swagger",
|
||||
Inner: false,
|
||||
UserAuthRequired: false,
|
||||
HttpMethod: http.MethodGet,
|
||||
Handler: func() json.RawMessage {
|
||||
return swaggerJson
|
||||
},
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// Package common_endpoints provides common HTTP endpoint descriptors for services.
|
||||
// It offers a simple way to register standard endpoints like Swagger documentation.
|
||||
package common_endpoints
|
||||
|
||||
// CommonEndpointOption is a functional option for configuring commonEndpointsCfg.
|
||||
type CommonEndpointOption func(cfg *commonEndpointsCfg)
|
||||
|
||||
// WithSwaggerEndpoint configures the CommonEndpoints builder to include a Swagger endpoint.
|
||||
// The swagger parameter should contain the JSON-formatted Swagger specification.
|
||||
// The endpoint is exposed at {basePath}/swagger and is accessible via HTTP GET.
|
||||
func WithSwaggerEndpoint(swagger []byte) CommonEndpointOption {
|
||||
return func(cfg *commonEndpointsCfg) {
|
||||
cfg.swagger = swagger
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
# Package `config`
|
||||
|
||||
Пакет `config` предназначен для работы с конфигурацией приложения с поддержкой:
|
||||
|
||||
- множественных источников данных (yaml, переменные окружения, кастомные источники)
|
||||
- валидации конфигурации
|
||||
- типизированного доступа к параметрам
|
||||
|
||||
## Types
|
||||
|
||||
### Config
|
||||
|
||||
Основная структура для работы с конфигурацией.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(opts ...Option) (*Config, error)`
|
||||
|
||||
Конструктор конфигурации с опциями:
|
||||
|
||||
- `WithExtraSource` - добавить дополнительные источники, реализующие интерфейс `Source`
|
||||
- `WithEnvPrefix` - установить префикс для переменных окружения
|
||||
- `WithValidator` - установить валидатор конфигурации, реализующий интерфейс `Validator`
|
||||
|
||||
#### `(c *Config) Set(key string, value any)`
|
||||
|
||||
Установить новое/перезаписать существующее значение параметра конфигурации.
|
||||
|
||||
#### `(c *Config) Delete(key string)`
|
||||
|
||||
Удалить параметра конфигурации.
|
||||
|
||||
#### `(c *Config) Mandatory() Mandatory`
|
||||
|
||||
Получить обязательные параметры конфигурации.
|
||||
|
||||
#### `(c *Config) Optional() Optional`
|
||||
|
||||
Получить опциональные параметры конфигурации (возвращает значения по-умолчанию).
|
||||
|
||||
#### `(c *Config) Read(ptr any) error`
|
||||
|
||||
Спарсить всю конфигурацию и записать ее по переданному указателю. Если был установлен валидатор, то спаршенная конфигурация будет провалидирована.
|
||||
|
||||
### YamlFileSource
|
||||
|
||||
Создание источника конфигурации из yaml-файла.
|
||||
|
||||
#### `(y YamlFileSource) Config() (map[string]string, error)`
|
||||
Получить конфигурацию из yaml-файла в виде мэпы.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/config"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
type appConfig struct {
|
||||
Host string `validate:"required"`
|
||||
Port int `validate:"required"`
|
||||
Timeout time.Duration
|
||||
Database struct {
|
||||
Dsn string
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
cfg, err := config.New(
|
||||
config.WithExtraSource(config.NewYamlConfig("config.yml")),
|
||||
config.WithEnvPrefix("APP_"),
|
||||
config.WithValidator(validator.Default),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var actual appConfig
|
||||
err = cfg.Read(&actual)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
/* access to parameters */
|
||||
port := cfg.Mandatory().Int("port")
|
||||
timeout := cfg.Optional().Duration("timeout", 5*time.Second)
|
||||
}
|
||||
|
||||
```
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
// Package config provides a flexible configuration management system with support for
|
||||
// multiple sources, environment variable overrides, and type-safe value retrieval.
|
||||
//
|
||||
// The package supports reading configuration from YAML files, environment variables,
|
||||
// and custom sources. Configuration values can be accessed as mandatory (required) or
|
||||
// optional (with defaults) values for common types like strings, integers, booleans,
|
||||
// and durations.
|
||||
//
|
||||
// Example usage:
|
||||
//
|
||||
// cfg, err := config.New(
|
||||
// config.WithEnvPrefix("MYAPP"),
|
||||
// config.WithExtraSource(config.NewYamlConfig("config.yaml")),
|
||||
// )
|
||||
// if err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
//
|
||||
// // Read mandatory values
|
||||
// host, err := cfg.Mandatory().String("server.host")
|
||||
// port, err := cfg.Mandatory().Int("server.port")
|
||||
//
|
||||
// // Read optional values with defaults
|
||||
// timeout := cfg.Optional().Duration("server.timeout", 30*time.Second)
|
||||
//
|
||||
// // Decode into a struct
|
||||
// var settings ServerSettings
|
||||
// if err := cfg.Read(&settings); err != nil {
|
||||
// log.Fatal(err)
|
||||
// }
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/mitchellh/mapstructure"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bellows"
|
||||
)
|
||||
|
||||
// Validator defines an interface for validating configuration values.
|
||||
// Implementations should return an error if the configuration structure is invalid.
|
||||
type Validator interface {
|
||||
ValidateToError(value any) error
|
||||
}
|
||||
|
||||
// Config manages application configuration from multiple sources.
|
||||
// It supports loading from YAML files, environment variables, and custom sources,
|
||||
// with automatic normalization of keys and value expansion.
|
||||
type Config struct {
|
||||
config map[string]string
|
||||
optional Optional
|
||||
mandatory Mandatory
|
||||
|
||||
envPrefix string
|
||||
validator Validator
|
||||
extraSources []Source
|
||||
}
|
||||
|
||||
// New creates a new Config instance with the provided options.
|
||||
// It loads configuration from extra sources and environment variables.
|
||||
// Environment variables are filtered by the envPrefix if set.
|
||||
// Keys are normalized to lowercase for case-insensitive access.
|
||||
// Returns an error if any extra source fails to load.
|
||||
func New(opts ...Option) (*Config, error) {
|
||||
config := map[string]string{}
|
||||
mandatory := Mandatory{config: config}
|
||||
optional := Optional{m: mandatory}
|
||||
cfg := &Config{
|
||||
config: config,
|
||||
mandatory: mandatory,
|
||||
optional: optional,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
for _, source := range cfg.extraSources {
|
||||
extraConfig, err := source.Config()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "read extra source, %T", source)
|
||||
}
|
||||
for key, value := range extraConfig {
|
||||
config[normalizeKey(key)] = value
|
||||
}
|
||||
}
|
||||
|
||||
for _, pairs := range os.Environ() {
|
||||
parts := strings.Split(pairs, "=")
|
||||
key := normalizeKey(parts[0])
|
||||
prefix := normalizeKey(cfg.envPrefix)
|
||||
if prefix != "" && !strings.HasPrefix(key, prefix) {
|
||||
continue
|
||||
}
|
||||
key = key[len(prefix):]
|
||||
config[key] = strings.Join(parts[1:], "")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Set assigns a value to the specified key.
|
||||
// The value is converted to a string representation.
|
||||
func (c *Config) Set(key string, value any) {
|
||||
c.config[key] = fmt.Sprintf("%v", value)
|
||||
}
|
||||
|
||||
// Delete removes a value by configuration key.
|
||||
func (c *Config) Delete(key string) {
|
||||
delete(c.config, key)
|
||||
}
|
||||
|
||||
// Mandatory returns a Mandatory accessor for required configuration values.
|
||||
// Values accessed through Mandatory will return an error if the key is not found.
|
||||
func (c *Config) Mandatory() Mandatory {
|
||||
return c.mandatory
|
||||
}
|
||||
|
||||
// Optional returns an Optional accessor for configuration values with defaults.
|
||||
// Values accessed through Optional will return the provided default if the key is not found.
|
||||
func (c *Config) Optional() Optional {
|
||||
return c.optional
|
||||
}
|
||||
|
||||
// Read decodes the configuration into the provided pointer.
|
||||
// It uses mapstructure for decoding with support for type conversions (e.g., string to time.Duration).
|
||||
// If a Validator is configured, it validates the decoded structure before returning.
|
||||
// Returns an error if decoding or validation fails.
|
||||
func (c *Config) Read(ptr any) error {
|
||||
decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
|
||||
DecodeHook: mapstructure.ComposeDecodeHookFunc(mapstructure.StringToTimeDurationHookFunc()),
|
||||
WeaklyTypedInput: true,
|
||||
Result: ptr,
|
||||
Squash: true,
|
||||
})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "mapstructure new decoder")
|
||||
}
|
||||
|
||||
expanded := make(map[string]any)
|
||||
for key, value := range c.config {
|
||||
expanded[key] = value
|
||||
}
|
||||
toDecode := bellows.Expand(expanded)
|
||||
err = decoder.Decode(toDecode)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "decode config")
|
||||
}
|
||||
|
||||
if c.validator != nil {
|
||||
err := c.validator.ValidateToError(ptr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "validate config")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeKey(key string) string {
|
||||
return strings.ToLower(key)
|
||||
}
|
||||
|
||||
// nolint:ireturn
|
||||
func get[T any](config map[string]string, key string, valueMapper func(value string) (T, error)) (T, error) {
|
||||
var ret T
|
||||
value, ok := config[normalizeKey(key)]
|
||||
if !ok {
|
||||
return ret, errors.Errorf("%s is expected in config", key)
|
||||
}
|
||||
mapped, err := valueMapper(value)
|
||||
if err != nil {
|
||||
return ret, err
|
||||
}
|
||||
|
||||
return mapped, nil
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Mandatory provides access to required configuration values.
|
||||
// All methods return an error if the requested key is not found or cannot be parsed.
|
||||
// Keys are normalized to lowercase for case-insensitive access.
|
||||
type Mandatory struct {
|
||||
config map[string]string
|
||||
}
|
||||
|
||||
// Int retrieves an integer configuration value.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (m Mandatory) Int(key string) (int, error) {
|
||||
value, err := get[int](m.config, key, strconv.Atoi)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// String retrieves a string configuration value.
|
||||
// Returns an error if the key is not found.
|
||||
func (m Mandatory) String(key string) (string, error) {
|
||||
value, err := get[string](m.config, key, func(value string) (string, error) {
|
||||
return value, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// Bool retrieves a boolean configuration value.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as a boolean.
|
||||
// Accepts "1", "t", "T", "true", "TRUE", "True", "0", "f", "F", "false", "FALSE", "False".
|
||||
func (m Mandatory) Bool(key string) (bool, error) {
|
||||
value, err := get[bool](m.config, key, strconv.ParseBool)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// Duration retrieves a time.Duration configuration value.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as a duration.
|
||||
// Accepts formats like "30s", "1m", "1h30m" as parsed by time.ParseDuration.
|
||||
func (m Mandatory) Duration(key string) (time.Duration, error) {
|
||||
value, err := get[time.Duration](m.config, key, time.ParseDuration)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Optional provides access to configuration values with defaults.
|
||||
// All methods return the provided default value if the key is not found or cannot be parsed.
|
||||
// Unlike Mandatory, these methods never return errors.
|
||||
type Optional struct {
|
||||
m Mandatory
|
||||
}
|
||||
|
||||
// Int retrieves an integer configuration value or returns the default.
|
||||
// Returns defValue if the key is not found or the value cannot be parsed as an integer.
|
||||
func (o Optional) Int(key string, defValue int) int {
|
||||
value, err := o.m.Int(key)
|
||||
if err != nil {
|
||||
return defValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// String retrieves a string configuration value or returns the default.
|
||||
// Returns defValue if the key is not found.
|
||||
func (o Optional) String(key string, defValue string) string {
|
||||
value, err := o.m.String(key)
|
||||
if err != nil {
|
||||
return defValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Bool retrieves a boolean configuration value or returns the default.
|
||||
// Returns defValue if the key is not found or the value cannot be parsed as a boolean.
|
||||
func (o Optional) Bool(key string, defValue bool) bool {
|
||||
value, err := o.m.Bool(key)
|
||||
if err != nil {
|
||||
return defValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Duration retrieves a time.Duration configuration value or returns the default.
|
||||
// Returns defValue if the key is not found or the value cannot be parsed as a duration.
|
||||
func (o Optional) Duration(key string, defValue time.Duration) time.Duration {
|
||||
value, err := o.m.Duration(key)
|
||||
if err != nil {
|
||||
return defValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package config
|
||||
|
||||
// Option is a function type that configures a Config instance.
|
||||
// Used with the functional options pattern to customize Config behavior.
|
||||
type Option func(l *Config)
|
||||
|
||||
// WithExtraSource adds a configuration source to be loaded before environment variables.
|
||||
// Multiple sources can be added and are processed in order.
|
||||
func WithExtraSource(source Source) Option {
|
||||
return func(config *Config) {
|
||||
config.extraSources = append(config.extraSources, source)
|
||||
}
|
||||
}
|
||||
|
||||
// WithEnvPrefix sets the prefix for environment variable filtering.
|
||||
// Only environment variables starting with this prefix (case-insensitive) will be loaded.
|
||||
// The prefix is stripped from the key name when stored.
|
||||
// Example: WithEnvPrefix("MYAPP") will load MYAPP_HOST as "host".
|
||||
func WithEnvPrefix(prefix string) Option {
|
||||
return func(config *Config) {
|
||||
config.envPrefix = prefix
|
||||
}
|
||||
}
|
||||
|
||||
// WithValidator sets a Validator for post-decoding configuration validation.
|
||||
// The validator is called after Read() decodes the configuration into a struct.
|
||||
func WithValidator(validator Validator) Option {
|
||||
return func(config *Config) {
|
||||
config.validator = validator
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bellows"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Source defines an interface for configuration providers.
|
||||
// Implementations should return a flat map of key-value pairs.
|
||||
// Nested YAML structures are automatically flattened using dot notation.
|
||||
type Source interface {
|
||||
Config() (map[string]string, error)
|
||||
}
|
||||
|
||||
// YamlFileSource is a configuration source that reads from a YAML file.
|
||||
// It supports nested structures which are flattened into dot-notation keys.
|
||||
// For example, a YAML key "server.host" will be stored as "server.host".
|
||||
type YamlFileSource struct {
|
||||
file string
|
||||
}
|
||||
|
||||
// NewYamlConfig creates a new YamlFileSource for the specified YAML file.
|
||||
// The file path can be absolute or relative to the working directory.
|
||||
func NewYamlConfig(file string) YamlFileSource {
|
||||
return YamlFileSource{file: file}
|
||||
}
|
||||
|
||||
// Config loads and parses the YAML file, returning a flat map of configuration values.
|
||||
// Nested YAML structures are flattened using bellows.Flatten.
|
||||
// All values are converted to strings.
|
||||
// Returns an error if the file cannot be opened or parsed as valid YAML.
|
||||
func (y YamlFileSource) Config() (map[string]string, error) {
|
||||
f, err := os.Open(y.file)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "open %s", y.file)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
fileProps := make(map[string]any)
|
||||
err = yaml.NewDecoder(f).Decode(&fileProps)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "yaml decode")
|
||||
}
|
||||
|
||||
flatten := bellows.Flatten(fileProps)
|
||||
config := map[string]string{}
|
||||
for key, value := range flatten {
|
||||
config[key] = fmt.Sprintf("%v", value)
|
||||
}
|
||||
return config, nil
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
# Package `db`
|
||||
|
||||
Пакет `db` предоставляет клиент-обёртку над библиотекой [`sqlx`](https://github.com/jmoiron/sqlx) с интеграцией `pgx` для работы с PostgreSQL. Реализует
|
||||
функциональность подключения к базе данных, выполнения запросов, транзакций и настройки трассировки запросов
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Основная структура-клиент для взаимодействия с базой данных PostgreSQL
|
||||
|
||||
**Methods:**
|
||||
|
||||
Содержит все методы клиента-предшественника из [`sqlx`](https://github.com/jmoiron/sqlx).
|
||||
|
||||
#### `Open(ctx context.Context, dsn string, opts ...Option) (*Client, error)`
|
||||
|
||||
Создать подключение к базе данных по переданному dsn. Доступные опции:
|
||||
- `WithQueryTracer(tracers ...pgx.QueryTracer) Option` – трассировка запросов с объектами реализующими интерфейс `pgx.QueryTracer`.
|
||||
|
||||
#### `(db *Client) Select(ctx context.Context, ptr any, query string, args ...any) error`
|
||||
|
||||
Выполнить sql-запрос с возвращением данных из БД. Использует стандартные плейсхолдеры для позиционирования параметров.
|
||||
|
||||
#### `(db *Client) SelectRow(ctx context.Context, ptr any, query string, args ...any) error`
|
||||
|
||||
Выполнить sql-запрос с возвращением одной строки данных из БД. Использует стандартные плейсхолдеры для позиционирования параметров.
|
||||
|
||||
#### `(db *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error)`
|
||||
|
||||
Выполнить sql-запрос без возврата данных из БД. Использует стандартные плейсхолдеры для позиционирования параметров.
|
||||
|
||||
#### `(db *Client) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error)`
|
||||
|
||||
Выполнить sql-запрос без возврата данных из БД. Позволяет использовать имена полей вместо плейсхолдеров для позиционирования параметров в sql-запросе.
|
||||
|
||||
#### `(db *Client) RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) (err error)`
|
||||
|
||||
Выполнить функцию `txFunc` в рамках транзакции. Доступны опции:
|
||||
- `IsolationLevel(level sql.IsolationLevel) TxOption` – изменить уровень изоляции транзакции
|
||||
- `ReadOnly() TxOption` – режим транзакции только на чтение
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Name string
|
||||
IsActive bool
|
||||
}
|
||||
|
||||
func main() {
|
||||
ctx := context.Background()
|
||||
client, err := db.Open(ctx, "postgres://user:pass@localhost:5432/db")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var users []user
|
||||
err = client.Select(ctx, &users, "SELECT * FROM users WHERE is_active = $1", true) /* read data */
|
||||
|
||||
/* transaction */
|
||||
err = client.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
|
||||
res, err := tx.Exec(ctx, "UPDATE accounts SET balance = balance - $1", 100)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
/* put here some business logic */
|
||||
return nil
|
||||
}, db.IsolationLevel(sql.LevelRepeatableRead))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package db
|
||||
|
||||
import "time"
|
||||
|
||||
type ConnectionSettings struct {
|
||||
maxConns int32
|
||||
minIdleConns int32
|
||||
maxConnsIdleTime time.Duration
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
// Package db provides a PostgreSQL database client wrapper that integrates
|
||||
// sqlx with pgx, offering transaction support, query tracing, and automatic
|
||||
// snake_case field mapping for struct tags.
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
// Client wraps a sqlx.DB instance with additional functionality for query
|
||||
// tracing and transaction management. It is safe for concurrent use.
|
||||
type Client struct {
|
||||
*sqlx.DB
|
||||
|
||||
pool *pgxpool.Pool
|
||||
queryTracers tracers
|
||||
connSettings ConnectionSettings
|
||||
}
|
||||
|
||||
// Open establishes a connection to a PostgreSQL database using the provided DSN.
|
||||
// It applies the given options, validates the connection, and returns a Client.
|
||||
// Returns an error if the configuration cannot be parsed or the connection fails.
|
||||
func Open(ctx context.Context, dsn string, opts ...Option) (*Client, error) {
|
||||
db := &Client{}
|
||||
for _, opt := range opts {
|
||||
opt(db)
|
||||
}
|
||||
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "parse config")
|
||||
}
|
||||
cfg.ConnConfig.Tracer = db.queryTracers
|
||||
cfg.MaxConns = db.connSettings.maxConns
|
||||
cfg.MinIdleConns = db.connSettings.minIdleConns
|
||||
cfg.MaxConnIdleTime = db.connSettings.maxConnsIdleTime
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create pool")
|
||||
}
|
||||
sqlDb := stdlib.OpenDBFromPool(pool)
|
||||
|
||||
pgDb := sqlx.NewDb(sqlDb, "pgx")
|
||||
pgDb.MapperFunc(ToSnakeCase)
|
||||
err = pgDb.PingContext(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "ping database")
|
||||
}
|
||||
|
||||
db.DB = pgDb
|
||||
db.pool = pool
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// Close closes SQL wrapper and underlying connection pool.
|
||||
func (db *Client) Close() error {
|
||||
err := db.DB.Close()
|
||||
db.pool.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
// RunInTransaction executes the provided function within a database transaction.
|
||||
// It automatically commits on success and rolls back on error or panic.
|
||||
// Transaction options can be provided to configure isolation level and other settings.
|
||||
// Returns an error if the transaction cannot be started, committed, or rolled back.
|
||||
func (db *Client) RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) (err error) {
|
||||
options := &txOptions{}
|
||||
for _, opt := range opts {
|
||||
opt(options)
|
||||
}
|
||||
tx, err := db.BeginTxx(
|
||||
txContext(ctx, options.metricsLabel),
|
||||
options.nativeOpts,
|
||||
)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "begin transaction")
|
||||
}
|
||||
defer func() {
|
||||
p := recover()
|
||||
if p != nil { // rollback and repanic
|
||||
_ = tx.Rollback()
|
||||
panic(p)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
rbErr := tx.Rollback()
|
||||
if rbErr != nil {
|
||||
err = errors.WithMessage(err, rbErr.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = tx.Commit()
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "commit tx")
|
||||
}
|
||||
}()
|
||||
|
||||
return txFunc(ctx, &Tx{tx})
|
||||
}
|
||||
|
||||
// Select executes a query that returns multiple rows and scans them into the provided pointer.
|
||||
// The pointer must be a slice or a type that sqlx can scan into.
|
||||
// Returns an error if the query fails or the scan is unsuccessful.
|
||||
func (db *Client) Select(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
return db.SelectContext(ctx, ptr, query, args...)
|
||||
}
|
||||
|
||||
// SelectRow executes a query that returns a single row and scans it into the provided pointer.
|
||||
// Returns an error if the query fails, no rows are returned, or the scan is unsuccessful.
|
||||
func (db *Client) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
return db.GetContext(ctx, ptr, query, args...)
|
||||
}
|
||||
|
||||
// Exec executes a query that does not return rows, such as INSERT, UPDATE, or DELETE.
|
||||
// Returns the sql.Result and any error that occurs during execution.
|
||||
func (db *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
return db.ExecContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
// ExecNamed executes a named-parameter query that does not return rows.
|
||||
// The arg parameter should be a struct or map that provides values for named placeholders.
|
||||
// Returns the sql.Result and any error that occurs during execution.
|
||||
func (db *Client) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
|
||||
return db.NamedExecContext(ctx, query, arg)
|
||||
}
|
||||
|
||||
// IsReadOnly checks whether the current database connection is in read-only mode.
|
||||
// Returns true if the connection is read-only, false otherwise.
|
||||
// Returns an error if the query fails.
|
||||
func (db *Client) IsReadOnly(ctx context.Context) (bool, error) {
|
||||
var isReadOnly string
|
||||
err := db.QueryRowContext(ctx, "SHOW transaction_read_only").Scan(&isReadOnly)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return isReadOnly == "on", nil
|
||||
}
|
||||
|
||||
func (db *Client) Stat() *pgxpool.Stat {
|
||||
return db.pool.Stat()
|
||||
}
|
||||
|
||||
func txContext(ctx context.Context, label string) context.Context {
|
||||
if label == "" {
|
||||
return ctx
|
||||
}
|
||||
return sql_metrics.OperationLabelToContext(ctx, label)
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
// DB defines the interface for basic database operations.
|
||||
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)
|
||||
}
|
||||
|
||||
// Transactional defines the interface for transactional database operations.
|
||||
type Transactional interface {
|
||||
RunInTransaction(ctx context.Context, txFunc TxFunc, opts ...TxOption) error
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package db
|
||||
|
||||
import "github.com/iancoleman/strcase"
|
||||
|
||||
// ToSnakeCase converts a string from camelCase or PascalCase to snake_case.
|
||||
// This is used for automatic mapping of struct field names to database column names.
|
||||
func ToSnakeCase(s string) string {
|
||||
return strcase.ToSnake(s)
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// Option is a function that configures a Client.
|
||||
type Option func(db *Client)
|
||||
|
||||
// WithQueryTracer registers one or more pgx QueryTracers for query lifecycle events.
|
||||
// Multiple tracers are invoked sequentially for each query.
|
||||
func WithQueryTracer(tracers ...pgx.QueryTracer) Option {
|
||||
return func(db *Client) {
|
||||
db.queryTracers = append(db.queryTracers, tracers...)
|
||||
}
|
||||
}
|
||||
|
||||
func WithMaxOpenConns(maxConns int32) Option {
|
||||
return func(db *Client) {
|
||||
db.connSettings.maxConns = maxConns
|
||||
}
|
||||
}
|
||||
|
||||
func WithMinIdleConns(minIdleConns int32) Option {
|
||||
return func(db *Client) {
|
||||
db.connSettings.minIdleConns = minIdleConns
|
||||
}
|
||||
}
|
||||
|
||||
func WithMaxConnIdleTime(maxIdleTime time.Duration) Option {
|
||||
return func(db *Client) {
|
||||
db.connSettings.maxConnsIdleTime = maxIdleTime
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
// Package query provides a fluent query builder for PostgreSQL using the
|
||||
// Masterminds/squirrel library with dollar-sign placeholder formatting.
|
||||
package query
|
||||
|
||||
import "github.com/Masterminds/squirrel"
|
||||
|
||||
// Query is a fluent query builder that wraps squirrel.StatementBuilderType
|
||||
// with PostgreSQL-compatible dollar-sign placeholders ($1, $2, etc.).
|
||||
type Query struct {
|
||||
squirrel.StatementBuilderType
|
||||
}
|
||||
|
||||
// New creates a new Query instance configured for PostgreSQL with dollar
|
||||
// sign placeholders. Use this to build SQL queries with a fluent API.
|
||||
func New() Query {
|
||||
return Query{squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// tracers is a slice of pgx QueryTracers that are invoked sequentially.
|
||||
type tracers []pgx.QueryTracer
|
||||
|
||||
// TraceQueryStart invokes all registered tracers when a query starts.
|
||||
// It passes the context through each tracer and returns the final context.
|
||||
// nolint:fatcontext
|
||||
func (t tracers) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
for _, tracer := range t {
|
||||
ctx = tracer.TraceQueryStart(ctx, conn, data)
|
||||
}
|
||||
return ctx
|
||||
}
|
||||
|
||||
// TraceQueryEnd invokes all registered tracers when a query completes.
|
||||
func (t tracers) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
for _, tracer := range t {
|
||||
tracer.TraceQueryEnd(ctx, conn, data)
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// txOptions holds configuration for database transactions.
|
||||
type txOptions struct {
|
||||
nativeOpts *sql.TxOptions
|
||||
metricsLabel string
|
||||
}
|
||||
|
||||
// TxOption is a function that configures transaction options.
|
||||
type TxOption func(options *txOptions)
|
||||
|
||||
// IsolationLevel sets the transaction isolation level.
|
||||
func IsolationLevel(level sql.IsolationLevel) TxOption {
|
||||
return func(options *txOptions) {
|
||||
if options.nativeOpts == nil {
|
||||
options.nativeOpts = &sql.TxOptions{}
|
||||
}
|
||||
options.nativeOpts.Isolation = level
|
||||
}
|
||||
}
|
||||
|
||||
// ReadOnly marks the transaction as read-only.
|
||||
func ReadOnly() TxOption {
|
||||
return func(options *txOptions) {
|
||||
if options.nativeOpts == nil {
|
||||
options.nativeOpts = &sql.TxOptions{}
|
||||
}
|
||||
options.nativeOpts.ReadOnly = true
|
||||
}
|
||||
}
|
||||
|
||||
// MetricsLabel sets a label for transaction metrics.
|
||||
func MetricsLabel(name string) TxOption {
|
||||
return func(options *txOptions) {
|
||||
options.metricsLabel = name
|
||||
}
|
||||
}
|
||||
|
||||
// TxFunc is a function that executes within a transaction.
|
||||
type TxFunc func(ctx context.Context, tx *Tx) error
|
||||
|
||||
// Tx wraps a sqlx.Tx with convenience methods for database operations.
|
||||
type Tx struct {
|
||||
*sqlx.Tx
|
||||
}
|
||||
|
||||
// Select executes a query that returns multiple rows and scans them into the provided pointer.
|
||||
func (t *Tx) Select(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
return t.SelectContext(ctx, ptr, query, args...)
|
||||
}
|
||||
|
||||
// SelectRow executes a query that returns a single row and scans it into the provided pointer.
|
||||
func (t *Tx) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
return t.GetContext(ctx, ptr, query, args...)
|
||||
}
|
||||
|
||||
// Exec executes a query that does not return rows.
|
||||
func (t *Tx) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
return t.ExecContext(ctx, query, args...)
|
||||
}
|
||||
|
||||
// ExecNamed executes a named-parameter query that does not return rows.
|
||||
func (t *Tx) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
|
||||
return t.NamedExecContext(ctx, query, arg)
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
# Package `dbrx`
|
||||
|
||||
Пакет `dbrx` предоставляет функциональность для работы с базой данных PostgreSQL через расширенный клиент,
|
||||
поддерживающий динамическое обновление конфигурацию, интеграцию с метриками и трейсингом, healthcheck для мониторинга,
|
||||
а также управление жизненным циклом подключения с безопасным обновлением соединений.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Клиент для взаимодействия с базой данных PostgreSQL, расширяющий клиент из [пакета `dbx`](../dbx/db.go).
|
||||
|
||||
**Methods:**
|
||||
|
||||
Содержит все методы клиента-предшественника.
|
||||
|
||||
#### `New(logger log.Logger, opts ...dbx.Option) *Client`
|
||||
|
||||
Создание клиента к базе данных с пустой конфигурацией подключения. По-умолчанию данный клиент автоматически создает
|
||||
схему БД. Доступные опции:
|
||||
|
||||
- `WithQueryTracer(tracers ...pgx.QueryTracer) Option` – трассировка запросов с объектами реализующими интерфейс
|
||||
`pgx.QueryTracer`.
|
||||
- `WithMigrationRunner(migrationDir string, logger log.Logger) Option` – применить sql-скрипты для миграции, находящиеся
|
||||
в указанной директории.
|
||||
- `WithCreateSchema(createSchema bool) Option` – включить/выключить функцию создания схемы БД.
|
||||
- `WithApplicationName(moduleName string) Option` - указать название модуля в поле application_name таблицы серверных
|
||||
процессов
|
||||
|
||||
#### `(c *Client) Upgrade(ctx context.Context, config dbx.Config) error`
|
||||
|
||||
Обновить конфигурацию подключения к базе данных.
|
||||
|
||||
#### `(c *Client) DB() (*dbx.Client, error)`
|
||||
|
||||
Получить родительский клиент из [пакета `dbx`](../dbx/db.go).
|
||||
|
||||
#### `(c *Client) Healthcheck(ctx context.Context) error`
|
||||
|
||||
Проверить доступность соединения с бд.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
cli := dbrx.New(logger)
|
||||
|
||||
ctx := context.Background()
|
||||
cfg := dbx.Config{
|
||||
Host: "127.0.0.1",
|
||||
Port: 5432,
|
||||
Database: "test",
|
||||
Username: "test",
|
||||
Password: "test",
|
||||
Schema: "test",
|
||||
}
|
||||
err = dbrx.Upgrade(ctx, cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var result int
|
||||
err = cli.SelectRow(ctx, &result, "SELECT COUNT(*) FROM users")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
// Package dbrx provides a dynamic database client that supports runtime
|
||||
// configuration updates. It wraps dbx.Client with atomic pointer access,
|
||||
// automatic metrics and tracing integration, and hot-reload capability.
|
||||
package dbrx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"os"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/pgx_metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/sql_tracing"
|
||||
)
|
||||
|
||||
// ErrClientIsNotInitialized is returned when the client has not been initialized.
|
||||
var (
|
||||
ErrClientIsNotInitialized = errors.New("client is not initialized")
|
||||
)
|
||||
|
||||
const (
|
||||
healthcheckTimeout = 500 * time.Millisecond
|
||||
)
|
||||
|
||||
// Client provides dynamic database client management with hot-reload support.
|
||||
// It wraps a dbx.Client and allows configuration updates at runtime.
|
||||
// It is safe for concurrent use.
|
||||
type Client struct {
|
||||
options []dbx.Option
|
||||
prevCfg *atomic.Value
|
||||
cli *atomic.Pointer[dbx.Client]
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// New creates a new Client with the provided logger and options.
|
||||
// The client is not initialized until Upgrade is called.
|
||||
func New(logger log.Logger, opts ...dbx.Option) *Client {
|
||||
prevCfg := &atomic.Value{}
|
||||
prevCfg.Store(dbx.Config{})
|
||||
return &Client{
|
||||
options: opts,
|
||||
prevCfg: prevCfg,
|
||||
cli: &atomic.Pointer[dbx.Client]{},
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade initializes or reinitializes the database client with the provided configuration.
|
||||
// If the new configuration is identical to the previous one, initialization is skipped.
|
||||
// It automatically adds metrics tracing, schema creation, and application name options.
|
||||
// Returns an error if the connection fails or if the client is in read-only mode.
|
||||
func (c *Client) Upgrade(ctx context.Context, config dbx.Config) error {
|
||||
c.logger.Debug(ctx, "db client: received new config")
|
||||
|
||||
if reflect.DeepEqual(c.prevCfg.Load(), config) {
|
||||
c.logger.Debug(ctx, "db client: configs are equal. skipping initialization")
|
||||
return nil
|
||||
}
|
||||
|
||||
c.logger.Debug(ctx, "db client: initialization began")
|
||||
|
||||
metricsTracer := sql_metrics.NewTracer(metrics.DefaultRegistry)
|
||||
tracingConfig := sql_tracing.NewConfig()
|
||||
tracingConfig.EnableStatement = true
|
||||
opts := append([]dbx.Option{
|
||||
dbx.WithQueryTracer(metricsTracer, tracingConfig.QueryTracer()),
|
||||
dbx.WithCreateSchema(true),
|
||||
dbx.WithApplicationName(os.Args[0]),
|
||||
}, c.options...)
|
||||
|
||||
newCli, err := dbx.Open(ctx, config, opts...)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "open new client")
|
||||
}
|
||||
|
||||
readOnly, err := newCli.IsReadOnly(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "check is new cli read only")
|
||||
}
|
||||
if readOnly {
|
||||
c.logger.Info(ctx, "db client: connection is in read-only mode")
|
||||
}
|
||||
|
||||
oldCli := c.cli.Swap(newCli)
|
||||
if oldCli != nil {
|
||||
_ = oldCli.Close()
|
||||
}
|
||||
|
||||
c.logger.Debug(ctx, "db client: initialization done")
|
||||
|
||||
c.prevCfg.Store(config)
|
||||
|
||||
pgx_metrics.Register(metrics.DefaultRegistry, newCli.Client, config.Database)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DB returns the underlying database client.
|
||||
// Returns an error if the client has not been initialized.
|
||||
func (c *Client) DB() (*dbx.Client, error) {
|
||||
return c.db()
|
||||
}
|
||||
|
||||
// Select executes a query that returns multiple rows and scans them into the provided pointer.
|
||||
// Returns an error if the client is not initialized or if the query fails.
|
||||
func (c *Client) Select(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
cli, err := c.db()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cli.Select(ctx, ptr, query, args...)
|
||||
}
|
||||
|
||||
// SelectRow executes a query that returns a single row and scans it into the provided pointer.
|
||||
// Returns an error if the client is not initialized or if the query fails.
|
||||
func (c *Client) SelectRow(ctx context.Context, ptr any, query string, args ...any) error {
|
||||
cli, err := c.db()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cli.SelectRow(ctx, ptr, query, args...)
|
||||
}
|
||||
|
||||
// Exec executes a query that does not return rows.
|
||||
// Returns an error if the client is not initialized or if the query fails.
|
||||
func (c *Client) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) {
|
||||
cli, err := c.db()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cli.Exec(ctx, query, args...)
|
||||
}
|
||||
|
||||
// ExecNamed executes a named-parameter query that does not return rows.
|
||||
// Returns an error if the client is not initialized or if the query fails.
|
||||
func (c *Client) ExecNamed(ctx context.Context, query string, arg any) (sql.Result, error) {
|
||||
cli, err := c.db()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cli.ExecNamed(ctx, query, arg)
|
||||
}
|
||||
|
||||
// RunInTransaction executes the provided function within a database transaction.
|
||||
// Returns an error if the client is not initialized or if the transaction fails.
|
||||
func (c *Client) RunInTransaction(ctx context.Context, txFunc db.TxFunc, opts ...db.TxOption) error {
|
||||
cli, err := c.db()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cli.RunInTransaction(ctx, txFunc, opts...)
|
||||
}
|
||||
|
||||
// Close closes the database connection and resets the client configuration.
|
||||
// Returns an error if the underlying client fails to close.
|
||||
func (c *Client) Close() error {
|
||||
c.logger.Debug(context.Background(), "db client: call close")
|
||||
c.prevCfg.Store(dbx.Config{})
|
||||
oldCli := c.cli.Swap(nil)
|
||||
if oldCli != nil {
|
||||
return oldCli.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Healthcheck verifies that the database connection is alive.
|
||||
// Executes a simple query with a 500ms timeout.
|
||||
// Returns an error if the client is not initialized or if the query fails.
|
||||
func (c *Client) Healthcheck(ctx context.Context) error {
|
||||
cli, err := c.db()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, healthcheckTimeout)
|
||||
defer cancel()
|
||||
_, err = cli.Exec(ctx, "SELECT 1")
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "exec")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// db returns the current database client or an error if not initialized.
|
||||
func (c *Client) db() (*dbx.Client, error) {
|
||||
oldCli := c.cli.Load()
|
||||
if oldCli == nil {
|
||||
return nil, ErrClientIsNotInitialized
|
||||
}
|
||||
return oldCli, nil
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
# Package `dbx`
|
||||
|
||||
Пакет `dbx` предоставляет функциональность для работы с базой данных PostgreSQL, включая настройку пула соединений,
|
||||
выполнение миграций через goose и возможностью создавать схемы БД.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Клиент для взаимодействия с базой данных PostgreSQL, расширяющий клиент из [пакета `db`](../db/db.go). По умолчанию
|
||||
максимальное количество открытых соединений равно `CPU * 10`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
Содержит все методы клиента-предшественника.
|
||||
|
||||
#### `Open(ctx context.Context, config Config, opts ...Option) (*Client, error)`
|
||||
|
||||
Создать соединение к базе данных по переданной конфигурации подключения. Доступные опции:
|
||||
|
||||
- `WithQueryTracer(tracers ...pgx.QueryTracer) Option` – трассировка запросов с объектами реализующими интерфейс
|
||||
`pgx.QueryTracer`.
|
||||
- `WithMigrationRunner(migrationDir string, logger log.Logger) Option` – применить sql-скрипты для миграции, находящиеся
|
||||
в указанной директории.
|
||||
- `WithCreateSchema(createSchema bool) Option` – включить/выключить функцию создания схемы БД.
|
||||
- `WithApplicationName(moduleName string) Option` - указать название модуля в поле application_name таблицы серверных
|
||||
процессов
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
cfg := dbx.Config{
|
||||
Host: "127.0.0.1",
|
||||
Port: 5432,
|
||||
Database: "test",
|
||||
Username: "test",
|
||||
Password: "test",
|
||||
MaxOpenConn: 10,
|
||||
}
|
||||
|
||||
/* create client with migrations */
|
||||
cli, err := dbx.Open(
|
||||
ctx,
|
||||
cfg,
|
||||
dbx.WithMigrationRunner("./migrations", logger),
|
||||
dbx.WithQueryTracer(dbx.NewLogTracer(logger)),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
var result int
|
||||
err = cli.SelectRow(ctx, &result, "SELECT COUNT(*) FROM users")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Connecting to db in slave mode
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
/* create client with migrations */
|
||||
cli, err := dbx.Open(context.Background(), dbx.Config{
|
||||
Host: "127.0.0.1",
|
||||
Port: 5432,
|
||||
Database: "test",
|
||||
Username: "test",
|
||||
Password: "test",
|
||||
Params: map[string]string{
|
||||
"target_session_attrs": "read-write",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// Config holds the configuration for establishing a database connection.
|
||||
type Config struct {
|
||||
Host string `validate:"required" schema:"Хост"`
|
||||
Port int `validate:"required" schema:"Порт"`
|
||||
Database string `validate:"required" schema:"База данных"`
|
||||
Username string `schema:"Логин"`
|
||||
Password string `schema:"Пароль"`
|
||||
Schema string `schema:"Схема"`
|
||||
MaxOpenConn int `schema:"Максимально количество соединений,если <=0 - используется значение по умолчанию равное cpu * 10"`
|
||||
MaxConnIdleTimeSec int `schema:"Максимальное время простоя подключения в секундах,если <=0 - используется значения по умолчанию равное 90"`
|
||||
Params map[string]string `schema:"Дополнительные параметры подключения"`
|
||||
}
|
||||
|
||||
// Dsn generates a PostgreSQL connection string from the configuration.
|
||||
// The applicationName parameter is included as a connection parameter.
|
||||
func (c Config) Dsn(applicationName string) string {
|
||||
u := url.URL{
|
||||
Scheme: "postgresql",
|
||||
User: nil,
|
||||
Host: fmt.Sprintf("%s:%d", c.Host, c.Port),
|
||||
Path: c.Database,
|
||||
}
|
||||
if c.Username != "" {
|
||||
u.User = url.UserPassword(c.Username, c.Password)
|
||||
}
|
||||
query := url.Values{}
|
||||
if c.Schema != "" {
|
||||
query.Set("search_path", c.Schema)
|
||||
}
|
||||
|
||||
if applicationName != "" {
|
||||
query.Set("application_name", applicationName)
|
||||
}
|
||||
|
||||
for key, value := range c.Params {
|
||||
query.Set(key, value)
|
||||
}
|
||||
u.RawQuery = query.Encode()
|
||||
return u.String()
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
// Package dbx extends the db package with additional features including
|
||||
// automatic schema creation, database migrations via goose, and connection
|
||||
// pool configuration. It provides a higher-level database client for PostgreSQL.
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
)
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
defaultMaxOpenConn = runtime.NumCPU() * 10
|
||||
)
|
||||
|
||||
const (
|
||||
minIdleConns = 2
|
||||
defaultMaxConnIdleTime = 90 * time.Second
|
||||
)
|
||||
|
||||
// MigrationRunner defines the interface for running database migrations.
|
||||
type MigrationRunner interface {
|
||||
Run(ctx context.Context, db *sql.DB, gooseOpts ...goose.ProviderOption) error
|
||||
}
|
||||
|
||||
// Client wraps a db.Client with migration support and schema management.
|
||||
// It is safe for concurrent use.
|
||||
type Client struct {
|
||||
*db.Client
|
||||
|
||||
migrationRunner MigrationRunner
|
||||
queryTraces []pgx.QueryTracer
|
||||
createSchema bool
|
||||
applicationName string
|
||||
}
|
||||
|
||||
// Open establishes a connection to a PostgreSQL database using the provided configuration.
|
||||
// It applies connection pool settings, creates the schema if needed, and runs migrations.
|
||||
// Returns an error if the connection fails, schema creation fails, or migrations fail.
|
||||
// nolint:cyclop,nonamedreturns
|
||||
func Open(ctx context.Context, config Config, opts ...Option) (cli *Client, err error) {
|
||||
cli = &Client{}
|
||||
for _, opt := range opts {
|
||||
opt(cli)
|
||||
}
|
||||
|
||||
maxOpenConn := defaultMaxOpenConn
|
||||
if config.MaxOpenConn > 0 {
|
||||
maxOpenConn = config.MaxOpenConn
|
||||
}
|
||||
|
||||
maxConnIdleTime := defaultMaxConnIdleTime
|
||||
if config.MaxConnIdleTimeSec > 0 {
|
||||
maxConnIdleTime = time.Duration(config.MaxConnIdleTimeSec) * time.Second
|
||||
}
|
||||
|
||||
dbCli, err := db.Open(
|
||||
ctx,
|
||||
config.Dsn(cli.applicationName),
|
||||
db.WithQueryTracer(cli.queryTraces...),
|
||||
db.WithMaxOpenConns(int32(maxOpenConn)), //nolint:gosec
|
||||
db.WithMinIdleConns(int32(minIdleConns)), //nolint:gosec
|
||||
db.WithMaxConnIdleTime(maxConnIdleTime),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "open db")
|
||||
}
|
||||
defer func() {
|
||||
if err != nil {
|
||||
_ = dbCli.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
isReadOnly, err := dbCli.IsReadOnly(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "check is read only connection")
|
||||
}
|
||||
|
||||
isCustomSchema := config.Schema != "public" && config.Schema != ""
|
||||
if !isReadOnly && cli.createSchema && isCustomSchema {
|
||||
_, err = dbCli.Exec(ctx, fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS %s", config.Schema))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "exec create schema query")
|
||||
}
|
||||
}
|
||||
|
||||
if isCustomSchema {
|
||||
err = checkSchemaExistence(ctx, config.Schema, dbCli)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "check schema existence")
|
||||
}
|
||||
}
|
||||
|
||||
if !isReadOnly && cli.migrationRunner != nil {
|
||||
err = cli.migrationRunner.Run(ctx, dbCli.DB.DB)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "migration run")
|
||||
}
|
||||
}
|
||||
|
||||
cli.Client = dbCli
|
||||
return cli, nil
|
||||
}
|
||||
|
||||
// checkSchemaExistence verifies that the specified schema exists in the database.
|
||||
// Returns an error if the schema does not exist or if the query fails.
|
||||
func checkSchemaExistence(ctx context.Context, schema string, dbCli *db.Client) error {
|
||||
query := `SELECT EXISTS (
|
||||
SELECT 1 FROM pg_namespace WHERE nspname = $1
|
||||
)`
|
||||
var exists bool
|
||||
err := dbCli.QueryRowContext(ctx, query, schema).Scan(&exists)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "check schema existence")
|
||||
}
|
||||
if !exists {
|
||||
return errors.Errorf("schema '%s' does not exist", schema)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// LogTracer is a pgx QueryTracer that logs queries at debug level.
|
||||
type LogTracer struct {
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// NewLogTracer creates a new LogTracer with the provided logger.
|
||||
func NewLogTracer(logger log.Logger) LogTracer {
|
||||
return LogTracer{
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// TraceQueryStart logs the SQL query when a query starts.
|
||||
func (l LogTracer) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
l.logger.Debug(ctx, "sql: log tracer", log.String("query", data.SQL))
|
||||
return ctx
|
||||
}
|
||||
|
||||
// TraceQueryEnd is called when a query completes. Currently a no-op.
|
||||
func (l LogTracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
// Package migration provides database migration functionality using the goose
|
||||
// library. It manages schema evolution by applying pending SQL or Go migrations
|
||||
// from a specified directory and tracks migration versions.
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// DialectPostgreSQL represents the PostgreSQL dialect for migrations.
|
||||
const (
|
||||
DialectPostgreSQL = goose.DialectPostgres
|
||||
// DialectSqlite3 represents the SQLite3 dialect for migrations.
|
||||
DialectSqlite3 = goose.DialectSQLite3
|
||||
// DialectClickhouse represents the ClickHouse dialect for migrations.
|
||||
DialectClickhouse = goose.DialectClickHouse
|
||||
)
|
||||
|
||||
// Runner manages database migrations using the goose library.
|
||||
// It applies pending migrations from a specified directory and tracks migration versions.
|
||||
type Runner struct {
|
||||
dialect goose.Dialect
|
||||
migrationDir string
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
// NewRunner creates a new migration Runner with the specified dialect,
|
||||
// migration directory, and logger.
|
||||
func NewRunner(
|
||||
dialect goose.Dialect,
|
||||
migrationDir string,
|
||||
logger log.Logger,
|
||||
) Runner {
|
||||
return Runner{
|
||||
dialect: dialect,
|
||||
migrationDir: migrationDir,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Run applies all pending migrations to the database.
|
||||
// It logs the current database version, lists all migrations with their status, and applies any pending migrations.
|
||||
// Returns an error if the migration directory does not exist, migrations cannot be loaded, or if applying migrations fails.
|
||||
func (r Runner) Run(ctx context.Context, db *sql.DB, gooseOpts ...goose.ProviderOption) error {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "goose_db_migration"))
|
||||
|
||||
_, err := os.Stat(r.migrationDir)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get file info")
|
||||
}
|
||||
|
||||
provider, err := goose.NewProvider(r.dialect, db, os.DirFS(r.migrationDir), gooseOpts...)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get goose provider")
|
||||
}
|
||||
|
||||
dbVersion, err := provider.GetDBVersion(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get db version")
|
||||
}
|
||||
r.logger.Info(ctx, fmt.Sprintf("current db version: %d", dbVersion))
|
||||
|
||||
migrations, err := provider.Status(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get status migrations")
|
||||
}
|
||||
r.logger.Info(ctx, "print migration list")
|
||||
if len(migrations) == 0 {
|
||||
r.logger.Info(ctx, "no migrations")
|
||||
}
|
||||
for _, migration := range migrations {
|
||||
appliedAt := "Pending"
|
||||
if !migration.AppliedAt.IsZero() {
|
||||
appliedAt = migration.AppliedAt.Format(time.RFC3339)
|
||||
}
|
||||
msg := fmt.Sprintf(
|
||||
"migration: %s %s %s",
|
||||
filepath.Base(migration.Source.Path),
|
||||
strings.ToUpper(string(migration.State)),
|
||||
appliedAt,
|
||||
)
|
||||
r.logger.Info(ctx, msg)
|
||||
}
|
||||
|
||||
result, err := provider.Up(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "apply pending migrations")
|
||||
}
|
||||
for _, migrationResult := range result {
|
||||
r.logger.Info(ctx, fmt.Sprintf("applied migration: %s", migrationResult.String()))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package dbx
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/txix-open/isp-kit/dbx/migration"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// Option is a function that configures a Client.
|
||||
type Option func(db *Client)
|
||||
|
||||
// WithMigrationRunner configures the client to run database migrations from the specified directory.
|
||||
// The logger is used for migration-related logging.
|
||||
func WithMigrationRunner(migrationDir string, logger log.Logger) Option {
|
||||
return func(db *Client) {
|
||||
db.migrationRunner = migration.NewRunner(migration.DialectPostgreSQL, migrationDir, logger)
|
||||
}
|
||||
}
|
||||
|
||||
// WithQueryTracer registers one or more pgx QueryTracers for query lifecycle events.
|
||||
func WithQueryTracer(tracers ...pgx.QueryTracer) Option {
|
||||
return func(db *Client) {
|
||||
db.queryTraces = append(db.queryTraces, tracers...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithCreateSchema enables automatic creation of the database schema if it does not exist.
|
||||
// This only applies to non-read-only connections with a custom schema.
|
||||
func WithCreateSchema(createSchema bool) Option {
|
||||
return func(db *Client) {
|
||||
db.createSchema = createSchema
|
||||
}
|
||||
}
|
||||
|
||||
// WithApplicationName sets the application name connection parameter.
|
||||
// This is used for identification in database logs and monitoring.
|
||||
func WithApplicationName(moduleName string) Option {
|
||||
return func(db *Client) {
|
||||
db.applicationName = moduleName
|
||||
}
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# Package `grpc`
|
||||
|
||||
Пакет `grpc` предоставляет инструменты для создания и управления gRPC-серверами, включая обработку аутентификации,
|
||||
маршрутизацию запросов и интеграцию с метаданными.
|
||||
Поддерживает гибкую настройку обработчиков, безопасное обновление сервисов и работу с заголовками.
|
||||
|
||||
## Types
|
||||
|
||||
### Server
|
||||
|
||||
gRPC-сервер с поддержкой динамического обновления обработчиков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `DefaultServer(restOptions ...grpc.ServerOption) *Server`
|
||||
|
||||
Создать gRPC-сервер с настройками по умолчанию (максимальный размер сообщения 64 МБ).
|
||||
|
||||
#### `NewServer(opts ...grpc.ServerOption) *Server`
|
||||
|
||||
Создать кастомный сервер с указанными опциями gRPC.
|
||||
|
||||
#### `(s *Server) Upgrade(service isp.BackendServiceServer)`
|
||||
|
||||
Атомарно обновить обработчик сервиса без остановки сервера.
|
||||
|
||||
#### `(s *Server) ListenAndServe(address string) error`
|
||||
|
||||
Запустить сервер на указанном адресе.
|
||||
|
||||
#### `(s *Server) Serve(listener net.Listener) error`
|
||||
|
||||
Запустить сервер на существующем listener.
|
||||
|
||||
#### `(s *Server) Shutdown()`
|
||||
|
||||
Остановить сервер
|
||||
|
||||
### Mux
|
||||
|
||||
Мультиплексор для маршрутизации gRPC-запросов. Регистрирует обработчики по имени эндпоинта.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewMux() *Mux`
|
||||
|
||||
Создать новый мультиплексор.
|
||||
|
||||
#### `(m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux`
|
||||
|
||||
Зарегистрировать обработчик для указанного эндпоинта.
|
||||
|
||||
#### `(m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error)`
|
||||
|
||||
Обрабатывает входящий запрос, определяя эндпоинт через заголовок `ProxyMethodNameHeader`.
|
||||
|
||||
### AuthData
|
||||
|
||||
Структура для работы с метаданными аутентификации в gRPC-запросах.
|
||||
Оборачивает `metadata.MD` и предоставляет методы для извлечения идентификаторов из заголовков.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(i AuthData) SystemId() (int, error)`
|
||||
|
||||
Получить идентификатор системы из заголовка `x-system-identity`.
|
||||
|
||||
#### `(i AuthData) DomainId() (int, error)`
|
||||
|
||||
Получить идентификатор домена из заголовка `x-domain-identity`.
|
||||
|
||||
#### `(i AuthData) ServiceId() (int, error)`
|
||||
|
||||
Получить идентификатор сервиса из заголовка `x-service-identity`.
|
||||
|
||||
#### `(i AuthData) ApplicationId() (int, error)`
|
||||
|
||||
Получить идентификатор системы из заголовка `x-application-identity`.
|
||||
|
||||
#### `(i AuthData) ApplicationName() (int, error)`
|
||||
|
||||
Получить название системы из заголовка `x-application-name`.
|
||||
|
||||
#### `(i AuthData) UserId() (int, error)`
|
||||
|
||||
Получить идентификатор пользователя из заголовка `x-user-identity`.
|
||||
|
||||
#### `(i AuthData) DeviceId() (int, error)`
|
||||
|
||||
Получить идентификатор устройства из заголовка `x-device-identity`.
|
||||
|
||||
#### `(i AuthData) UserToken() (string, error)`
|
||||
|
||||
Получить токен пользователя из заголовка `x-user-token`.
|
||||
|
||||
#### `(i AuthData) DeviceToken() (string, error)`
|
||||
|
||||
Получить токен устройства из заголовка `x-device-token`.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `StringFromMd(key string, md metadata.MD) (string, error)`
|
||||
|
||||
Извлекает строковое значение из метаданных по ключу.
|
||||
|
||||
#### `IntFromMd(key string, md metadata.MD) (int, error)`
|
||||
|
||||
Извлекает целочисленное значение из метаданных по ключу.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mux := grpc.NewMux()
|
||||
mux.Handle("/get_users", func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
/* put here business logic */
|
||||
return new(isp.Message), nil
|
||||
})
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err := srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
# Package `apierrors`
|
||||
|
||||
Пакет `apierrors` предоставляет структурированный формат ошибок для gRPC-сервисов с поддержкой кодов ошибок, деталей,
|
||||
уровней логирования и интеграции с gRPC-статусами. Позволяет единообразно обрабатывать бизнес-ошибки и технические сбои.
|
||||
|
||||
## Types
|
||||
|
||||
### Error
|
||||
|
||||
Структура для представления ошибки API. Реализует интерфейс `error`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewInternalServiceError(err error) Error`
|
||||
|
||||
Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с gRPC-статусом 13 (internal), бизнесовым кодом 900 и
|
||||
уровнем
|
||||
логирования error.
|
||||
|
||||
#### `NewBusinessError(errorCode int, errorMessage string, err error) Error`
|
||||
|
||||
Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с gRPC-статусом 3 (invalid argument),
|
||||
указанным
|
||||
бизнесовым кодом и уровнем логирования warn.
|
||||
|
||||
#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error`
|
||||
|
||||
Создает кастомную ошибку с полным контролем параметров.
|
||||
|
||||
#### `(e Error) Error() string`
|
||||
|
||||
Получить строковое представление ошибки.
|
||||
|
||||
#### `(e Error) GrpcStatusError() error`
|
||||
|
||||
Конвертирует ошибку в gRPC-сообщение с сериализованными деталями об ошибке в формате JSON.
|
||||
|
||||
#### `(e Error) WithDetails(details map[string]any) Error`
|
||||
|
||||
Добавить детали информации об ошибке.
|
||||
|
||||
#### `(e Error) WithLogLevel(level log.Level) Error`
|
||||
|
||||
Изменить уровень логирования ошибки.
|
||||
|
||||
#### `(e Error) LogLevel() log.Level`
|
||||
|
||||
Получить текущий уровень логирования ошибки
|
||||
|
||||
## Functions
|
||||
|
||||
#### `FromError(err error) *Error`
|
||||
|
||||
Извлекает структурированную бизнесовую ошибку из gRPC-сообщения спрятанного под интерфейс `error`.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
ErrUserNotFoundCode = 700
|
||||
)
|
||||
|
||||
type userService interface {
|
||||
GetUserById(ctx context.Context, id string) (*User, error)
|
||||
}
|
||||
|
||||
type userController struct {
|
||||
svc userService
|
||||
}
|
||||
|
||||
func (c userController) GetUser(ctx context.Context, userId string) (*User, error) {
|
||||
result, err := c.svc.GetUserById(ctx, userId)
|
||||
switch {
|
||||
case errors.Is(err, ErrUserNotFound):
|
||||
/* user isn't found so we have to send back specific error code */
|
||||
return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err)
|
||||
case err != nil:
|
||||
/* got some internal error */
|
||||
return nil, apierrors.NewInternalServiceError(err)
|
||||
default:
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
// Package apierrors provides structured error handling for gRPC services.
|
||||
// It defines custom error types with business error codes, gRPC status codes,
|
||||
// and structured details for comprehensive error reporting.
|
||||
//
|
||||
// Errors can be converted to gRPC status errors with JSON-encoded details,
|
||||
// enabling rich error information to be transmitted across service boundaries.
|
||||
package apierrors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
// ErrCodeInternal is the default error code for internal service errors.
|
||||
ErrCodeInternal = 900
|
||||
)
|
||||
|
||||
// Error represents a structured error with business and gRPC status codes.
|
||||
// Includes optional details for field-specific errors and a configurable log level.
|
||||
// Implements the GrpcError interface for conversion to gRPC status errors.
|
||||
//
|
||||
// Fields:
|
||||
// - ErrorCode: Business-level error code (e.g., 400 for bad request)
|
||||
// - ErrorMessage: Human-readable error message
|
||||
// - Details: Optional map of field-specific error details
|
||||
// - grpcStatusCode: gRPC status code (e.g., codes.InvalidArgument)
|
||||
// - cause: Underlying error cause
|
||||
// - level: Log level for error logging
|
||||
type Error struct {
|
||||
ErrorCode int
|
||||
ErrorMessage string
|
||||
Details map[string]any `json:",omitempty"`
|
||||
|
||||
grpcStatusCode codes.Code
|
||||
cause error
|
||||
level log.Level
|
||||
}
|
||||
|
||||
// NewInternalServiceError creates a new internal service error.
|
||||
// Uses gRPC status code Internal and business error code 900.
|
||||
// Sets log level to Error.
|
||||
func NewInternalServiceError(err error) Error {
|
||||
return New(codes.Internal, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel)
|
||||
}
|
||||
|
||||
// NewBusinessError creates a new business validation error.
|
||||
// Uses gRPC status code InvalidArgument and the specified error code.
|
||||
// Sets log level to Warn.
|
||||
func NewBusinessError(errorCode int, errorMessage string, err error) Error {
|
||||
return New(codes.InvalidArgument, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel)
|
||||
}
|
||||
|
||||
// New creates a new Error with the specified parameters.
|
||||
// Sets default log level to Error.
|
||||
func New(
|
||||
grpcStatusCode codes.Code,
|
||||
errorCode int,
|
||||
errorMessage string,
|
||||
err error,
|
||||
) Error {
|
||||
return Error{
|
||||
ErrorCode: errorCode,
|
||||
ErrorMessage: errorMessage,
|
||||
grpcStatusCode: grpcStatusCode,
|
||||
cause: err,
|
||||
level: log.ErrorLevel,
|
||||
}
|
||||
}
|
||||
|
||||
// Error returns a string representation of the error.
|
||||
// Includes error code, message, and underlying cause.
|
||||
func (e Error) Error() string {
|
||||
return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause)
|
||||
}
|
||||
|
||||
// GrpcStatusError converts the Error to a gRPC status error.
|
||||
// Serializes the error to JSON and attaches it as gRPC status details.
|
||||
// Returns an error if JSON marshaling or status creation fails.
|
||||
func (e Error) GrpcStatusError() error {
|
||||
data, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
|
||||
msg := &isp.Message{
|
||||
Body: &isp.Message_BytesBody{
|
||||
BytesBody: data,
|
||||
},
|
||||
}
|
||||
s, err := status.New(e.grpcStatusCode, e.ErrorMessage).WithDetails(msg)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "set status details")
|
||||
}
|
||||
return s.Err()
|
||||
}
|
||||
|
||||
// WithDetails sets the error details map.
|
||||
// Returns the Error for method chaining.
|
||||
func (e Error) WithDetails(details map[string]any) Error {
|
||||
e.Details = details
|
||||
return e
|
||||
}
|
||||
|
||||
// WithLogLevel sets the log level for this error.
|
||||
// Returns the Error for method chaining.
|
||||
func (e Error) WithLogLevel(level log.Level) Error {
|
||||
e.level = level
|
||||
return e
|
||||
}
|
||||
|
||||
// LogLevel returns the log level for this error.
|
||||
func (e Error) LogLevel() log.Level {
|
||||
return e.level
|
||||
}
|
||||
|
||||
// FromError extracts an Error from a gRPC status error.
|
||||
// Returns nil if the error is not a gRPC status error or if the details cannot be parsed.
|
||||
// Useful for checking if an error originated from a remote service.
|
||||
func FromError(err error) *Error {
|
||||
s, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, detail := range s.Details() {
|
||||
typedDetail, ok := detail.(*isp.Message)
|
||||
if ok {
|
||||
errData := Error{}
|
||||
err := json.Unmarshal(typedDetail.GetBytesBody(), &errData)
|
||||
// not an error
|
||||
if err != nil {
|
||||
return nil // nolint:nilerr
|
||||
}
|
||||
if errData.ErrorCode == 0 {
|
||||
return nil
|
||||
}
|
||||
return &errData
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
// ApplicationIdHeader is the metadata key for application identity.
|
||||
ApplicationIdHeader = "x-application-identity"
|
||||
// ApplicationNameHeader is the metadata key for application name.
|
||||
ApplicationNameHeader = "x-application-name"
|
||||
// UserIdHeader is the metadata key for user identity.
|
||||
UserIdHeader = "x-user-identity"
|
||||
// DeviceIdHeader is the metadata key for device identity.
|
||||
DeviceIdHeader = "x-device-identity"
|
||||
// ServiceIdHeader is the metadata key for service identity.
|
||||
ServiceIdHeader = "x-service-identity"
|
||||
// DomainIdHeader is the metadata key for domain identity.
|
||||
DomainIdHeader = "x-domain-identity"
|
||||
// SystemIdHeader is the metadata key for system identity.
|
||||
SystemIdHeader = "x-system-identity"
|
||||
// UserTokenHeader is the metadata key for user token.
|
||||
UserTokenHeader = "x-user-token"
|
||||
// DeviceTokenHeader is the metadata key for device token.
|
||||
DeviceTokenHeader = "x-device-token"
|
||||
)
|
||||
|
||||
// AuthData wraps metadata.MD to provide structured access to authentication
|
||||
// and authorization information from gRPC request metadata.
|
||||
// All methods return an error if the key is not found or cannot be parsed.
|
||||
type AuthData metadata.MD
|
||||
|
||||
// SystemId extracts the system identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) SystemId() (int, error) {
|
||||
return IntFromMd(SystemIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DomainId extracts the domain identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) DomainId() (int, error) {
|
||||
return IntFromMd(DomainIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ServiceId extracts the service identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) ServiceId() (int, error) {
|
||||
return IntFromMd(ServiceIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ApplicationId extracts the application identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) ApplicationId() (int, error) {
|
||||
return IntFromMd(ApplicationIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// ApplicationName extracts the application name from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) ApplicationName() (string, error) {
|
||||
return StringFromMd(ApplicationNameHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// UserId extracts the user identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) UserId() (int, error) {
|
||||
return IntFromMd(UserIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DeviceId extracts the device identity from metadata as an integer.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func (i AuthData) DeviceId() (int, error) {
|
||||
return IntFromMd(DeviceIdHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// UserToken extracts the user token from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) UserToken() (string, error) {
|
||||
return StringFromMd(UserTokenHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// DeviceToken extracts the device token from metadata as a string.
|
||||
// Returns an error if the key is not found.
|
||||
func (i AuthData) DeviceToken() (string, error) {
|
||||
return StringFromMd(DeviceTokenHeader, metadata.MD(i))
|
||||
}
|
||||
|
||||
// StringFromMd extracts a string value from metadata by key.
|
||||
// Returns an error if metadata is nil or the key is not found.
|
||||
func StringFromMd(key string, md metadata.MD) (string, error) {
|
||||
if md == nil {
|
||||
return "", errors.New("metadata is nil")
|
||||
}
|
||||
values := md[key]
|
||||
if len(values) == 0 {
|
||||
return "", errors.Errorf("'%s' is expected in metadata", key)
|
||||
}
|
||||
return values[0], nil
|
||||
}
|
||||
|
||||
// IntFromMd extracts an integer value from metadata by key.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func IntFromMd(key string, md metadata.MD) (int, error) {
|
||||
value, err := StringFromMd(key, md)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# Package `client`
|
||||
|
||||
Пакет `client` предоставляет гибкий gRPC-клиент с поддержкой балансировки нагрузки, middleware для логирования, метрик,
|
||||
трассировки и динамическим обновлением списка хостов.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Основная структура клиента для взаимодействия с gRPC-серверами. Поддерживает балансировку нагрузки, цепочки middleware и
|
||||
динамическое обновление списка хостов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(initialHosts []string, opts ...Option) (*Client, error)`
|
||||
|
||||
Создать новый клиент с указанными начальными хостами и опциями:
|
||||
|
||||
- `WithMiddlewares(middlewares ...request.Middleware) Option` – добавить middleware в цепочку обработки запроса.
|
||||
- `WithDialOptions(dialOptions ...grpc.DialOption) Option` – опция для передачи параметров подключения gRPC (например,
|
||||
TLS, таймауты)
|
||||
- `WithCodec(codec Codec) Option` – переопределяет codec для кодирования/декодирования, по умолчанию `zstd`
|
||||
- `WithEncodeThreshold(threshold int) Option` – переопределяет значение выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest), по умолчанию 128 КБ (параметр в байтах).
|
||||
- `WithEncodeRequest(encode bool) Option` – переопределить флаг кодирования запроса. Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `x-content-encoding` со значением типа codec и тело запроса будет закодировано, по умолчанию false.
|
||||
- `WithAcceptEncodedResponse(accept bool) Option` – переопределить флаг флаг приёма закодированных ответов. Если включен, то в заголовки запроса будет добавлен `x-accept-encoding` со значением типа codec + identity (пример `zstd, identity`), по умолчанию true.
|
||||
|
||||
#### `(cli *Client) Invoke(endpoint string) *request.Builder`
|
||||
|
||||
Инициирует запрос к указанному эндпоинту. Возвращает билдер для выполнения запроса.
|
||||
|
||||
#### `(cli *Client) Upgrade(hosts []string)`
|
||||
|
||||
Атомарно обновить список хостов.
|
||||
|
||||
#### `(cli *Client) Close() error`
|
||||
|
||||
Закрыть соединение с сервером.
|
||||
|
||||
#### `(cli *Client) BackendClient() isp.BackendServiceClient`
|
||||
|
||||
Получить низкоуровневый клиент для прямого взаимодействия с gRPC-сервисом.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(restMiddlewares ...request.Middleware) (*Client, error)`
|
||||
|
||||
Создать клиент с настройками по умолчанию:
|
||||
|
||||
- Максимальный размер сообщения 64 МБ.
|
||||
- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга
|
||||
|
||||
#### `RequestId() request.Middleware`
|
||||
|
||||
Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то
|
||||
передаваться будет именно он.
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) request.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`.
|
||||
|
||||
#### `Metrics(storage MetricStorage) request.Middleware`
|
||||
|
||||
Middleware для сбора метрик длительности запросов.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli, err := client.Default(client.Log(logger, true))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
|
||||
cli.Upgrade([]string{"host1:8080", "host2:9000"})
|
||||
|
||||
users := make([]user, 0)
|
||||
err = cli.Invoke("/get_users").
|
||||
JsonResponseBody(&users).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
for _, u := range users {
|
||||
/* handle each user */
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
// Package client provides a gRPC client implementation with built-in load balancing,
|
||||
// middleware support, and observability features.
|
||||
//
|
||||
// The client supports dynamic host updates for service discovery and integrates with
|
||||
// the ISP kit framework's logging, metrics, and tracing systems.
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
grpc2 "github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/resolver"
|
||||
"google.golang.org/grpc/resolver/manual"
|
||||
)
|
||||
|
||||
const (
|
||||
// resolverScheme defines the custom resolver scheme for host discovery.
|
||||
resolverScheme = "isp"
|
||||
// resolverUrl is the target URL for the manual resolver.
|
||||
resolverUrl = resolverScheme + ":///"
|
||||
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
type Codec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// Client is a gRPC client with support for middleware, load balancing, and dynamic host updates.
|
||||
// It provides a fluent API for building requests and automatically handles connection management.
|
||||
// Client is safe for concurrent use by multiple goroutines.
|
||||
type Client struct {
|
||||
middlewares []request.Middleware
|
||||
dialOptions []grpc.DialOption
|
||||
|
||||
roundTripper request.RoundTripper
|
||||
hostsResolver *manual.Resolver
|
||||
grpcCli *grpc.ClientConn
|
||||
backendCli isp.BackendServiceClient
|
||||
|
||||
currentHosts atomic.Value
|
||||
|
||||
codec Codec
|
||||
encodeThreshold int
|
||||
acceptEncodedResponse bool
|
||||
encodeRequest bool
|
||||
}
|
||||
|
||||
// New creates a new Client with the specified initial hosts and options.
|
||||
// Returns an error if the gRPC client cannot be initialized.
|
||||
// The client automatically connects to the provided hosts and applies all configured middleware.
|
||||
func New(initialHosts []string, opts ...Option) (*Client, error) {
|
||||
cli := &Client{
|
||||
codec: codec.Default,
|
||||
acceptEncodedResponse: true,
|
||||
encodeRequest: false,
|
||||
encodeThreshold: defaultEncodeThreshold,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cli)
|
||||
}
|
||||
|
||||
hostsResolver := manual.NewBuilderWithScheme(resolverScheme)
|
||||
hostsResolver.InitialState(resolver.State{
|
||||
Addresses: toAddresses(initialHosts),
|
||||
})
|
||||
dialOptions := cli.dialOptions
|
||||
dialOptions = append(
|
||||
dialOptions,
|
||||
grpc.WithResolvers(hostsResolver),
|
||||
grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
|
||||
)
|
||||
|
||||
grpcCli, err := grpc.NewClient(resolverUrl, dialOptions...)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "new grpc client")
|
||||
}
|
||||
grpcCli.Connect()
|
||||
backendCli := isp.NewBackendServiceClient(grpcCli)
|
||||
|
||||
cli.currentHosts = atomic.Value{}
|
||||
cli.currentHosts.Store(initialHosts)
|
||||
cli.hostsResolver = hostsResolver
|
||||
cli.backendCli = backendCli
|
||||
cli.grpcCli = grpcCli
|
||||
|
||||
roundTripper := cli.do
|
||||
for i := len(cli.middlewares) - 1; i >= 0; i-- {
|
||||
roundTripper = cli.middlewares[i](roundTripper)
|
||||
}
|
||||
cli.roundTripper = roundTripper
|
||||
|
||||
return cli, nil
|
||||
}
|
||||
|
||||
// Invoke creates a request builder for the specified endpoint.
|
||||
// The builder provides a fluent API for configuring and executing the request.
|
||||
func (cli *Client) Invoke(endpoint string) *request.Builder {
|
||||
return request.NewBuilder(
|
||||
cli.roundTripper,
|
||||
endpoint,
|
||||
request.EncodeSettings{
|
||||
EncodeRequest: cli.encodeRequest,
|
||||
EncodeThreshold: cli.encodeThreshold,
|
||||
AcceptEncodedResponse: cli.acceptEncodedResponse,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// Upgrade updates the list of backend hosts for load balancing.
|
||||
// This enables dynamic service discovery without restarting the client.
|
||||
// Thread-safe for concurrent use.
|
||||
func (cli *Client) Upgrade(hosts []string) {
|
||||
cli.currentHosts.Store(hosts)
|
||||
cli.hostsResolver.UpdateState(resolver.State{
|
||||
Addresses: toAddresses(hosts),
|
||||
})
|
||||
}
|
||||
|
||||
// Close closes the gRPC client connection.
|
||||
// Should be called when the client is no longer needed.
|
||||
func (cli *Client) Close() error {
|
||||
return cli.grpcCli.Close()
|
||||
}
|
||||
|
||||
// BackendClient returns the underlying gRPC BackendServiceClient.
|
||||
// Useful for direct gRPC calls bypassing the client abstraction.
|
||||
func (cli *Client) BackendClient() isp.BackendServiceClient {
|
||||
return cli.backendCli
|
||||
}
|
||||
|
||||
// do executes the actual gRPC request through the middleware chain.
|
||||
// Returns an error if the client is not properly initialized or the request fails.
|
||||
func (cli *Client) do(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
currentHosts := cli.currentHosts.Load().([]string) // nolint:forcetypeassert
|
||||
if len(currentHosts) == 0 {
|
||||
return nil, errors.New("grpc client: client is not initialized properly: empty hosts array")
|
||||
}
|
||||
|
||||
encodeSettings := builder.EncodeSettings
|
||||
if encodeSettings.AcceptEncodedResponse {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx,
|
||||
grpc2.AcceptEncodingHeader,
|
||||
strings.Join([]string{cli.codec.Type(), "identity"}, ", "),
|
||||
)
|
||||
}
|
||||
|
||||
requestBody := message.GetBytesBody()
|
||||
if encodeSettings.EncodeRequest && len(requestBody) > encodeSettings.EncodeThreshold {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx,
|
||||
grpc2.ContentEncodingHeader,
|
||||
cli.codec.Type(),
|
||||
)
|
||||
requestBody, err := cli.codec.EncodeBytes(requestBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
message.Body = &isp.Message_BytesBody{
|
||||
BytesBody: requestBody,
|
||||
}
|
||||
}
|
||||
|
||||
var header metadata.MD
|
||||
resp, err := cli.backendCli.Request(
|
||||
ctx,
|
||||
message,
|
||||
grpc.Header(&header),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
contentEncoding, _ := grpc2.StringFromMd(grpc2.ContentEncodingHeader, header)
|
||||
if contentEncoding != cli.codec.Type() {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
decoded, err := cli.codec.DecodeBytes(resp.GetBytesBody())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &isp.Message_BytesBody{
|
||||
BytesBody: decoded,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// toAddresses converts a slice of host strings to gRPC resolver addresses.
|
||||
func toAddresses(hosts []string) []resolver.Address {
|
||||
addresses := make([]resolver.Address, len(hosts))
|
||||
for i, host := range hosts {
|
||||
addresses[i] = resolver.Address{
|
||||
Addr: host,
|
||||
}
|
||||
}
|
||||
return addresses
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
ispgrpc "github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/grpc_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
// Default creates a Client with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, and distributed tracing.
|
||||
// Uses insecure transport by default (suitable for development and testing).
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
// Returns an error if the client cannot be initialized.
|
||||
func Default(restMiddlewares ...request.Middleware) (*Client, error) {
|
||||
middlewares := append(
|
||||
[]request.Middleware{
|
||||
RequestId(),
|
||||
Metrics(grpc_metrics.NewClientStorage(metrics.DefaultRegistry)),
|
||||
client_tracing.NewConfig().Middleware(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return New(
|
||||
nil,
|
||||
WithDialOptions(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultCallOptions(
|
||||
grpc.WaitForReady(true),
|
||||
grpc.MaxCallSendMsgSize(ispgrpc.DefaultMaxSizeByte),
|
||||
grpc.MaxCallRecvMsgSize(ispgrpc.DefaultMaxSizeByte),
|
||||
),
|
||||
),
|
||||
WithMiddlewares(middlewares...),
|
||||
)
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// logConfig holds logging configuration for client middleware.
|
||||
type logConfig struct {
|
||||
logRequestBody bool
|
||||
logResponseBody bool
|
||||
combinedLog bool
|
||||
}
|
||||
|
||||
// RequestId is a middleware that propagates request IDs across service boundaries.
|
||||
// If no request ID is present in the context, it generates a new one.
|
||||
// The request ID is added to outgoing metadata for tracing purposes.
|
||||
func RequestId() request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
requestId := requestid.FromContext(ctx)
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, requestid.Header, requestId)
|
||||
return next(ctx, builder, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Log creates a middleware that logs gRPC client requests and responses.
|
||||
// When logBody is true, request and response bodies are included in the logs.
|
||||
// Logs at Debug level for requests and responses.
|
||||
func Log(logger log.Logger, logBody bool) request.Middleware {
|
||||
cfg := &logConfig{
|
||||
logRequestBody: logBody,
|
||||
logResponseBody: logBody,
|
||||
}
|
||||
return logMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// LogWithOptions creates a middleware that logs gRPC client requests and responses with custom options.
|
||||
// Provides fine-grained control over what is logged (request body, response body, combined logs).
|
||||
func LogWithOptions(logger log.Logger, opts ...LogOption) request.Middleware {
|
||||
cfg := &logConfig{
|
||||
logRequestBody: false,
|
||||
logResponseBody: false,
|
||||
combinedLog: false,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(cfg)
|
||||
}
|
||||
|
||||
if cfg.combinedLog {
|
||||
return logCombinedMiddleware(logger, cfg)
|
||||
}
|
||||
return logMiddleware(logger, cfg)
|
||||
}
|
||||
|
||||
// logMiddleware implements request/response logging with separate log entries.
|
||||
func logMiddleware(logger log.Logger, cfg *logConfig) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
requestFields := []log.Field{
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
}
|
||||
if cfg.logRequestBody {
|
||||
requestFields = append(requestFields, log.ByteString("requestBody", message.GetBytesBody()))
|
||||
}
|
||||
logger.Debug(ctx, "grpc client: request", requestFields...)
|
||||
|
||||
var responseFields []log.Field
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next(ctx, builder, message)
|
||||
if err != nil {
|
||||
responseFields = append(responseFields,
|
||||
log.Any("error", err),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
logger.Debug(ctx, "grpc client: response with error", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
|
||||
responseFields = append(responseFields,
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
if cfg.logResponseBody {
|
||||
responseFields = append(responseFields, log.ByteString("responseBody", resp.GetBytesBody()))
|
||||
}
|
||||
|
||||
logger.Debug(ctx, "grpc client: response", responseFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// logCombinedMiddleware implements logging with a single combined log entry.
|
||||
func logCombinedMiddleware(logger log.Logger, cfg *logConfig) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
logFields := []log.Field{
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
}
|
||||
if cfg.logRequestBody {
|
||||
logFields = append(logFields, log.ByteString("requestBody", message.GetBytesBody()))
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
resp, err := next(ctx, builder, message)
|
||||
|
||||
logFields = append(logFields,
|
||||
log.String("endpoint", builder.Endpoint),
|
||||
log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
logFields = append(logFields, log.Any("error", err))
|
||||
logger.Debug(ctx, "grpc client: log with error", logFields...)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
if cfg.logResponseBody {
|
||||
logFields = append(logFields, log.ByteString("responseBody", resp.GetBytesBody()))
|
||||
}
|
||||
logger.Debug(ctx, "grpc client: log", logFields...)
|
||||
|
||||
return resp, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MetricStorage defines the interface for metric storage implementations.
|
||||
// Used by the Metrics middleware to collect timing information.
|
||||
type MetricStorage interface {
|
||||
// ObserveDuration records the duration of a request for the given endpoint.
|
||||
ObserveDuration(endpoint string, duration time.Duration)
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that collects timing metrics for gRPC client requests.
|
||||
// The storage implementation receives the endpoint name and request duration.
|
||||
func Metrics(storage MetricStorage) request.Middleware {
|
||||
return func(next request.RoundTripper) request.RoundTripper {
|
||||
return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) {
|
||||
start := time.Now()
|
||||
response, err := next(ctx, builder, message)
|
||||
storage.ObserveDuration(builder.Endpoint, time.Since(start))
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/grpc/client/request"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Option configures a Client using the functional options pattern.
|
||||
type Option func(cli *Client)
|
||||
|
||||
// WithMiddlewares adds one or more request middleware to the client.
|
||||
// Middleware are executed in the order they are provided.
|
||||
func WithMiddlewares(middlewares ...request.Middleware) Option {
|
||||
return func(cli *Client) {
|
||||
cli.middlewares = append(cli.middlewares, middlewares...)
|
||||
}
|
||||
}
|
||||
|
||||
// WithDialOptions sets custom gRPC dial options for the client.
|
||||
// Note: This replaces any previously set dial options.
|
||||
func WithDialOptions(dialOptions ...grpc.DialOption) Option {
|
||||
return func(cli *Client) {
|
||||
cli.dialOptions = dialOptions
|
||||
}
|
||||
}
|
||||
|
||||
// WithAcceptEncodedResponse sets acceptEncodedResponse flag.
|
||||
func WithAcceptEncodedResponse(accept bool) Option {
|
||||
return func(c *Client) {
|
||||
c.acceptEncodedResponse = accept
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncodeRequest sets encodeRequest flag.
|
||||
func WithEncodeRequest(encode bool) Option {
|
||||
return func(c *Client) {
|
||||
c.encodeRequest = encode
|
||||
}
|
||||
}
|
||||
|
||||
// WithEncodeThreshold sets the request encoding threshold in bytes.
|
||||
func WithEncodeThreshold(thresholdBytes int) Option {
|
||||
return func(c *Client) {
|
||||
c.encodeThreshold = thresholdBytes
|
||||
}
|
||||
}
|
||||
|
||||
// WithCodec sets codec.
|
||||
func WithCodec(codec Codec) Option {
|
||||
return func(c *Client) {
|
||||
c.codec = codec
|
||||
}
|
||||
}
|
||||
|
||||
// LogOption configures logging behavior for request middleware.
|
||||
type LogOption func(cfg *logConfig)
|
||||
|
||||
// WithLogBody enables logging of both request and response bodies.
|
||||
func WithLogBody(logBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logBody
|
||||
cfg.logRequestBody = logBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogResponseBody enables or disables logging of response bodies.
|
||||
func WithLogResponseBody(logResponseBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logResponseBody = logResponseBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithLogRequestBody enables or disables logging of request bodies.
|
||||
func WithLogRequestBody(logRequestBody bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.logRequestBody = logRequestBody
|
||||
}
|
||||
}
|
||||
|
||||
// WithCombinedLog enables a single combined log entry for request and response.
|
||||
// When disabled, requests and responses are logged separately.
|
||||
func WithCombinedLog(enable bool) LogOption {
|
||||
return func(cfg *logConfig) {
|
||||
cfg.combinedLog = enable
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
# Package `request`
|
||||
|
||||
Пакет `request` предоставляет билдер для построения gRPC-запросов с поддержкой JSON-сериализации, таймаутов, метаданных
|
||||
и цепочек обработки через middleware. Интегрируется с клиентом из пакета [`client`](../client.go).
|
||||
|
||||
## Types
|
||||
|
||||
### Builder
|
||||
|
||||
Структура для пошагового конструирования gRPC-запроса. Обрабатывает сериализацию/десериализацию JSON, управление
|
||||
контекстом и метаданными.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewBuilder(roundTripper RoundTripper, endpoint string) *Builder`
|
||||
|
||||
Создать новый билдер для указанного эндпоинта.
|
||||
|
||||
#### `(req *Builder) ApplicationId(appId int) *Builder`
|
||||
|
||||
Установить идентификатор системы в заголовок `x-application-identity`.
|
||||
|
||||
#### `(req *Builder) JsonRequestBody(reqBody any) *Builder`
|
||||
|
||||
Задать тело запроса в формате JSON. Объект будет сериализован автоматически при помощи функций из пакета [
|
||||
`json`](../../json) (маршалинг без тэгов в camelCase).
|
||||
|
||||
#### `(req *Builder) JsonResponseBody(respPtr any) *Builder`
|
||||
|
||||
Задать указатель для десериализации тела ответа из JSON.
|
||||
|
||||
#### `(req *Builder) Timeout(timeout time.Duration) *Builder`
|
||||
|
||||
Установить тайм-аут для запроса. По умолчанию: 15 секунд.
|
||||
|
||||
#### `(req *Builder) AppendMetadata(k string, v ...string) *Builder`
|
||||
|
||||
Добавить кастомные метаданные в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг кодирования запроса.
|
||||
Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `content-encoding` со значением типа codec и тело запроса будет закодировано.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder`
|
||||
|
||||
Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest).
|
||||
|
||||
#### `(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder`
|
||||
|
||||
Установить флаг приёма закодированных ответов.
|
||||
Если включен, то в заголовки запроса будет добавлен `accept-encoding` со значением типа codec + identity (пример `zstd, identity`).
|
||||
|
||||
#### `(req *Builder) Do(ctx context.Context) error`
|
||||
|
||||
Выполнить запрос. Автоматически:
|
||||
|
||||
1. Сериализует тело запроса в JSON
|
||||
2. Добавляет системные заголовки (`x-application-identity`, `proxy_method_name`)
|
||||
3. Обрабатывает цепочку middleware
|
||||
4. Десериализует ответ (если задан `responsePtr`)
|
||||
|
||||
## Functions
|
||||
|
||||
#### `Default(restMiddlewares ...request.Middleware) (*Client, error)`
|
||||
|
||||
Создать клиент с настройками по умолчанию:
|
||||
|
||||
- Максимальный размер сообщения 64 МБ.
|
||||
- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга
|
||||
|
||||
#### `RequestId() request.Middleware`
|
||||
|
||||
Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то
|
||||
передаваться будет именно он.
|
||||
|
||||
#### `Log(logger log.Logger, logBody bool) request.Middleware`
|
||||
|
||||
Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`.
|
||||
|
||||
#### `Metrics(storage MetricStorage) request.Middleware`
|
||||
|
||||
Middleware для сбора метрик длительности запросов.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
cli, err := client.Default(client.Log(logger, true))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer cli.Close()
|
||||
|
||||
cli.Upgrade([]string{"host1:8080", "host2:9000"})
|
||||
|
||||
u := new(user)
|
||||
err = cli.Invoke("/get_user").
|
||||
ApplicationId(88).
|
||||
JsonRequestBody(getUserRequest{Id: "some-user-id"}).
|
||||
JsonResponseBody(u).
|
||||
Timeout(5 * time.Second).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
log.Printf("username: %s\n", u.Name)
|
||||
}
|
||||
|
||||
```
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
// Package request provides a fluent builder for constructing and executing gRPC requests.
|
||||
// It handles JSON marshaling/unmarshaling, metadata management, and timeout configuration.
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultTimeout is the default request timeout when none is specified.
|
||||
defaultTimeout = 15 * time.Second
|
||||
)
|
||||
|
||||
type EncodeSettings struct {
|
||||
EncodeRequest bool
|
||||
EncodeThreshold int
|
||||
AcceptEncodedResponse bool
|
||||
}
|
||||
|
||||
// Builder provides a fluent API for constructing and executing gRPC requests.
|
||||
// It handles JSON marshaling, metadata management, and timeout configuration.
|
||||
// Builder is not safe for concurrent use; create a new instance for each request.
|
||||
type Builder struct {
|
||||
Endpoint string
|
||||
MD metadata.MD
|
||||
EncodeSettings EncodeSettings
|
||||
|
||||
requestBody any
|
||||
responsePtr any
|
||||
applicationId int
|
||||
timeout time.Duration
|
||||
roundTripper RoundTripper
|
||||
}
|
||||
|
||||
// NewBuilder creates a new Builder for the specified endpoint.
|
||||
// Initializes with default timeout and empty metadata.
|
||||
func NewBuilder(
|
||||
roundTripper RoundTripper,
|
||||
endpoint string,
|
||||
encodeSettings EncodeSettings,
|
||||
) *Builder {
|
||||
return &Builder{
|
||||
Endpoint: endpoint,
|
||||
MD: metadata.New(make(map[string]string)),
|
||||
roundTripper: roundTripper,
|
||||
timeout: defaultTimeout,
|
||||
EncodeSettings: encodeSettings,
|
||||
}
|
||||
}
|
||||
|
||||
// ApplicationId sets the application identity header for the request.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) ApplicationId(appId int) *Builder {
|
||||
req.applicationId = appId
|
||||
return req
|
||||
}
|
||||
|
||||
// JsonRequestBody sets the request body as a JSON-encodable value.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) JsonRequestBody(reqBody any) *Builder {
|
||||
req.requestBody = reqBody
|
||||
return req
|
||||
}
|
||||
|
||||
// JsonResponseBody sets the pointer to unmarshal the JSON response into.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) JsonResponseBody(respPtr any) *Builder {
|
||||
req.responsePtr = respPtr
|
||||
return req
|
||||
}
|
||||
|
||||
// Timeout sets the request timeout duration.
|
||||
// A timeout of zero or negative disables the timeout.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) Timeout(timeout time.Duration) *Builder {
|
||||
req.timeout = timeout
|
||||
return req
|
||||
}
|
||||
|
||||
// AppendMetadata adds one or more values to the metadata key.
|
||||
// Returns the Builder for method chaining.
|
||||
func (req *Builder) AppendMetadata(k string, v ...string) *Builder {
|
||||
req.MD[k] = append(req.MD[k], v...)
|
||||
return req
|
||||
}
|
||||
|
||||
// EncodeRequest sets encoding for request body.
|
||||
// It affects content-encoding and request body serialization.
|
||||
func (b *Builder) EncodeRequest(encode bool) *Builder {
|
||||
b.EncodeSettings.EncodeRequest = encode
|
||||
return b
|
||||
}
|
||||
|
||||
// AcceptEncodedResponse enables transparent handling of encoded GRPC responses.
|
||||
//
|
||||
// When enabled, the client adds "accept-encoding" (e.g. zstd) to request headers,
|
||||
// allowing the server to return encoded payloads.
|
||||
func (b *Builder) AcceptEncodedResponse(accept bool) *Builder {
|
||||
b.EncodeSettings.AcceptEncodedResponse = accept
|
||||
return b
|
||||
}
|
||||
|
||||
// EncodeThreshold sets the request encoding threshold in bytes.
|
||||
func (b *Builder) EncodeThreshold(thresholdBytes int) *Builder {
|
||||
b.EncodeSettings.EncodeThreshold = thresholdBytes
|
||||
return b
|
||||
}
|
||||
|
||||
// Do executes the request and unmarshals the response if a response pointer was provided.
|
||||
// Returns an error if JSON marshaling, request execution, or response unmarshaling fails.
|
||||
// Automatically applies the configured timeout to the request context.
|
||||
func (req *Builder) Do(ctx context.Context) error {
|
||||
var (
|
||||
reqCtx = ctx
|
||||
cancel context.CancelFunc
|
||||
)
|
||||
if req.timeout > 0 {
|
||||
reqCtx, cancel = context.WithTimeout(ctx, req.timeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
req.MD.Set(grpc.ProxyMethodNameHeader, req.Endpoint)
|
||||
if req.applicationId != 0 {
|
||||
req.MD.Set(grpc.ApplicationIdHeader, strconv.Itoa(req.applicationId))
|
||||
}
|
||||
ctx = metadata.NewOutgoingContext(reqCtx, req.MD)
|
||||
|
||||
var body []byte
|
||||
var err error
|
||||
if req.requestBody != nil {
|
||||
body, err = json.Marshal(req.requestBody)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal to json request body")
|
||||
}
|
||||
}
|
||||
message := &isp.Message{Body: &isp.Message_BytesBody{BytesBody: body}}
|
||||
|
||||
resp, err := req.roundTripper(ctx, req, message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if req.responsePtr != nil {
|
||||
err = json.Unmarshal(resp.GetBytesBody(), req.responsePtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "unmarshal response body")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package request
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// RoundTripper defines the interface for executing gRPC requests.
|
||||
// Receives a context, request builder, and message; returns a response message and optional error.
|
||||
// Used as the base for middleware chains.
|
||||
type RoundTripper func(ctx context.Context, builder *Builder, message *isp.Message) (*isp.Message, error)
|
||||
|
||||
// Middleware wraps a RoundTripper to add cross-cutting concerns like logging,
|
||||
// metrics, authentication, or error handling.
|
||||
// Middleware functions are typically chained in reverse order of execution.
|
||||
type Middleware func(next RoundTripper) RoundTripper
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// HandlerFunc defines the signature for gRPC request handlers.
|
||||
// Receives a context and message, returns a response message and optional error.
|
||||
type HandlerFunc func(ctx context.Context, message *isp.Message) (*isp.Message, error)
|
||||
|
||||
// Middleware wraps a HandlerFunc to add cross-cutting concerns like logging,
|
||||
// metrics, authentication, or error handling.
|
||||
// Middleware functions are typically chained in reverse order of execution.
|
||||
type Middleware func(next HandlerFunc) HandlerFunc
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package grpc
|
||||
|
||||
const (
|
||||
// AcceptEncodingHeader is the metadata key for accept encoding.
|
||||
AcceptEncodingHeader = "x-accept-encoding"
|
||||
|
||||
// ContentEncodingHeader is the metadata key for content encoding.
|
||||
ContentEncodingHeader = "x-content-encoding"
|
||||
)
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
# Package `endpoint`
|
||||
|
||||
Пакет `endpoint` предоставляет инструменты для создания gRPC-обработчиков с автоматической сериализацией JSON,
|
||||
валидацией запросов, middleware-цепочками и интеграцией метрик/логирования. Реализует паттерн "Endpoint" для изоляции
|
||||
бизнес-логики от транспортного слоя.
|
||||
|
||||
## Types
|
||||
|
||||
### Wrapper
|
||||
|
||||
Основная структура для создания цепочек обработки запросов. Объединяет:
|
||||
|
||||
- Маппинг параметров
|
||||
- Middleware (логирование, метрики, восстановление после паник)
|
||||
- Сериализацию/валидацию JSON
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper) Wrapper`
|
||||
|
||||
Создает конфигурацию для обработчиков.
|
||||
Параметры:
|
||||
|
||||
- `paramMappers` – правила извлечения параметров из контекста/метаданных
|
||||
- `bodyExtractor` – десериализация и валидация тела запроса
|
||||
- `bodyMapper` – сериализация ответа
|
||||
|
||||
#### `(m Wrapper) Endpoint(f any) grpc.HandlerFunc`
|
||||
|
||||
Преобразует пользовательскую функцию в gRPC-обработчик.
|
||||
Функция `f` может содержать параметры:
|
||||
|
||||
- `context.Context`
|
||||
- `grpc.AuthData` (метаданные аутентификации)
|
||||
- Пользовательский тип (десериализуется из JSON-тела)
|
||||
|
||||
#### `(m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Добавляет middleware в цепочку обработки.
|
||||
|
||||
### Caller
|
||||
|
||||
Внутренняя структура для вызова пользовательских обработчиков. Автоматически:
|
||||
|
||||
- Извлекает параметры
|
||||
- Вызывает middleware
|
||||
- Обрабатывает ошибки
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`NewCaller(f any,bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)`
|
||||
|
||||
Создает экземпляр `Caller` для функции-обработчика.
|
||||
|
||||
#### `(h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error)`
|
||||
|
||||
Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса.
|
||||
|
||||
### JsonRequestExtractor
|
||||
|
||||
Реализация интерфейса `RequestBodyExtractor` для работы с JSON. Валидирует данные с помощью объекта, реализующего
|
||||
интерфейс `Validator`.
|
||||
|
||||
**Methods:**
|
||||
|
||||
####
|
||||
|
||||
`(j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)`
|
||||
|
||||
Десериализует и валидирует JSON-тело запроса через `Validator`.
|
||||
|
||||
### JsonResponseMapper
|
||||
|
||||
Сериализует ответ обработчика в JSON-тело gRPC-сообщения.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(j JsonResponseMapper) Map(result any) (*isp.Message, error)`
|
||||
|
||||
Конвертирует результат обработчика в gRPC-сообщение в формате JSON.
|
||||
|
||||
## Middlewares
|
||||
|
||||
### `MaxRequestBodySize`
|
||||
|
||||
Ограничивает размер тела запроса (по умолчанию 64 МБ).
|
||||
|
||||
### `RequestId`
|
||||
|
||||
Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит.
|
||||
|
||||
### `DecodeRequest`
|
||||
Декодирует запрос при помощи переданного codec, если заголовок `x-content-encoding` совпадает с типом codec.
|
||||
|
||||
### `Metrics`
|
||||
|
||||
Собирает метрики: время выполнения, статусы, размеры тел.
|
||||
|
||||
### `Tracing`
|
||||
|
||||
Интеграция с трейсингом (OpenTelemetry).
|
||||
|
||||
### `EncodeResponse`
|
||||
|
||||
Кодирует ответ при помощи переданного codec, если заголовок `x-accept-encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах).
|
||||
|
||||
### `ErrorHandler`
|
||||
|
||||
Перехватывает и обрабатывает ошибки. Ошибки типа `GrpcError` возвращают структурированный ответ.
|
||||
Остальные ошибки логируются и возвращаются как Internal Server Error с gRPC-кодом 13.
|
||||
|
||||
### `Recovery`
|
||||
|
||||
Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку.
|
||||
|
||||
## Functions
|
||||
|
||||
#### `DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `RequestId`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
#### `DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper`
|
||||
|
||||
Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами.
|
||||
Упрощает создание эндпоинтов, включая валидацию, декодирование запросов, кодировение ответов, метрики и обработку ошибок "из коробки".
|
||||
|
||||
Список Middleware:
|
||||
|
||||
- `RequestId`
|
||||
- `DecodeRequest`
|
||||
- `Metrics`
|
||||
- `Tracing`
|
||||
- `EncodeResponse`
|
||||
- `ErrorHandler`
|
||||
- `Recovery`
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) {
|
||||
appId, _ := authData.ApplicationId()
|
||||
log.Printf("Request from app with id %d", appId)
|
||||
|
||||
/* put here business logic */
|
||||
|
||||
return &user{Id: req.Id, Name: "Alice"}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
mux := grpc.NewMux()
|
||||
wrapper := endpoint.DefaultWrapper(logger)
|
||||
mux.Handle("/get_user", wrapper.Endpoint(getUser))
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Codec usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
type getUserRequest struct {
|
||||
Id string
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) {
|
||||
appId, _ := authData.ApplicationId()
|
||||
log.Printf("Request from app with id %d", appId)
|
||||
|
||||
/* put here business logic */
|
||||
|
||||
return &user{Id: req.Id, Name: "Alice"}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
mux := grpc.NewMux()
|
||||
wrapper := endpoint.DefaultCodecWrapper(logger)
|
||||
mux.Handle("/get_user", wrapper.Endpoint(getUser))
|
||||
|
||||
srv := grpc.DefaultServer()
|
||||
srv.Upgrade(mux)
|
||||
|
||||
shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */
|
||||
log.Println("shutting down...")
|
||||
srv.Shutdown()
|
||||
log.Println("shutdown completed")
|
||||
})
|
||||
|
||||
err = srv.ListenAndServe(":8080")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// param represents a single parameter to be injected into a wrapped function.
|
||||
type param struct {
|
||||
index int
|
||||
builder ParamBuilder
|
||||
}
|
||||
|
||||
// Caller wraps a function for gRPC invocation using reflection.
|
||||
// It analyzes the function signature, injects dependencies, and handles
|
||||
// request/response marshaling automatically.
|
||||
type Caller struct {
|
||||
bodyExtractor RequestBodyExtractor
|
||||
bodyMapper ResponseBodyMapper
|
||||
|
||||
handler reflect.Value
|
||||
paramsCount int
|
||||
params []param
|
||||
reqBodyIndex int
|
||||
reqBodyType reflect.Type
|
||||
|
||||
hasResult bool
|
||||
hasError bool
|
||||
errorIndex int
|
||||
}
|
||||
|
||||
// NewCaller creates a new Caller for the specified function.
|
||||
// Analyzes the function signature to determine parameter types and return values.
|
||||
// Returns an error if the input is not a function or if parameter types cannot be resolved.
|
||||
func NewCaller(
|
||||
f any,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
bodyMapper ResponseBodyMapper,
|
||||
paramMappers map[string]ParamMapper,
|
||||
) (*Caller, error) {
|
||||
rt := reflect.TypeOf(f)
|
||||
if rt.Kind() != reflect.Func {
|
||||
return nil, errors.New("function expected")
|
||||
}
|
||||
|
||||
paramsCount := rt.NumIn()
|
||||
reqBodyIndex := -1
|
||||
handler := reflect.ValueOf(f)
|
||||
var reqBodyType reflect.Type
|
||||
params := make([]param, 0, paramsCount)
|
||||
|
||||
for i := range paramsCount {
|
||||
p := rt.In(i)
|
||||
paramType := p.String()
|
||||
mapper, ok := paramMappers[paramType]
|
||||
|
||||
if !ok { // maybe it's a request body
|
||||
if reqBodyIndex != -1 {
|
||||
return nil, errors.Errorf("param mapper not found for type %s", paramType)
|
||||
}
|
||||
reqBodyIndex = i
|
||||
reqBodyType = p
|
||||
continue
|
||||
}
|
||||
|
||||
// it's a simple param
|
||||
params = append(params, param{index: i, builder: mapper.Builder})
|
||||
}
|
||||
|
||||
numOut := rt.NumOut()
|
||||
hasResult := numOut > 0 && rt.Out(0) != reflect.TypeFor[*error]().Elem()
|
||||
hasError := numOut > 0 && rt.Out(numOut-1) == reflect.TypeFor[*error]().Elem()
|
||||
|
||||
return &Caller{
|
||||
bodyExtractor: bodyExtractor,
|
||||
bodyMapper: bodyMapper,
|
||||
handler: handler,
|
||||
paramsCount: paramsCount,
|
||||
params: params,
|
||||
reqBodyIndex: reqBodyIndex,
|
||||
reqBodyType: reqBodyType,
|
||||
hasResult: hasResult,
|
||||
hasError: hasError,
|
||||
errorIndex: numOut - 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Handle executes the wrapped function with the provided context and message.
|
||||
// Injects parameters, extracts request body, calls the function, and maps the result.
|
||||
// Returns the response message and any error from the function or parameter extraction.
|
||||
func (h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
args := make([]reflect.Value, h.paramsCount)
|
||||
|
||||
if h.reqBodyIndex != -1 {
|
||||
value, err := h.bodyExtractor.Extract(ctx, message, h.reqBodyType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args[h.reqBodyIndex] = value
|
||||
}
|
||||
|
||||
for _, p := range h.params {
|
||||
value, err := p.builder(ctx, message)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
args[p.index] = reflect.ValueOf(value)
|
||||
}
|
||||
|
||||
out := h.handler.Call(args)
|
||||
|
||||
if h.hasError && !out[h.errorIndex].IsNil() {
|
||||
return nil, out[h.errorIndex].Interface().(error) // nolint:forcetypeassert
|
||||
}
|
||||
|
||||
if h.hasResult {
|
||||
return h.bodyMapper.Map(out[0].Interface())
|
||||
}
|
||||
|
||||
return nil, nil // nolint:nilnil
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/grpc_metrics"
|
||||
"github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing"
|
||||
"github.com/txix-open/isp-kit/validator"
|
||||
)
|
||||
|
||||
// DefaultWrapper creates a Wrapper with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, distributed tracing, error handling,
|
||||
// and panic recovery. Uses JSON for request extraction and response mapping.
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
func DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
Metrics(metricStorage),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
|
||||
// DefaultCodecWrapper creates a Wrapper with pre-configured middleware for observability.
|
||||
// Includes request ID propagation, metrics collection, distributed tracing, error handling, encode response, decode request,
|
||||
// and panic recovery. Uses JSON for request extraction and response mapping.
|
||||
// Accepts additional middleware to be appended after the default ones.
|
||||
func DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper {
|
||||
paramMappers := []ParamMapper{
|
||||
ContextParam(),
|
||||
AuthDataParam(),
|
||||
}
|
||||
metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||
codec := codec.Default
|
||||
middlewares := append(
|
||||
[]grpc.Middleware{
|
||||
RequestId(),
|
||||
DecodeRequest(codec),
|
||||
Metrics(metricStorage),
|
||||
server_tracing.NewConfig().Middleware(),
|
||||
EncodeResponse(codec, defaultEncodeThreshold),
|
||||
ErrorHandler(logger),
|
||||
Recovery(),
|
||||
},
|
||||
restMiddlewares...,
|
||||
)
|
||||
return NewWrapper(
|
||||
paramMappers,
|
||||
JsonRequestExtractor{Validator: validator.Default},
|
||||
JsonResponseMapper{},
|
||||
).WithMiddlewares(middlewares...)
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"unicode"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
const (
|
||||
// errCodeBadRequest is the error code for invalid request body errors.
|
||||
errCodeBadRequest = 400
|
||||
)
|
||||
|
||||
// Validator defines the interface for request validation.
|
||||
// Implementations should validate a value and return whether it's valid
|
||||
// along with field-specific error details.
|
||||
type Validator interface {
|
||||
// Validate checks if the value is valid.
|
||||
// Returns true if valid, false otherwise, along with a map of field names to error messages.
|
||||
Validate(value any) (bool, map[string]string)
|
||||
}
|
||||
|
||||
// JsonRequestExtractor extracts and validates JSON request bodies from gRPC messages.
|
||||
// Unmarshals the message body into the target type and validates it using the configured validator.
|
||||
type JsonRequestExtractor struct {
|
||||
Validator Validator
|
||||
}
|
||||
|
||||
// Extract unmarshals the message body as JSON and validates it.
|
||||
// Returns a reflect.Value of the created instance or an error if unmarshaling or validation fails.
|
||||
// Business validation errors are returned as apierrors.BusinessError with code 400.
|
||||
func (j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error) {
|
||||
instance := reflect.New(reqBodyType)
|
||||
err := json.Unmarshal(message.GetBytesBody(), instance.Interface())
|
||||
if err != nil {
|
||||
err = errors.WithMessage(err, "unmarshal json request body")
|
||||
return reflect.Value{}, apierrors.NewBusinessError(errCodeBadRequest, err.Error(), err)
|
||||
}
|
||||
|
||||
elem := instance.Elem()
|
||||
|
||||
ok, details := j.Validator.Validate(elem.Interface())
|
||||
if ok {
|
||||
return elem, nil
|
||||
}
|
||||
formattedDetails := formatDetails(details)
|
||||
return reflect.Value{}, apierrors.NewBusinessError(
|
||||
errCodeBadRequest,
|
||||
"invalid request body",
|
||||
errors.Errorf("validation errors: %v", formattedDetails),
|
||||
).WithDetails(formattedDetails)
|
||||
}
|
||||
|
||||
// formatDetails converts a map of field error messages to a format suitable for API responses.
|
||||
// Converts field names to lowercase (first character) for consistency.
|
||||
func formatDetails(details map[string]string) map[string]any {
|
||||
result := make(map[string]any, len(details))
|
||||
for k, v := range details {
|
||||
arr := []rune(k)
|
||||
arr[0] = unicode.ToLower(arr[0])
|
||||
result[string(arr)] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// JsonResponseMapper maps handler results to gRPC messages with JSON-encoded bodies.
|
||||
// Implements the ResponseBodyMapper interface.
|
||||
type JsonResponseMapper struct{}
|
||||
|
||||
// Map marshals the result to JSON and creates a gRPC message.
|
||||
// Returns an empty message body if result is nil.
|
||||
// Returns an error if JSON marshaling fails.
|
||||
func (j JsonResponseMapper) Map(result any) (*isp.Message, error) {
|
||||
if result == nil {
|
||||
return &isp.Message{Body: &isp.Message_BytesBody{}}, nil
|
||||
}
|
||||
data, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "marshal json")
|
||||
}
|
||||
return &isp.Message{
|
||||
Body: &isp.Message_BytesBody{
|
||||
BytesBody: data,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// MetricStorage defines the interface for collecting gRPC server metrics.
|
||||
// Implementations should record request durations, payload sizes, and response codes.
|
||||
type MetricStorage interface {
|
||||
// ObserveDuration records the duration of a request for the given method.
|
||||
ObserveDuration(method string, duration time.Duration)
|
||||
// ObserveRequestBodySize records the size of the request body.
|
||||
ObserveRequestBodySize(method string, size int)
|
||||
// ObserveResponseBodySize records the size of the response body.
|
||||
ObserveResponseBodySize(method string, size int)
|
||||
// CountStatusCode increments the counter for the given endpoint and status code.
|
||||
CountStatusCode(endpoint string, code codes.Code)
|
||||
}
|
||||
|
||||
// Metrics creates a middleware that collects metrics for gRPC server requests.
|
||||
// Records request duration, request/response body sizes, and response status codes.
|
||||
// The endpoint name is extracted from the ProxyMethodNameHeader in request metadata.
|
||||
func Metrics(storage MetricStorage) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
endpoint, err := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
storage.ObserveRequestBodySize(endpoint, len(message.GetBytesBody()))
|
||||
start := time.Now()
|
||||
response, err := next(ctx, message)
|
||||
storage.ObserveDuration(endpoint, time.Since(start))
|
||||
storage.CountStatusCode(endpoint, status.Code(err))
|
||||
if response != nil {
|
||||
storage.ObserveResponseBodySize(endpoint, len(response.GetBytesBody()))
|
||||
}
|
||||
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/log/logutil"
|
||||
sentry2 "github.com/txix-open/isp-kit/observability/sentry"
|
||||
"github.com/txix-open/isp-kit/panic_recovery"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
grpc2 "google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEncodeThreshold = codec.DefaultEncodeThreshold
|
||||
)
|
||||
|
||||
// Recovery creates a middleware that catches panics and converts them to errors.
|
||||
// Prevents gRPC server crashes from handler panics by recovering and returning the error.
|
||||
func Recovery() grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (msg *isp.Message, err error) {
|
||||
defer panic_recovery.Recover(func(panicErr error) {
|
||||
err = panicErr
|
||||
})
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ErrorHandler creates a middleware that handles errors from downstream handlers.
|
||||
// Logs errors at appropriate levels, enriches them with Sentry context, and
|
||||
// converts custom GrpcError types to gRPC status errors.
|
||||
// Returns a generic "internal service error" for unknown error types to prevent
|
||||
// information leakage.
|
||||
func ErrorHandler(logger log.Logger) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
result, err := next(ctx, message)
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
|
||||
logFunc := logutil.LogLevelFuncForError(err, logger)
|
||||
logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) {
|
||||
event.Request = sentryRequest(ctx)
|
||||
})
|
||||
logFunc(logContext, err)
|
||||
|
||||
var grpcErr GrpcError
|
||||
if errors.As(err, &grpcErr) {
|
||||
return result, grpcErr.GrpcStatusError()
|
||||
}
|
||||
|
||||
// deprecated approach
|
||||
_, ok := status.FromError(err)
|
||||
if ok {
|
||||
return result, err
|
||||
}
|
||||
|
||||
// hide error details to prevent potential security leaks
|
||||
return result, status.Error(codes.Internal, "internal service error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RequestId creates a middleware that manages request IDs for tracing.
|
||||
// Extracts the request ID from incoming metadata, generates a new one if absent,
|
||||
// and injects it into the context for downstream use.
|
||||
func RequestId() grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
values := md.Get(requestid.Header)
|
||||
requestId := ""
|
||||
if len(values) > 0 {
|
||||
requestId = values[0]
|
||||
}
|
||||
if requestId == "" {
|
||||
requestId = requestid.Next()
|
||||
}
|
||||
ctx = requestid.ToContext(ctx, requestId)
|
||||
ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId))
|
||||
|
||||
return next(ctx, message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type DecodeCodec interface {
|
||||
Type() string
|
||||
DecodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// DecodeRequest returns middleware that transparently handles decoded requests.
|
||||
//
|
||||
// If x-content-encoding matches codec, request body is decoded.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see decoded data.
|
||||
func DecodeRequest(codec DecodeCodec) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
|
||||
contentEncoding, _ := grpc.StringFromMd(grpc.ContentEncodingHeader, md)
|
||||
reqBody := msg.GetBytesBody()
|
||||
if contentEncoding == codec.Type() {
|
||||
decoded, err := codec.DecodeBytes(reqBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msg.Body = &isp.Message_BytesBody{
|
||||
BytesBody: decoded,
|
||||
}
|
||||
md.Delete(grpc.ContentEncodingHeader)
|
||||
ctx = metadata.NewIncomingContext(ctx, md)
|
||||
}
|
||||
|
||||
return next(ctx, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type EncodeCodec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// EncodeResponse returns middleware that transparently handles response encoding.
|
||||
//
|
||||
// If client supports x-accept-encoding and response body size > encodeThresholdBytes,
|
||||
// the response is encoded using codec.
|
||||
//
|
||||
// Important:
|
||||
// - Should be placed before logging middleware if logs must see plain data.
|
||||
func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) grpc.Middleware {
|
||||
return func(next grpc.HandlerFunc) grpc.HandlerFunc {
|
||||
return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
|
||||
resp, err := next(ctx, msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check accept
|
||||
acceptEncoding, _ := grpc.StringFromMd(grpc.AcceptEncodingHeader, md)
|
||||
if !acceptsEncoding(acceptEncoding, codec.Type()) {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
responseBody := resp.GetBytesBody()
|
||||
if len(responseBody) <= encodeThresholdBytes {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
err = grpc2.SetHeader(ctx, metadata.Pairs(
|
||||
grpc.ContentEncodingHeader, codec.Type(),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
encoded, err := codec.EncodeBytes(responseBody)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp.Body = &isp.Message_BytesBody{
|
||||
BytesBody: encoded,
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// acceptsEncoding split header and check contains encoding in it.
|
||||
func acceptsEncoding(header, encoding string) bool {
|
||||
for part := range strings.SplitSeq(header, ",") {
|
||||
if strings.TrimSpace(part) == encoding {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// sentryRequest creates a Sentry request object from the gRPC context.
|
||||
// Extracts endpoint and application ID from metadata for error tracking.
|
||||
func sentryRequest(ctx context.Context) *sentry.Request {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
endpoint, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md)
|
||||
applicationId, _ := grpc.StringFromMd(grpc.ApplicationIdHeader, md)
|
||||
return &sentry.Request{
|
||||
URL: endpoint,
|
||||
Method: "POST",
|
||||
Headers: map[string]string{
|
||||
grpc.ApplicationIdHeader: applicationId,
|
||||
},
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
// ContextParam creates a ParamMapper for injecting context.Context into handlers.
|
||||
// The context is passed through from the incoming gRPC request context.
|
||||
func ContextParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "context.Context",
|
||||
Builder: func(ctx context.Context, message *isp.Message) (any, error) {
|
||||
return ctx, nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// AuthDataParam creates a ParamMapper for injecting grpc.AuthData into handlers.
|
||||
// Extracts authentication and authorization information from the incoming request metadata.
|
||||
// Returns an error if metadata is not present in the context.
|
||||
func AuthDataParam() ParamMapper {
|
||||
return ParamMapper{
|
||||
Type: "grpc.AuthData",
|
||||
Builder: func(ctx context.Context, message *isp.Message) (any, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context") // nolint:err113
|
||||
}
|
||||
return grpc.AuthData(md), nil
|
||||
},
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
// Package endpoint provides a higher-level abstraction for building gRPC handlers.
|
||||
// It enables reflection-based function wrapping with automatic request/response
|
||||
// marshaling, parameter injection, and middleware support.
|
||||
//
|
||||
// The package integrates with the ISP kit framework's logging, metrics, and
|
||||
// validation systems for comprehensive observability and error handling.
|
||||
package endpoint
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"slices"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
// GrpcError is an interface for errors that can be converted to gRPC status errors.
|
||||
// Implementations should return a gRPC status error with appropriate details.
|
||||
type GrpcError interface {
|
||||
GrpcStatusError() error
|
||||
}
|
||||
|
||||
// RequestBodyExtractor defines the interface for extracting request bodies from gRPC messages.
|
||||
// Implementations should unmarshal the message body into the target type and return a reflect.Value.
|
||||
type RequestBodyExtractor interface {
|
||||
// Extract unmarshals the message body into an instance of reqBodyType.
|
||||
// Returns the reflect.Value of the created instance and any unmarshaling or validation errors.
|
||||
Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)
|
||||
}
|
||||
|
||||
// ResponseBodyMapper defines the interface for mapping handler results to gRPC messages.
|
||||
// Implementations should marshal the result into a gRPC message body.
|
||||
type ResponseBodyMapper interface {
|
||||
// Map converts a handler result into a gRPC message.
|
||||
// Returns the message and any marshaling errors.
|
||||
Map(result any) (*isp.Message, error)
|
||||
}
|
||||
|
||||
// ParamBuilder defines a function that builds a parameter value from context and message.
|
||||
// Used by ParamMapper to inject dependencies like context, auth data, etc.
|
||||
type ParamBuilder func(ctx context.Context, message *isp.Message) (any, error)
|
||||
|
||||
// ParamMapper maps a parameter type string to a builder function.
|
||||
// Used to inject dependencies into handler functions automatically.
|
||||
type ParamMapper struct {
|
||||
// Type is the string representation of the parameter type.
|
||||
Type string
|
||||
// Builder is the function that creates the parameter value.
|
||||
Builder ParamBuilder
|
||||
}
|
||||
|
||||
// Wrapper is a high-level handler factory that wraps functions with middleware and
|
||||
// automatic request/response handling. It uses reflection to analyze function signatures
|
||||
// and inject dependencies like context and auth data.
|
||||
type Wrapper struct {
|
||||
ParamMappers map[string]ParamMapper
|
||||
BodyExtractor RequestBodyExtractor
|
||||
BodyMapper ResponseBodyMapper
|
||||
Middlewares []grpc.Middleware
|
||||
}
|
||||
|
||||
// NewWrapper creates a new Wrapper with the specified configuration.
|
||||
// Accepts variadic paramMappers, a body extractor, and a body mapper.
|
||||
func NewWrapper(
|
||||
paramMappers []ParamMapper,
|
||||
bodyExtractor RequestBodyExtractor,
|
||||
bodyMapper ResponseBodyMapper,
|
||||
) Wrapper {
|
||||
mappers := make(map[string]ParamMapper)
|
||||
for _, mapper := range paramMappers {
|
||||
mappers[mapper.Type] = mapper
|
||||
}
|
||||
return Wrapper{
|
||||
ParamMappers: mappers,
|
||||
BodyExtractor: bodyExtractor,
|
||||
BodyMapper: bodyMapper,
|
||||
}
|
||||
}
|
||||
|
||||
// Endpoint wraps a function to create a gRPC HandlerFunc.
|
||||
// The function is analyzed via reflection to determine parameter types and return values.
|
||||
// Middleware is applied in reverse order (last added, first executed).
|
||||
// Panics if the function signature is invalid or cannot be wrapped.
|
||||
func (m Wrapper) Endpoint(f any) grpc.HandlerFunc {
|
||||
caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
handler := caller.Handle
|
||||
for i := range slices.Backward(m.Middlewares) {
|
||||
handler = m.Middlewares[i](handler)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
|
||||
// WithMiddlewares returns a new Wrapper with additional middleware appended.
|
||||
// The original Wrapper is not modified.
|
||||
func (m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper {
|
||||
return Wrapper{
|
||||
ParamMappers: m.ParamMappers,
|
||||
BodyExtractor: m.BodyExtractor,
|
||||
BodyMapper: m.BodyMapper,
|
||||
Middlewares: append(m.Middlewares, middlewares...),
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.31.0
|
||||
// protoc v3.21.12
|
||||
// source: backed_service.proto
|
||||
|
||||
package isp
|
||||
|
||||
import (
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
structpb "google.golang.org/protobuf/types/known/structpb"
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
state protoimpl.MessageState
|
||||
sizeCache protoimpl.SizeCache
|
||||
unknownFields protoimpl.UnknownFields
|
||||
|
||||
// Types that are assignable to Body:
|
||||
//
|
||||
// *Message_StructBody
|
||||
// *Message_ListBody
|
||||
// *Message_NullBody
|
||||
// *Message_BytesBody
|
||||
Body isMessage_Body `protobuf_oneof:"body"`
|
||||
}
|
||||
|
||||
func (x *Message) Reset() {
|
||||
*x = Message{}
|
||||
if protoimpl.UnsafeEnabled {
|
||||
mi := &file_backed_service_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
}
|
||||
|
||||
func (x *Message) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Message) ProtoMessage() {}
|
||||
|
||||
func (x *Message) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_backed_service_proto_msgTypes[0]
|
||||
if protoimpl.UnsafeEnabled && x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Message.ProtoReflect.Descriptor instead.
|
||||
func (*Message) Descriptor() ([]byte, []int) {
|
||||
return file_backed_service_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (m *Message) GetBody() isMessage_Body {
|
||||
if m != nil {
|
||||
return m.Body
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetStructBody() *structpb.Struct {
|
||||
if x, ok := x.GetBody().(*Message_StructBody); ok {
|
||||
return x.StructBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetListBody() *structpb.ListValue {
|
||||
if x, ok := x.GetBody().(*Message_ListBody); ok {
|
||||
return x.ListBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *Message) GetNullBody() structpb.NullValue {
|
||||
if x, ok := x.GetBody().(*Message_NullBody); ok {
|
||||
return x.NullBody
|
||||
}
|
||||
return structpb.NullValue(0)
|
||||
}
|
||||
|
||||
func (x *Message) GetBytesBody() []byte {
|
||||
if x, ok := x.GetBody().(*Message_BytesBody); ok {
|
||||
return x.BytesBody
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type isMessage_Body interface {
|
||||
isMessage_Body()
|
||||
}
|
||||
|
||||
type Message_StructBody struct {
|
||||
StructBody *structpb.Struct `protobuf:"bytes,1,opt,name=structBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
type Message_ListBody struct {
|
||||
ListBody *structpb.ListValue `protobuf:"bytes,2,opt,name=listBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
type Message_NullBody struct {
|
||||
NullBody structpb.NullValue `protobuf:"varint,3,opt,name=NullBody,proto3,enum=google.protobuf.NullValue,oneof"`
|
||||
}
|
||||
|
||||
type Message_BytesBody struct {
|
||||
BytesBody []byte `protobuf:"bytes,4,opt,name=BytesBody,proto3,oneof"`
|
||||
}
|
||||
|
||||
func (*Message_StructBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_ListBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_NullBody) isMessage_Body() {}
|
||||
|
||||
func (*Message_BytesBody) isMessage_Body() {}
|
||||
|
||||
var File_backed_service_proto protoreflect.FileDescriptor
|
||||
|
||||
var file_backed_service_proto_rawDesc = []byte{
|
||||
0x0a, 0x14, 0x62, 0x61, 0x63, 0x6b, 0x65, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65,
|
||||
0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03, 0x69, 0x73, 0x70, 0x1a, 0x1c, 0x67, 0x6f, 0x6f,
|
||||
0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72,
|
||||
0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe0, 0x01, 0x0a, 0x07, 0x4d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42,
|
||||
0x6f, 0x64, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67,
|
||||
0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75,
|
||||
0x63, 0x74, 0x48, 0x00, 0x52, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x6f, 0x64, 0x79,
|
||||
0x12, 0x38, 0x0a, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x02, 0x20, 0x01,
|
||||
0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
|
||||
0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00,
|
||||
0x52, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x38, 0x0a, 0x08, 0x4e, 0x75,
|
||||
0x6c, 0x6c, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x67,
|
||||
0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4e,
|
||||
0x75, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00, 0x52, 0x08, 0x4e, 0x75, 0x6c, 0x6c,
|
||||
0x42, 0x6f, 0x64, 0x79, 0x12, 0x1e, 0x0a, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73, 0x42, 0x6f, 0x64,
|
||||
0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73,
|
||||
0x42, 0x6f, 0x64, 0x79, 0x42, 0x06, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x32, 0x6c, 0x0a, 0x0e,
|
||||
0x42, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x27,
|
||||
0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e,
|
||||
0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65,
|
||||
0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x65,
|
||||
0x73, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d,
|
||||
0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65, 0x73,
|
||||
0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x3b,
|
||||
0x69, 0x73, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
|
||||
}
|
||||
|
||||
var (
|
||||
file_backed_service_proto_rawDescOnce sync.Once
|
||||
file_backed_service_proto_rawDescData = file_backed_service_proto_rawDesc
|
||||
)
|
||||
|
||||
func file_backed_service_proto_rawDescGZIP() []byte {
|
||||
file_backed_service_proto_rawDescOnce.Do(func() {
|
||||
file_backed_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_backed_service_proto_rawDescData)
|
||||
})
|
||||
return file_backed_service_proto_rawDescData
|
||||
}
|
||||
|
||||
var file_backed_service_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
|
||||
var file_backed_service_proto_goTypes = []interface{}{
|
||||
(*Message)(nil), // 0: isp.Message
|
||||
(*structpb.Struct)(nil), // 1: google.protobuf.Struct
|
||||
(*structpb.ListValue)(nil), // 2: google.protobuf.ListValue
|
||||
(structpb.NullValue)(0), // 3: google.protobuf.NullValue
|
||||
}
|
||||
var file_backed_service_proto_depIdxs = []int32{
|
||||
1, // 0: isp.Message.structBody:type_name -> google.protobuf.Struct
|
||||
2, // 1: isp.Message.listBody:type_name -> google.protobuf.ListValue
|
||||
3, // 2: isp.Message.NullBody:type_name -> google.protobuf.NullValue
|
||||
0, // 3: isp.BackendService.Request:input_type -> isp.Message
|
||||
0, // 4: isp.BackendService.RequestStream:input_type -> isp.Message
|
||||
0, // 5: isp.BackendService.Request:output_type -> isp.Message
|
||||
0, // 6: isp.BackendService.RequestStream:output_type -> isp.Message
|
||||
5, // [5:7] is the sub-list for method output_type
|
||||
3, // [3:5] is the sub-list for method input_type
|
||||
3, // [3:3] is the sub-list for extension type_name
|
||||
3, // [3:3] is the sub-list for extension extendee
|
||||
0, // [0:3] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_backed_service_proto_init() }
|
||||
func file_backed_service_proto_init() {
|
||||
if File_backed_service_proto != nil {
|
||||
return
|
||||
}
|
||||
if !protoimpl.UnsafeEnabled {
|
||||
file_backed_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
|
||||
switch v := v.(*Message); i {
|
||||
case 0:
|
||||
return &v.state
|
||||
case 1:
|
||||
return &v.sizeCache
|
||||
case 2:
|
||||
return &v.unknownFields
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
file_backed_service_proto_msgTypes[0].OneofWrappers = []interface{}{
|
||||
(*Message_StructBody)(nil),
|
||||
(*Message_ListBody)(nil),
|
||||
(*Message_NullBody)(nil),
|
||||
(*Message_BytesBody)(nil),
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: file_backed_service_proto_rawDesc,
|
||||
NumEnums: 0,
|
||||
NumMessages: 1,
|
||||
NumExtensions: 0,
|
||||
NumServices: 1,
|
||||
},
|
||||
GoTypes: file_backed_service_proto_goTypes,
|
||||
DependencyIndexes: file_backed_service_proto_depIdxs,
|
||||
MessageInfos: file_backed_service_proto_msgTypes,
|
||||
}.Build()
|
||||
File_backed_service_proto = out.File
|
||||
file_backed_service_proto_rawDesc = nil
|
||||
file_backed_service_proto_goTypes = nil
|
||||
file_backed_service_proto_depIdxs = nil
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
syntax = "proto3";
|
||||
package isp;
|
||||
// protoc --go_out=plugins=grpc:. *.proto
|
||||
|
||||
option go_package = ".;isp";
|
||||
|
||||
import "google/protobuf/struct.proto";
|
||||
|
||||
message Message {
|
||||
oneof body {
|
||||
google.protobuf.Struct structBody = 1;
|
||||
google.protobuf.ListValue listBody = 2;
|
||||
google.protobuf.NullValue NullBody = 3;
|
||||
bytes BytesBody = 4;
|
||||
}
|
||||
}
|
||||
|
||||
service BackendService {
|
||||
// ===== SYSTEM =====
|
||||
rpc Request (Message) returns (Message) {}
|
||||
|
||||
rpc RequestStream(stream Message) returns (stream Message) {}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.2.0
|
||||
// - protoc v3.21.12
|
||||
// source: backed_service.proto
|
||||
|
||||
package isp
|
||||
|
||||
import (
|
||||
context "context"
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.32.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion7
|
||||
|
||||
// BackendServiceClient is the client API for BackendService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type BackendServiceClient interface {
|
||||
// ===== SYSTEM =====
|
||||
Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error)
|
||||
RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error)
|
||||
}
|
||||
|
||||
type backendServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewBackendServiceClient(cc grpc.ClientConnInterface) BackendServiceClient {
|
||||
return &backendServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *backendServiceClient) Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) {
|
||||
out := new(Message)
|
||||
err := c.cc.Invoke(ctx, "/isp.BackendService/Request", in, out, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *backendServiceClient) RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error) {
|
||||
stream, err := c.cc.NewStream(ctx, &BackendService_ServiceDesc.Streams[0], "/isp.BackendService/RequestStream", opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &backendServiceRequestStreamClient{stream}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
type BackendService_RequestStreamClient interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
type backendServiceRequestStreamClient struct {
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamClient) Send(m *Message) error {
|
||||
return x.ClientStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamClient) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ClientStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// BackendServiceServer is the server API for BackendService service.
|
||||
// All implementations must embed UnimplementedBackendServiceServer
|
||||
// for forward compatibility
|
||||
type BackendServiceServer interface {
|
||||
// ===== SYSTEM =====
|
||||
Request(context.Context, *Message) (*Message, error)
|
||||
RequestStream(BackendService_RequestStreamServer) error
|
||||
mustEmbedUnimplementedBackendServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedBackendServiceServer must be embedded to have forward compatible implementations.
|
||||
type UnimplementedBackendServiceServer struct {
|
||||
}
|
||||
|
||||
func (UnimplementedBackendServiceServer) Request(context.Context, *Message) (*Message, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method Request not implemented")
|
||||
}
|
||||
func (UnimplementedBackendServiceServer) RequestStream(BackendService_RequestStreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "method RequestStream not implemented")
|
||||
}
|
||||
func (UnimplementedBackendServiceServer) mustEmbedUnimplementedBackendServiceServer() {}
|
||||
|
||||
// UnsafeBackendServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to BackendServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeBackendServiceServer interface {
|
||||
mustEmbedUnimplementedBackendServiceServer()
|
||||
}
|
||||
|
||||
func RegisterBackendServiceServer(s grpc.ServiceRegistrar, srv BackendServiceServer) {
|
||||
s.RegisterService(&BackendService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _BackendService_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(Message)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(BackendServiceServer).Request(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: "/isp.BackendService/Request",
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(BackendServiceServer).Request(ctx, req.(*Message))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _BackendService_RequestStream_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
return srv.(BackendServiceServer).RequestStream(&backendServiceRequestStreamServer{stream})
|
||||
}
|
||||
|
||||
type BackendService_RequestStreamServer interface {
|
||||
Send(*Message) error
|
||||
Recv() (*Message, error)
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
type backendServiceRequestStreamServer struct {
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamServer) Send(m *Message) error {
|
||||
return x.ServerStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *backendServiceRequestStreamServer) Recv() (*Message, error) {
|
||||
m := new(Message)
|
||||
if err := x.ServerStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// BackendService_ServiceDesc is the grpc.ServiceDesc for BackendService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var BackendService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "isp.BackendService",
|
||||
HandlerType: (*BackendServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "Request",
|
||||
Handler: _BackendService_Request_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "RequestStream",
|
||||
Handler: _BackendService_RequestStream_Handler,
|
||||
ServerStreams: true,
|
||||
ClientStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "backed_service.proto",
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
// ProxyMethodNameHeader is the metadata key used to specify the target endpoint.
|
||||
ProxyMethodNameHeader = "proxy_method_name"
|
||||
)
|
||||
|
||||
// Mux is a request router that dispatches gRPC requests to registered handlers based on endpoint name.
|
||||
// It extracts the endpoint from request metadata and invokes the corresponding HandlerFunc.
|
||||
// Mux implements the BackendServiceServer interface but does not support streaming RPCs.
|
||||
type Mux struct {
|
||||
isp.UnimplementedBackendServiceServer
|
||||
|
||||
unaryHandlers map[string]HandlerFunc
|
||||
}
|
||||
|
||||
// NewMux creates a new Mux with an empty handler registry.
|
||||
func NewMux() *Mux {
|
||||
return &Mux{
|
||||
unaryHandlers: make(map[string]HandlerFunc),
|
||||
}
|
||||
}
|
||||
|
||||
// Handle registers a HandlerFunc for the specified endpoint.
|
||||
// Panics if a handler is already registered for the endpoint.
|
||||
// Returns the Mux for method chaining.
|
||||
func (m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux {
|
||||
_, ok := m.unaryHandlers[endpoint]
|
||||
if ok {
|
||||
panic(errors.Errorf("handler for endpoint %v is already provided", endpoint))
|
||||
}
|
||||
m.unaryHandlers[endpoint] = handler
|
||||
return m
|
||||
}
|
||||
|
||||
// Request handles unary gRPC requests by routing to the registered handler for the endpoint.
|
||||
// The endpoint is extracted from the ProxyMethodNameHeader in request metadata.
|
||||
// Returns an error if metadata is missing, endpoint is not found, or handler fails.
|
||||
func (m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("metadata is expected in context")
|
||||
}
|
||||
endpoint, err := StringFromMd(ProxyMethodNameHeader, md)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handler, ok := m.unaryHandlers[endpoint]
|
||||
if !ok {
|
||||
return nil, status.Errorf(codes.NotFound, "handler not found for endpoint %s", endpoint)
|
||||
}
|
||||
ctx = log.ToContext(ctx, log.String("endpoint", endpoint))
|
||||
return handler(ctx, message)
|
||||
}
|
||||
|
||||
// RequestStream returns an unimplemented error for streaming RPCs.
|
||||
// Mux does not support streaming; use a custom implementation for streaming support.
|
||||
func (m *Mux) RequestStream(_ isp.BackendService_RequestStreamServer) error {
|
||||
return status.Errorf(codes.Unimplemented, "service does not support streaming RPC")
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// Package grpc provides a gRPC server and client implementation for the ISP kit framework.
|
||||
// It enables building scalable microservices with support for hot-swappable handlers,
|
||||
// middleware integration, and structured authentication via metadata.
|
||||
//
|
||||
// The package supports both unary and streaming RPCs, with built-in features for
|
||||
// request/response logging, metrics collection, and distributed tracing.
|
||||
package grpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultMaxSizeByte defines the default maximum message size in bytes (64MB).
|
||||
DefaultMaxSizeByte = 64 * 1024 * 1024
|
||||
)
|
||||
|
||||
// service implements the BackendServiceServer interface with hot-swappable handler support.
|
||||
// It uses atomic.Value for thread-safe handler replacement without interrupting in-flight requests.
|
||||
type service struct {
|
||||
isp.UnimplementedBackendServiceServer
|
||||
|
||||
delegate atomic.Value
|
||||
}
|
||||
|
||||
// Request handles unary gRPC requests by delegating to the registered BackendServiceServer.
|
||||
// Returns an error if the handler is not initialized.
|
||||
func (s *service) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) {
|
||||
delegate, ok := s.delegate.Load().(isp.BackendServiceServer)
|
||||
if !ok {
|
||||
return nil, errors.New("handler is not initialized")
|
||||
}
|
||||
return delegate.Request(ctx, message)
|
||||
}
|
||||
|
||||
// RequestStream handles streaming gRPC requests by delegating to the registered BackendServiceServer.
|
||||
// Returns an error if the handler is not initialized.
|
||||
func (s *service) RequestStream(server isp.BackendService_RequestStreamServer) error {
|
||||
delegate, ok := s.delegate.Load().(isp.BackendServiceServer)
|
||||
if !ok {
|
||||
return errors.New("handler is not initialized")
|
||||
}
|
||||
return delegate.RequestStream(server)
|
||||
}
|
||||
|
||||
// Server wraps a gRPC server with hot-swappable handler support.
|
||||
// It provides a clean interface for starting, stopping, and upgrading gRPC services
|
||||
// without requiring server restart.
|
||||
type Server struct {
|
||||
server *grpc.Server
|
||||
service *service
|
||||
}
|
||||
|
||||
// DefaultServer creates a new Server with default configuration including 64MB message size limits.
|
||||
// Accepts additional grpc.ServerOption for further customization.
|
||||
// Thread-safe for concurrent use.
|
||||
func DefaultServer(restOptions ...grpc.ServerOption) *Server {
|
||||
opts := append([]grpc.ServerOption{
|
||||
grpc.MaxRecvMsgSize(DefaultMaxSizeByte),
|
||||
grpc.MaxSendMsgSize(DefaultMaxSizeByte),
|
||||
}, restOptions...)
|
||||
return NewServer(opts...)
|
||||
}
|
||||
|
||||
// NewServer creates a new Server with custom gRPC options.
|
||||
// Accepts variadic grpc.ServerOption for full configuration control.
|
||||
// Thread-safe for concurrent use.
|
||||
func NewServer(opts ...grpc.ServerOption) *Server {
|
||||
s := &Server{
|
||||
server: grpc.NewServer(opts...),
|
||||
service: &service{
|
||||
delegate: atomic.Value{},
|
||||
},
|
||||
}
|
||||
isp.RegisterBackendServiceServer(s.server, s.service)
|
||||
return s
|
||||
}
|
||||
|
||||
// Shutdown gracefully stops the server, waiting for in-flight requests to complete.
|
||||
// Thread-safe for concurrent use.
|
||||
func (s *Server) Shutdown() {
|
||||
s.server.GracefulStop()
|
||||
}
|
||||
|
||||
// Upgrade atomically replaces the backend service handler without interrupting in-flight requests.
|
||||
// This enables hot-reload of business logic without server restart.
|
||||
// Thread-safe for concurrent use.
|
||||
func (s *Server) Upgrade(service isp.BackendServiceServer) {
|
||||
s.service.delegate.Store(service)
|
||||
}
|
||||
|
||||
// ListenAndServe binds the server to the specified TCP address and starts serving.
|
||||
// Returns an error if binding fails or serving encounters a fatal error.
|
||||
func (s *Server) ListenAndServe(address string) error {
|
||||
var lc net.ListenConfig
|
||||
listener, err := lc.Listen(context.Background(), "tcp", address)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "listen: %s", address)
|
||||
}
|
||||
return s.Serve(listener)
|
||||
}
|
||||
|
||||
// Serve starts serving gRPC requests on the provided listener.
|
||||
// Blocks until the server is stopped or an error occurs.
|
||||
// Returns an error if serving encounters a fatal error.
|
||||
func (s *Server) Serve(listener net.Listener) error {
|
||||
err := s.server.Serve(listener)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "serve grpc")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
# Package `healthcheck`
|
||||
|
||||
Пакет `healthcheck` предоставляет инструменты для реализации и управления проверками состояния (health checks) в
|
||||
приложениях. Он позволяет регистрировать проверки компонентов, кэшировать результаты и предоставлять их через
|
||||
HTTP-эндпоинт в формате JSON.
|
||||
|
||||
## Types
|
||||
|
||||
### Registry
|
||||
|
||||
Структура `Registry` управляет проверками состояния и кэширует их результаты.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewRegistry() *Registry`
|
||||
|
||||
Конструктор реестра проверок состояния.
|
||||
|
||||
#### `(r *Registry) Register(name string, checker Checker)`
|
||||
|
||||
Зарегистрировать компоненту проверки состояния с именем `name`. Такой компонентой может быть объект, реализующий
|
||||
интерфейс `Checker`, либо же функция, обернутая в тип `CheckerFunc`.
|
||||
|
||||
#### `(r *Registry) Handler() http.Handler`
|
||||
|
||||
HTTP-обработчик для интеграции с HTTP-сервером.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/grmqx"
|
||||
"github.com/txix-open/isp-kit/healthcheck"
|
||||
log2 "github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger, err := log2.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
var (
|
||||
dbCli = dbrx.New(logger)
|
||||
rmqCli = grmqx.New(logger)
|
||||
)
|
||||
|
||||
registry := healthcheck.NewRegistry()
|
||||
registry.Register("database", dbCli)
|
||||
registry.Register("mq", rmqCli)
|
||||
registry.Register("auth-service", healthcheck.CheckerFunc(func(ctx context.Context) error {
|
||||
/* health check auth service */
|
||||
return nil
|
||||
}))
|
||||
|
||||
/* integration with HTTP-server */
|
||||
http.Handle("/health", registry.Handler())
|
||||
}
|
||||
|
||||
```
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package healthcheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Checker is the interface that wraps the basic health check method.
|
||||
// Implementations should return nil if the component is healthy, or an error
|
||||
// describing the problem if it is not.
|
||||
type Checker interface {
|
||||
// Healthcheck performs a health check on the component.
|
||||
// It returns nil if the component is healthy, or an error otherwise.
|
||||
Healthcheck(ctx context.Context) error
|
||||
}
|
||||
|
||||
// CheckerFunc is a function type that implements the Checker interface.
|
||||
// It allows using regular functions as health check implementations.
|
||||
type CheckerFunc func(ctx context.Context) error
|
||||
|
||||
// Healthcheck calls the underlying function f with the provided context.
|
||||
func (r CheckerFunc) Healthcheck(ctx context.Context) error {
|
||||
return r(ctx)
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
// Package healthcheck provides utilities for implementing and managing health checks
|
||||
// in applications. It allows registering component checks, caching results, and
|
||||
// exposing them via an HTTP endpoint in JSON format compliant with the
|
||||
// draft-inadarei-api-health-check specification.
|
||||
package healthcheck
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
// StatusPass indicates a healthy component.
|
||||
StatusPass = "pass"
|
||||
// StatusFail indicates an unhealthy component.
|
||||
StatusFail = "fail"
|
||||
)
|
||||
|
||||
// Detail represents the health status of a single component.
|
||||
//
|
||||
// nolint:tagliatelle
|
||||
type Detail struct {
|
||||
// componentName is the name of the component being checked.
|
||||
ComponentName string
|
||||
// componentType describes the type of the component.
|
||||
ComponentType string
|
||||
// status indicates whether the component is healthy ("pass") or unhealthy ("fail").
|
||||
Status string
|
||||
// output contains additional information about the health check, such as error messages.
|
||||
Output string `json:",omitempty"`
|
||||
// time is the timestamp when the health check was performed.
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// Result represents the aggregate health status of all registered components.
|
||||
type Result struct {
|
||||
// status is the overall health status ("pass" if all components are healthy, "fail" otherwise).
|
||||
Status string
|
||||
// details maps component names to their individual health details.
|
||||
Details map[string][]Detail
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package healthcheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
const (
|
||||
// cacheTime specifies how long to cache health check results before re-running them.
|
||||
cacheTime = 1 * time.Second
|
||||
// defaultHandleTimeout is the default timeout for the HTTP handler.
|
||||
defaultHandleTimeout = 1 * time.Second
|
||||
)
|
||||
|
||||
// Registry manages a collection of health check components and provides an HTTP
|
||||
// handler to expose their status. It caches results to avoid excessive checks.
|
||||
//
|
||||
// Registry is safe for concurrent use by multiple goroutines.
|
||||
type Registry struct {
|
||||
checkers map[string]Checker
|
||||
lastResult Result
|
||||
lastCheckTime time.Time
|
||||
lock sync.Locker
|
||||
handleTimeout time.Duration
|
||||
}
|
||||
|
||||
// NewRegistry creates a new Registry with the specified handle timeout.
|
||||
// If handleTimeout is zero, it defaults to 1 second.
|
||||
func NewRegistry(handleTimeout time.Duration) *Registry {
|
||||
if handleTimeout == 0 {
|
||||
handleTimeout = defaultHandleTimeout
|
||||
}
|
||||
|
||||
return &Registry{
|
||||
checkers: make(map[string]Checker),
|
||||
lock: &sync.Mutex{},
|
||||
handleTimeout: handleTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
// Register adds a health check component to the registry.
|
||||
// The name parameter is used as the identifier for the component in the results.
|
||||
// The checker parameter must implement the Checker interface.
|
||||
func (r *Registry) Register(name string, checker Checker) {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
r.checkers[name] = checker
|
||||
}
|
||||
|
||||
// Unregister removes a health check component from the registry.
|
||||
// If the component does not exist, this method has no effect.
|
||||
func (r *Registry) Unregister(name string) {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
delete(r.checkers, name)
|
||||
}
|
||||
|
||||
// Handler returns an HTTP handler that exposes the health status of all
|
||||
// registered components. The handler returns:
|
||||
// - 200 OK with status "pass" if all components are healthy
|
||||
// - 500 Internal Server Error with status "fail" if any component is unhealthy
|
||||
//
|
||||
// The response is encoded in application/health+json format according to
|
||||
// the draft-inadarei-api-health-check specification.
|
||||
func (r *Registry) Handler() http.Handler {
|
||||
return http.TimeoutHandler(http.HandlerFunc(r.handle), r.handleTimeout, "timeout")
|
||||
}
|
||||
|
||||
// handle processes HTTP requests and returns the health check results.
|
||||
func (r *Registry) handle(writer http.ResponseWriter, _ *http.Request) {
|
||||
result := r.result()
|
||||
|
||||
statusCode := http.StatusOK
|
||||
if result.Status == StatusFail {
|
||||
statusCode = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
writer.Header().Set("Content-Type", "application/health+json")
|
||||
writer.WriteHeader(statusCode)
|
||||
_ = json.NewEncoder(writer).Encode(result)
|
||||
}
|
||||
|
||||
// result computes and returns the current health check result.
|
||||
// Results are cached for cacheTime to avoid running checks on every request.
|
||||
func (r *Registry) result() Result {
|
||||
r.lock.Lock()
|
||||
defer r.lock.Unlock()
|
||||
|
||||
now := time.Now().UTC()
|
||||
if now.Before(r.lastCheckTime.Add(cacheTime)) {
|
||||
return r.lastResult
|
||||
}
|
||||
|
||||
details := make(map[string][]Detail)
|
||||
resultStatus := StatusPass
|
||||
for name, checker := range r.checkers {
|
||||
resultErr := checker.Healthcheck(context.Background())
|
||||
status := StatusPass
|
||||
output := ""
|
||||
if resultErr != nil {
|
||||
resultStatus = StatusFail
|
||||
status = StatusFail
|
||||
output = resultErr.Error()
|
||||
}
|
||||
detail := Detail{
|
||||
Status: status,
|
||||
Output: output,
|
||||
ComponentName: name,
|
||||
ComponentType: "component",
|
||||
Time: time.Now().UTC(),
|
||||
}
|
||||
details[name] = []Detail{detail}
|
||||
}
|
||||
result := Result{
|
||||
Status: resultStatus,
|
||||
Details: details,
|
||||
}
|
||||
|
||||
r.lastCheckTime = now
|
||||
r.lastResult = result
|
||||
|
||||
return result
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
# Package `httpcli`
|
||||
|
||||
Пакет `httpcli` предоставляет расширенный HTTP-клиент с поддержкой middleware, ретраев, различных типов запросов и
|
||||
обработки ошибок.
|
||||
Интегрируется с системами логирования, метриками и политиками повторов.
|
||||
|
||||
## Types
|
||||
|
||||
### Client
|
||||
|
||||
Основная структура для выполнения HTTP-запросов. Управляет настройками транспорта, middleware и глобальными параметрами.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(opts ...Option) *Client`
|
||||
|
||||
Конструктор клиента с настройками по умолчанию. Принимает опции:
|
||||
|
||||
- `WithMiddlewares(mws ...Middleware) Option` – добавляет цепочку middleware к запросам клиента.
|
||||
- `WithCodec(codec Codec) Option` – переопределяет codec для кодирования/декодирования, по умолчанию стоит `zstd`
|
||||
|
||||
#### `NewWithClient(cli *http.Client, opts ...Option) *Client`
|
||||
|
||||
Конструктор клиента на основе базового клиента из стандартной библиотеки `net/http`.
|
||||
|
||||
#### `(c *Client) GlobalRequestConfig() *GlobalRequestConfig`
|
||||
|
||||
Получить глобальную конфигурацию запросов (таймауты, базовый URL, заголовки и т.д.).
|
||||
|
||||
#### `(c *Client) Post(url string) *RequestBuilder`
|
||||
|
||||
Создать билдер для POST-запроса. Аналогичные методы: `Get()`, `Put()`, `Delete()`, `Patch()`.
|
||||
|
||||
#### `(c *Client) Execute(ctx context.Context, builder *RequestBuilder) (*Response, error)`
|
||||
|
||||
Выполнить HTTP-запрос из переданного билдера.
|
||||
|
||||
### RequestBuilder
|
||||
|
||||
Структура для построения HTTP-запросов с цепочкой методов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `(b *RequestBuilder) Header(name string, value string) *RequestBuilder`
|
||||
|
||||
Добавить заголовок к запросу.
|
||||
|
||||
#### `(b *RequestBuilder) BaseUrl(baseUrl string) *RequestBuilder`
|
||||
|
||||
Установить базовый url в запросе на переданный.
|
||||
|
||||
#### `(b *RequestBuilder) Url(url string) *RequestBuilder`
|
||||
|
||||
Установить url запроса на переданный.
|
||||
|
||||
#### `(b *RequestBuilder) Method(method string) *RequestBuilder`
|
||||
|
||||
Изменить HTTP-метод запроса на указанный.
|
||||
|
||||
#### `(b *RequestBuilder) Cookie(cookie *http.Cookie) *RequestBuilder`
|
||||
|
||||
Добавить cookie к запросу.
|
||||
|
||||
#### `(b *RequestBuilder) RequestBody(body []byte) *RequestBuilder`
|
||||
|
||||
Добавить тело запроса.
|
||||
|
||||
#### `(b *RequestBuilder) JsonRequestBody(value any) *RequestBuilder`
|
||||
|
||||
Добавить тело запроса в формате JSON. Использует пакет [`json`](../../json), поэтому может маршалить без тэгов в
|
||||
camelCase.
|
||||
|
||||
#### `(b *RequestBuilder) JsonResponseBody(responsePtr any) *RequestBuilder`
|
||||
|
||||
Записать JSON-ответ на запрос по переданному указателю. Операция выполнится только при статус кодах от 200 до 299.
|
||||
|
||||
#### `(b *RequestBuilder) FormDataRequestBody(data map[string][]string) *RequestBuilder`
|
||||
|
||||
Добавить тело запроса в формате формы.
|
||||
|
||||
#### `(b *RequestBuilder) BasicAuth(ba BasicAuth) *RequestBuilder`
|
||||
|
||||
Добавить базую аутентификацию в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) QueryParams(queryParams map[string]any) *RequestBuilder`
|
||||
|
||||
Добавить query-параметры в запрос.
|
||||
|
||||
#### `(b *RequestBuilder) Retry(cond RetryCondition, retryer Retryer) *RequestBuilder`
|
||||
|
||||
Задать политику ретраев по заданному условию. Пример условия: `httpcli.IfErrorOr5XXStatus()`
|
||||
|
||||
#### `(b *RequestBuilder) MultipartRequestBody(data *MultipartData) *RequestBuilder`
|
||||
|
||||
Устанавить multipart/form-data тело запроса (для передачи файлов). Не поддерживает `Request.Body` в middleware и
|
||||
игнорирует ретраи.
|
||||
|
||||
#### `(b *RequestBuilder) StatusCodeToError() *RequestBuilder`
|
||||
|
||||
Возвращает `ErrorResponse` как ошибку при `Response.IsSuccess = true`.
|
||||
|
||||
#### `(b *RequestBuilder) Timeout(timeout time.Duration) *RequestBuilder`
|
||||
|
||||
Установить тайм-аут для каждой попытки запроса, тайм-аут по умолчанию 15 секунд.
|
||||
|
||||
#### `(b *RequestBuilder) Middlewares(middlewares ...Middleware) *RequestBuilder`
|
||||
|
||||
Добавить middleware в цепочку запроса.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг кодирования запроса.
|
||||
Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `Content-Encoding` со значением типа codec и тело запроса будет закодировано.
|
||||
|
||||
#### `(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder`
|
||||
|
||||
Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest).
|
||||
|
||||
#### `(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder`
|
||||
|
||||
Установить флаг приёма закодированных ответов.
|
||||
Если включен, то в заголовки запроса будет добавлен `Accept-Encoding` со значением типа codec + identity (пример `zstd, identity`).
|
||||
|
||||
#### `(b *RequestBuilder) DecodeResponse(decode bool) *RequestBuilder`
|
||||
|
||||
Установить флаг декодирования ответа.
|
||||
Если включен, то ответ сервера с заголовком `Content-Encoding` типом codec в клиенте будет декодирован.
|
||||
|
||||
#### `(b *RequestBuilder) Do(ctx context.Context) (*Response, error)`
|
||||
|
||||
Выполнить запрос собранный билдером.
|
||||
|
||||
#### `(b *RequestBuilder) DoWithoutResponse(ctx context.Context) error`
|
||||
|
||||
То же самое, что и `Do`, но записывает ответ по переданному раннее в билдере указателю.
|
||||
|
||||
#### `(b *RequestBuilder) DoWithoutResponse(ctx context.Context) error`
|
||||
|
||||
То же самое, что и `Do`, но не возвращает объект `Response`. Записывает тело ответа по переданному в метод
|
||||
`JsonResponseBody` указателю.
|
||||
|
||||
#### `(b *RequestBuilder) DoAndReadBody(ctx context.Context) ([]byte, int, error)`
|
||||
|
||||
То же самое, что и `Do`, но считывает из ответа только тело и статус код, а затем возвращает их.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
cli := httpcli.New()
|
||||
u := new(user)
|
||||
|
||||
resp, err := cli.Get("https://api.example.com/users/1").
|
||||
JsonResponseBody(u).
|
||||
Do(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer resp.Close()
|
||||
|
||||
if !resp.IsSuccess() {
|
||||
log.Fatalf("invalid status code: %d", resp.StatusCode())
|
||||
}
|
||||
log.Println(u.Name) /* result decoded from JSON */
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Without response
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
func main() {
|
||||
cli := httpcli.New()
|
||||
u := new(user)
|
||||
|
||||
err := cli.Get("https://api.example.com/users/1").
|
||||
JsonResponseBody(u).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Println(u.Name) /* result decoded from JSON */
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Exponential retries
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/retry"
|
||||
)
|
||||
|
||||
type user struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
|
||||
const (
|
||||
maxRetryElapsedTime = 5 * time.Second
|
||||
)
|
||||
|
||||
func main() {
|
||||
cli := httpcli.New()
|
||||
u := user{
|
||||
Id: "x.x",
|
||||
Name: "Mark",
|
||||
}
|
||||
|
||||
err := cli.Post("https://api.example.com/users").
|
||||
JsonRequestBody(u).
|
||||
Retry(httpcli.IfErrorOr5XXStatus(), retry.NewExponentialBackoff(maxRetryElapsedTime)).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(context.Background())
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// nolint:gochecknoglobals,mnd
|
||||
var (
|
||||
bpool = sync.Pool{New: func() any {
|
||||
return bytes.NewBuffer(make([]byte, 1024))
|
||||
}}
|
||||
)
|
||||
|
||||
func acquireBuffer() *bytes.Buffer {
|
||||
buf := bpool.Get().(*bytes.Buffer) // nolint:forcetypeassert
|
||||
buf.Reset()
|
||||
return buf
|
||||
}
|
||||
|
||||
func releaseBuffer(buf *bytes.Buffer) {
|
||||
bpool.Put(buf)
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package httpcli
|
||||
|
||||
// BasicAuth holds HTTP basic authentication credentials.
|
||||
type BasicAuth struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// RequestBodyWriter defines the interface for writing request bodies.
|
||||
type RequestBodyWriter interface {
|
||||
Write(req *http.Request, w io.Writer) error
|
||||
}
|
||||
|
||||
// jsonRequest handles JSON-encoded request bodies.
|
||||
type jsonRequest struct {
|
||||
value any
|
||||
}
|
||||
|
||||
// Write sets the Content-Type header to application/json and encodes the value as JSON.
|
||||
func (j jsonRequest) Write(req *http.Request, w io.Writer) error {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
return json.EncodeInto(w, j.value)
|
||||
}
|
||||
|
||||
// plainRequest handles raw byte request bodies.
|
||||
type plainRequest struct {
|
||||
value []byte
|
||||
}
|
||||
|
||||
// Write writes the raw bytes to the request body.
|
||||
func (p plainRequest) Write(_ *http.Request, w io.Writer) error {
|
||||
_, err := w.Write(p.value)
|
||||
return err
|
||||
}
|
||||
|
||||
// formRequest handles form-encoded request bodies.
|
||||
type formRequest struct {
|
||||
data map[string][]string
|
||||
}
|
||||
|
||||
// Write sets the Content-Type header to application/x-www-form-urlencoded
|
||||
// and encodes the data as form parameters.
|
||||
func (f formRequest) Write(req *http.Request, w io.Writer) error {
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
data := url.Values(f.data).Encode()
|
||||
_, err := w.Write([]byte(data))
|
||||
return err
|
||||
}
|
||||
|
||||
// ResponseBodyReader defines the interface for reading response bodies.
|
||||
type ResponseBodyReader interface {
|
||||
Read(r io.Reader) error
|
||||
}
|
||||
|
||||
// jsonResponse handles JSON-encoded response bodies.
|
||||
type jsonResponse struct {
|
||||
ptr any
|
||||
}
|
||||
|
||||
// Read unmarshals the response body into the target pointer.
|
||||
// Uses optimized unmarshaling when the source is a bytes.Buffer.
|
||||
func (j jsonResponse) Read(r io.Reader) error {
|
||||
buff, isBuff := r.(*bytes.Buffer)
|
||||
if isBuff {
|
||||
return json.Unmarshal(buff.Bytes(), j.ptr)
|
||||
}
|
||||
return json.NewDecoder(r).Decode(j.ptr)
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package httpcli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/codec"
|
||||
)
|
||||
|
||||
// RoundTripper defines the interface for executing HTTP requests.
|
||||
// Implementations can wrap requests with middleware functionality.
|
||||
type RoundTripper interface {
|
||||
RoundTrip(ctx context.Context, request *Request) (*Response, error)
|
||||
}
|
||||
|
||||
// RoundTripperFunc is a function type that implements the RoundTripper interface.
|
||||
type RoundTripperFunc func(ctx context.Context, request *Request) (*Response, error)
|
||||
|
||||
// RoundTrip executes an HTTP request using the function.
|
||||
func (f RoundTripperFunc) RoundTrip(ctx context.Context, request *Request) (*Response, error) {
|
||||
return f(ctx, request)
|
||||
}
|
||||
|
||||
// Middleware is a function that wraps a RoundTripper with additional functionality.
|
||||
// Middlewares are executed in the order they are added.
|
||||
type Middleware func(next RoundTripper) RoundTripper
|
||||
|
||||
type Codec interface {
|
||||
Type() string
|
||||
EncodeBytes(b []byte) ([]byte, error)
|
||||
Decode(r io.ReadCloser) (io.ReadCloser, error)
|
||||
}
|
||||
|
||||
// Client is a high-level HTTP client with support for middleware, retries,
|
||||
// and flexible request/response handling.
|
||||
type Client struct {
|
||||
cli *http.Client
|
||||
globalConfig *GlobalRequestConfig
|
||||
mws []Middleware
|
||||
|
||||
roundTripper RoundTripper
|
||||
|
||||
codec Codec
|
||||
}
|
||||
|
||||
// StdClient is the default http.Client used by New() with optimized connection pooling
|
||||
// and HTTP/2 support.
|
||||
//
|
||||
// nolint:mnd,gochecknoglobals
|
||||
var (
|
||||
StdClient = &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: defaultTransportDialContext(&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}),
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 512,
|
||||
MaxIdleConnsPerHost: 32,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
ReadBufferSize: 8 * 1024,
|
||||
WriteBufferSize: 8 * 1024,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
// New creates a new Client with default configuration.
|
||||
// It uses StdClient as the underlying http.Client.
|
||||
//
|
||||
// Options are applied in the order they are passed.
|
||||
func New(opts ...Option) *Client {
|
||||
return NewWithClient(StdClient, opts...)
|
||||
}
|
||||
|
||||
// NewWithClient creates a new Client with a custom http.Client.
|
||||
// This allows customization of the underlying transport and connection pooling.
|
||||
//
|
||||
// Options are applied in the order they are passed.
|
||||
func NewWithClient(cli *http.Client, opts ...Option) *Client {
|
||||
c := &Client{
|
||||
cli: cli,
|
||||
globalConfig: NewGlobalRequestConfig(),
|
||||
codec: codec.Default,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(c)
|
||||
}
|
||||
|
||||
c.roundTripper = joinMiddlewares(RoundTripperFunc(c.executeWithRetries), c.mws...)
|
||||
return c
|
||||
}
|
||||
|
||||
// GlobalRequestConfig returns the global request configuration for this client.
|
||||
// Settings here apply to all requests made by this client.
|
||||
func (c *Client) GlobalRequestConfig() *GlobalRequestConfig {
|
||||
return c.globalConfig
|
||||
}
|
||||
|
||||
// Post creates a new POST request builder for the given URL.
|
||||
func (c *Client) Post(url string) *RequestBuilder {
|
||||
return NewRequestBuilder(http.MethodPost, url, c.globalConfig, c.Execute)
|
||||
}
|
||||
|
||||
// Get creates a new GET request builder for the given URL.
|
||||
func (c *Client) Get(url string) *RequestBuilder {
|
||||
return NewRequestBuilder(http.MethodGet, url, c.globalConfig, c.Execute)
|
||||
}
|
||||
|
||||
// Put creates a new PUT request builder for the given URL.
|
||||
func (c *Client) Put(url string) *RequestBuilder {
|
||||
return NewRequestBuilder(http.MethodPut, url, c.globalConfig, c.Execute)
|
||||
}
|
||||
|
||||
// Delete creates a new DELETE request builder for the given URL.
|
||||
func (c *Client) Delete(url string) *RequestBuilder {
|
||||
return NewRequestBuilder(http.MethodDelete, url, c.globalConfig, c.Execute)
|
||||
}
|
||||
|
||||
// Patch creates a new PATCH request builder for the given URL.
|
||||
func (c *Client) Patch(url string) *RequestBuilder {
|
||||
return NewRequestBuilder(http.MethodPatch, url, c.globalConfig, c.Execute)
|
||||
}
|
||||
|
||||
// Execute sends an HTTP request using the provided builder and returns the response.
|
||||
// It handles request construction, middleware execution, and response processing.
|
||||
//
|
||||
// If a responseBody is set on the builder and the response is successful,
|
||||
// the response body will be automatically unmarshalled into the target.
|
||||
//
|
||||
// nolint:cyclop,funlen
|
||||
func (c *Client) Execute(ctx context.Context, builder *RequestBuilder) (*Response, error) {
|
||||
request, err := builder.newHttpRequest(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for name, value := range builder.headers {
|
||||
request.Header.Set(name, value)
|
||||
}
|
||||
for _, cookie := range builder.cookies {
|
||||
request.AddCookie(cookie)
|
||||
}
|
||||
if builder.basicAuth != nil {
|
||||
request.SetBasicAuth(builder.basicAuth.Username, builder.basicAuth.Password)
|
||||
}
|
||||
if builder.queryParams != nil {
|
||||
values := url.Values{}
|
||||
for key, value := range builder.queryParams {
|
||||
values.Set(key, fmt.Sprintf("%v", value))
|
||||
}
|
||||
request.URL.RawQuery = values.Encode()
|
||||
}
|
||||
|
||||
rr := &Request{
|
||||
Raw: request,
|
||||
timeout: builder.timeout,
|
||||
retryOptions: builder.retryOptions,
|
||||
decodeResponse: builder.decodeResponse,
|
||||
encodeRequest: builder.encodeRequest,
|
||||
encodeThreshold: builder.encodeThreshold,
|
||||
}
|
||||
|
||||
if builder.multipartData != nil {
|
||||
ct, reader := builder.multipartData.openReader()
|
||||
request.Header.Set("Content-Type", ct)
|
||||
request.Body = reader
|
||||
}
|
||||
|
||||
if builder.requestBody != nil {
|
||||
buff := acquireBuffer()
|
||||
defer releaseBuffer(buff)
|
||||
|
||||
err := builder.requestBody.Write(request, buff)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rr.body = buff.Bytes()
|
||||
}
|
||||
|
||||
if builder.acceptEncodedResponse {
|
||||
request.Header.Set("Accept-Encoding", strings.Join([]string{c.codec.Type(), "identity"}, ", "))
|
||||
}
|
||||
|
||||
roundTripper := c.roundTripper
|
||||
if len(builder.middlewares) > 0 {
|
||||
roundTripper = joinMiddlewares(roundTripper, builder.middlewares...)
|
||||
}
|
||||
|
||||
resp, err := roundTripper.RoundTrip(ctx, rr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.IsSuccess() && builder.responseBody != nil {
|
||||
body, err := resp.UnsafeBody()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = builder.responseBody.Read(bytes.NewBuffer(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// nolint:bodyclose
|
||||
func (c *Client) executeWithRetries(ctx context.Context, request *Request) (*Response, error) {
|
||||
var (
|
||||
response *Response
|
||||
err error
|
||||
)
|
||||
origCtx := ctx
|
||||
|
||||
if request.encodeRequest && len(request.body) > request.encodeThreshold {
|
||||
request.Raw.Header.Set("Content-Encoding", c.codec.Type())
|
||||
request.body, err = c.codec.EncodeBytes(request.body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
_ = request.retryOptions.retrier.Do(ctx, func() error {
|
||||
if response != nil {
|
||||
response.Close() // prevent context and buffer leak from previous failed attempt
|
||||
}
|
||||
var (
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
)
|
||||
if request.timeout > 0 {
|
||||
ctx, cancel = context.WithTimeout(origCtx, request.timeout)
|
||||
request.Raw = request.Raw.WithContext(ctx)
|
||||
}
|
||||
if request.body != nil { // it's a none multipart
|
||||
request.Raw.Body = io.NopCloser(bytes.NewBuffer(request.body))
|
||||
}
|
||||
var resp *http.Response
|
||||
resp, err = c.cli.Do(request.Raw)
|
||||
buff := acquireBuffer()
|
||||
response = &Response{
|
||||
Raw: resp,
|
||||
buff: buff,
|
||||
cancel: cancel,
|
||||
}
|
||||
retryErr := request.retryOptions.condition(err, response)
|
||||
return retryErr
|
||||
})
|
||||
|
||||
if err != nil || !request.decodeResponse {
|
||||
return response, err
|
||||
}
|
||||
|
||||
enc := response.Raw.Header.Get("Content-Encoding")
|
||||
if enc != c.codec.Type() {
|
||||
return response, nil
|
||||
}
|
||||
|
||||
response.Raw.Body, err = c.codec.Decode(response.Raw.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response.Raw.Header.Del("Content-Encoding")
|
||||
response.Raw.Header.Del("Content-Length")
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// defaultTransportDialContext creates a dial context function with the given dialer.
|
||||
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
||||
return dialer.DialContext
|
||||
}
|
||||
|
||||
// joinMiddlewares chains multiple middlewares together, wrapping the root RoundTripper.
|
||||
// Middlewares are applied in reverse order (last middleware is executed first).
|
||||
//
|
||||
// nolint:ireturn
|
||||
func joinMiddlewares(root RoundTripper, mws ...Middleware) RoundTripper {
|
||||
roundTripper := root
|
||||
for i := len(mws) - 1; i >= 0; i-- {
|
||||
roundTripper = mws[i](roundTripper)
|
||||
}
|
||||
return roundTripper
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// Package httpcli provides a high-level HTTP client with support for middleware,
|
||||
// retries, and flexible request/response handling.
|
||||
//
|
||||
// The package offers a builder pattern API for constructing HTTP requests with
|
||||
// various options including headers, cookies, authentication, and request bodies.
|
||||
package httpcli
|
||||
Loaded 100 of 2619 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user