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

+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)
}