MSP-8172 Add vendor

This commit is contained in:
Синельник Тимур Романович committed 2026-07-29 12:52:27 +03:00
1 parent 5175d87e08
commit eb066cb055
2619 files changed
+757077 -2

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Charles Phillips
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.
+35
View File
@@ -0,0 +1,35 @@
# bellows
Flatten and expand golang maps and structs
## Features
There are some existing golang flatten/expand implementations, but they are targeted to specific use-cases, and none of them flatten Structs.
This `Flatten` will skip parsing a Map that does not have a String as the index.
This `Flatten` recursively passes values as their original Interface, so it is simpler than implementations that rely on passing reflect.Value.
## Usage
```go
// Expand a dot-separated flat map into a nested maps and slices
func Expand(flat map[string]interface{}) interface{}
// Flatten a nested map into a dot-separated flat map
func Flatten(value interface{}) map[string]interface{} {}
// Flatten a nested map into a dot-separated flat map, with a prefix
func FlattenPrefixed(value interface{}, prefix string) map[string]interface{} {}
// Flatten a nested map into an existing dot-separated flat map, with a prefix
func FlattenPrefixedToResult(value interface{}, prefix string, m map[string]interface{}) {}
```
## Other golang flatten/expand implementations
* [hashicorp/terraform/flatmap](https://github.com/hashicorp/terraform/tree/master/flatmap)
* [turtlemonvh/mapmap](https://github.com/turtlemonvh/mapmap)
* [peking2/func-go](https://github.com/peking2/func-go)
* [wolfeidau/unflatten](https://github.com/wolfeidau/unflatten)
* [jeremywohl/flatten](https://github.com/jeremywohl/flatten)
(C) Copyright 2015 doublerebel. MIT Licensed.
+89
View File
@@ -0,0 +1,89 @@
package bellows
import (
"regexp"
"strconv"
"strings"
)
var (
arrayIndexRegexp = regexp.MustCompile("\\[\\d*]")
)
func Expand(flatMap map[string]interface{}, opts ...option) interface{} {
options := &bellowsOptions{sep: "."}
for _, opt := range opts {
opt(options)
}
var dst interface{}
for path, value := range flatMap {
parts := strings.Split(path, options.sep)
dst = put(dst, parts, value)
}
return dst
}
func put(dst interface{}, path []string, value interface{}) interface{} {
if len(path) == 0 {
return value
}
p := path[0]
index, isArray := getArrayIndex(p)
if isArray {
if dst == nil {
dst = make([]interface{}, 0, 3)
}
if arr, ok := dst.([]interface{}); ok {
i := len(arr)
if i == index {
arr = append(arr, put(nil, path[1:], value))
} else if i < index {
toInsert := make([]interface{}, index-i)
newItem := put(nil, path[1:], value)
switch newItem.(type) {
case []interface{}:
for i := range toInsert {
toInsert[i] = make([]interface{}, 0)
}
case map[string]interface{}:
for i := range toInsert {
toInsert[i] = make(map[string]interface{}, 0)
}
}
arr = append(arr[:i], append(toInsert, newItem)...)
} else {
arr[index] = put(arr[index], path[1:], value)
}
dst = arr
}
} else {
if dst == nil {
dst = make(map[string]interface{}, 3)
}
if m, ok := dst.(map[string]interface{}); ok {
if val, ok := m[p]; ok {
m[p] = put(val, path[1:], value)
} else {
m[p] = put(nil, path[1:], value)
}
}
}
return dst
}
func getArrayIndex(part string) (int, bool) {
index := arrayIndexRegexp.FindString(part)
if index == "" {
return 0, false
}
i, err := strconv.Atoi(index[1 : len(index)-1])
if err != nil {
return 0, false
}
return i, true
}
+88
View File
@@ -0,0 +1,88 @@
package bellows
import (
"fmt"
"reflect"
)
func Flatten(value interface{}, opts ...option) map[string]interface{} {
options := &bellowsOptions{
prefix: "",
sep: ".",
}
for _, opt := range opts {
opt(options)
}
m := make(map[string]interface{}, 5)
FlattenPrefixedToResult(value, options, m)
return m
}
func FlattenPrefixedToResult(value interface{}, opts *bellowsOptions, m map[string]interface{}) {
original := reflect.ValueOf(value)
kind := original.Kind()
if kind == reflect.Ptr || kind == reflect.Interface {
original = reflect.Indirect(original)
kind = original.Kind()
}
if !original.IsValid() {
if opts.prefix != "" {
m[opts.prefix] = nil
}
return
}
t := original.Type()
switch kind {
case reflect.Map:
if t.Key().Kind() != reflect.String {
break
}
keys := original.MapKeys()
base := ""
if opts.prefix != "" {
base = opts.prefix + opts.sep
}
for _, childKey := range keys {
childValue := original.MapIndex(childKey)
FlattenPrefixedToResult(childValue.Interface(), &bellowsOptions{
prefix: base + childKey.String(),
sep: opts.sep,
}, m)
}
case reflect.Struct:
numField := original.NumField()
base := ""
for i := 0; i < numField; i++ {
childValue := original.Field(i)
f := t.Field(i)
childKey := f.Name
if f.Anonymous {
childKey = ""
base = opts.prefix
} else if opts.prefix != "" {
base = opts.prefix + opts.sep
}
FlattenPrefixedToResult(childValue.Interface(), &bellowsOptions{
prefix: base + childKey,
sep: opts.sep,
}, m)
}
case reflect.Array, reflect.Slice:
l := original.Len()
base := opts.prefix
for i := 0; i < l; i++ {
childValue := original.Index(i)
FlattenPrefixedToResult(childValue.Interface(), &bellowsOptions{
prefix: fmt.Sprintf("%s%s[%d]", base, opts.sep, i),
sep: opts.sep,
}, m)
}
default:
if opts.prefix != "" {
m[opts.prefix] = value
}
}
}
+20
View File
@@ -0,0 +1,20 @@
package bellows
type bellowsOptions struct {
prefix string
sep string
}
type option func(o *bellowsOptions)
func WithPrefix(prefix string) option {
return func(o *bellowsOptions) {
o.prefix = prefix
}
}
func WithSep(sep string) option {
return func(o *bellowsOptions) {
o.sep = sep
}
}
+80
View File
@@ -0,0 +1,80 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
*.iml
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
.idea
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
### Go template
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
vendor
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
+21
View File
@@ -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.
+177
View File
@@ -0,0 +1,177 @@
# bgjob
![Build and test](https://github.com/txix-open/bgjob/actions/workflows/main.yml/badge.svg)
[![codecov](https://codecov.io/gh/txix-open/bgjob/branch/master/graph/badge.svg?token=ZEX2Y8ZWKZ)](https://codecov.io/gh/txix-open/bgjob)
[![Go Report Card](https://goreportcard.com/badge/github.com/txix-open/bgjob)](https://goreportcard.com/report/github.com/txix-open/bgjob)
Tiny library to handle background jobs.
Uses PostgreSQL to organize job queues.
Highly inspired by [gue](https://github.com/vgarvardt/gue)
## Features
* Durable job storage
* At-least-ones execution
* Job uniqueness
* Delayed execution
* Retries with dynamic timeout
* [Enqueuing jobs in transaction](#enqueue-job-in-transaction)
* DLQ
* Zero dependencies (database/sql is used, to log events you can use `Observer`)
## Why ?
* You need flexible and robust job processing tool
* You already use PostgreSQL
* You require strong guaranties for task processing and consistency
* You have a quite small load. Queues on database usually can handle around 1000 rps
## State
* The package has been used in production for 3 years with a small load
## Install
1. ```go get github.com/txix-open/bgjob```
2. Add to your db migration tool sql from migration/init.sql
## Complete example
```go
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"runtime"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/txix-open/bgjob"
)
type Observer struct {
bgjob.NoopObserver //"extend" NoopObserver to override method you need
}
func (o Observer) WorkerError(ctx context.Context, err error) {
log.Printf("worker: %v", err)
}
func main() {
dsn := "postgres://test:test@localhost:5432/test"
db, err := sql.Open("pgx", dsn) //be sure you add tables and indexes from migration/init.sql
if err != nil {
panic(err)
}
handleComplete := bgjob.HandlerFunc(func(ctx context.Context, job bgjob.Job) bgjob.Result {
fmt.Printf("%s\n", job.Arg)
return bgjob.Complete() //complete job, job will be deleted
})
handleRetry := bgjob.HandlerFunc(func(ctx context.Context, job bgjob.Job) bgjob.Result {
if job.Attempt == 2 {
return bgjob.Complete()
}
//here you have attempts counter, you can easily do backoff retries
return bgjob.Retry(1*time.Second, errors.New("some error"))
})
handleMoveToDlq := bgjob.HandlerFunc(func(ctx context.Context, job bgjob.Job) bgjob.Result {
//you can move the job to permanent storage if you can't handle it
return bgjob.MoveToDlq(errors.New("move to dlq"))
})
ctx := context.Background()
store, err := bgjob.NewPgStoreV2(ctx, db)
if err != nil {
panic(err)
}
cli := bgjob.NewClient(store)
//if handler for job type wasn't provided, job will be moved to dlq
handler := bgjob.NewMux().
Register("complete_me", handleComplete).
Register("retry_me", handleRetry).
Register("move_to_dlq", handleMoveToDlq)
queueName := "test"
observer := Observer{}
worker := bgjob.NewWorker(
cli,
queueName,
handler,
bgjob.WithObserver(observer), //default noop
bgjob.WithConcurrency(runtime.NumCPU()), //default 1
bgjob.WithPollInterval(500*time.Millisecond), //default 1s
)
worker.Run(ctx) //call ones, non-blocking
err = cli.Enqueue(ctx, bgjob.EnqueueRequest{
Id: "test", //you can provide you own id
Queue: queueName,
Type: "complete_me",
Arg: []byte(`{"simpleJson": 1}`), //it can be json or protobuf or a simple string
Delay: 1 * time.Second, //you can delay job execution
})
if err != nil {
panic(err)
}
err = cli.Enqueue(ctx, bgjob.EnqueueRequest{
Queue: queueName,
Type: "retry_me",
//those fields must be specified
})
if err != nil {
panic(err)
}
err = cli.Enqueue(ctx, bgjob.EnqueueRequest{
Queue: queueName,
Type: "move_to_dlq",
})
if err != nil {
panic(err)
}
time.Sleep(1 * time.Second)
worker.Shutdown() //graceful shutdown, call ones
}
```
## Enqueue job in transaction
* `bgjob.Enqueue` and `bgjob.BulkEnqueue` can help
```go
package main
func enqueueInTx(db *sql.DB) (err error) {
tx, err := db.Begin()
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() {
if err != nil {
_ = tx.Rollback()
}
}()
// YOUR BUSINESS TRANSACTION HERE
err = bgjob.Enqueue(context.Background(), tx, bgjob.EnqueueRequest{
Queue: "work",
Type: "send_email",
})
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("commit tx: %w", err)
}
return nil
}
```
+135
View File
@@ -0,0 +1,135 @@
package bgjob
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"time"
)
type Tx interface {
Job() Job
Update(ctx context.Context, id string, attempt int32, lastError string, nextRunAt int64) error
UpdateNextRun(ctx context.Context, id string, nextRunAt int64) error
UpdateArg(ctx context.Context, id string, arg []byte) error
Delete(ctx context.Context, id string) error
SaveInDlq(ctx context.Context, job Job) error
}
type Store interface {
Acquire(ctx context.Context, queue string, tx func(tx Tx) error) error
BulkInsert(ctx context.Context, jobs []Job) error
}
type Client struct {
store Store
}
func NewClient(store Store) *Client {
return &Client{
store: store,
}
}
func (c *Client) Enqueue(ctx context.Context, req EnqueueRequest) error {
return c.BulkEnqueue(ctx, []EnqueueRequest{req})
}
func (c *Client) BulkEnqueue(ctx context.Context, list []EnqueueRequest) error {
jobs, err := requestsToJobs(list)
if err != nil {
return err
}
err = c.store.BulkInsert(ctx, jobs)
if err == ErrJobAlreadyExist {
return err
}
if err != nil {
return fmt.Errorf("bulk insert: %w", err)
}
return nil
}
func (c *Client) Do(ctx context.Context, queue string, f func(ctx context.Context, job Job) Result) error {
err := c.store.Acquire(ctx, queue, func(tx Tx) error {
return c.jobTx(ctx, tx, f)
})
return err
}
func (c *Client) jobTx(ctx context.Context, tx Tx, f func(ctx context.Context, job Job) Result) error {
job := tx.Job()
job.Attempt++
result := f(ctx, job)
if result.complete {
err := tx.Delete(ctx, job.Id)
if err != nil {
return fmt.Errorf("delete job: %w", err)
}
}
if result.retry {
err := tx.Update(
ctx,
job.Id,
job.Attempt,
result.err.Error(),
timeNow().Add(result.retryDelay).Unix(),
)
if err != nil {
return fmt.Errorf("update job: %w", err)
}
}
if result.moveToDlq {
errorString := result.err.Error()
job.LastError = &errorString
err := tx.SaveInDlq(ctx, job)
if err != nil {
return fmt.Errorf("insert into dlq: %w", err)
}
err = tx.Delete(ctx, job.Id)
if err != nil {
return fmt.Errorf("delete job: %w", err)
}
}
if result.reschedule {
err := tx.UpdateNextRun(
ctx,
job.Id,
timeNow().Add(result.rescheduleDelay).Unix(),
)
if err != nil {
return fmt.Errorf("update job: %w", err)
}
}
if result.overrideArg {
err := tx.UpdateArg(ctx, job.Id, result.arg)
if err != nil {
return fmt.Errorf("update job arg: %w", err)
}
}
return nil
}
func nextId() (string, error) {
arr := make([]byte, 24)
_, err := rand.Read(arr)
if err != nil {
return "", fmt.Errorf("read rand: %w", err)
}
id := hex.EncodeToString(arr)
return id, nil
}
func timeNow() time.Time {
return time.Now().UTC()
}
+111
View File
@@ -0,0 +1,111 @@
package bgjob
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
)
type ExecerContext interface {
ExecContext(ctx context.Context, s string, args ...any) (sql.Result, error)
}
func Enqueue(ctx context.Context, e ExecerContext, req EnqueueRequest) error {
return BulkEnqueue(ctx, e, []EnqueueRequest{req})
}
func BulkEnqueue(ctx context.Context, e ExecerContext, list []EnqueueRequest) error {
jobs, err := requestsToJobs(list)
if err != nil {
return err
}
err = bulkInsert(ctx, e, jobs)
if err == ErrJobAlreadyExist {
return err
}
if err != nil {
return fmt.Errorf("bulk insert: %w", err)
}
return nil
}
func requestsToJobs(list []EnqueueRequest) ([]Job, error) {
if len(list) == 0 {
return nil, errors.New("list is empty. at least one job is expected")
}
jobs := make([]Job, 0, len(list))
now := timeNow()
for _, req := range list {
if req.Queue == "" {
return nil, ErrQueueIsRequired
}
if req.Type == "" {
return nil, ErrTypeIsRequired
}
id := req.Id
if id == "" {
generated, err := nextId()
if err != nil {
return nil, fmt.Errorf("generate id: %w", err)
}
id = generated
}
job := Job{
Id: id,
Queue: req.Queue,
Type: req.Type,
Arg: req.Arg,
RequestId: req.RequestId,
Attempt: 0,
LastError: nil,
NextRunAt: now.Add(req.Delay).Unix(),
CreatedAt: now,
UpdatedAt: now,
}
jobs = append(jobs, job)
}
return jobs, nil
}
func bulkInsert(ctx context.Context, e ExecerContext, jobs []Job) error {
valueStrings := make([]string, 0, len(jobs))
valueArgs := make([]any, 0, len(jobs)*9)
placeholderNum := 0
for _, job := range jobs {
placeholders := make([]string, 0)
for i := 0; i < 9; i++ {
placeholderNum++
placeholders = append(placeholders, fmt.Sprintf("$%d", placeholderNum))
}
valueStrings = append(valueStrings, fmt.Sprintf("(%s)", strings.Join(placeholders, ",")))
valueArgs = append(
valueArgs,
job.Id,
job.Queue,
job.Type,
job.Arg,
job.Attempt,
job.NextRunAt,
job.CreatedAt,
job.UpdatedAt,
job.RequestId,
)
}
query := fmt.Sprintf("INSERT INTO bgjob_job (id, queue, type, arg, attempt, next_run_at, created_at, updated_at, request_id) VALUES %s",
strings.Join(valueStrings, ","))
_, err := e.ExecContext(ctx, query, valueArgs...)
if err != nil {
if strings.Contains(err.Error(), "23505") { //unique_violation
return ErrJobAlreadyExist
}
return err
}
return nil
}
+14
View File
@@ -0,0 +1,14 @@
package bgjob
import (
"time"
)
type EnqueueRequest struct {
Id string //optional
Queue string //required
Type string //required
Arg []byte //optional
Delay time.Duration //optional
RequestId string //optional
}
+14
View File
@@ -0,0 +1,14 @@
package bgjob
import (
"errors"
)
var (
ErrQueueIsRequired = errors.New("queue is required")
ErrTypeIsRequired = errors.New("type is required")
ErrEmptyQueue = errors.New("queue is empty")
ErrJobAlreadyExist = errors.New("job already exist")
ErrUnknownType = errors.New("unknown type")
)
+18
View File
@@ -0,0 +1,18 @@
package bgjob
import (
"time"
)
type Job struct {
Id string
Queue string
Type string
Arg []byte
Attempt int32
LastError *string
NextRunAt int64
CreatedAt time.Time
UpdatedAt time.Time
RequestId string
}
+45
View File
@@ -0,0 +1,45 @@
package bgjob
import (
"context"
"time"
)
type Observer interface {
JobStarted(ctx context.Context, job Job)
JobCompleted(ctx context.Context, job Job)
JobRescheduled(ctx context.Context, job Job, after time.Duration)
JobWillBeRetried(ctx context.Context, job Job, after time.Duration, err error)
JobMovedToDlq(ctx context.Context, job Job, err error)
QueueIsEmpty(ctx context.Context)
WorkerError(ctx context.Context, err error)
}
type NoopObserver struct {
}
func (n NoopObserver) JobStarted(ctx context.Context, job Job) {
}
func (n NoopObserver) JobCompleted(ctx context.Context, job Job) {
}
func (n NoopObserver) JobWillBeRetried(ctx context.Context, job Job, after time.Duration, err error) {
}
func (n NoopObserver) JobRescheduled(ctx context.Context, job Job, after time.Duration) {
}
func (n NoopObserver) JobMovedToDlq(ctx context.Context, job Job, err error) {
}
func (n NoopObserver) QueueIsEmpty(ctx context.Context) {
}
func (n NoopObserver) WorkerError(ctx context.Context, err error) {
}
func NewNoopObserver() NoopObserver {
return NoopObserver{}
}
+160
View File
@@ -0,0 +1,160 @@
package bgjob
import (
"context"
"database/sql"
"fmt"
)
type pgStore struct {
db *sql.DB
}
func NewPgStoreV2(ctx context.Context, db *sql.DB) (*pgStore, error) {
err := assertHasColumn(ctx, db, "bgjob_job", "request_id")
if err != nil {
return nil, fmt.Errorf("%w; please apply 'add_request_id.sql' migration adding column `request_id` to `bgjob_job`", err)
}
err = assertHasColumn(ctx, db, "bgjob_dead_job", "request_id")
if err != nil {
return nil, fmt.Errorf("%w; please apply 'add_request_id.sql' migration adding column `request_id` to `bgjob_dead_job`", err)
}
return &pgStore{
db: db,
},
nil
}
func (p *pgStore) BulkInsert(ctx context.Context, jobs []Job) error {
return bulkInsert(ctx, p.db, jobs)
}
func (p *pgStore) Acquire(ctx context.Context, queue string, handler func(tx Tx) error) error {
return runTx(ctx, p.db, func(ctx context.Context, tx *sql.Tx) error {
query := `
SELECT id, queue, type, arg, attempt, last_error, next_run_at, created_at, updated_at, request_id
FROM bgjob_job
WHERE queue = $1 AND next_run_at <= $2
ORDER BY next_run_at, created_at
LIMIT 1 FOR UPDATE SKIP LOCKED
`
now := timeNow().Unix()
job := Job{}
err := tx.QueryRowContext(ctx, query, queue, now).Scan(
&job.Id,
&job.Queue,
&job.Type,
&job.Arg,
&job.Attempt,
&job.LastError,
&job.NextRunAt,
&job.CreatedAt,
&job.UpdatedAt,
&job.RequestId,
)
if err == sql.ErrNoRows {
return ErrEmptyQueue
}
if err != nil {
return err
}
return handler(&pgTx{
job: job,
tx: tx,
})
})
}
func runTx(ctx context.Context, db *sql.DB, txFunc func(ctx context.Context, tx *sql.Tx) error) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin: %w", err)
}
defer func() {
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
err = fmt.Errorf("%w, rollback error: %v", err, rbErr.Error())
}
} else {
comErr := tx.Commit()
if comErr != nil {
err = fmt.Errorf("commit: %w", comErr)
}
}
}()
return txFunc(ctx, tx)
}
type pgTx struct {
job Job
tx *sql.Tx
}
func (p *pgTx) Job() Job {
return p.job
}
func (p *pgTx) Update(ctx context.Context, id string, attempt int32, lastError string, nextRunAt int64) error {
query := "UPDATE bgjob_job SET attempt = $1, last_error = $2, next_run_at = $3, updated_at = $4 WHERE id = $5"
_, err := p.tx.ExecContext(ctx, query, attempt, lastError, nextRunAt, timeNow(), id)
return err
}
func (p *pgTx) UpdateNextRun(ctx context.Context, id string, nextRunAt int64) error {
query := "UPDATE bgjob_job SET next_run_at = $1, updated_at = $2 WHERE id = $3"
_, err := p.tx.ExecContext(ctx, query, nextRunAt, timeNow(), id)
return err
}
func (p *pgTx) Delete(ctx context.Context, id string) error {
query := `DELETE FROM bgjob_job WHERE id = $1`
_, err := p.tx.ExecContext(ctx, query, id)
return err
}
func (p *pgTx) SaveInDlq(ctx context.Context, job Job) error {
query := `INSERT INTO bgjob_dead_job
(job_id, queue, type, arg, attempt, next_run_at, last_error, job_created_at, job_updated_at, moved_at, request_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
`
_, err := p.tx.ExecContext(
ctx,
query,
job.Id,
job.Queue,
job.Type,
job.Arg,
job.Attempt,
job.NextRunAt,
job.LastError,
job.CreatedAt,
job.UpdatedAt,
timeNow(),
job.RequestId,
)
return err
}
func (p *pgTx) UpdateArg(ctx context.Context, id string, arg []byte) error {
query := "UPDATE bgjob_job SET arg = $1, updated_at = $2 WHERE id = $3"
_, err := p.tx.ExecContext(ctx, query, arg, timeNow(), id)
return err
}
func assertHasColumn(ctx context.Context, db *sql.DB, table, column string) error {
query := fmt.Sprintf("SELECT %s FROM %s LIMIT 1", column, table)
err := db.QueryRowContext(ctx, query).Scan(new(any))
if err != nil {
if err == sql.ErrNoRows {
return nil
}
return fmt.Errorf("bgjob: schema check error for %s.%s: %w", table, column, err)
}
return nil
}
+38
View File
@@ -0,0 +1,38 @@
package bgjob
import (
"time"
)
type Result struct {
complete bool
err error
moveToDlq bool
retry bool
retryDelay time.Duration
reschedule bool
rescheduleDelay time.Duration
overrideArg bool
arg []byte
}
func Complete() Result {
return Result{complete: true}
}
func Retry(after time.Duration, err error) Result {
return Result{retry: true, retryDelay: after, err: err}
}
func MoveToDlq(err error) Result {
return Result{moveToDlq: true, err: err}
}
func Reschedule(after time.Duration) Result {
return Result{reschedule: true, rescheduleDelay: after}
}
func RescheduleWithArg(after time.Duration, arg []byte) Result {
return Result{reschedule: true, overrideArg: true, rescheduleDelay: after, arg: arg}
}
+28
View File
@@ -0,0 +1,28 @@
package bgjob
import (
"context"
)
type Mux struct {
data map[string]Handler
}
func NewMux() *Mux {
return &Mux{
data: make(map[string]Handler),
}
}
func (m *Mux) Register(jobType string, handler Handler) *Mux {
m.data[jobType] = handler
return m
}
func (m *Mux) Handle(ctx context.Context, job Job) Result {
handler, ok := m.data[job.Type]
if !ok {
return MoveToDlq(ErrUnknownType)
}
return handler.Handle(ctx, job)
}
+113
View File
@@ -0,0 +1,113 @@
package bgjob
import (
"context"
"sync"
"time"
)
type Handler interface {
Handle(ctx context.Context, job Job) Result
}
type HandlerFunc func(ctx context.Context, job Job) Result
func (h HandlerFunc) Handle(ctx context.Context, job Job) Result {
return h(ctx, job)
}
type Worker struct {
cli *Client
queue string
handler Handler
pollInterval time.Duration
concurrency int
wg *sync.WaitGroup
observer Observer
close chan struct{}
}
func NewWorker(cli *Client, queue string, handler Handler, opts ...WorkerOption) *Worker {
w := &Worker{
cli: cli,
queue: queue,
handler: handler,
pollInterval: 1 * time.Second,
concurrency: 1,
wg: &sync.WaitGroup{},
close: make(chan struct{}),
observer: NewNoopObserver(),
}
for _, opt := range opts {
opt(w)
}
return w
}
func (w *Worker) Run(ctx context.Context) {
for i := 0; i < w.concurrency; i++ {
w.wg.Add(1)
go w.run(ctx)
}
}
func (w *Worker) run(ctx context.Context) {
defer w.wg.Done()
for {
select {
case <-w.close:
return
default:
}
var lastResult Result
var lastJob Job
err := w.cli.Do(ctx, w.queue, func(ctx context.Context, job Job) Result {
w.observer.JobStarted(ctx, job)
result := w.handler.Handle(ctx, job)
lastResult = result
lastJob = job
return result
})
if err != nil {
if err == ErrEmptyQueue {
w.observer.QueueIsEmpty(ctx)
} else {
w.observer.WorkerError(ctx, err)
}
select {
case <-ctx.Done():
return
case <-w.close:
return
case <-time.After(w.pollInterval):
}
continue
}
if lastResult.overrideArg {
lastJob.Arg = lastResult.arg
}
if lastResult.complete {
w.observer.JobCompleted(ctx, lastJob)
}
if lastResult.retry {
w.observer.JobWillBeRetried(ctx, lastJob, lastResult.retryDelay, lastResult.err)
}
if lastResult.moveToDlq {
w.observer.JobMovedToDlq(ctx, lastJob, lastResult.err)
}
if lastResult.reschedule {
w.observer.JobRescheduled(ctx, lastJob, lastResult.rescheduleDelay)
}
}
}
func (w *Worker) Shutdown() {
close(w.close)
w.wg.Wait()
}
+25
View File
@@ -0,0 +1,25 @@
package bgjob
import (
"time"
)
type WorkerOption func(w *Worker)
func WithPollInterval(interval time.Duration) WorkerOption {
return func(w *Worker) {
w.pollInterval = interval
}
}
func WithConcurrency(value int) WorkerOption {
return func(w *Worker) {
w.concurrency = value
}
}
func WithObserver(observer Observer) WorkerOption {
return func(w *Worker) {
w.observer = observer
}
}
+74
View File
@@ -0,0 +1,74 @@
# Created by .ignore support plugin (hsz.mobi)
### JetBrains template
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
/.idea/
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
*.iml
convert_service
convert-service
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
### Go template
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
/node_modules/
/vendor/
google/
package.json
yarn.lock
+1
View File
@@ -0,0 +1 @@
4.1.1
+32
View File
@@ -0,0 +1,32 @@
### v4.1.1
* `EncodeEvent` returns error
### v4.1.0
* extract `msg.Codec` iface
* add `etp.WithClientCodec` `etp.WithServerCodec`
* provide Godoc
### v4.0.0
* change conn id type to string, generate it from `crypto/rand`
### v3.0.0
* fully reimplemented with API change (see Migrated to V3 in README.MD)
### v2.1.3
- client: fully process workers channel before closing connection
- fix closing server connection
- use atomic for connection context
- server rooms: add api to retrieve all connections
### v2.1.2
- add worker queue for client to prevent read blocking
### v2.1.1
- fix bug in server.BroadcastToAll method
### v2.1.0
- migrate to go modules
- add ping method
### v2.0.2
- fixed deadlock on ack data chan when Acker.Notify() executed before Acker.Await()
### v2.0.1
- fixed data race when pushing response data to EmitWithAck channel
- add using buffer from pool in parser.EncodeEvent to decrease allocations
### v2.0.0
**NOTE**: protocol has changed, release is not compatible with 1.x.x
- add `OnWithAck` `EmitWithAck` methods for sync RPC
- add `sync.Pool` using
- add tests
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 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.
+172
View File
@@ -0,0 +1,172 @@
# etp
[![GoDoc](https://godoc.org/github.com/txix-open/etp/v4?status.svg)](https://godoc.org/github.com/txix-open/etp/v4)
![Build and test](https://github.com/txix-open/etp/actions/workflows/main.yml/badge.svg)
[![codecov](https://codecov.io/gh/txix-open/etp/branch/master/graph/badge.svg?token=JMTTJ5O6WB)](https://codecov.io/gh/txix-open/etp)
[![Go Report Card](https://goreportcard.com/badge/github.com/txix-open/etp/v4)](https://goreportcard.com/report/github.com/txix-open/etp/v4)
ETP - event transport protocol on WebSocket, simple and powerful.
Highly inspired by [socket.io](https://socket.io/). But there is no good implementation in Go, that is why `etp` exists.
The package based on [github.com/nhooyr/websocket](https://github.com/nhooyr/websocket).
## Install
```bash
go get -u github.com/txix-open/etp/v4
```
## Features:
- Rooms for server
- [Javascript client](https://github.com/txix-open/isp-etp-js-client)
- Concurrent event emitting
- Context based API
- Event acknowledgment (for sync communication)
## Internals
- WebSocket message
- `websocket.MessageText` (not binary)
- `<eventName>||<ackId>||<eventData>`
- can be overridden by custom `msg.Codec`
- Each event is handled concurrently in separated goroutine
- Message limit is `1MB` by default
## Complete example
```go
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/msg"
)
func main() {
srv := etp.NewServer(etp.WithServerAcceptOptions(&etp.AcceptOptions{
InsecureSkipVerify: true, //completely ignore CORS checks, enable only for dev purposes
}))
//callback to handle new connection
srv.OnConnect(func(conn *etp.Conn) {
//you have access to original HTTP request
fmt.Printf("id: %d, url: %s, connected\n", conn.Id(), conn.HttpRequest().URL)
srv.Rooms().Join(conn, "goodClients") //leave automatically then disconnected
conn.Data().Set("key", "value") //put any data associative with connection
})
//callback to handle disconnection
srv.OnDisconnect(func(conn *etp.Conn, err error) {
fmt.Println("disconnected", conn.Id(), err, etp.IsNormalClose(err))
})
//callback to handle any error during serving
srv.OnError(func(conn *etp.Conn, err error) {
connId := uint64(0)
// be careful, conn can be nil on upgrading protocol error (before success WebSocket connection)
if conn != nil {
connId = conn.Id()
}
fmt.Println("error", connId, err)
})
//your business event handler
//each event is handled in separated goroutine
srv.On("hello", etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fmt.Printf("hello event received: %s, %s\n", event.Name, event.Data)
return []byte("hello handled")
}))
//fallback handler
srv.OnUnknownEvent(etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fmt.Printf("unknown event received, %s, %s\n", event.Name, event.Data)
_ = conn.Close() //you may close a connection whenever you want
return nil
}))
mux := http.NewServeMux()
mux.Handle("GET /ws", srv)
go func() {
err := http.ListenAndServe(":8080", mux)
if err != nil {
panic(err)
}
}()
time.Sleep(1 * time.Second)
cli := etp.NewClient().
OnDisconnect(func(conn *etp.Conn, err error) { //basically you have all handlers like a server here
fmt.Println("client disconnected", conn.Id(), err)
})
err := cli.Dial(context.Background(), "ws://localhost:8080/ws")
if err != nil {
panic(err)
}
//to check connection is still alive
err = cli.Ping(context.Background())
if err != nil {
panic(err)
}
//simply emit event
err = cli.Emit(context.Background(), "hello", []byte("fire and forget"))
if err != nil {
panic(err)
}
//emit event and wait server response
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) //highly recommended to set up timeout for waiting acknowledgment
defer cancel()
resp, err := cli.EmitWithAck(ctx, "hello", []byte("wait acknowledgment"))
if err != nil {
panic(err)
}
fmt.Printf("hello resposne: '%s'\n", resp)
//data can be empty
err = cli.Emit(ctx, "unknown event", nil)
if err != nil {
panic(err)
}
time.Sleep(15 * time.Second)
//call to disconnect all clients
srv.Shutdown()
}
```
## V4 Migration
* Internal message format is the same as `v2`
* Each event now is handled in separated goroutine (completely async)
* Significantly reduce code base, removed redundant interfaces
* Fixed some memory leaks and potential deadlocks
* Main package `github.com/txix-open/isp-etp-go/v2` -> `github.com/txix-open/etp/v4`
* `OnDefault` -> `OnUnknownEvent`
* `On*` API are the same either `etp.Client` and `etp.Server`
* WAS
```go
srv.On("event", func (conn etp.Conn, data []byte) {
log.Println("Received " + testEvent + ":" + string(data))
}).
```
* BECOME
```go
srv.On("hello", etp.HandlerFunc(func(ctx context.Context, conn *etp.Conn, event msg.Event) []byte {
fmt.Printf("hello event received: %s, %s\n", event.Name, event.Data)
return []byte("hello handled")
}))
```
The second param now is an interface.
+27
View File
@@ -0,0 +1,27 @@
// Package bpool provides a buffer pool for reusing *bytes.Buffer instances.
// It reduces memory allocations by recycling buffers.
package bpool
import (
"bytes"
"sync"
)
var (
bpool = sync.Pool{New: func() any {
return bytes.NewBuffer(make([]byte, 1024))
}}
)
// Get returns a buffer from the pool. The buffer is reset before being returned.
// Callers must call Put when done using the buffer.
func Get() *bytes.Buffer {
b := bpool.Get().(*bytes.Buffer)
b.Reset()
return b
}
// Put returns a buffer to the pool for reuse.
func Put(b *bytes.Buffer) {
bpool.Put(b)
}
+166
View File
@@ -0,0 +1,166 @@
// Package etp provides a client-server communication library using WebSockets.
// It supports event-based messaging, acknowledgments, and room-based broadcasting.
package etp
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/internal"
)
var (
// ErrClientClosed is returned when the client is closed or not connected.
ErrClientClosed = errors.New("client closed")
)
// Client represents a WebSocket client for event-based communication.
// It is safe for concurrent use.
type Client struct {
mux *mux
idGenerator *internal.IdGenerator
opts *clientOptions
conn *atomic.Pointer[Conn]
lock sync.Locker
}
// NewClient creates a new Client instance with the provided options.
func NewClient(opts ...ClientOption) *Client {
options := defaultClientOptions()
for _, opt := range opts {
opt(options)
}
return &Client{
mux: newMux(),
idGenerator: internal.NewIdGenerator(),
opts: options,
conn: &atomic.Pointer[Conn]{},
lock: &sync.Mutex{},
}
}
// On registers an event handler for the specified event name.
// It returns the Client to allow method chaining.
func (c *Client) On(event string, handler Handler) *Client {
c.mux.On(event, handler)
return c
}
// OnConnect registers a handler to be called when the client connects.
// It returns the Client to allow method chaining.
func (c *Client) OnConnect(handler ConnectHandler) *Client {
c.mux.OnConnect(handler)
return c
}
// OnDisconnect registers a handler to be called when the client disconnects.
// It returns the Client to allow method chaining.
func (c *Client) OnDisconnect(handler DisconnectHandler) *Client {
c.mux.OnDisconnect(handler)
return c
}
// OnError registers a handler to be called when an error occurs.
// It returns the Client to allow method chaining.
func (c *Client) OnError(handler ErrorHandler) *Client {
c.mux.OnError(handler)
return c
}
// OnUnknownEvent registers a handler to be called when an unknown event is received.
// It returns the Client to allow method chaining.
func (c *Client) OnUnknownEvent(handler Handler) *Client {
c.mux.OnUnknownEvent(handler)
return c
}
// Dial establishes a WebSocket connection to the specified URL.
// It returns an error if already connected or if the WebSocket dial fails.
func (c *Client) Dial(ctx context.Context, url string) error {
c.lock.Lock()
defer c.lock.Unlock()
if c.conn.Load() != nil {
return errors.New("already connected")
}
ws, resp, err := websocket.Dial(ctx, url, c.opts.dialOptions)
if err != nil {
return fmt.Errorf("websocket dial: %w", err)
}
ws.SetReadLimit(c.opts.readLimit)
id := c.idGenerator.Next()
conn := newConn(id, resp.Request, ws, c.opts.codec)
c.conn.Store(conn)
keeper := newKeeper(conn, c.mux)
go func() {
defer func() {
_ = ws.CloseNow()
}()
keeper.Serve(context.Background())
c.lock.Lock()
defer c.lock.Unlock()
conn := c.conn.Load()
if conn != nil && conn.Id() == id {
c.conn.Store(nil)
}
}()
return nil
}
// Emit sends an event with the specified data to the server.
// It returns ErrClientClosed if the client is not connected.
func (c *Client) Emit(ctx context.Context, event string, data []byte) error {
conn := c.conn.Load()
if conn == nil {
return ErrClientClosed
}
return conn.Emit(ctx, event, data)
}
// EmitWithAck sends an event with the specified data to the server and waits for an acknowledgment.
// It returns ErrClientClosed if the client is not connected.
// The response data from the server is returned on success.
func (c *Client) EmitWithAck(ctx context.Context, event string, data []byte) ([]byte, error) {
conn := c.conn.Load()
if conn == nil {
return nil, ErrClientClosed
}
return conn.EmitWithAck(ctx, event, data)
}
// Ping sends a ping to the server to check the connection health.
// It returns ErrClientClosed if the client is not connected.
func (c *Client) Ping(ctx context.Context) error {
conn := c.conn.Load()
if conn == nil {
return ErrClientClosed
}
return conn.Ping(ctx)
}
// Close closes the client connection.
// It returns ErrClientClosed if the client is already closed.
func (c *Client) Close() error {
c.lock.Lock()
defer c.lock.Unlock()
conn := c.conn.Load()
if conn == nil {
return ErrClientClosed
}
err := conn.Close()
c.conn.Store(nil)
return err
}
+48
View File
@@ -0,0 +1,48 @@
package etp
import (
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/msg"
)
// DialOptions is an alias for websocket.DialOptions.
type DialOptions = websocket.DialOptions
// ClientOption is a function that configures a clientOptions struct.
type ClientOption func(*clientOptions)
// clientOptions holds configuration options for a Client.
type clientOptions struct {
dialOptions *DialOptions
readLimit int64
codec msg.Codec
}
// defaultClientOptions returns the default client configuration.
func defaultClientOptions() *clientOptions {
return &clientOptions{
readLimit: defaultReadLimit,
codec: msg.NewLineCodec(),
}
}
// WithClientDialOptions sets the WebSocket dial options for the client.
func WithClientDialOptions(opts *DialOptions) ClientOption {
return func(o *clientOptions) {
o.dialOptions = opts
}
}
// WithClientReadLimit sets the maximum message size in bytes that the client can read.
func WithClientReadLimit(limit int64) ClientOption {
return func(o *clientOptions) {
o.readLimit = limit
}
}
// WithClientCodec sets the codec for encoding and decoding events.
func WithClientCodec(codec msg.Codec) ClientOption {
return func(o *clientOptions) {
o.codec = codec
}
}
+15
View File
@@ -0,0 +1,15 @@
package etp
import (
"errors"
"github.com/coder/websocket"
)
// IsNormalClose checks if the error is a WebSocket normal closure.
func IsNormalClose(err error) bool {
if wsError, ok := errors.AsType[websocket.CloseError](err); ok {
return wsError.Code == websocket.StatusNormalClosure
}
return false
}
+122
View File
@@ -0,0 +1,122 @@
package etp
import (
"context"
"fmt"
"net/http"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/bpool"
"github.com/txix-open/etp/v4/internal"
"github.com/txix-open/etp/v4/msg"
"github.com/txix-open/etp/v4/store"
)
// Conn represents a WebSocket connection associated with a client or server.
type Conn struct {
id string
request *http.Request
ws *websocket.Conn
data *store.Store
acks *internal.Acks
codec msg.Codec
}
// newConn creates a new connection with the provided parameters.
func newConn(
id string,
request *http.Request,
ws *websocket.Conn,
codec msg.Codec,
) *Conn {
return &Conn{
id: id,
request: request,
ws: ws,
data: store.New(),
acks: internal.NewAcks(),
codec: codec,
}
}
// Id returns the unique identifier for the connection.
func (c *Conn) Id() string {
return c.id
}
// HttpRequest returns the underlying HTTP request associated with the connection.
func (c *Conn) HttpRequest() *http.Request {
return c.request
}
// Data returns the key-value store for connection-specific data.
func (c *Conn) Data() *store.Store {
return c.data
}
// Emit sends an event with the specified data over the connection.
func (c *Conn) Emit(ctx context.Context, event string, data []byte) error {
message := msg.Event{
Name: event,
AckId: 0,
Data: data,
}
return c.emit(ctx, message)
}
// EmitWithAck sends an event with the specified data and waits for an acknowledgment.
// It returns the response data from the receiver on success.
func (c *Conn) EmitWithAck(ctx context.Context, event string, data []byte) ([]byte, error) {
ack := c.acks.NextAck()
defer c.acks.DeleteAck(ack.Id())
message := msg.Event{
Name: event,
AckId: ack.Id(),
Data: data,
}
err := c.emit(ctx, message)
if err != nil {
return nil, err
}
response, err := ack.Wait(ctx)
if err != nil {
return nil, fmt.Errorf("failed to wait ack: %w", err)
}
return response, nil
}
// Ping sends a WebSocket ping to check connection health.
func (c *Conn) Ping(ctx context.Context) error {
return c.ws.Ping(ctx)
}
// Close closes the WebSocket connection with a normal closure status.
func (c *Conn) Close() error {
return c.ws.Close(websocket.StatusNormalClosure, "")
}
// emit encodes and writes an event to the WebSocket connection.
func (c *Conn) emit(ctx context.Context, event msg.Event) error {
buff := bpool.Get()
defer bpool.Put(buff)
err := c.codec.EncodeEvent(buff, event)
if err != nil {
return fmt.Errorf("failed to encode event: %w", err)
}
err = c.ws.Write(ctx, websocket.MessageText, buff.Bytes())
if err != nil {
return fmt.Errorf("failed to write event: %w", err)
}
return nil
}
// notifyAck notifies the acknowledgment handler with the received response data.
func (c *Conn) notifyAck(ackId uint64, data []byte) {
c.acks.NotifyAck(ackId, data)
}
+136
View File
@@ -0,0 +1,136 @@
package etp
import (
"context"
"sync"
"github.com/txix-open/etp/v4/msg"
)
// Handler is an interface for handling events.
// The Handle method processes an event and returns a response.
type Handler interface {
Handle(ctx context.Context, conn *Conn, event msg.Event) []byte
}
// HandlerFunc is a function type that implements the Handler interface.
type HandlerFunc func(ctx context.Context, conn *Conn, event msg.Event) []byte
// Handle calls the underlying function.
func (h HandlerFunc) Handle(ctx context.Context, conn *Conn, event msg.Event) []byte {
return h(ctx, conn, event)
}
// ConnectHandler is a function type called when a connection is established.
type ConnectHandler func(conn *Conn)
// DisconnectHandler is a function type called when a connection is closed.
type DisconnectHandler func(conn *Conn, err error)
// ErrorHandler is a function type called when an error occurs.
type ErrorHandler func(conn *Conn, err error)
// mux is an internal event multiplexer that manages handlers.
type mux struct {
handlers map[string]Handler
onUnknownEvent Handler
onConnect ConnectHandler
onDisconnect DisconnectHandler
onError ErrorHandler
readLock sync.Locker
writeLock sync.Locker
}
// newMux creates a new mux instance.
func newMux() *mux {
lock := &sync.RWMutex{}
return &mux{
handlers: make(map[string]Handler),
readLock: lock.RLocker(),
writeLock: lock,
}
}
// On registers an event handler for the specified event name.
func (m *mux) On(event string, handler Handler) {
m.writeLock.Lock()
m.handlers[event] = handler
m.writeLock.Unlock()
}
// OnConnect registers a handler to be called when a connection is established.
func (m *mux) OnConnect(handler ConnectHandler) {
m.writeLock.Lock()
m.onConnect = handler
m.writeLock.Unlock()
}
// OnDisconnect registers a handler to be called when a connection is closed.
func (m *mux) OnDisconnect(handler DisconnectHandler) {
m.writeLock.Lock()
m.onDisconnect = handler
m.writeLock.Unlock()
}
// OnError registers a handler to be called when an error occurs.
func (m *mux) OnError(handler ErrorHandler) {
m.writeLock.Lock()
m.onError = handler
m.writeLock.Unlock()
}
// OnUnknownEvent registers a handler to be called when an unknown event is received.
func (m *mux) OnUnknownEvent(handler Handler) {
m.writeLock.Lock()
m.onUnknownEvent = handler
m.writeLock.Unlock()
}
// handle dispatches an event to the appropriate handler.
// It returns the response from the handler.
func (m *mux) handle(ctx context.Context, conn *Conn, event msg.Event) []byte {
m.readLock.Lock()
handler, ok := m.handlers[event.Name]
if !ok {
handler = m.onUnknownEvent
}
m.readLock.Unlock()
if handler != nil {
return handler.Handle(ctx, conn, event)
}
return nil
}
// handleConnect calls the registered connect handler.
func (m *mux) handleConnect(conn *Conn) {
m.readLock.Lock()
onConnect := m.onConnect
m.readLock.Unlock()
if onConnect != nil {
onConnect(conn)
}
}
// handleDisconnect calls the registered disconnect handler.
func (m *mux) handleDisconnect(conn *Conn, err error) {
m.readLock.Lock()
onDisconnect := m.onDisconnect
m.readLock.Unlock()
if onDisconnect != nil {
onDisconnect(conn, err)
}
}
// handleError calls the registered error handler.
func (m *mux) handleError(conn *Conn, err error) {
m.readLock.Lock()
onError := m.onError
m.readLock.Unlock()
if onError != nil {
onError(conn, err)
}
}
+50
View File
@@ -0,0 +1,50 @@
package internal
import (
"context"
"strings"
)
type Ack struct {
id uint64
response chan []byte
}
func NewAck(id uint64) *Ack {
return &Ack{
id: id,
response: make(chan []byte, 1),
}
}
func (a *Ack) Wait(ctx context.Context) ([]byte, error) {
select {
case data := <-a.response:
return data, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (a *Ack) Notify(data []byte) {
select {
case a.response <- data:
default:
}
}
func (a *Ack) Id() uint64 {
return a.id
}
const (
ackPrefix = "__ack_"
)
func ToAckEvent(event string) string {
return ackPrefix + event
}
func IsAckEvent(event string) bool {
return strings.HasPrefix(event, ackPrefix)
}
+46
View File
@@ -0,0 +1,46 @@
package internal
import (
"sync"
)
type Acks struct {
lock sync.Locker
acks map[uint64]*Ack
idGenerator *SequenceGenerator
}
func NewAcks() *Acks {
return &Acks{
lock: &sync.Mutex{},
acks: make(map[uint64]*Ack),
idGenerator: NewSequenceGenerator(),
}
}
func (a *Acks) NextAck() *Ack {
a.lock.Lock()
defer a.lock.Unlock()
id := a.idGenerator.Next()
ack := NewAck(id)
a.acks[id] = ack
return ack
}
func (a *Acks) NotifyAck(ackId uint64, data []byte) {
a.lock.Lock()
defer a.lock.Unlock()
ack, ok := a.acks[ackId]
if ok {
ack.Notify(data)
}
}
func (a *Acks) DeleteAck(ackId uint64) {
a.lock.Lock()
defer a.lock.Unlock()
delete(a.acks, ackId)
}
+37
View File
@@ -0,0 +1,37 @@
package internal
import (
"crypto/rand"
"encoding/hex"
"sync/atomic"
)
type SequenceGenerator struct {
next *atomic.Uint64
}
func NewSequenceGenerator() *SequenceGenerator {
return &SequenceGenerator{
next: &atomic.Uint64{},
}
}
func (g *SequenceGenerator) Next() uint64 {
return g.next.Add(1)
}
type IdGenerator struct {
}
func NewIdGenerator() *IdGenerator {
return &IdGenerator{}
}
func (g *IdGenerator) Next() string {
value := make([]byte, 16)
_, err := rand.Read(value)
if err != nil {
panic(err)
}
return hex.EncodeToString(value)
}
+68
View File
@@ -0,0 +1,68 @@
package etp
import (
"context"
"github.com/txix-open/etp/v4/internal"
"github.com/txix-open/etp/v4/msg"
)
type keeper struct {
conn *Conn
mux *mux
}
func newKeeper(conn *Conn, mux *mux) *keeper {
return &keeper{
conn: conn,
mux: mux,
}
}
func (k *keeper) Serve(ctx context.Context) {
k.mux.handleConnect(k.conn)
for {
err := k.readAndHandleMessage(ctx)
if err != nil {
k.mux.handleDisconnect(k.conn, err)
return
}
}
}
func (k *keeper) readAndHandleMessage(ctx context.Context) error {
_, data, err := k.conn.ws.Read(ctx)
if err != nil {
return err
}
event, err := k.conn.codec.UnmarshalEvent(data)
if err != nil {
k.mux.onError(k.conn, err)
return nil
}
if internal.IsAckEvent(event.Name) {
k.conn.notifyAck(event.AckId, event.Data)
return nil
}
go func() {
response := k.mux.handle(ctx, k.conn, event)
if !event.IsAckRequired() {
return
}
message := msg.Event{
Name: internal.ToAckEvent(event.Name),
AckId: event.AckId,
Data: response,
}
err := k.conn.emit(ctx, message)
if err != nil {
k.mux.onError(k.conn, err)
}
}()
return nil
}
+26
View File
@@ -0,0 +1,26 @@
// Package msg provides message types and codecs for event-based communication.
package msg
import (
"bytes"
)
// Codec defines an interface for encoding and decoding events.
type Codec interface {
// UnmarshalEvent decodes event data from bytes.
UnmarshalEvent(data []byte) (Event, error)
// EncodeEvent encodes an event to bytes.
EncodeEvent(w *bytes.Buffer, event Event) error
}
// Event represents a communication event with a name, optional acknowledgment ID, and data payload.
type Event struct {
Name string
AckId uint64
Data []byte
}
// IsAckRequired returns true if the event requires an acknowledgment.
func (e Event) IsAckRequired() bool {
return e.AckId > 0
}
+65
View File
@@ -0,0 +1,65 @@
package msg
import (
"bytes"
"fmt"
"strconv"
)
const (
// Delimiter is the separator used between event name, ack ID, and data.
Delimiter = "||"
noBodyEventParts = 2
)
var (
delimiter = []byte(Delimiter)
)
// LineCodec is a simple text-based codec that uses "||" as a delimiter.
// The format is: <eventName>||<ackId>||<eventData>
type LineCodec struct{}
// NewLineCodec creates a new LineCodec instance.
func NewLineCodec() LineCodec {
return LineCodec{}
}
// UnmarshalEvent decodes an event from the line-based format.
// It returns an error if the format is invalid or if the ackId cannot be parsed.
func (LineCodec) UnmarshalEvent(data []byte) (Event, error) {
parts := bytes.SplitN(data, delimiter, 3)
if len(parts) < noBodyEventParts {
return Event{}, fmt.Errorf("expected format: <eventName>||<ackId>||<eventData>, got: %s", string(data))
}
ackId, err := strconv.Atoi(string(parts[1]))
if err != nil {
return Event{}, fmt.Errorf("parse ackId: %w", err)
}
var eventData []byte
if len(parts) > noBodyEventParts {
eventData = parts[2]
}
return Event{
Name: string(parts[0]),
AckId: uint64(ackId),
Data: eventData,
}, nil
}
// EncodeEvent encodes an event to the line-based format.
func (LineCodec) EncodeEvent(buff *bytes.Buffer, event Event) error {
ackId := strconv.FormatInt(int64(event.AckId), 10)
buff.Grow(len(event.Name) + len(ackId) + len(event.Data) + len(delimiter)*2)
buff.WriteString(event.Name)
buff.Write(delimiter)
buff.WriteString(ackId)
if len(event.Data) > 0 {
buff.Write(delimiter)
buff.Write(event.Data)
}
return nil
}
+138
View File
@@ -0,0 +1,138 @@
package etp
import "sync"
const (
// idsRoom is the internal room name for tracking all connections.
idsRoom = "__id"
)
// Rooms manages groups of connections for broadcasting.
// It is safe for concurrent use.
type Rooms struct {
mu sync.RWMutex
rooms map[string]map[string]*Conn
}
// newRooms creates a new Rooms instance.
func newRooms() *Rooms {
return &Rooms{
rooms: make(map[string]map[string]*Conn),
}
}
// Get retrieves a connection by its ID from the internal room.
// It returns the connection and a boolean indicating whether it exists.
func (s *Rooms) Get(connId string) (*Conn, bool) {
s.mu.RLock()
var (
conn *Conn
ok bool
)
idRoom, roomExist := s.rooms[idsRoom]
if roomExist {
conn, ok = idRoom[connId]
}
s.mu.RUnlock()
return conn, ok
}
// Join adds a connection to the specified rooms.
// New rooms are created if they do not exist.
func (s *Rooms) Join(conn *Conn, rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
conns[conn.Id()] = conn
} else {
s.rooms[room] = map[string]*Conn{
conn.Id(): conn,
}
}
}
s.mu.Unlock()
}
// LeaveByConnId removes a connection from the specified rooms.
// Empty rooms are automatically deleted.
func (s *Rooms) LeaveByConnId(id string, rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
delete(conns, id)
if len(conns) == 0 {
delete(s.rooms, room)
}
}
}
s.mu.Unlock()
}
// Len returns the number of connections in the specified room.
func (s *Rooms) Len(room string) int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.rooms[room])
}
// Clear removes the specified rooms.
func (s *Rooms) Clear(rooms ...string) {
s.mu.Lock()
for _, room := range rooms {
delete(s.rooms, room)
}
s.mu.Unlock()
}
// Rooms returns a slice of all room names, excluding the internal room.
func (s *Rooms) Rooms() []string {
s.mu.RLock()
result := make([]string, 0, len(s.rooms))
for room := range s.rooms {
if room != idsRoom {
result = append(result, room)
}
}
s.mu.RUnlock()
return result
}
// ToBroadcast returns all connections in the specified rooms for broadcasting.
// Duplicate connections are included multiple times if they belong to multiple rooms.
func (s *Rooms) ToBroadcast(rooms ...string) []*Conn {
s.mu.RLock()
result := make([]*Conn, 0)
for _, room := range rooms {
if conns, ok := s.rooms[room]; ok {
for _, conn := range conns {
result = append(result, conn)
}
}
}
s.mu.RUnlock()
return result
}
// AllConns returns all connections managed by the server.
func (s *Rooms) AllConns() []*Conn {
return s.ToBroadcast(idsRoom)
}
// add adds a connection to the internal room.
func (s *Rooms) add(conn *Conn) {
s.Join(conn, idsRoom)
}
// remove removes a connection from all rooms.
func (s *Rooms) remove(conn *Conn) {
s.mu.Lock()
defer s.mu.Unlock()
for room, conns := range s.rooms {
delete(conns, conn.Id())
if len(conns) == 0 {
delete(s.rooms, room)
}
}
}
+103
View File
@@ -0,0 +1,103 @@
package etp
import (
"fmt"
"net/http"
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/internal"
)
// Server represents a WebSocket server for event-based communication.
// It is safe for concurrent use.
type Server struct {
idGenerator *internal.IdGenerator
mux *mux
rooms *Rooms
opts *serverOptions
}
// NewServer creates a new Server instance with the provided options.
func NewServer(opts ...ServerOption) *Server {
options := defaultServerOptions()
for _, opt := range opts {
opt(options)
}
return &Server{
idGenerator: internal.NewIdGenerator(),
mux: newMux(),
rooms: newRooms(),
opts: options,
}
}
// On registers an event handler for the specified event name.
// It returns the Server to allow method chaining.
func (s *Server) On(event string, handler Handler) *Server {
s.mux.On(event, handler)
return s
}
// OnConnect registers a handler to be called when a client connects.
// It returns the Server to allow method chaining.
func (s *Server) OnConnect(handler ConnectHandler) *Server {
s.mux.OnConnect(handler)
return s
}
// OnDisconnect registers a handler to be called when a client disconnects.
// It returns the Server to allow method chaining.
func (s *Server) OnDisconnect(handler DisconnectHandler) *Server {
s.mux.OnDisconnect(handler)
return s
}
// OnError registers a handler to be called when an error occurs.
// It returns the Server to allow method chaining.
func (s *Server) OnError(handler ErrorHandler) *Server {
s.mux.OnError(handler)
return s
}
// OnUnknownEvent registers a handler to be called when an unknown event is received.
// It returns the Server to allow method chaining.
func (s *Server) OnUnknownEvent(handler Handler) *Server {
s.mux.OnUnknownEvent(handler)
return s
}
// Rooms returns the Rooms instance for managing connection groups.
func (s *Server) Rooms() *Rooms {
return s.rooms
}
// ServeHTTP handles HTTP requests by upgrading them to WebSocket connections.
// It implements the http.Handler interface.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ws, err := websocket.Accept(w, r, s.opts.acceptOptions)
if err != nil {
s.mux.handleError(nil, fmt.Errorf("websocket accept error: %w", err))
return
}
defer func() {
_ = ws.CloseNow()
}()
ws.SetReadLimit(s.opts.readLimit)
id := s.idGenerator.Next()
conn := newConn(id, r, ws, s.opts.codec)
s.rooms.add(conn)
defer s.rooms.remove(conn)
keeper := newKeeper(conn, s.mux)
keeper.Serve(r.Context())
}
// Shutdown closes all active connections on the server.
func (s *Server) Shutdown() {
for _, conn := range s.rooms.AllConns() {
_ = conn.Close()
}
}
+53
View File
@@ -0,0 +1,53 @@
package etp
import (
"github.com/coder/websocket"
"github.com/txix-open/etp/v4/msg"
)
const (
// defaultReadLimit is the default maximum message size in bytes.
defaultReadLimit = 1 * 1024 * 1024
)
// AcceptOptions is an alias for websocket.AcceptOptions.
type AcceptOptions = websocket.AcceptOptions
// ServerOption is a function that configures a serverOptions struct.
type ServerOption func(*serverOptions)
// serverOptions holds configuration options for a Server.
type serverOptions struct {
acceptOptions *AcceptOptions
readLimit int64
codec msg.Codec
}
// defaultServerOptions returns the default server configuration.
func defaultServerOptions() *serverOptions {
return &serverOptions{
readLimit: defaultReadLimit,
codec: msg.NewLineCodec(),
}
}
// WithServerAcceptOptions sets the WebSocket accept options for the server.
func WithServerAcceptOptions(opts *AcceptOptions) ServerOption {
return func(options *serverOptions) {
options.acceptOptions = opts
}
}
// WithServerReadLimit sets the maximum message size in bytes that the server can read.
func WithServerReadLimit(limit int64) ServerOption {
return func(options *serverOptions) {
options.readLimit = limit
}
}
// WithServerCodec sets the codec for encoding and decoding events.
func WithServerCodec(codec msg.Codec) ServerOption {
return func(o *serverOptions) {
o.codec = codec
}
}
+71
View File
@@ -0,0 +1,71 @@
// Package store provides a thread-safe key-value store for arbitrary data.
package store
import (
"fmt"
"sync"
)
// Store is a thread-safe key-value store for arbitrary data.
type Store struct {
data map[string]any
lock sync.Locker
}
// New creates a new Store instance.
func New() *Store {
return &Store{
data: make(map[string]any),
lock: &sync.Mutex{},
}
}
// Set stores a value with the specified key.
func (s *Store) Set(key string, value any) {
s.lock.Lock()
defer s.lock.Unlock()
s.data[key] = value
}
// Get retrieves a value by key. It returns nil if the key does not exist.
func (s *Store) Get(key string) any {
s.lock.Lock()
defer s.lock.Unlock()
return s.data[key]
}
// Range iterates over all key-value pairs in the store.
// The iteration stops if the function f returns false.
func (s *Store) Range(f func(key string, value any) bool) {
s.lock.Lock()
defer s.lock.Unlock()
for k, v := range s.data {
if !f(k, v) {
return
}
}
}
// Get is a type-safe helper function to retrieve a typed value from the store.
// It returns an error if the key does not exist or if the value cannot be cast to the requested type.
func Get[T any](store *Store, key string) (T, error) {
store.lock.Lock()
defer store.lock.Unlock()
var empty T
value, ok := store.data[key]
if !ok {
return empty, fmt.Errorf("value for key %s not found", key)
}
casted, ok := value.(T)
if !ok {
return empty, fmt.Errorf("expected type %T, but got %T", empty, value)
}
return casted, nil
}
+21
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,9 @@
package codec
const DefaultEncodeThreshold = 128 * 1024
var (
Default Codec = NewZstd(ZstdConfig{
Level: ZstdLevel(ZstdSpeedDefault),
})
)
+28
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -0,0 +1,9 @@
package db
import "time"
type ConnectionSettings struct {
maxConns int32
minIdleConns int32
maxConnsIdleTime time.Duration
}
+157
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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) {
}
Loaded 100 of 2619 files, more files were not shown because too many files have changed in this diff. Show more