MSP-8172 Add vendor
This commit is contained in:
1 parent
5175d87e08
commit
eb066cb055
2619 files changed
+757077
-2
No files matched your search
+75
@@ -0,0 +1,75 @@
|
||||
# Package `rc`
|
||||
|
||||
Пакет `rc` предоставляет механизм управления удалённой конфигурацией с возможностью её обновления, объединения с конфигурацией-переопределением и валидации.
|
||||
|
||||
## Types
|
||||
|
||||
### Validator
|
||||
|
||||
Интерфейс Validator определяет метод для валидации конфигурации.
|
||||
|
||||
### Config
|
||||
|
||||
Структура Config реализует управление конфигурацией с учётом переопределений, поддерживает блокировки и валидацию.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `New(validator Validator, overrideData []byte) *Config`
|
||||
|
||||
Создаёт новый экземпляр Config с указанным валидатором и данными переопределения.
|
||||
|
||||
#### `(c *Config) Upgrade(data []byte, newConfigPtr any, prevConfigPtr any) error`
|
||||
|
||||
Обновляет конфигурацию:
|
||||
|
||||
* объединяет переданные данные с переопределениями,
|
||||
* десериализует в `newConfigPtr`,
|
||||
* валидирует конфигурацию,
|
||||
* десериализует предыдущую конфигурацию в `prevConfigPtr`,
|
||||
* сохраняет новую конфигурацию как предыдущую.
|
||||
|
||||
### Functions
|
||||
|
||||
#### `Upgrade[T any](rc *Config, data []byte) (newCfg T, prevCfg T, err error)`
|
||||
|
||||
Удобная обобщённая функция для обновления конфигурации с использованием типа T.
|
||||
|
||||
#### `GenerateConfigSchema(cfgPtr any) schema.Schema`
|
||||
|
||||
Генерирует схему конфигурации для переданной структуры с помощью генератора из пакета `rc/schema`.
|
||||
|
||||
## Usage
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/rc"
|
||||
)
|
||||
|
||||
type MyConfig struct {
|
||||
// поля конфигурации
|
||||
}
|
||||
|
||||
type MyValidator struct{}
|
||||
|
||||
func (v MyValidator) ValidateToError(value any) error {
|
||||
// реализовать валидацию
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
validator := MyValidator{}
|
||||
overrideData := []byte(`{"some.key":"override value"}`)
|
||||
rcConfig := rc.New(validator, overrideData)
|
||||
|
||||
data := []byte(`{"some.key":"value"}`)
|
||||
|
||||
var newCfg, prevCfg MyConfig
|
||||
err := rcConfig.Upgrade(data, &newCfg, &prevCfg)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
// newCfg - новая конфигурация
|
||||
// prevCfg - предыдущая конфигурация
|
||||
}
|
||||
```
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
// Package rc provides a configuration management system with support for override merging,
|
||||
// validation, and hot-reloading capabilities. It uses JSON as the internal format and
|
||||
// supports hierarchical configuration through path delimiters.
|
||||
package rc
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"sync"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bellows"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
// Validator defines an interface for validating configuration values.
|
||||
// Implementations should return an error if the provided value is invalid.
|
||||
type Validator interface {
|
||||
ValidateToError(value any) error
|
||||
}
|
||||
|
||||
// Config manages configuration state with support for override merging and validation.
|
||||
// It is safe for concurrent use.
|
||||
type Config struct {
|
||||
prevConfig []byte
|
||||
overrideConfig []byte
|
||||
delim string
|
||||
validator Validator
|
||||
lock sync.Locker
|
||||
}
|
||||
|
||||
// New creates a new Config instance with the provided validator and override data.
|
||||
// The overrideData is merged with new configuration data during upgrades.
|
||||
// The default delimiter for hierarchical paths is "~".
|
||||
func New(validator Validator, overrideData []byte) *Config {
|
||||
return &Config{
|
||||
prevConfig: nil,
|
||||
overrideConfig: overrideData,
|
||||
delim: "~",
|
||||
validator: validator,
|
||||
lock: &sync.Mutex{},
|
||||
}
|
||||
}
|
||||
|
||||
// Upgrade processes new configuration data by merging it with overrides,
|
||||
// unmarshaling into the provided config pointer, and validating the result.
|
||||
// If validation succeeds, it stores the new config as the previous config.
|
||||
// The prevConfigPtr is populated with the previous configuration state if available.
|
||||
// Returns an error if merging, unmarshaling, or validation fails.
|
||||
func (c *Config) Upgrade(data []byte, newConfigPtr any, prevConfigPtr any) error {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
newConfig, err := c.mergeWithOverride(data)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "merge with override new config")
|
||||
}
|
||||
|
||||
err = json.Unmarshal(newConfig, newConfigPtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "unmarshal new config")
|
||||
}
|
||||
|
||||
err = c.validator.ValidateToError(newConfigPtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "validate config")
|
||||
}
|
||||
|
||||
if len(c.prevConfig) > 0 {
|
||||
err = json.Unmarshal(c.prevConfig, prevConfigPtr)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "unmarshal previous config")
|
||||
}
|
||||
}
|
||||
|
||||
c.prevConfig = newConfig
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// mergeWithOverride merges the provided config data with the override configuration.
|
||||
// It flattens both configs, applies overrides, and expands the result back to hierarchical form.
|
||||
// Returns the merged configuration as JSON bytes, or an error if merging fails.
|
||||
func (c *Config) mergeWithOverride(data []byte) ([]byte, error) {
|
||||
config := make(map[string]any)
|
||||
err := json.Unmarshal(data, &config)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal config")
|
||||
}
|
||||
|
||||
overrideData := make(map[string]any)
|
||||
if len(c.overrideConfig) > 0 {
|
||||
err = json.Unmarshal(c.overrideConfig, &overrideData)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "unmarshal override data")
|
||||
}
|
||||
}
|
||||
|
||||
config = bellows.Flatten(config, bellows.WithSep(c.delim))
|
||||
overrideData = bellows.Flatten(overrideData, bellows.WithSep(c.delim))
|
||||
maps.Copy(config, overrideData)
|
||||
|
||||
result := bellows.Expand(config, bellows.WithSep(c.delim))
|
||||
if result == nil {
|
||||
result = make(map[string]any)
|
||||
}
|
||||
config, ok := result.(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.WithMessagef(err, "unexpected type from bellows, expected map, got %T", result)
|
||||
}
|
||||
|
||||
data, err = json.Marshal(config)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "marshal config")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// Upgrade is a generic wrapper for Config.Upgrade that returns typed configuration structs.
|
||||
// It unmarshals the new and previous configurations into the generic types T.
|
||||
// Returns the new configuration, the previous configuration, and any error encountered.
|
||||
func Upgrade[T any](rc *Config, data []byte) (newCfg T, prevCfg T, err error) {
|
||||
err = rc.Upgrade(data, &newCfg, &prevCfg)
|
||||
return newCfg, prevCfg, err
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package rc
|
||||
|
||||
import (
|
||||
"github.com/txix-open/isp-kit/rc/schema"
|
||||
)
|
||||
|
||||
// GenerateConfigSchema creates a JSON schema from a configuration struct pointer.
|
||||
// It sets the title to "Remote config" and returns the generated schema.
|
||||
// The cfgPtr should be a pointer to a struct that represents the configuration.
|
||||
func GenerateConfigSchema(cfgPtr any) schema.Schema {
|
||||
s := schema.NewGenerator().Generate(cfgPtr)
|
||||
s.Title = "Remote config"
|
||||
s.Version = ""
|
||||
return s
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
# Package `schema`
|
||||
|
||||
Пакет `schema` реализует генерацию и настройку JSON схем для структур Go с поддержкой кастомных генераторов и тегов валидации.
|
||||
|
||||
## Types
|
||||
|
||||
### CustomGenerator
|
||||
|
||||
Функция для кастомной генерации схемы по полю структуры.
|
||||
|
||||
### customSchema
|
||||
|
||||
Внутренняя структура для управления реестром кастомных генераторов.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `Register(name string, f CustomGenerator)`
|
||||
|
||||
Регистрирует кастомный генератор под именем.
|
||||
|
||||
#### `Remove(name string)`
|
||||
|
||||
Удаляет кастомный генератор по имени.
|
||||
|
||||
### Schema
|
||||
|
||||
Псевдоним для `*github.com/txix-open/jsonschema.Schema`
|
||||
|
||||
### Generator
|
||||
|
||||
Генератор схемы.
|
||||
|
||||
**Methods:**
|
||||
|
||||
#### `NewGenerator()`
|
||||
|
||||
Создать и инициализировать генератор с настройками:
|
||||
|
||||
- `FieldNameReflector` — функция получения имени и признака обязательного поля,
|
||||
- `FieldReflector` — функция установки свойств поля,
|
||||
- `ExpandedStruct: true`,
|
||||
- `DoNotReference: true`.
|
||||
|
||||
#### `Generate(obj any) Schema`
|
||||
|
||||
Сгенерировать JSON-схему для переданной структуры.
|
||||
|
||||
## Functions
|
||||
|
||||
### `func GetNameAndRequiredFlag(field reflect.StructField) (string, bool)`
|
||||
|
||||
- Возвращает имя поля (с учётом тега `json`) и флаг обязательности (наличие `validate:"required"`).
|
||||
- Игнорирует неэкспортируемые поля.
|
||||
|
||||
### `func SetProperties(field reflect.StructField, s *jsonschema.Schema)`
|
||||
|
||||
- Извлекает из тегов поля `schema`, `default`, `validate`, `schemaGen`.
|
||||
- Устанавливает свойства схемы: `Title`, `Description`, `Default`, валидационные ограничения.
|
||||
- Если указан кастомный генератор (`schemaGen`), вызывает его.
|
||||
|
||||
### Валидация и ограничения
|
||||
|
||||
- Поддерживаются теги `validate` с опциями: `max`/`lte`, `min`/`gte`, `oneof`.
|
||||
- Ограничения применяются к типам `string`, `integer`, `array`.
|
||||
- Примеры:
|
||||
- `max=10` ограничение максимальной длины/значения,
|
||||
- `oneof='val1' 'val2'` — перечисление допустимых значений.
|
||||
|
||||
## Usage
|
||||
|
||||
### Default usage flow
|
||||
|
||||
```go
|
||||
type MyConfig struct {
|
||||
Name string `json:"name" validate:"required,min=3" schema:"Имя,Описание поля"`
|
||||
Age int `json:"age" validate:"min=18,max=100" default:"18"`
|
||||
}
|
||||
|
||||
gen := schema.NewGenerator()
|
||||
jsonSchema := gen.Generate(MyConfig{})
|
||||
// jsonSchema теперь содержит JSON-схему с ограничениями и описаниями
|
||||
```
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/txix-open/jsonschema"
|
||||
)
|
||||
|
||||
// CustomGenerator is a function type for customizing JSON schema generation.
|
||||
// It receives the struct field and the schema to modify.
|
||||
type CustomGenerator func(field reflect.StructField, s *jsonschema.Schema)
|
||||
|
||||
// customSchema manages the registry of custom schema generators.
|
||||
// It is safe for concurrent use.
|
||||
type customSchema struct {
|
||||
mx sync.RWMutex
|
||||
mapSchema map[string]CustomGenerator
|
||||
}
|
||||
|
||||
// CustomGenerators is the global registry for custom schema generators.
|
||||
// Use Register to add custom generators and Remove to delete them.
|
||||
var CustomGenerators = &customSchema{
|
||||
mapSchema: make(map[string]CustomGenerator),
|
||||
}
|
||||
|
||||
// Register adds a custom schema generator to the registry.
|
||||
// The name is used as the key to reference this generator from struct tags.
|
||||
func (c *customSchema) Register(name string, f CustomGenerator) {
|
||||
c.mx.Lock()
|
||||
c.mapSchema[name] = f
|
||||
c.mx.Unlock()
|
||||
}
|
||||
|
||||
// Remove deletes a custom schema generator from the registry by name.
|
||||
func (c *customSchema) Remove(name string) {
|
||||
c.mx.Lock()
|
||||
delete(c.mapSchema, name)
|
||||
c.mx.Unlock()
|
||||
}
|
||||
|
||||
// getGeneratorByName retrieves a custom generator from the registry by name.
|
||||
// Returns nil if no generator is registered with the given name.
|
||||
func (c *customSchema) getGeneratorByName(name string) CustomGenerator {
|
||||
c.mx.RLock()
|
||||
defer c.mx.RUnlock()
|
||||
|
||||
return c.mapSchema[name]
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
// Package schema provides JSON schema generation for Go structs with support for
|
||||
// custom field properties, validation constraints, and tag-based configuration.
|
||||
package schema
|
||||
|
||||
import (
|
||||
"github.com/txix-open/jsonschema"
|
||||
)
|
||||
|
||||
// Schema is a pointer to a jsonschema.Schema, representing a JSON Schema document.
|
||||
type Schema *jsonschema.Schema
|
||||
|
||||
// Generator creates JSON schemas from Go types with custom field reflection logic.
|
||||
// It uses a jsonschema.Reflector configured with custom field name and property handlers.
|
||||
type Generator struct {
|
||||
Reflector *jsonschema.Reflector
|
||||
}
|
||||
|
||||
// NewGenerator creates a new Generator instance with default configuration.
|
||||
// The reflector is set to expand structs and avoid using references ($ref).
|
||||
func NewGenerator() *Generator {
|
||||
return &Generator{
|
||||
Reflector: &jsonschema.Reflector{
|
||||
FieldNameReflector: GetNameAndRequiredFlag,
|
||||
FieldReflector: SetProperties,
|
||||
ExpandedStruct: true,
|
||||
DoNotReference: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Generate creates a JSON schema from the provided Go value.
|
||||
// The obj should typically be a pointer to a struct.
|
||||
// Returns the generated Schema representing the JSON schema document.
|
||||
func (g *Generator) Generate(obj any) Schema {
|
||||
return g.Reflector.Reflect(obj)
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
// nolint:goconst,mnd
|
||||
package schema
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/txix-open/jsonschema"
|
||||
)
|
||||
|
||||
const (
|
||||
tagDefault = "default"
|
||||
tagSchema = "schema"
|
||||
tagCustomSchema = "schemaGen"
|
||||
)
|
||||
|
||||
// GetNameAndRequiredFlag extracts the JSON field name and determines if the field is required.
|
||||
// It checks the struct field's json tag for the name and validate tag for the "required" constraint.
|
||||
// Returns the field name and a boolean indicating if the field is required.
|
||||
// Unexported fields (those with non-empty PkgPath) are ignored.
|
||||
func GetNameAndRequiredFlag(field reflect.StructField) (string, bool) {
|
||||
if field.PkgPath != "" { // unexported field, ignore it
|
||||
return "", false
|
||||
}
|
||||
|
||||
name, accept := GetFieldName(field)
|
||||
if !accept {
|
||||
return "", false
|
||||
}
|
||||
|
||||
validators := getValidatorsMap(field)
|
||||
if validators != nil {
|
||||
_, present := validators["required"]
|
||||
return name, present
|
||||
}
|
||||
|
||||
return name, false
|
||||
}
|
||||
|
||||
// SetProperties populates a JSON schema with properties from struct field tags.
|
||||
// It processes the following tags:
|
||||
// - "schema": sets Title and Description (format: "title,description")
|
||||
// - "default": sets the Default value
|
||||
// - "validate": sets validation constraints (min, max, oneof, etc.)
|
||||
// - "schemaGen": applies a custom generator by name
|
||||
func SetProperties(field reflect.StructField, s *jsonschema.Schema) {
|
||||
schema, ok := field.Tag.Lookup(tagSchema)
|
||||
if ok { //nolint:nestif
|
||||
parts := strings.SplitN(schema, ",", 2)
|
||||
if len(parts) > 0 {
|
||||
if len(parts) == 2 {
|
||||
s.Description = parts[1]
|
||||
}
|
||||
if parts[0] != "" {
|
||||
s.Title = parts[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
defaultValue, ok := field.Tag.Lookup(tagDefault)
|
||||
if ok {
|
||||
s.Default = defaultValue
|
||||
}
|
||||
|
||||
setValidators(field, s)
|
||||
|
||||
customValue, ok := field.Tag.Lookup(tagCustomSchema)
|
||||
if ok {
|
||||
if f := CustomGenerators.getGeneratorByName(customValue); f != nil {
|
||||
f(field, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// setValidators applies validation constraints from struct field tags to the schema.
|
||||
// Supported constraints: max/lte, min/gte, oneof.
|
||||
func setValidators(field reflect.StructField, s *jsonschema.Schema) {
|
||||
validators := getValidatorsMap(field)
|
||||
if validators == nil {
|
||||
return
|
||||
}
|
||||
for k, v := range validators {
|
||||
switch k {
|
||||
case "max", "lte":
|
||||
setMax(s, v)
|
||||
case "min", "gte":
|
||||
setMin(s, v)
|
||||
case "oneof":
|
||||
setOneOf(s, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// setMax sets the maximum constraint on a schema based on type.
|
||||
// For strings, it sets MaxLength; for integers, Maximum; for arrays, MaxItems.
|
||||
// Returns early if the value cannot be parsed as an unsigned integer.
|
||||
func setMax(s *jsonschema.Schema, v string) {
|
||||
value, err := strconv.ParseUint(v, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch s.Type {
|
||||
case "string":
|
||||
s.MaxLength = &value
|
||||
case "integer":
|
||||
s.Maximum = json.Number(v)
|
||||
case "array":
|
||||
s.MaxItems = &value
|
||||
}
|
||||
}
|
||||
|
||||
// setMin sets the minimum constraint on a schema based on type.
|
||||
// For strings, it sets MinLength; for integers, Minimum; for arrays, MinItems.
|
||||
// Returns early if the value cannot be parsed as an unsigned integer.
|
||||
func setMin(s *jsonschema.Schema, v string) {
|
||||
value, err := strconv.ParseUint(v, 10, 64)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch s.Type {
|
||||
case "string":
|
||||
s.MinLength = &value
|
||||
case "integer":
|
||||
s.Minimum = json.Number(v)
|
||||
case "array":
|
||||
s.MinItems = &value
|
||||
}
|
||||
}
|
||||
|
||||
// setOneOf sets an Enum list on the schema for string or integer types.
|
||||
// Returns early if the schema type is not string or integer.
|
||||
func setOneOf(s *jsonschema.Schema, v string) {
|
||||
if s.Type != "string" && s.Type != "integer" {
|
||||
return
|
||||
}
|
||||
for _, value := range parseOneOfParam(v) {
|
||||
s.Enum = append(s.Enum, value)
|
||||
}
|
||||
}
|
||||
|
||||
// getValidatorsMap extracts validation constraints from the "validate" struct tag.
|
||||
// Returns a map of constraint names to their values, or nil if no validate tag exists.
|
||||
func getValidatorsMap(field reflect.StructField) tagOptionsMap {
|
||||
value, ok := field.Tag.Lookup("validate")
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" || value == "-" {
|
||||
return nil
|
||||
}
|
||||
return parseTagIntoMap(value)
|
||||
}
|
||||
|
||||
// tagOptionsMap represents a map of tag option names to their values.
|
||||
type tagOptionsMap map[string]string
|
||||
|
||||
// parseTagIntoMap converts a comma-separated tag string into a map.
|
||||
// Supports both key-only (e.g., "required") and key=value (e.g., "oneof='a','b'") formats.
|
||||
func parseTagIntoMap(tag string) tagOptionsMap {
|
||||
optionsMap := make(tagOptionsMap)
|
||||
for option := range strings.SplitSeq(tag, ",") {
|
||||
option = strings.TrimSpace(option)
|
||||
keyValue := strings.Split(option, "=")
|
||||
switch len(keyValue) {
|
||||
case 1:
|
||||
optionsMap[keyValue[0]] = ""
|
||||
case 2:
|
||||
optionsMap[keyValue[0]] = keyValue[1]
|
||||
}
|
||||
}
|
||||
return optionsMap
|
||||
}
|
||||
|
||||
// GetFieldName extracts the JSON field name from a struct field.
|
||||
// It checks the "json" tag for an explicit name; if absent, it uses the field name
|
||||
// converted to camelCase (first letter lowercase).
|
||||
// Returns the field name and true if the field should be included, or empty string and false if not.
|
||||
func GetFieldName(fieldType reflect.StructField) (string, bool) {
|
||||
original := fieldType.Name
|
||||
transform := true
|
||||
value, ok := fieldType.Tag.Lookup("json")
|
||||
if ok { //nolint:nestif
|
||||
opts := strings.Split(value, ",")
|
||||
if len(opts) > 0 {
|
||||
if opts[0] == "-" {
|
||||
return "", false
|
||||
}
|
||||
name := opts[0]
|
||||
if len(name) > 0 {
|
||||
original = name
|
||||
transform = false
|
||||
} else {
|
||||
transform = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if transform {
|
||||
arr := []rune(original)
|
||||
arr[0] = unicode.ToLower(arr[0])
|
||||
original = string(arr)
|
||||
}
|
||||
return original, true
|
||||
}
|
||||
|
||||
var splitParamsRegex = regexp.MustCompile(`'[^']*'|\S+`)
|
||||
|
||||
// parseOneOfParam parses a oneOf validation parameter string.
|
||||
// It handles both quoted values (e.g., "'a','b','c'") and unquoted values.
|
||||
// Returns a slice of parsed values with quotes removed.
|
||||
func parseOneOfParam(param string) []string {
|
||||
values := splitParamsRegex.FindAllString(param, -1)
|
||||
for i := range values {
|
||||
values[i] = strings.ReplaceAll(values[i], "'", "")
|
||||
}
|
||||
return values
|
||||
}
|
||||
Reference in new issue
Block a user