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

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