Documentation
¶
Overview ¶
Package config defines the configuration structures and validation logic for all infrastructure components managed by go-atlas.
Structure Types ¶
Each infrastructure concern is represented by one or more exported structs (e.g. Mongodb, Nats, Redis, Grpc, Http, Auth, Observability). Struct fields carry YAML struct tags and default-value tags; the config/loader package populates them from files, environment variables, and secret references.
Every top-level config struct exposes:
- A Default* constructor that returns the struct with sensible defaults.
- A Validate method that uses ozzo-validation to enforce invariants.
- A Normalize method (where applicable) that initializes sub-structs implied by a type-selector field.
Storage Pattern ¶
Several features (rate limiting, idempotency, caching) share a common storage abstraction: a type-selector field (CacheStorageType) paired with provider-specific sub-configs (StorageMemoryConfig, StorageRedisConfig, StorageNATSConfig). The CacheStorageConfig struct implements this pattern; call Normalize before Validate to allocate the right sub-struct.
Interceptors and Middlewares ¶
gRPC interceptor configs embed BaseGrpcInterceptorConfig which bundles EnableMixin and InterceptorFilterConfig. HTTP middleware configs embed BaseHttpMiddlewareConfig with HttpMiddlewareFilterConfig. Both provide shared enable/disable and method/path exclusion logic so that concrete interceptor and middleware configs only declare their unique fields.
Secret Handling ¶
The Secret type wraps sensitive strings and automatically redacts them in fmt, JSON, YAML, and slog output. Use it for passwords, tokens, and keys.
Subpackages ¶
- config/loader: Multi-source configuration loading (YAML/TOML files, environment variables, default tags, secret expansion).
- config/loader/secrets: Secret placeholder expansion ($__secret{ns:key}).
- config/loader/backend: Backend interface and implementations (YAML, TOML).
- config/internal/utils: Internal file-lookup helpers.
- config/internal/validators: Internal custom validators.
- templates: Default configuration file templates (no Go source).
Index ¶
- Constants
- func PrettyError(err error) string
- func ValidateIgnoreConfig(ignoreMethods, ignorePatterns *[]string) []*validation.FieldRules
- func ValidateStruct(structPtr any, fields ...*validation.FieldRules) error
- func ValidateStructIfEnabled(enabled bool, structPtr any, fields ...*validation.FieldRules) error
- func ValidationErrorsToFlatMap(in validation.Errors) validation.Errors
- type AckPolicy
- type Auth
- type BaseGrpcInterceptorConfig
- type BaseHttpMiddlewareConfig
- type Broker
- type BrokerProvider
- type CacheStorageConfig
- type CacheStorageType
- type DeliverPolicy
- type DistributionLock
- type DistributionLockNats
- type DistributionLockProvider
- type EnableMixin
- type Enableable
- type FallbackBehavior
- type Grpc
- type GrpcEnforcementPolicy
- type GrpcInterAuthConfig
- type GrpcInterCacheCompressionPreset
- type GrpcInterCacheConfig
- type GrpcInterHealthConfig
- type GrpcInterIdempotencyConfig
- type GrpcInterLimiterConfig
- type GrpcInterLoggerConfig
- type GrpcInterPrometheusConfig
- type GrpcInterPrometheusSamplingStrategy
- type GrpcInterRealIpConfig
- type GrpcInterRecoveryConfig
- type GrpcInterRequestIdConfig
- type GrpcInterTracingConfig
- type GrpcKeepAlive
- type GrpcTls
- type Health
- type Http
- type HttpInterBodyLimitConfig
- type HttpInterCorsConfig
- type HttpInterIdempotencyConfig
- type HttpInterLimiterConfig
- type HttpInterLoggerConfig
- type HttpInterPrometheusConfig
- type HttpInterRealIpConfig
- type HttpInterRecoveryConfig
- type HttpInterRequestIdConfig
- type HttpInterSecurityHeadersConfig
- type HttpInterTracingConfig
- type HttpMiddlewareFilterConfig
- type HttpTls
- type Idempotency
- type IgnoreConfig
- type InProgress
- type InProgressMetrics
- type InterceptorFilterConfig
- type InterceptorsConfig
- type LeaderElector
- type LeaderElectorProvider
- type Limiter
- type LimiterDefaultRule
- type LimiterRules
- type LimiterTargetRule
- type LogFormat
- type Logger
- type LoggerConsoleOutput
- type LoggerLevel
- type Metrics
- type MetricsAdapters
- type MetricsPrometheus
- type MetricsType
- type MiddlewaresConfig
- type MongoAuthMechanismType
- type MongoCompressionType
- type MongoCompressionTypes
- type MongoEncryption
- type MongoEncryptionType
- type MongoKMS
- type MongoKMSAmazon
- type MongoKMSAzure
- type MongoKMSGoogle
- type MongoKMSLocal
- type MongoKMSProvider
- type MongoPLAINCredentials
- type MongoSCRAMCredentials
- type Mongodb
- type MongodbCredentials
- type Nats
- type NatsConsumer
- type NatsConsumers
- type NatsRecovery
- type Node
- type OIDC
- func (a *OIDC) IsCacheConfigured() bool
- func (a *OIDC) IsIntrospectionConfigured() bool
- func (a *OIDC) IsJWKSConfigured() bool
- func (a *OIDC) IsPresetsConfigured() bool
- func (a *OIDC) IsRevocationConfigured() bool
- func (a *OIDC) IsServiceAccountConfigured() bool
- func (a *OIDC) IsValidationConfigured() bool
- func (a *OIDC) Validate() error
- type OIDCCache
- type OIDCClaims
- type OIDCExpression
- type OIDCIntrospection
- type OIDCJwks
- type OIDCPreset
- type OIDCPresets
- type OIDCRevocation
- type OIDCRevocationSource
- type OIDCSelector
- type OIDCServiceAccount
- type OIDCValidation
- type OPA
- type OPACache
- type OTLPProtocol
- type Observability
- type Outbox
- type ProbabilisticFilter
- type ProbabilisticFilterBloomConfig
- type ProbabilisticFilterBloomDefaults
- type ProbabilisticFilterConfig
- type ProbabilisticFilterCuckooConfig
- type ProbabilisticFilterCuckooDefaults
- type ProbabilisticFilterDefaults
- type ProbabilisticFilterStorageType
- type ProbabilisticFilterType
- type Redis
- type ReplayPolicy
- type RequestsLimiter
- type S3
- type STS
- type SamplerType
- type Scheduler
- type SchedulerStorageConfig
- type SchedulerStorageMemoryConfig
- type SchedulerStorageMongoConfig
- type SchedulerStorageRedisConfig
- type SchedulerStorageType
- type Secret
- func (s Secret) Expose() string
- func (s Secret) GoString() string
- func (s Secret) IsEmpty() bool
- func (s Secret) LogValue() slog.Value
- func (s Secret) MarshalJSON() ([]byte, error)
- func (s Secret) MarshalText() ([]byte, error)
- func (s Secret) MarshalYAML() (any, error)
- func (s Secret) SecureString() *corestrings.SecureString
- func (s Secret) String() string
- type Secrets
- type SecretsCache
- type SecretsGCP
- type SecretsLockbox
- type SecretsProvider
- type SecretsRetry
- type SecretsVault
- type StorageMemoryConfig
- type StorageNATSConfig
- type StorageRedisConfig
- type TlsClient
- type TlsClientAuth
- type TlsProvider
- type TlsProviderFile
- type TlsProviderLetsEncrypt
- type TlsProviderType
- type TlsProviderVault
- type TlsServer
- type Tracing
- type TracingAdapters
- type TracingConsole
- type TracingOTLP
- type TracingSampler
- type TracingType
- type Vault
- type VaultAuth
- type VaultAuthApprole
- type VaultAuthMethod
- type VaultAuthUserpass
Constants ¶
const ( // MaxNATSReplicas defines the maximum number of NATS KeyValue replicas. // This limit prevents excessive replication that could impact performance. MaxNATSReplicas = 3 // MaxKeyPrefixLength defines the maximum length for storage key prefixes. // Reasonable limit to prevent storage key bloat and ensure compatibility. MaxKeyPrefixLength = 64 )
Storage configuration constants used across different storage backends.
const ( // GrpcInterIdempotencyMaxKeyHeaderLength defines the maximum length for idempotency key header names. // Prevents excessively long header names that could cause HTTP/gRPC issues. GrpcInterIdempotencyMaxKeyHeaderLength = 128 // GrpcInterIdempotencyMaxKeyFieldLength defines the maximum length for idempotency key field names. // Limits field name length for request parsing and proto field access. GrpcInterIdempotencyMaxKeyFieldLength = 100 )
const ( // DefaultCorsMaxAge is the default max age for preflight cache (24 hours in seconds). DefaultCorsMaxAge = 86400 // DefaultCorsOptionsSuccessStatus is the default HTTP status for successful OPTIONS requests. DefaultCorsOptionsSuccessStatus = 204 )
CORS configuration defaults.
const ( // DefaultOPAQuery is the default Rego query for authorization decisions. DefaultOPAQuery = "data.profiles.authz.allow" // DefaultOPACacheTTL is the default cache TTL for authorization decisions. DefaultOPACacheTTL = 5 * time.Minute // DefaultOPADecisionLogging is the default decision logging setting. DefaultOPADecisionLogging = false // DefaultOPAWatchBundle is the default bundle watching setting. DefaultOPAWatchBundle = false // DefaultOPARunOnStart is the default setting for running update on start. DefaultOPARunOnStart = true )
const DefaultBodyLimitMaxSize int64 = 10 * 1024 * 1024
DefaultBodyLimitMaxSize is the default maximum body size (10MB).
const (
// DefaultHstsMaxAge is the default max-age for HSTS (1 year in seconds).
DefaultHstsMaxAge = 31536000
)
Security headers configuration defaults.
const MasterKeyLength = 96
MasterKeyLength is the required length in bytes for local master keys. Local master keys must be exactly 96 bytes when base64 encoded.
Variables ¶
This section is empty.
Functions ¶
func PrettyError ¶
PrettyError formats validation errors into a human-readable string. If the error is a validation.Errors type, it flattens the structure and formats each error with field names. For other error types, it returns the standard error message.
Example output:
Configuration in not valid: - server.port: invalid port number - database.host: cannot be blank
func ValidateIgnoreConfig ¶
func ValidateIgnoreConfig(ignoreMethods, ignorePatterns *[]string) []*validation.FieldRules
ValidateIgnoreConfig returns validation field rules for IgnoreConfig embedded fields. Use this helper to validate IgnoreMethods and IgnorePatterns fields in config structs.
func ValidateStruct ¶
func ValidateStruct(structPtr any, fields ...*validation.FieldRules) error
ValidateStruct validates a struct and enhances ozzo-validation's internal errors (ErrFieldNotFound, ErrFieldPointer) with the struct type name and actionable hints.
Use this instead of validation.ValidateStruct to get clearer error messages when a validation.Field pointer does not reference a field in the target struct.
Example:
func (c *Config) Validate() error {
return config.ValidateStruct(c,
validation.Field(&c.Field1, validation.Required),
)
}
func ValidateStructIfEnabled ¶
func ValidateStructIfEnabled(enabled bool, structPtr any, fields ...*validation.FieldRules) error
ValidateStructIfEnabled validates a struct only if the enabled flag is true. This helper reduces boilerplate in configuration structs that have an "Enable" field.
Example:
func (c *Config) Validate() error {
return ValidateStructIfEnabled(c.Enable, c,
validation.Field(&c.Field1, validation.Required),
)
}
func ValidationErrorsToFlatMap ¶
func ValidationErrorsToFlatMap(in validation.Errors) validation.Errors
ValidationErrorsToFlatMap converts nested validation.Errors into a flat map structure. It recursively flattens nested validation errors using dot notation for keys. This is useful for displaying validation errors in a user-friendly format.
Example:
errs := validation.Errors{
"server": validation.Errors{
"port": fmt.Errorf("invalid port"),
},
}
flat := ValidationErrorsToFlatMap(errs)
// Result: {"server.port": "invalid port"}
Types ¶
type AckPolicy ¶
type AckPolicy string
AckPolicy defines how messages should be acknowledged.
const ( // AckPolicyNone requires no acknowledgement. // Messages are considered delivered immediately. AckPolicyNone AckPolicy = "none" // AckPolicyAll acknowledges all messages up to and including the current one. AckPolicyAll AckPolicy = "all" // AckPolicyExplicit requires explicit acknowledgement for each message. AckPolicyExplicit AckPolicy = "explicit" )
type Auth ¶
type Auth struct {
// OIDC contains configuration for OpenID Connect authentication.
// If nil, OIDC authentication is disabled.
OIDC *OIDC `yaml:"oidc" default:"-"`
// OPA contains configuration for Open Policy Agent authorization.
// If nil, OPA authorization is disabled.
OPA *OPA `yaml:"opa" default:"-"`
}
Auth represents the combined authentication and authorization configuration. It includes settings for OIDC (Authentication) and OPA (Authorization).
Example:
auth := &config.Auth{
OIDC: &config.DefaultOIDC(),
OPA: &config.DefaultOPA(),
}
func DefaultAuth ¶
func DefaultAuth() Auth
DefaultAuth returns an Auth configuration with default values. Both OIDC and OPA are included with their respective default values.
type BaseGrpcInterceptorConfig ¶
type BaseGrpcInterceptorConfig struct {
// EnableMixin controls whether this interceptor is active.
EnableMixin `yaml:",inline"`
// InterceptorFilterConfig provides method filtering settings.
InterceptorFilterConfig `yaml:",inline"`
}
BaseGrpcInterceptorConfig provides common configuration structure for gRPC interceptors. It combines EnableMixin and InterceptorFilterConfig with a standard Validate method that can be extended with additional validation rules.
Embed this struct in gRPC interceptor configurations to get standard validation behavior:
type MyInterceptorConfig struct {
BaseGrpcInterceptorConfig `yaml:",inline"`
// ... additional fields
}
func (c *MyInterceptorConfig) Validate() error {
if !c.Enable {
return nil
}
rules := c.BaseValidationRules()
rules = append(rules,
validation.Field(&c.CustomField, validation.Required),
// ... additional rules
)
return ValidateStruct(c, rules...)
}
func (*BaseGrpcInterceptorConfig) BaseValidationRules ¶
func (c *BaseGrpcInterceptorConfig) BaseValidationRules() []*validation.FieldRules
BaseValidationRules returns the base validation rules for the interceptor. Callers should append their own rules and call validation.ValidateStruct themselves.
func (*BaseGrpcInterceptorConfig) ValidateBase ¶
func (c *BaseGrpcInterceptorConfig) ValidateBase(fn ...func() error) error
ValidateBase performs standard validation for the base interceptor configuration and then calls fn for additional validation rules specific to the concrete config.
Returns an error if validation fails, nil otherwise.
type BaseHttpMiddlewareConfig ¶
type BaseHttpMiddlewareConfig struct {
// EnableMixin controls whether this middleware is active.
EnableMixin `yaml:",inline"`
// HttpMiddlewareFilterConfig provides path filtering settings.
HttpMiddlewareFilterConfig `yaml:",inline"`
}
BaseHttpMiddlewareConfig provides common configuration structure for HTTP middlewares. It combines EnableMixin and HttpMiddlewareFilterConfig with a standard Validate method that can be extended with additional validation rules.
Embed this struct in HTTP middleware configurations to get standard validation behavior:
type MyMiddlewareConfig struct {
BaseHttpMiddlewareConfig `yaml:",inline"`
// ... additional fields
}
func (*BaseHttpMiddlewareConfig) ValidateBase ¶
func (c *BaseHttpMiddlewareConfig) ValidateBase(fn ...func() error) error
ValidateBase performs standard validation for HTTP middleware configurations. It validates the Enable field and filter configuration, then applies additional rules.
Parameters:
- additionalRules: extra validation rules specific to the middleware
Returns an error if validation fails, nil otherwise.
type Broker ¶
type Broker struct {
// Provider is the type of broker to use.
Provider BrokerProvider `yaml:"provider" default:"nats"`
// Nats contains NATS-specific configuration.
// Required when Provider is "nats".
Nats *Nats `yaml:"nats"`
// InProgress contains configuration for InProgress heartbeat manager.
InProgress InProgress `yaml:"inProgress"`
// Outbox contains configuration for reliable message delivery.
Outbox Outbox `yaml:"outbox"`
}
Broker defines the configuration for message broker operations. Supports multiple broker providers with provider-specific settings.
Example:
broker := &config.Broker{Provider: config.BrokerProviderNats}
func DefaultBroker ¶
func DefaultBroker() Broker
DefaultBroker returns a Broker configuration with default values.
type BrokerProvider ¶
type BrokerProvider string
BrokerProvider defines the type of message broker to use. Currently, only NATS is supported as a broker provider.
const ( // BrokerProviderNats represents the NATS broker provider. BrokerProviderNats BrokerProvider = "nats" )
type CacheStorageConfig ¶
type CacheStorageConfig struct {
// Type defines the storage backend type.
// Must be one of the supported storage types (memory, redis, nats).
Type CacheStorageType `yaml:"type"`
// Memory defines the in-memory configuration.
// Required when Type is CacheStorageTypeMemory, ignored otherwise.
Memory *StorageMemoryConfig `yaml:"memory,omitempty" default:"-"`
// Nats defines the NATS configuration.
// Required when Type is CacheStorageTypeNats, ignored otherwise.
Nats *StorageNATSConfig `yaml:"nats,omitempty" default:"-"`
// Redis defines the Redis configuration.
// Required when Type is CacheStorageTypeRedis, ignored otherwise.
Redis *StorageRedisConfig `yaml:"redis,omitempty" default:"-"`
}
CacheStorageConfig defines storage backend configuration with type selector. Provides a unified storage configuration for idempotency, rate limiting, and other features that require distributed storage.
func (*CacheStorageConfig) Normalize ¶
func (c *CacheStorageConfig) Normalize()
Normalize allocates the provider-specific sub-config implied by [CacheStorageConfig.Type]. Call Normalize before Validate so the correct sub-struct is present for validation.
func (*CacheStorageConfig) Validate ¶
func (c *CacheStorageConfig) Validate() error
Validate performs validation of the cache storage configuration. Ensures storage type is valid and corresponding configuration is provided.
type CacheStorageType ¶
type CacheStorageType string
CacheStorageType defines storage backend types for caching. Used by idempotency, rate limiting, and other features that need distributed storage.
const ( // CacheStorageTypeMemory represents in-memory storage. // Provides fast access but is not shared across instances. // Useful for testing or single-instance deployments. CacheStorageTypeMemory CacheStorageType = "memory" // CacheStorageTypeRedis represents Redis storage. // Provides shared storage across instances with persistence options. CacheStorageTypeRedis CacheStorageType = "redis" // CacheStorageTypeNats represents NATS KeyValue storage. // Offers distributed storage with built-in replication and stream features. CacheStorageTypeNats CacheStorageType = "nats" )
type DeliverPolicy ¶
type DeliverPolicy string
DeliverPolicy defines the point in the stream to start delivering messages.
const ( // DeliverPolicyAll delivers all available messages from the stream. DeliverPolicyAll DeliverPolicy = "all" // DeliverPolicyLast delivers starting with the last message in the stream. DeliverPolicyLast DeliverPolicy = "last" // DeliverPolicyNew delivers only new messages that arrive after consumer creation. DeliverPolicyNew DeliverPolicy = "new" // DeliverPolicyByStartSequence delivers starting from a specific sequence number. DeliverPolicyByStartSequence DeliverPolicy = "by_start_sequence" // DeliverPolicyByStartTime delivers starting from a specific time. DeliverPolicyByStartTime DeliverPolicy = "by_start_time" )
type DistributionLock ¶
type DistributionLock struct {
// Provider defines the type of distributed locking implementation to use.
// Must be one of the supported providers (currently only "nats").
Provider DistributionLockProvider `yaml:"provider"`
// Nats defines the NATS configuration for distributed locking.
// Required when Provider is DistributionLockProviderNats, ignored otherwise.
Nats *DistributionLockNats `yaml:"nats" default:"-"`
}
DistributionLock defines the configuration for distributed locking. Coordinates operations across multiple service instances using distributed locks.
Example:
dlock := &config.DistributionLock{
Provider: config.DistributionLockProviderNats,
Nats: &config.DistributionLockNats{Bucket: "myapp-locks"},
}
func DefaultDistributionLock ¶
func DefaultDistributionLock() DistributionLock
DefaultDistributionLock returns a DistributionLock configuration with default values. Note: Provider is left as zero value since it is a required field.
func (*DistributionLock) Validate ¶
func (dl *DistributionLock) Validate() error
Validate performs validation of the distributed lock configuration. Ensures provider is valid and corresponding configuration is provided. Returns an error if validation fails, nil otherwise.
type DistributionLockNats ¶
type DistributionLockNats struct {
// Bucket is the name of the NATS JetStream Key-Value bucket
// where distributed locks will be stored.
// Defaults to "dlock" if not specified.
Bucket string `yaml:"bucket" default:"dlock"`
}
DistributionLockNats defines the NATS-specific configuration for distributed locking. Contains settings for NATS JetStream Key-Value bucket creation and management.
func DefaultDistributionLockNats ¶
func DefaultDistributionLockNats() DistributionLockNats
DefaultDistributionLockNats returns a DistributionLockNats configuration with default values.
type DistributionLockProvider ¶
type DistributionLockProvider string
DistributionLockProvider defines the distributed locking provider type.
const ( // DistributionLockProviderNats represents the NATS JetStream distributed lock provider. DistributionLockProviderNats DistributionLockProvider = "nats" )
type EnableMixin ¶
type EnableMixin struct {
// Enable controls whether this feature is active.
// When false, the feature is disabled and has no effect.
Enable bool `yaml:"enable" default:"false"`
}
EnableMixin provides a common Enable field for configurations that can be toggled. Embed this struct with `yaml:",inline"` to add an Enable field to your config.
Note: Each config should still implement its own IsEnabled() method for nil-safety:
func (c *MyConfig) IsEnabled() bool {
return c != nil && c.Enable
}
Example:
type MyInterceptorConfig struct {
EnableMixin `yaml:",inline"`
// ... other fields
}
type Enableable ¶
type Enableable interface {
IsEnabled() bool
}
Enableable is an interface for configurations that can be enabled or disabled. Implement this interface to provide consistent enable/disable behavior across configs.
type FallbackBehavior ¶
type FallbackBehavior string
FallbackBehavior defines how interceptors behave when encountering errors or when storage backends are unavailable. Used by rate limiting, idempotency, and other interceptors that require graceful degradation.
const ( // FallbackBehaviorAllow allows all requests when the underlying service fails. // This provides maximum availability but no protection. // Use for non-critical services where availability is more important than protection. FallbackBehaviorAllow FallbackBehavior = "allow" // FallbackBehaviorDeny rejects all requests when the underlying service fails. // This provides maximum protection but may impact availability. // Use for critical services where protection is essential for stability. FallbackBehaviorDeny FallbackBehavior = "deny" // FallbackBehaviorError returns an error when the underlying service fails. // This is useful for debugging and testing, but not recommended for production. FallbackBehaviorError FallbackBehavior = "error" )
func AllFallbackBehaviors ¶
func AllFallbackBehaviors() []FallbackBehavior
AllFallbackBehaviors returns all valid FallbackBehavior values.
type Grpc ¶
type Grpc struct {
// TLS contains optional TLS configuration for secure gRPC connections.
// If nil, the server will run without TLS encryption.
TLS *GrpcTls `yaml:"tls" default:"-"`
// ListenAddress specifies the address and port to bind the gRPC server to.
// Defaults to "0.0.0.0:7777" which binds to all interfaces on port 7777.
ListenAddress string `yaml:"listenAddress" default:"0.0.0.0:7777"`
// Reflection enables or disables gRPC server reflection.
// When enabled, clients can discover available services and methods.
// Defaults to false for security reasons.
Reflection bool `yaml:"reflection" default:"false"`
// ConnectionTimeout specifies the timeout for establishing connections.
// If not set, gRPC uses the default behavior.
// A zero or negative value will result in an immediate timeout.
// Default value: not set
ConnectionTimeout *time.Duration `yaml:"connectionTimeout"`
// MaxConcurrentStreams limits the maximum number of concurrent streams.
// If not set, gRPC uses math.MaxUint32 as the default limit.
// Default value: not set
MaxConcurrentStreams *uint32 `yaml:"maxConcurrentStreams"`
// MaxSendMsgSize sets the maximum message size in bytes that can be sent.
// If not set, gRPC uses the default of 4MB (4194304 bytes).
// Default value: not set
MaxSendMsgSize *int `yaml:"maxSendMsgSize"`
// MaxRecvMsgSize sets the maximum message size in bytes that can be received.
// If not set, gRPC uses the default of 4MB (4194304 bytes).
// Default value: not set
MaxRecvMsgSize *int `yaml:"maxRecvMsgSize"`
// WriteBufferSize sets the size of the write buffer in bytes.
// If not set, gRPC uses the default of 32KB.
// Zero or negative values will disable the write buffer.
// Default value: not set
WriteBufferSize *int `yaml:"writeBufferSize"`
// ReadBufferSize sets the size of the read buffer in bytes.
// If not set, gRPC uses the default of 32KB.
// Zero or negative values will disable the read buffer.
// Default value: not set
ReadBufferSize *int `yaml:"readBufferSize"`
// KeepAlive contains server-side keepalive parameters for connection management.
KeepAlive *GrpcKeepAlive `yaml:"keepAlive" default:"-"`
// Interceptors contains configuration for gRPC middleware components.
// Includes settings for cache, realIp, requestId, recovery, idempotency, auth, and limiter interceptors.
Interceptors *InterceptorsConfig `yaml:"interceptors" default:"-"`
}
Grpc represents the configuration for gRPC server settings. It contains all necessary parameters for configuring a gRPC server including network binding, TLS settings, and debugging features.
Example:
grpcCfg := &config.Grpc{
ListenAddress: "0.0.0.0:9090",
Reflection: true,
}
func DefaultGrpc ¶
func DefaultGrpc() Grpc
DefaultGrpc returns a Grpc configuration with default values.
type GrpcEnforcementPolicy ¶
type GrpcEnforcementPolicy struct {
// MinTime is the minimum amount of time a client should wait before sending a keepalive ping.
// Defaults to 5s.
MinTime time.Duration `yaml:"minTime" default:"5s"`
// PermitWithoutStream allows clients to send keepalive pings even when there are no active streams.
// If false, server will close the connection if a keepalive ping is received when no streams are active.
// Defaults to true.
PermitWithoutStream bool `yaml:"permitWithoutStream" default:"false"`
}
GrpcEnforcementPolicy represents keepalive enforcement policy for gRPC server. It defines rules for connection keepalive behavior and stream requirements.
type GrpcInterAuthConfig ¶
type GrpcInterAuthConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
}
GrpcInterAuthConfig defines the configuration for authentication interceptor. It controls authentication behavior, method exclusions, and caching settings.
func DefaultGrpcInterAuthConfig ¶
func DefaultGrpcInterAuthConfig() GrpcInterAuthConfig
DefaultGrpcInterAuthConfig returns a GrpcInterAuthConfig with default values. Authentication is disabled by default.
func (*GrpcInterAuthConfig) IsEnabled ¶
func (c *GrpcInterAuthConfig) IsEnabled() bool
IsEnabled returns true if authentication is enabled.
func (*GrpcInterAuthConfig) Validate ¶
func (c *GrpcInterAuthConfig) Validate() error
Validate performs validation of the authentication interceptor configuration. It ensures all patterns are valid regexes.
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterCacheCompressionPreset ¶
type GrpcInterCacheCompressionPreset string
GrpcInterCacheCompressionPreset defines the compression levels available for cached responses. Different presets balance compression ratio vs CPU usage for optimal performance.
const ( // GrpcInterCacheCompressionPresetNone disables compression for cached responses. // Fastest option with no CPU overhead but largest storage usage. GrpcInterCacheCompressionPresetNone GrpcInterCacheCompressionPreset = "none" // GrpcInterCacheCompressionPresetFast provides a fast compression level for cached responses. // Good balance between speed and compression ratio for most use cases. GrpcInterCacheCompressionPresetFast GrpcInterCacheCompressionPreset = "fast" // GrpcInterCacheCompressionPresetBalanced provides a balanced compression level for cached responses. // Optimized for balanced CPU usage and compression efficiency. GrpcInterCacheCompressionPresetBalanced GrpcInterCacheCompressionPreset = "balanced" // GrpcInterCacheCompressionPresetBest provides the best compression level for cached responses. // Highest compression ratio but increased CPU usage for compression/decompression. GrpcInterCacheCompressionPresetBest GrpcInterCacheCompressionPreset = "best" )
type GrpcInterCacheConfig ¶
type GrpcInterCacheConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// SuccessTTL defines the default TTL for successful responses.
// Successful responses (no gRPC errors) are cached for this duration.
// Must be at least 1 minute to prevent cache thrashing.
SuccessTTL time.Duration `yaml:"successTTL" default:"24h"`
// ErrorTTL defines the default TTL for error responses.
// Error responses are cached for shorter periods to allow quick recovery.
// Must be at least 1 minute to prevent cache thrashing.
ErrorTTL time.Duration `yaml:"errorTTL" default:"1h"`
// EnableCacheHeaders controls whether cache hit/miss headers are added to responses.
// When enabled, responses include headers indicating cache status for debugging.
EnableCacheHeaders bool `yaml:"enableCacheHeaders" default:"true"`
// CompressionPreset defines compression level for cached responses.
// Higher compression reduces storage but increases CPU usage.
CompressionPreset GrpcInterCacheCompressionPreset `yaml:"compressionPreset" default:"fast"`
// KeysPrefix is a prefix for all cache keys in storage.
// Useful for namespacing cache keys when sharing storage between services.
KeysPrefix string `yaml:"keysPrefix"`
// KeyMetadata is a list of gRPC metadata keys (headers) to include in the cache key hash.
// If empty, a standard set of security and identity headers is used.
KeyMetadata []string `yaml:"keyMetadata"`
}
GrpcInterCacheConfig defines the configuration for gRPC response caching. Controls TTL, compression, and header behavior for cached responses.
func DefaultGrpcInterCacheConfig ¶
func DefaultGrpcInterCacheConfig() GrpcInterCacheConfig
DefaultGrpcInterCacheConfig returns a GrpcInterCacheConfig with default values. Caching is disabled by default.
func (*GrpcInterCacheConfig) IsEnabled ¶
func (c *GrpcInterCacheConfig) IsEnabled() bool
IsEnabled returns true if response caching is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterCacheConfig) Validate ¶
func (c *GrpcInterCacheConfig) Validate() error
Validate performs validation of the cache interceptor configuration. Ensures TTL values are reasonable and compression preset is valid.
Validation rules:
- SuccessTTL: must be at least 1 minute when caching is enabled
- ErrorTTL: must be at least 1 minute when caching is enabled
- CompressionPreset: must be one of the defined preset values
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterHealthConfig ¶
type GrpcInterHealthConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
}
GrpcInterHealthConfig defines the configuration for health check interceptor. When enabled, every incoming RPC is preceded by a health check; if the service is unhealthy the call is rejected with Unavailable status.
func DefaultGrpcInterHealthConfig ¶
func DefaultGrpcInterHealthConfig() GrpcInterHealthConfig
DefaultGrpcInterHealthConfig returns a GrpcInterHealthConfig with default values. Health interceptor is disabled by default.
func (*GrpcInterHealthConfig) IsEnabled ¶
func (c *GrpcInterHealthConfig) IsEnabled() bool
IsEnabled returns true if the health interceptor is enabled.
func (*GrpcInterHealthConfig) Validate ¶
func (c *GrpcInterHealthConfig) Validate() error
Validate performs validation of the health interceptor configuration.
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterIdempotencyConfig ¶
type GrpcInterIdempotencyConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// IdempotencyKeyHeader is the header name for idempotency key.
// Clients can provide idempotency keys via this header.
// Must be a valid HTTP header name, defaults to "idempotency-key".
IdempotencyKeyHeader string `yaml:"idempotencyKeyHeader" default:"idempotency-key"`
// IdempotencyKeyField is the field name to extract idempotency key from request.
// Used when idempotency key is embedded in the request message itself.
// Must be a valid protobuf field name, defaults to "idempotencyKey".
IdempotencyKeyField string `yaml:"idempotencyKeyField" default:"idempotencyKey"`
// FallbackBehavior defines how the idempotency checker behaves when encountering errors
// or when storage backends are unavailable, providing graceful degradation options.
// See FallbackBehavior type for available options.
FallbackBehavior FallbackBehavior `yaml:"fallbackBehavior" default:"deny"`
// IdempotencyKeyStatusMetadata is the metadata key for idempotency status.
IdempotencyKeyStatusMetadata string `yaml:"idempotencyKeyStatusMetadata" default:"Idempotency-Key-Status"`
// IdempotencyKeyEntityIdMetadata is the metadata key for entity ID.
IdempotencyKeyEntityIdMetadata string `yaml:"idempotencyKeyEntityIdMetadata" default:"Idempotency-Key-Entity-Id"`
// EnforceMandatory controls whether the idempotency key is mandatory for all methods.
EnforceMandatory bool `yaml:"enforceMandatory" default:"true"`
}
GrpcInterIdempotencyConfig defines the configuration for idempotency interceptor. Controls how duplicate requests are detected and handled using configurable storage.
func DefaultGrpcInterIdempotencyConfig ¶
func DefaultGrpcInterIdempotencyConfig() GrpcInterIdempotencyConfig
DefaultGrpcInterIdempotencyConfig returns a GrpcInterIdempotencyConfig with default values. Idempotency checking is disabled by default.
func (*GrpcInterIdempotencyConfig) IsEnabled ¶
func (c *GrpcInterIdempotencyConfig) IsEnabled() bool
IsEnabled returns true if idempotency checking is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterIdempotencyConfig) Validate ¶
func (c *GrpcInterIdempotencyConfig) Validate() error
Validate performs validation of the idempotency interceptor configuration. Ensures all fields are properly configured and storage settings are valid.
Validation rules:
- IdempotencyKeyHeader: must be non-empty and within length limits
- IdempotencyKeyField: must be non-empty and within length limits
- FallbackBehavior: must be a valid behavior
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterLimiterConfig ¶
type GrpcInterLimiterConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// FallbackBehavior defines how the rate limiter behaves when encountering errors
// or when storage backends are unavailable, providing graceful degradation options.
// See FallbackBehavior type for available options.
FallbackBehavior FallbackBehavior `yaml:"fallbackBehavior" default:"deny"`
}
GrpcInterLimiterConfig defines the configuration for rate limiting interceptor. It controls which requests are subject to rate limiting and provides exclusion mechanisms for specific methods or patterns.
func DefaultGrpcInterLimiterConfig ¶
func DefaultGrpcInterLimiterConfig() GrpcInterLimiterConfig
DefaultGrpcInterLimiterConfig returns a GrpcInterLimiterConfig with default values. Rate limiting is disabled by default.
func (*GrpcInterLimiterConfig) IsEnabled ¶
func (c *GrpcInterLimiterConfig) IsEnabled() bool
IsEnabled returns true if rate limiting is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterLimiterConfig) Validate ¶
func (c *GrpcInterLimiterConfig) Validate() error
Validate performs validation of the rate limiter interceptor configuration. Ensures that all ignored methods and patterns are properly specified when provided and that rate limiting rules and storage are correctly configured.
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
- FallbackBehavior: must be a valid behavior
Returns an error if validation fails, nil otherwise.
type GrpcInterLoggerConfig ¶
type GrpcInterLoggerConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// TimeFormat defines how timestamps should be formatted in log entries.
// Must be one of the supported TimeFormat constants.
// Different formats offer trade-offs between readability and performance.
TimeFormat timeformat.Format `yaml:"timeFormat" default:"rfc3339"`
// LogRequest controls whether to log request payloads.
// Set to true to include request content in logs for debugging purposes.
LogRequest bool `yaml:"logRequest" default:"false"`
// LogResponse controls whether to log response payloads.
// Set to true to include response content in logs for debugging purposes.
LogResponse bool `yaml:"logResponse" default:"true"`
// IgnoreGrpcResponseCodes is a list of gRPC response codes to never log.
// Takes precedence over LogGrpcResponseCodes.
// Example: [0, 1] to ignore OK and CANCELED codes.
// Useful for filtering out expected or non-error responses.
IgnoreGrpcResponseCodes []uint32 `yaml:"ignoreGrpcResponseCodes"`
// LogGrpcResponseCodes is a list of gRPC response codes to always log.
// Example: [5, 13] to always log NOT_FOUND and INTERNAL codes.
// Useful for ensuring important error responses are always captured.
LogGrpcResponseCodes []uint32 `yaml:"logGrpcResponseCodes"`
// EnableContextLogger controls whether the logger instance is injected into the context.
// When enabled, handlers can retrieve the logger using slogx.FromContextOrDefault(ctx).
EnableContextLogger bool `yaml:"enableContextLogger" default:"false"`
}
GrpcInterLoggerConfig defines the configuration for request/response logging interceptor. Controls what information is logged and how timestamps are formatted.
func DefaultGrpcInterLoggerConfig ¶
func DefaultGrpcInterLoggerConfig() GrpcInterLoggerConfig
DefaultGrpcInterLoggerConfig returns a GrpcInterLoggerConfig with default values. Logging is disabled by default.
func (*GrpcInterLoggerConfig) IsEnabled ¶
func (c *GrpcInterLoggerConfig) IsEnabled() bool
IsEnabled returns true if request/response logging is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterLoggerConfig) Validate ¶
func (c *GrpcInterLoggerConfig) Validate() error
Validate performs validation of the logger interceptor configuration. Ensures all fields are properly configured for logging functionality.
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
- TimeFormat: must be one of the supported timestamp formats
Returns an error if validation fails, nil otherwise.
type GrpcInterPrometheusConfig ¶
type GrpcInterPrometheusConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// Namespace is the Prometheus metric namespace.
// Used as the first part of metric names (e.g., "myapp" -> "myapp_grpc_server_requests_total").
// Empty namespace is allowed and results in metrics without namespace prefix.
Namespace string `yaml:"namespace" default:""`
// Subsystem is the Prometheus metric subsystem.
// Used as the second part of metric names after namespace (e.g., "api" -> "myapp_api_server_requests_total").
// Default is "grpc" which results in standard gRPC metric names.
Subsystem string `yaml:"subsystem" default:"grpc"`
// DurationBuckets defines custom histogram buckets for request duration metrics in seconds.
// Must be in increasing order. If not specified, reasonable defaults are used.
// Example: [0.001, 0.01, 0.1, 1.0, 10.0]
DurationBuckets []float64 `yaml:"durationBuckets"`
// SizeBuckets defines custom histogram buckets for message size metrics in bytes.
// Only used when EnableSizeMetrics is true. Must be in increasing order.
// If not specified, reasonable defaults are used.
// Example: [1024, 4096, 16384, 65536]
SizeBuckets []float64 `yaml:"sizeBuckets"`
// EnableSizeMetrics controls whether request/response size metrics are collected.
// Size metrics add overhead as they require inspecting message payloads.
// When enabled, collects grpc_server_request_size_bytes and grpc_server_response_size_bytes histograms.
EnableSizeMetrics bool `yaml:"enableSizeMetrics" default:"false"`
// EnableStreamMetrics controls whether per-message streaming metrics are collected.
// Streaming metrics track individual message counts and sizes within gRPC streams but add overhead.
// When enabled, collects grpc_server_stream_messages_sent_total and grpc_server_stream_messages_received_total counters.
EnableStreamMetrics bool `yaml:"enableStreamMetrics" default:"false"`
// StreamSamplingRate controls the sampling rate for streaming message metrics (0.0 to 1.0).
// Only effective when EnableStreamMetrics is true. Used to reduce overhead in high-throughput scenarios.
// 1.0 = no sampling (record all), 0.1 = record 10% of messages, 0.0 = disable streaming metrics.
StreamSamplingRate float64 `yaml:"streamSamplingRate" default:"1.0"`
// StreamSamplingStrategy defines how sampling is applied to streaming messages.
// Only effective when EnableStreamMetrics is true and StreamSamplingRate < 1.0.
// "per_message" = sample individual messages, "per_stream" = sample entire streams.
StreamSamplingStrategy GrpcInterPrometheusSamplingStrategy `yaml:"streamSamplingStrategy" default:"per_message"`
}
GrpcInterPrometheusConfig defines the configuration for Prometheus metrics interceptor. Controls which metrics are collected and how they are configured.
func DefaultGrpcInterPrometheusConfig ¶
func DefaultGrpcInterPrometheusConfig() GrpcInterPrometheusConfig
DefaultGrpcInterPrometheusConfig returns a GrpcInterPrometheusConfig with default values. Prometheus metrics collection is disabled by default.
func (*GrpcInterPrometheusConfig) IsEnabled ¶
func (c *GrpcInterPrometheusConfig) IsEnabled() bool
IsEnabled returns true if Prometheus metrics collection is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterPrometheusConfig) Validate ¶
func (c *GrpcInterPrometheusConfig) Validate() error
Validate performs validation of the Prometheus interceptor configuration. Ensures all fields are properly configured for metrics collection.
Validation rules:
- DurationBuckets: must be in strictly increasing order if specified
- SizeBuckets: must be in strictly increasing order if specified
- StreamSamplingRate: must be between 0.0 and 1.0
- StreamSamplingStrategy: must be a valid strategy
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterPrometheusSamplingStrategy ¶
type GrpcInterPrometheusSamplingStrategy string
GrpcInterPrometheusSamplingStrategy defines how sampling is applied to streaming messages.
const ( // GrpcInterPrometheusPerMessageSampling samples individual messages within a stream. // Each message is sampled independently based on the sampling rate. GrpcInterPrometheusPerMessageSampling GrpcInterPrometheusSamplingStrategy = "per_message" // GrpcInterPrometheusPerStreamSampling samples entire streams as a unit. // Either the entire stream is sampled or not at all. GrpcInterPrometheusPerStreamSampling GrpcInterPrometheusSamplingStrategy = "per_stream" )
type GrpcInterRealIpConfig ¶
type GrpcInterRealIpConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// TrustedProxies is a list of trusted proxy IP addresses or CIDR blocks.
// Only requests from these proxies will have their X-Forwarded-For headers processed.
// Example: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
TrustedProxies []string `yaml:"trustedProxies"`
// TrustedProxiesCount specifies the number of trusted proxies that may append X-Forwarded-For.
// This helps prevent IP spoofing by limiting the number of hops we trust.
// Set to 0 to trust unlimited proxy hops (not recommended for production).
TrustedProxiesCount uint `yaml:"trustedProxiesCount" default:"0"`
// TrustedPeers is a list of trusted peer IP addresses or CIDR blocks.
// These are additional trusted sources beyond the standard proxy list.
// Useful for direct connections from known services or clusters.
TrustedPeers []string `yaml:"trustedPeers"`
// Headers is a list of headers to check for real IP (in order of preference).
// The interceptor will check these headers in order until a valid IP is found.
// Default headers: X-Forwarded-For, X-Real-IP, X-Client-IP, CF-Connecting-IP,
// Fastly-Client-Ip, True-Client-Ip.
Headers []string `yaml:"headers"`
// CacheSize specifies the size of the IP validation cache (0 to disable).
// Caching improves performance by avoiding repeated IP prefix parsing.
// Recommended values: 1000-10000 for high-traffic services.
CacheSize int `yaml:"cacheSize" default:"1000"`
}
GrpcInterRealIpConfig defines the configuration for real IP extraction from proxy headers. Used by the realip interceptor to extract client IP addresses from various proxy headers while validating trust relationships with intermediate proxies.
func DefaultGrpcInterRealIpConfig ¶
func DefaultGrpcInterRealIpConfig() GrpcInterRealIpConfig
DefaultGrpcInterRealIpConfig returns a GrpcInterRealIpConfig with default values. Real IP extraction is disabled by default.
func (*GrpcInterRealIpConfig) IsEnabled ¶
func (c *GrpcInterRealIpConfig) IsEnabled() bool
IsEnabled returns true if real IP extraction is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterRealIpConfig) Validate ¶
func (c *GrpcInterRealIpConfig) Validate() error
Validate performs validation of the real IP interceptor configuration. Ensures all IP addresses and CIDR blocks are valid and configuration is sane.
Validation rules:
- TrustedProxies: each entry must be a valid IP address or CIDR prefix
- TrustedPeers: each entry must be a valid IP address or CIDR prefix
- Headers: each header name must be non-empty when specified
- CacheSize: must be non-negative
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterRecoveryConfig ¶
type GrpcInterRecoveryConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
}
GrpcInterRecoveryConfig defines the configuration for panic recovery interceptor. It controls which methods benefit from panic recovery and provides options to disable recovery for specific critical methods.
func DefaultGrpcInterRecoveryConfig ¶
func DefaultGrpcInterRecoveryConfig() GrpcInterRecoveryConfig
DefaultGrpcInterRecoveryConfig returns a GrpcInterRecoveryConfig with default values. Panic recovery is disabled by default.
func (*GrpcInterRecoveryConfig) IsEnabled ¶
func (c *GrpcInterRecoveryConfig) IsEnabled() bool
IsEnabled returns true if panic recovery is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterRecoveryConfig) Validate ¶
func (c *GrpcInterRecoveryConfig) Validate() error
Validate performs validation of the recovery interceptor configuration. Ensures that all ignored methods and patterns are properly specified when provided.
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
Returns an error if validation fails, nil otherwise.
type GrpcInterRequestIdConfig ¶
type GrpcInterRequestIdConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// GenerateIfMissing controls whether to generate a request ID if none is provided.
// When true, missing request IDs are automatically generated using UUIDs.
// When false, requests without IDs proceed without modification.
// Recommended: true for production systems to ensure complete tracing coverage.
GenerateIfMissing bool `yaml:"generateIfMissing" default:"true"`
}
GrpcInterRequestIdConfig defines the configuration for request ID generation. Controls how request IDs are generated, validated, and propagated throughout the gRPC interceptor chain and service call graph.
func DefaultGrpcInterRequestIdConfig ¶
func DefaultGrpcInterRequestIdConfig() GrpcInterRequestIdConfig
DefaultGrpcInterRequestIdConfig returns a GrpcInterRequestIdConfig with default values. Request ID generation is disabled by default.
func (*GrpcInterRequestIdConfig) IsEnabled ¶
func (c *GrpcInterRequestIdConfig) IsEnabled() bool
IsEnabled returns true if request ID generation is enabled. This is a convenience method to check if the interceptor should be active.
func (*GrpcInterRequestIdConfig) Validate ¶
func (c *GrpcInterRequestIdConfig) Validate() error
Validate performs validation of the request ID interceptor configuration. Validates base configuration including method filtering.
Returns an error if validation fails, nil otherwise.
type GrpcInterTracingConfig ¶
type GrpcInterTracingConfig struct {
// BaseGrpcInterceptorConfig provides common interceptor configuration.
BaseGrpcInterceptorConfig `yaml:",inline"`
// RecordPayload determines whether request/response payloads are recorded.
// Warning: This can significantly increase trace size and may expose sensitive data.
// Defaults to false.
RecordPayload bool `yaml:"recordPayload" default:"false"`
// RecordMetadata determines whether gRPC metadata is recorded as span attributes.
// Defaults to true.
RecordMetadata bool `yaml:"recordMetadata" default:"true"`
// RecordEvents determines whether streaming message events are recorded.
// Defaults to true.
RecordEvents bool `yaml:"recordEvents" default:"true"`
// PropagateContext determines whether trace context is propagated from incoming requests.
// When true, parent spans from incoming requests are linked to server spans.
// Defaults to true.
PropagateContext bool `yaml:"propagateContext" default:"true"`
}
GrpcInterTracingConfig defines the configuration for the tracing interceptor. Controls distributed tracing for gRPC requests.
func DefaultGrpcInterTracingConfig ¶
func DefaultGrpcInterTracingConfig() GrpcInterTracingConfig
DefaultGrpcInterTracingConfig returns a GrpcInterTracingConfig with default values. Tracing interceptor is disabled by default.
func (*GrpcInterTracingConfig) IsEnabled ¶
func (c *GrpcInterTracingConfig) IsEnabled() bool
IsEnabled returns true if the tracing interceptor is enabled.
func (*GrpcInterTracingConfig) Validate ¶
func (c *GrpcInterTracingConfig) Validate() error
Validate performs validation of the tracing interceptor configuration.
type GrpcKeepAlive ¶
type GrpcKeepAlive struct {
// MaxConnectionIdle is a duration for the amount of time after which an
// idle connection would be closed by sending a GoAway. Idleness duration is
// defined since the most recent time the number of outstanding RPCs became
// zero or the connection establishment.
// Defaults to 15m (15 minutes).
MaxConnectionIdle time.Duration `yaml:"maxConnectionIdle" default:"15m"`
// MaxConnectionAge is a duration for the maximum amount of time a
// connection may exist before it will be closed by sending a GoAway. A
// random jitter of +/-10% will be added to MaxConnectionAge to spread out
// connection storms.
// Defaults to 30m (30 minutes).
MaxConnectionAge time.Duration `yaml:"maxConnectionAge" default:"30m"`
// MaxConnectionAgeGrace is an additive period after MaxConnectionAge after
// which the connection will be forcibly closed.
// Defaults to 5s (5 seconds).
MaxConnectionAgeGrace time.Duration `yaml:"maxConnectionAgeGrace" default:"5s"`
// Time specifies the duration after which if the server doesn't see any
// activity it pings the client to see if the transport is still alive.
// If set below 1s, a minimum value of 1s will be used instead.
// Defaults to 5s (5 seconds).
Time time.Duration `yaml:"time" default:"30s"`
// Timeout specifies the duration the server waits for a response after
// having pinged for keepalive check. If no activity is seen even after
// that, the connection is closed.
// Defaults to 1s (1 second).
Timeout time.Duration `yaml:"timeout" default:"10s"`
// EnforcementPolicy contains optional keepalive enforcement rules.
// If nil, default enforcement policy is used.
EnforcementPolicy *GrpcEnforcementPolicy `yaml:"enforcementPolicy" default:"-"`
}
GrpcKeepAlive represents keepalive parameters for gRPC server connections. These parameters control connection lifecycle and health checking behavior.
func (*GrpcKeepAlive) Validate ¶
func (k *GrpcKeepAlive) Validate() error
Validate performs validation on the GrpcKeepAlive configuration. It validates all duration fields to ensure they are valid duration strings.
Returns an error if any validation rules fail.
type GrpcTls ¶
type GrpcTls struct {
// TlsServer contains the base server TLS configuration (embedded inline).
*TlsServer `yaml:",inline"`
// Client contains optional client certificate authentication settings.
// If nil, client authentication is disabled.
Client *TlsClientAuth `yaml:"client" default:"-"`
}
GrpcTls represents TLS configuration for gRPC servers. It extends TlsServer configuration with optional client authentication settings.
type Health ¶
type Health struct {
// HealthCheckInterval defines how often a watcher polls health status.
// Determines the freshness of health updates for active subscriptions.
// Defaults to 5s.
HealthCheckInterval time.Duration `yaml:"healthCheckInterval" default:"5s"`
// WatcherChannelBuffer is the base buffer size for notification channels.
// Controls how many status changes can be queued before non-blocking drops.
// Defaults to 10.
WatcherChannelBuffer int `yaml:"watcherChannelBuffer" default:"10"`
// MaxWatchersPerService limits concurrent subscriptions per service.
// Protects resources by capping the number of active watchers.
// Value 0 means unlimited. Defaults to 1000.
MaxWatchersPerService int `yaml:"maxWatchersPerService" default:"1000"`
// NumShards is the number of lock shards for contention reduction.
// Distributes activity across multiple mutexes to improve performance.
// Defaults to 32.
NumShards int `yaml:"numShards" default:"32"`
// MaxConcurrentHealthChecks limits worker pool for ListStatuses.
// Controls the parallelism of batch health check operations.
// Defaults to 10.
MaxConcurrentHealthChecks int `yaml:"maxConcurrentHealthChecks" default:"10"`
// StatusCacheTTL is the cache duration for check results.
// Reduces the load on checked services by reusing recent results.
// Defaults to 500ms.
StatusCacheTTL time.Duration `yaml:"statusCacheTTL" default:"500ms"`
// CheckTimeout is the timeout per individual health check.
// Ensures that slow or hung checks do not block the coordinator.
// Defaults to 2s.
CheckTimeout time.Duration `yaml:"checkTimeout" default:"2s"`
// AdaptiveBufferThreshold is the watcher count to trigger adaptive buffering.
// Automatically increases channel sizes when the system is under high load.
// Defaults to 100.
AdaptiveBufferThreshold int32 `yaml:"adaptiveBufferThreshold" default:"100"`
// AdaptiveBufferMultiplier is the buffer multiplier under load.
// Scale factor applied to the base buffer size when threshold is reached.
// Defaults to 2.
AdaptiveBufferMultiplier int `yaml:"adaptiveBufferMultiplier" default:"2"`
// MaxAdaptiveBuffer is the maximum adaptive buffer size.
// Cap for buffer growth to prevent excessive memory consumption.
// Defaults to 100.
MaxAdaptiveBuffer int `yaml:"maxAdaptiveBuffer" default:"100"`
}
Health defines the configuration for health check coordination. It manages health status for multiple services, supporting caching, subscriptions, and adaptive buffering for high-concurrency scenarios.
func DefaultHealth ¶
func DefaultHealth() Health
DefaultHealth returns a Health configuration with default values.
type Http ¶
type Http struct {
// RouterPrefix is an optional prefix for all Http routes.
// Allows mounting the service under a specific path prefix.
// If empty, routes are mounted at the root level.
RouterPrefix string `yaml:"routerPrefix"`
// ListenAddress specifies the address and port to bind the Http server to.
// Defaults to "0.0.0.0:9080" which binds to all interfaces on port 9080.
ListenAddress string `yaml:"listenAddress" default:"0.0.0.0:9080"`
// MaxRequestPayloadSize sets the maximum size in bytes for request payloads.
// Defaults to 10485760 bytes (10MB). Set to 0 for unlimited size.
MaxRequestPayloadSize int64 `yaml:"maxRequestPayloadSize" default:"10485760"`
// ReadTimeout is the maximum duration for reading the entire request,
// including the body. Defaults to 300 seconds.
ReadTimeout time.Duration `yaml:"readTimeout" default:"300s"`
// WriteTimeout is the maximum duration before timing out writes of the response.
// Defaults to 300 seconds.
WriteTimeout time.Duration `yaml:"writeTimeout" default:"300s"`
// IdleTimeout is the maximum amount of time to wait for the next request
// when keep-alives are enabled. Defaults to 600 seconds.
IdleTimeout time.Duration `yaml:"idleTimeout" default:"600s"`
// LogRequests enables or disables Http request logging.
// Defaults to false.
LogRequests bool `yaml:"logRequests" default:"false"`
// Tls contains optional Tls configuration for HTTPS.
// If nil, the server will run in Http mode only.
TLS *HttpTls `yaml:"tls" default:"-"`
// Middlewares contains configuration for HTTP server middleware components.
Middlewares *MiddlewaresConfig `yaml:"middlewares" default:"-"`
}
Http represents the configuration for HTTP server settings. It contains all necessary parameters for configuring an HTTP server including timeouts, payload limits, and optional TLS configuration.
Example:
httpCfg := &config.Http{
ListenAddress: "0.0.0.0:8080",
ReadTimeout: 30 * time.Second,
}
func DefaultHttp ¶
func DefaultHttp() Http
DefaultHttp returns an Http configuration with default values.
type HttpInterBodyLimitConfig ¶
type HttpInterBodyLimitConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// MaxSize is the maximum allowed size of the request body in bytes.
// Defaults to 10MB (10485760 bytes).
MaxSize int64 `yaml:"maxSize" default:"10485760"`
}
HttpInterBodyLimitConfig defines the configuration for HTTP body size limiting middleware.
func DefaultHttpInterBodyLimitConfig ¶
func DefaultHttpInterBodyLimitConfig() HttpInterBodyLimitConfig
DefaultHttpInterBodyLimitConfig returns a configuration for bodylimit middleware with default values.
func (*HttpInterBodyLimitConfig) IsEnabled ¶
func (c *HttpInterBodyLimitConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterBodyLimitConfig) Validate ¶
func (c *HttpInterBodyLimitConfig) Validate() error
Validate performs validation of the HttpInterBodyLimitConfig.
type HttpInterCorsConfig ¶
type HttpInterCorsConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// AllowedOrigins is a list of origins that are allowed to access the resource.
// Use ["*"] to allow all origins.
AllowedOrigins []string `yaml:"allowedOrigins"`
// AllowedMethods is a list of HTTP methods allowed when accessing the resource.
// Defaults to standard methods if not specified.
AllowedMethods []string `yaml:"allowedMethods"`
// AllowedHeaders is a list of request headers that can be used when making the actual request.
AllowedHeaders []string `yaml:"allowedHeaders"`
// ExposedHeaders is a whitelist of headers that browsers are allowed to access.
ExposedHeaders []string `yaml:"exposedHeaders"`
// AllowCredentials indicates whether the request can include user credentials like cookies or auth headers.
AllowCredentials bool `yaml:"allowCredentials" default:"false"`
// MaxAge indicates how long (in seconds) the results of a preflight request can be cached.
MaxAge int `yaml:"maxAge" default:"86400"`
// AllowPrivateNetwork enables support for Private Network Access preflight requests.
AllowPrivateNetwork bool `yaml:"allowPrivateNetwork" default:"false"`
// OptionsPassthrough passes OPTIONS requests to the next handler instead of handling them internally.
OptionsPassthrough bool `yaml:"optionsPassthrough" default:"false"`
// OptionsSuccessStatus is the status code to return for successful OPTIONS requests.
// Defaults to 204.
OptionsSuccessStatus int `yaml:"optionsSuccessStatus" default:"204"`
}
HttpInterCorsConfig defines the configuration for HTTP Cross-Origin Resource Sharing (CORS) middleware.
func DefaultHttpInterCorsConfig ¶
func DefaultHttpInterCorsConfig() HttpInterCorsConfig
DefaultHttpInterCorsConfig returns a configuration for cors middleware with default values.
func (*HttpInterCorsConfig) IsEnabled ¶
func (c *HttpInterCorsConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterCorsConfig) Validate ¶
func (c *HttpInterCorsConfig) Validate() error
Validate performs validation of the HttpInterCorsConfig.
type HttpInterIdempotencyConfig ¶
type HttpInterIdempotencyConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// IdempotencyKeyHeader is the name of the HTTP header used to pass the idempotency key.
// Defaults to "Idempotency-Key".
IdempotencyKeyHeader string `yaml:"idempotencyKeyHeader" default:"Idempotency-Key"`
// IdempotencyKeyStatusHeader is the name of the HTTP header used to return idempotency status.
// Defaults to "Idempotency-Key-Status".
IdempotencyKeyStatusHeader string `yaml:"idempotencyKeyStatusHeader" default:"Idempotency-Key-Status"`
// IdempotencyKeyEntityIdHeader is the name of the HTTP header used to return an entity ID if captured.
// Defaults to "Idempotency-Key-Entity-Id".
IdempotencyKeyEntityIdHeader string `yaml:"idempotencyKeyEntityIdHeader" default:"Idempotency-Key-Entity-Id"`
// FallbackBehavior defines how the idempotency checker behaves when encountering errors
// or when storage backends are unavailable, providing graceful degradation options.
FallbackBehavior FallbackBehavior `yaml:"fallbackBehavior" default:"deny"`
// EnforceMandatory, when true, requires all requests (not ignored) to have an idempotency key.
EnforceMandatory bool `yaml:"enforceMandatory" default:"true"`
}
HttpInterIdempotencyConfig defines the configuration for HTTP idempotency middleware.
func DefaultHttpInterIdempotencyConfig ¶
func DefaultHttpInterIdempotencyConfig() HttpInterIdempotencyConfig
DefaultHttpInterIdempotencyConfig returns a configuration for idempotency middleware with default values.
func (*HttpInterIdempotencyConfig) IsEnabled ¶
func (c *HttpInterIdempotencyConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterIdempotencyConfig) Validate ¶
func (c *HttpInterIdempotencyConfig) Validate() error
Validate performs validation of the HttpInterIdempotencyConfig.
type HttpInterLimiterConfig ¶
type HttpInterLimiterConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// FallbackBehavior determines what happens if the rate limiter itself fails.
FallbackBehavior FallbackBehavior `yaml:"fallbackBehavior" default:"error"`
}
HttpInterLimiterConfig defines the configuration for HTTP rate limiting middleware.
func DefaultHttpInterLimiterConfig ¶
func DefaultHttpInterLimiterConfig() HttpInterLimiterConfig
DefaultHttpInterLimiterConfig returns a configuration for limiter middleware with default values.
func (*HttpInterLimiterConfig) IsEnabled ¶
func (c *HttpInterLimiterConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterLimiterConfig) Validate ¶
func (c *HttpInterLimiterConfig) Validate() error
Validate performs validation of the HttpInterLimiterConfig.
type HttpInterLoggerConfig ¶
type HttpInterLoggerConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// LogRequest enables or disables logging of the request body.
// CAUTION: Enabling this may log sensitive data.
LogRequest bool `yaml:"logRequest" default:"false"`
// LogResponse enables or disables logging of the response body.
// CAUTION: Enabling this may log sensitive data.
LogResponse bool `yaml:"logResponse" default:"false"`
// TimeFormat defines how timestamps should be formatted in log entries.
// Must be one of the supported TimeFormat constants.
TimeFormat timeformat.Format `yaml:"timeFormat" default:"rfc3339"`
// IgnoreResponseCodes is a list of HTTP status codes that should not be logged.
// Takes precedence over LogResponseCodes.
IgnoreResponseCodes []int `yaml:"ignoreResponseCodes"`
// LogResponseCodes is a list of HTTP status codes that SHOULD be logged.
// If set, only these codes (minus those in IgnoreResponseCodes) will be logged.
LogResponseCodes []int `yaml:"logResponseCodes"`
// IgnoreHttpMethods is a list of HTTP methods to skip logging for.
// Example: ["OPTIONS", "HEAD"] to skip logging preflight and HEAD requests.
IgnoreHttpMethods []string `yaml:"ignoreHttpMethods"`
}
HttpInterLoggerConfig defines the configuration for HTTP request logging middleware.
func DefaultHttpInterLoggerConfig ¶
func DefaultHttpInterLoggerConfig() HttpInterLoggerConfig
DefaultHttpInterLoggerConfig returns a configuration for logger middleware with default values.
func (*HttpInterLoggerConfig) IsEnabled ¶
func (c *HttpInterLoggerConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterLoggerConfig) Validate ¶
func (c *HttpInterLoggerConfig) Validate() error
Validate performs validation of the HttpInterLoggerConfig.
type HttpInterPrometheusConfig ¶
type HttpInterPrometheusConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// Namespace is the Prometheus metric namespace.
Namespace string `yaml:"namespace"`
// Subsystem is the Prometheus metric subsystem.
Subsystem string `yaml:"subsystem"`
// EnableSizeMetrics enables collection of request and response size metrics.
EnableSizeMetrics bool `yaml:"enableSizeMetrics" default:"false"`
// DurationBuckets defines the buckets for request duration histogram.
DurationBuckets []float64 `yaml:"durationBuckets"`
// SizeBuckets defines the buckets for request/response size histograms.
SizeBuckets []float64 `yaml:"sizeBuckets"`
}
HttpInterPrometheusConfig defines the configuration for HTTP Prometheus metrics collection middleware.
func DefaultHttpInterPrometheusConfig ¶
func DefaultHttpInterPrometheusConfig() HttpInterPrometheusConfig
DefaultHttpInterPrometheusConfig returns a configuration for prometheus middleware with default values.
func (*HttpInterPrometheusConfig) IsEnabled ¶
func (c *HttpInterPrometheusConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterPrometheusConfig) Validate ¶
func (c *HttpInterPrometheusConfig) Validate() error
Validate performs validation of the HttpInterPrometheusConfig.
type HttpInterRealIpConfig ¶
type HttpInterRealIpConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// Headers is a list of HTTP headers to check for the real client IP.
// Headers are checked in the order specified.
// Common values: ["X-Forwarded-For", "X-Real-IP", "True-Client-IP"].
Headers []string `yaml:"headers"`
// TrustedProxies is a list of IP addresses or CIDR ranges of trusted proxies.
// Only IP addresses from these proxies will be considered when extracting IP from headers.
TrustedProxies []string `yaml:"trustedProxies"`
}
HttpInterRealIpConfig defines the configuration for HTTP real IP extraction middleware.
func DefaultHttpInterRealIpConfig ¶
func DefaultHttpInterRealIpConfig() HttpInterRealIpConfig
DefaultHttpInterRealIpConfig returns a configuration for realip middleware with default values.
func (*HttpInterRealIpConfig) IsEnabled ¶
func (c *HttpInterRealIpConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterRealIpConfig) Validate ¶
func (c *HttpInterRealIpConfig) Validate() error
Validate performs validation of the HttpInterRealIpConfig.
type HttpInterRecoveryConfig ¶
type HttpInterRecoveryConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// LogStack enables or disables logging of the stack trace when a panic is recovered.
// Defaults to true.
LogStack bool `yaml:"logStack" default:"true"`
}
HttpInterRecoveryConfig defines the configuration for HTTP panic recovery middleware.
func DefaultHttpInterRecoveryConfig ¶
func DefaultHttpInterRecoveryConfig() HttpInterRecoveryConfig
DefaultHttpInterRecoveryConfig returns a configuration for recovery middleware with default values.
func (*HttpInterRecoveryConfig) IsEnabled ¶
func (c *HttpInterRecoveryConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterRecoveryConfig) Validate ¶
func (c *HttpInterRecoveryConfig) Validate() error
Validate performs validation of the HttpInterRecoveryConfig.
type HttpInterRequestIdConfig ¶
type HttpInterRequestIdConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// HeaderName is the name of the HTTP header used to pass/return the request ID.
// Defaults to "X-Request-ID".
HeaderName string `yaml:"headerName" default:"X-Request-ID"`
// GenerateIfMissing determines whether to generate a new request ID if none is provided.
// Defaults to true.
GenerateIfMissing bool `yaml:"generateIfMissing" default:"true"`
}
HttpInterRequestIdConfig defines the configuration for HTTP request ID middleware.
func DefaultHttpInterRequestIdConfig ¶
func DefaultHttpInterRequestIdConfig() HttpInterRequestIdConfig
DefaultHttpInterRequestIdConfig returns a configuration for requestid middleware with default values.
func (*HttpInterRequestIdConfig) IsEnabled ¶
func (c *HttpInterRequestIdConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterRequestIdConfig) Validate ¶
func (c *HttpInterRequestIdConfig) Validate() error
Validate performs validation of the HttpInterRequestIdConfig.
type HttpInterSecurityHeadersConfig ¶
type HttpInterSecurityHeadersConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// FrameOptions sets the X-Frame-Options header.
// Common values: "DENY", "SAMEORIGIN".
FrameOptions string `yaml:"frameOptions" default:"DENY"`
// ReferrerPolicy sets the Referrer-Policy header.
// Common values: "strict-origin-when-cross-origin", "no-referrer".
ReferrerPolicy string `yaml:"referrerPolicy" default:"strict-origin-when-cross-origin"`
// ContentSecurityPolicy sets the Content-Security-Policy header.
ContentSecurityPolicy string `yaml:"contentSecurityPolicy"`
// PermissionsPolicy sets the Permissions-Policy header.
PermissionsPolicy string `yaml:"permissionsPolicy"`
// HstsEnabled enables the Strict-Transport-Security (HSTS) header.
HstsEnabled bool `yaml:"hstsEnabled" default:"false"`
// HstsMaxAge sets the max-age value for HSTS.
HstsMaxAge int `yaml:"hstsMaxAge" default:"31536000"`
// HstsIncludeSubDomains includes subdomains in HSTS policy.
HstsIncludeSubDomains bool `yaml:"hstsIncludeSubDomains" default:"true"`
// HstsPreload enables the HSTS preload directive.
HstsPreload bool `yaml:"hstsPreload" default:"false"`
// ContentTypeNoSniff sets X-Content-Type-Options: nosniff.
ContentTypeNoSniff bool `yaml:"contentTypeNoSniff" default:"true"`
// XssProtectionDisabled sets X-XSS-Protection: 0.
XssProtectionDisabled bool `yaml:"xssProtectionDisabled" default:"true"`
}
HttpInterSecurityHeadersConfig defines the configuration for HTTP security headers middleware.
func DefaultHttpInterSecurityHeadersConfig ¶
func DefaultHttpInterSecurityHeadersConfig() HttpInterSecurityHeadersConfig
DefaultHttpInterSecurityHeadersConfig returns a configuration for securityheaders middleware with default values.
func (*HttpInterSecurityHeadersConfig) IsEnabled ¶
func (c *HttpInterSecurityHeadersConfig) IsEnabled() bool
IsEnabled returns true if the middleware is enabled.
func (*HttpInterSecurityHeadersConfig) Validate ¶
func (c *HttpInterSecurityHeadersConfig) Validate() error
Validate performs validation of the HttpInterSecurityHeadersConfig.
type HttpInterTracingConfig ¶
type HttpInterTracingConfig struct {
// BaseHttpMiddlewareConfig provides standard enable and filtering fields.
BaseHttpMiddlewareConfig `yaml:",inline"`
// RecordBody determines whether request/response bodies are recorded.
// Warning: This can significantly increase trace size and may expose sensitive data.
// Defaults to false.
RecordBody bool `yaml:"recordBody" default:"false"`
// RecordHeaders determines whether HTTP headers are recorded as span attributes.
// Sensitive headers (Authorization, Cookie, etc.) are automatically redacted.
// Defaults to true.
RecordHeaders bool `yaml:"recordHeaders" default:"true"`
// RedactedHeaders is a list of header names to redact from traces.
// Values are replaced with "[REDACTED]".
// Defaults include Authorization, Cookie, Set-Cookie, X-API-Key.
RedactedHeaders []string `yaml:"redactedHeaders"`
// PropagateContext determines whether trace context is propagated from incoming requests.
// When true, parent spans from incoming requests are linked to server spans.
// Defaults to true.
PropagateContext bool `yaml:"propagateContext" default:"true"`
// RecordClientIP determines whether client IP is recorded as span attribute.
// Defaults to true.
RecordClientIP bool `yaml:"recordClientIP" default:"true"`
}
HttpInterTracingConfig defines the configuration for HTTP tracing middleware. Controls distributed tracing for HTTP requests.
func DefaultHttpInterTracingConfig ¶
func DefaultHttpInterTracingConfig() HttpInterTracingConfig
DefaultHttpInterTracingConfig returns a HttpInterTracingConfig with default values. Tracing middleware is disabled by default.
func (*HttpInterTracingConfig) IsEnabled ¶
func (c *HttpInterTracingConfig) IsEnabled() bool
IsEnabled returns true if the tracing middleware is enabled.
func (*HttpInterTracingConfig) Validate ¶
func (c *HttpInterTracingConfig) Validate() error
Validate performs validation of the tracing middleware configuration.
type HttpMiddlewareFilterConfig ¶
type HttpMiddlewareFilterConfig struct {
// IgnorePaths is a list of exact URL paths to skip processing for.
// Example: ["/health", "/metrics"]
IgnorePaths []string `yaml:"ignorePaths"`
// IgnorePatterns is a list of regex patterns for URL paths to skip processing.
// Example: ["^/health\\..*", ".*\\.html$"]
IgnorePatterns []string `yaml:"ignorePatterns"`
}
HttpMiddlewareFilterConfig defines common path filtering settings used by HTTP middlewares. Many middlewares need to exclude specific paths from processing, either by exact path name or by regex pattern matching. This struct provides a reusable configuration for such filtering behavior.
When embedded in middleware configurations, use the `yaml:",inline"` tag to flatten the fields in the YAML structure.
Example usage:
type MyMiddlewareConfig struct {
Enable bool `yaml:"enable"`
HttpMiddlewareFilterConfig `yaml:",inline"`
// ... other fields
}
func (*HttpMiddlewareFilterConfig) FilterValidationRules ¶
func (c *HttpMiddlewareFilterConfig) FilterValidationRules(ptr *HttpMiddlewareFilterConfig) []*validation.FieldRules
FilterValidationRules returns validation rules for IgnorePaths and IgnorePatterns fields. This method generates validation rules that can be used with ozzo-validation.
Validation rules:
- IgnorePaths: each path must be non-empty when specified
- IgnorePatterns: each pattern must be a valid regex when specified
type HttpTls ¶
type HttpTls struct {
*TlsServer `yaml:",inline"`
// StrictTransport configures Http Strict Transport Security (HSTS) headers
StrictTransport *STS `yaml:"sts" default:"-"`
}
HttpTls configures Tls settings specifically for Http servers. It embeds TlsServer configuration to provide certificate management, Tls versions, and cipher suite configuration for Http endpoints. It also supports Http Strict Transport Security (HSTS) configuration.
type Idempotency ¶
type Idempotency struct {
// TTL defines the time-to-live for idempotency keys.
// Keys are automatically expired after this duration to prevent storage bloat.
TTL time.Duration `yaml:"ttl" default:"24h"`
// Storage defines the storage configuration for idempotency keys.
// Required, specifies backend and settings.
Storage *CacheStorageConfig `yaml:"storage"`
}
Idempotency defines the configuration for idempotency key management. Controls how idempotency keys are stored and managed for duplicate request detection.
Example:
idem := &config.Idempotency{
TTL: 24 * time.Hour,
Storage: &config.CacheStorageConfig{
Type: config.CacheStorageTypeRedis,
},
}
func DefaultIdempotency ¶
func DefaultIdempotency() Idempotency
DefaultIdempotency returns an Idempotency configuration with default values. Note: Storage is left as nil since it is a required field.
func (*Idempotency) Validate ¶
func (i *Idempotency) Validate() error
Validate performs validation of the idempotency configuration. Ensures that TTL and storage are correctly configured. Returns an error if validation fails, nil otherwise.
type IgnoreConfig ¶
type IgnoreConfig struct {
// IgnoreMethods is a list of gRPC methods to skip processing for.
// Methods should be specified in the format "/service.Service/Method".
IgnoreMethods []string `yaml:"ignoreMethods"`
// IgnorePatterns is a list of regex patterns for methods to skip processing.
// Pattern-based rules for bypass.
IgnorePatterns []string `yaml:"ignorePatterns"`
}
IgnoreConfig defines common configuration for method/pattern-based exclusions. Used by interceptors to skip processing for certain methods or patterns.
type InProgress ¶
type InProgress struct {
// Enabled determines whether the InProgress manager is enabled.
// Defaults to true.
Enabled bool `yaml:"enabled" default:"true"`
// TickSchedule defines the cron schedule for the heartbeat tick cycle.
// Uses standard cron format with seconds: "second minute hour day month weekday"
// Defaults to "*/1 * * * * *" (every second).
// Examples:
// - "*/1 * * * * *" - every second
// - "*/5 * * * * *" - every 5 seconds
// - "0 * * * * *" - every minute
TickSchedule string `yaml:"tickSchedule" default:"*/1 * * * * *"`
// DefaultHeartbeatInterval specifies the default interval for heartbeats.
// Defaults to 10 seconds.
DefaultHeartbeatInterval time.Duration `yaml:"defaultHeartbeatInterval" default:"10s"`
// MaxEntries defines the maximum number of registered heartbeaters.
// Must be between 1 and 100000. Setting a reasonable limit prevents
// resource exhaustion from unbounded registration.
// Defaults to 10000.
MaxEntries int `yaml:"maxEntries" default:"10000"`
// Metrics contains metrics-related settings.
Metrics InProgressMetrics `yaml:"metrics"`
}
InProgress defines the configuration for InProgress heartbeat manager. Manages periodic heartbeat sending for long-running message handlers.
func (InProgress) Validate ¶
func (c InProgress) Validate() error
Validate performs validation of the InProgress configuration.
type InProgressMetrics ¶
type InProgressMetrics struct {
// Enabled allows enabling or disabling metrics collection.
// Defaults to true.
Enabled bool `yaml:"enabled" default:"true"`
// Prefix for InProgress heartbeat manager metrics.
// Defaults to "inprogress".
Prefix string `yaml:"prefix" default:"inprogress"`
}
InProgressMetrics defines the metrics configuration for InProgress heartbeat manager.
func (InProgressMetrics) Validate ¶
func (c InProgressMetrics) Validate() error
Validate performs validation of the InProgressMetrics configuration.
type InterceptorFilterConfig ¶
type InterceptorFilterConfig struct {
// IgnoreMethods is a list of gRPC methods to skip processing for.
// Methods should be specified in the format "/service.Service/Method".
// Example: ["/health.Health/Check", "/metrics.Metrics/Get"]
IgnoreMethods []string `yaml:"ignoreMethods"`
// IgnorePatterns is a list of regex patterns for methods to skip processing.
// Patterns are matched against the full method name.
// Example: ["^/health\\..*", ".*\\.Get$"]
IgnorePatterns []string `yaml:"ignorePatterns"`
}
InterceptorFilterConfig defines common method filtering settings used by interceptors. Many gRPC interceptors need to exclude specific methods from processing, either by exact method name or by regex pattern matching. This struct provides a reusable configuration for such filtering behavior.
When embedded in interceptor configurations, use the `yaml:",inline"` tag to flatten the fields in the YAML structure.
Example usage:
type MyInterceptorConfig struct {
Enable bool `yaml:"enable"`
InterceptorFilterConfig `yaml:",inline"`
// ... other fields
}
func (*InterceptorFilterConfig) FilterValidationRules ¶
func (c *InterceptorFilterConfig) FilterValidationRules(ptr *InterceptorFilterConfig) []*validation.FieldRules
FilterValidationRules returns validation rules for IgnoreMethods and IgnorePatterns fields. This method generates validation rules that can be used with ozzo-validation.
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be a valid regex when specified
Example usage:
func (c *MyInterceptorConfig) Validate() error {
return ValidateStructIfEnabled(c.Enable, c,
append(c.InterceptorFilterConfig.FilterValidationRules(&c.InterceptorFilterConfig),
validation.Field(&c.OtherField, validation.Required),
)...,
)
}
func (*InterceptorFilterConfig) FilterValidationRulesBasic ¶
func (c *InterceptorFilterConfig) FilterValidationRulesBasic(ptr *InterceptorFilterConfig) []*validation.FieldRules
FilterValidationRulesBasic returns validation rules without regex validation for patterns. Use this when patterns don't need to be valid regexes (just non-empty strings).
Validation rules:
- IgnoreMethods: each method name must be non-empty when specified
- IgnorePatterns: each pattern must be non-empty when specified
type InterceptorsConfig ¶
type InterceptorsConfig struct {
// Cache contains configuration for response caching interceptor.
Cache *GrpcInterCacheConfig `yaml:"cache" default:"-"`
// RealIp contains configuration for real IP extraction interceptor.
RealIp *GrpcInterRealIpConfig `yaml:"realIp" default:"-"`
// RequestId contains configuration for request ID generation interceptor.
RequestId *GrpcInterRequestIdConfig `yaml:"requestId" default:"-"`
// Recovery contains configuration for panic recovery interceptor.
Recovery *GrpcInterRecoveryConfig `yaml:"recovery" default:"-"`
// Idempotency contains configuration for idempotency interceptor.
Idempotency *GrpcInterIdempotencyConfig `yaml:"idempotency" default:"-"`
// Auth contains configuration for authentication interceptor.
Auth *GrpcInterAuthConfig `yaml:"auth" default:"-"`
// Health contains configuration for health check interceptor.
Health *GrpcInterHealthConfig `yaml:"health" default:"-"`
// Limiter contains configuration for rate limiting interceptor.
Limiter *GrpcInterLimiterConfig `yaml:"limiter" default:"-"`
// Logger contains configuration for logging interceptor.
Logger *GrpcInterLoggerConfig `yaml:"logger" default:"-"`
// Prometheus contains configuration for Prometheus metrics interceptor.
Prometheus *GrpcInterPrometheusConfig `yaml:"prometheus" default:"-"`
// Tracing contains configuration for distributed tracing interceptor.
Tracing *GrpcInterTracingConfig `yaml:"tracing" default:"-"`
}
InterceptorsConfig defines the configuration for gRPC interceptors. Contains settings for various middleware components in the gRPC interceptor chain.
func DefaultInterceptorsConfig ¶
func DefaultInterceptorsConfig() InterceptorsConfig
DefaultInterceptorsConfig returns an InterceptorsConfig with default values for all interceptors. All interceptors are disabled by default.
func (*InterceptorsConfig) Validate ¶
func (c *InterceptorsConfig) Validate() error
Validate performs validation of the InterceptorsConfig. Returns an error if validation fails, nil otherwise.
type LeaderElector ¶
type LeaderElector struct {
// Provider specifies which leader election provider to use
Provider LeaderElectorProvider `yaml:"provider" default:"nats"`
// Ttl defines the time-to-live for leader election locks
Ttl time.Duration `yaml:"ttl" default:"10s"`
}
LeaderElector defines the configuration for distributed leader election. Used to coordinate leadership among multiple service instances.
Example:
le := &config.LeaderElector{
Provider: config.LeaderElectorProviderNats,
Ttl: 10 * time.Second,
}
func DefaultLeaderElector ¶
func DefaultLeaderElector() LeaderElector
DefaultLeaderElector returns a LeaderElector configuration with default values. Note: Provider is left as zero value since it is a required field.
func (*LeaderElector) Validate ¶
func (le *LeaderElector) Validate() error
Validate performs validation of the LeaderElector configuration. Returns an error if validation fails, nil otherwise.
type LeaderElectorProvider ¶
type LeaderElectorProvider string
LeaderElectorProvider defines the type of leader election provider.
const ( // LeaderElectorProviderNats represents the NATS leader election provider. LeaderElectorProviderNats LeaderElectorProvider = "nats" )
type Limiter ¶
type Limiter struct {
// IpCacheSize defines the size of the LRU cache for IP-to-settings mappings.
// This cache optimizes repeated lookups for the same client IP.
IpCacheSize int `yaml:"ipCacheSize" default:"1000"`
// Storage defines the storage configuration for rate limit counters.
// Required, specifies backend and settings.
Storage *CacheStorageConfig `yaml:"storage"`
// Rules contains the rate limiting rules configuration.
// Includes default settings and specific rules for targeted clients.
Rules *LimiterRules `yaml:"rules"`
}
Limiter defines the configuration for rate limiting. It controls rate limiting behavior including storage, rules, and IP-based settings.
Example:
limiter := &config.Limiter{
Storage: &config.CacheStorageConfig{Type: config.CacheStorageTypeMemory},
Rules: &config.LimiterRules{Default: &config.LimiterDefaultRule{Limit: 1000, Period: time.Hour}},
}
func DefaultLimiter ¶
func DefaultLimiter() Limiter
DefaultLimiter returns a Limiter configuration with default values. Note: Storage and Rules are left as nil since they are required fields.
type LimiterDefaultRule ¶
type LimiterDefaultRule struct {
// Limit is the maximum number of requests allowed within the period.
// Must be a positive integer greater than 0.
Limit int64 `yaml:"limit" default:"1000"`
// Period is the time window for the limit (e.g., "1h", "30m", "60s").
// Must be a valid duration string parseable by time.ParseDuration.
Period time.Duration `yaml:"period" default:"1h"`
}
LimiterDefaultRule defines the default rate limiting settings. Applied when no specific target rule matches the client.
func DefaultLimiterDefaultRule ¶
func DefaultLimiterDefaultRule() LimiterDefaultRule
DefaultLimiterDefaultRule returns a LimiterDefaultRule configuration with default values.
func (*LimiterDefaultRule) Validate ¶
func (d *LimiterDefaultRule) Validate() error
Validate performs validation of the default rule configuration. Ensures limit is positive and period is a valid duration.
type LimiterRules ¶
type LimiterRules struct {
// Default contains the default rate limiting settings.
// Applied when no specific target rule matches the client.
Default *LimiterDefaultRule `yaml:"default"`
// Targets contains specific rate limiting rules for different clients.
// Rules are evaluated in order; the first matching rule is applied.
// If no target rule matches, the default rule (if specified) is used.
Targets []LimiterTargetRule `yaml:"targets,omitempty"`
}
LimiterRules defines the complete set of rate limiting rules. Includes default settings and specific rules for targeted clients.
func (*LimiterRules) Validate ¶
func (r *LimiterRules) Validate() error
Validate performs validation of the rules configuration. Ensures default rule and all target rules are properly configured.
type LimiterTargetRule ¶
type LimiterTargetRule struct {
// Target specifies the client identifier (IP address, CIDR block, etc.).
// Examples: "192.168.1.100", "10.0.0.0/8", "client-id-123"
Target string `yaml:"target"`
// Limit is the maximum number of requests allowed within the period.
// Must be a positive integer greater than 0.
Limit int64 `yaml:"limit"`
// Period is the time window for the limit (e.g., "1h", "30m", "60s").
// Must be a valid duration string parseable by time.ParseDuration.
Period time.Duration `yaml:"period"`
}
LimiterTargetRule defines rate limiting settings for specific targets. Targets can be IP addresses, CIDR blocks, or other client identifiers.
func (*LimiterTargetRule) Validate ¶
func (t *LimiterTargetRule) Validate() error
Validate performs validation of the target rule configuration. Ensures target is specified, limit is positive, and period is valid.
type Logger ¶
type Logger struct {
// Level sets the minimum logging level for message output
Level LoggerLevel `yaml:"level" default:"error"`
// Tags contains key-value pairs to include with all log messages
Tags map[string]string `yaml:"tags"`
// TimeFormat specifies the format for timestamps in log messages
TimeFormat string `yaml:"timeFormat"`
// Colorized enables colored output for console logging
Colorized bool `yaml:"colorized"`
// Output specifies whether to write to stdout or stderr
Output LoggerConsoleOutput `yaml:"output" default:"stdout"`
// OutputFormat controls whether logs are in text or JSON format
OutputFormat LogFormat `yaml:"outputFormat" default:"text"`
// SensitiveTags lists tag keys that should be redacted in log output
SensitiveTags []string `yaml:"sensitiveTags"`
// MaskString is the string used for masking sensitive fields
MaskString string `yaml:"maskString" default:"****"`
// AppGroupName is the group name for application metadata
AppGroupName string `yaml:"appGroupName" default:"app"`
// OutputSource includes source file and line information in log messages
OutputSource bool `yaml:"outputSource"`
// Buffered enables asynchronous log writing
Buffered bool `yaml:"buffered"`
// BufferSize specifies the size of the log buffer (default: 100)
BufferSize int `yaml:"bufferSize" default:"100"`
// BypassLevel specifies the minimum level to bypass the buffer (write synchronously, default: error)
BypassLevel LoggerLevel `yaml:"bypassLevel" default:"error"`
}
Logger configures logging behavior for applications. It controls log levels, output destinations, formatting, and metadata handling.
Example:
logger := &config.Logger{
Level: config.LoggerLevelInfo,
OutputFormat: config.LogFormatJSON,
}
func DefaultLogger ¶
func DefaultLogger() Logger
DefaultLogger returns a Logger configuration with default values.
type LoggerConsoleOutput ¶
type LoggerConsoleOutput = string
LoggerConsoleOutput represents the console output destination for logging.
const ( // LoggerConsoleOutputStdout directs log output to standard output. LoggerConsoleOutputStdout LoggerConsoleOutput = "stdout" // LoggerConsoleOutputStderr directs log output to standard error. LoggerConsoleOutputStderr LoggerConsoleOutput = "stderr" )
type LoggerLevel ¶
type LoggerLevel = string
LoggerLevel represents the minimum logging level for message output.
const ( // LoggerLevelError logs only error messages. LoggerLevelError LoggerLevel = "error" // LoggerLevelWarning logs warning and error messages. LoggerLevelWarning LoggerLevel = "warning" // LoggerLevelInfo logs informational, warning, and error messages. LoggerLevelInfo LoggerLevel = "info" // LoggerLevelDebug logs all messages including debug information. LoggerLevelDebug LoggerLevel = "debug" // LoggerLevelNone disables all logging output. LoggerLevelNone LoggerLevel = "none" )
type Metrics ¶
type Metrics struct {
// Enable determines whether metrics collection is enabled.
// Defaults to false.
Enable bool `yaml:"enable" default:"false"`
// Type specifies the metrics backend type.
// Valid values: "prometheus", "noop".
// Defaults to "prometheus".
Type MetricsType `yaml:"type" default:"prometheus"`
// ServiceName is the global prefix for all metrics.
// This becomes the first part of the metric name: {serviceName}_{subsystem}_{name}.
// Example: "myapp" results in metrics like "myapp_http_requests_total".
ServiceName string `yaml:"serviceName"`
// Adapters contains adapter-specific configurations.
Adapters *MetricsAdapters `yaml:"adapters,omitempty" default:"-"`
}
Metrics represents the configuration for the metrics system.
Example:
metrics:
enable: true
type: prometheus
serviceName: myapp
adapters:
prometheus:
customRegistry: false
func DefaultMetrics ¶
func DefaultMetrics() Metrics
DefaultMetrics returns a Metrics configuration with default values.
type MetricsAdapters ¶
type MetricsAdapters struct {
// Prometheus contains Prometheus-specific configuration.
// Only used when Type is "prometheus".
Prometheus *MetricsPrometheus `yaml:"prometheus,omitempty" default:"-"`
}
MetricsAdapters contains configurations for different metrics adapters.
func (MetricsAdapters) Validate ¶
func (a MetricsAdapters) Validate() error
Validate performs validation on the MetricsAdapters configuration.
type MetricsPrometheus ¶
type MetricsPrometheus struct {
// CustomRegistry determines whether to use a custom Prometheus registry
// instead of the default global registry.
// Use this when running tests or when you need isolated metrics.
CustomRegistry bool `yaml:"customRegistry" default:"false"`
}
MetricsPrometheus contains Prometheus-specific configuration.
func (MetricsPrometheus) Validate ¶
func (m MetricsPrometheus) Validate() error
Validate performs validation on the MetricsPrometheus configuration.
type MetricsType ¶
type MetricsType string
MetricsType represents the type of metrics backend.
const ( // MetricsTypePrometheus uses Prometheus for metrics collection. MetricsTypePrometheus MetricsType = "prometheus" // MetricsTypeNoop disables metrics collection. MetricsTypeNoop MetricsType = "noop" )
Supported metrics types.
type MiddlewaresConfig ¶
type MiddlewaresConfig struct {
// BodyLimit contains configuration for request body size limiting middleware.
BodyLimit *HttpInterBodyLimitConfig `yaml:"bodyLimit" default:"-"`
// Cors contains configuration for CORS middleware.
Cors *HttpInterCorsConfig `yaml:"cors" default:"-"`
// Idempotency contains configuration for idempotency middleware.
Idempotency *HttpInterIdempotencyConfig `yaml:"idempotency" default:"-"`
// Limiter contains configuration for rate limiting middleware.
Limiter *HttpInterLimiterConfig `yaml:"limiter" default:"-"`
// Logger contains configuration for logging middleware.
Logger *HttpInterLoggerConfig `yaml:"logger" default:"-"`
// Prometheus contains configuration for Prometheus metrics middleware.
Prometheus *HttpInterPrometheusConfig `yaml:"prometheus" default:"-"`
// RealIp contains configuration for real IP extraction middleware.
RealIp *HttpInterRealIpConfig `yaml:"realIp" default:"-"`
// Recovery contains configuration for panic recovery middleware.
Recovery *HttpInterRecoveryConfig `yaml:"recovery" default:"-"`
// RequestId contains configuration for request ID middleware.
RequestId *HttpInterRequestIdConfig `yaml:"requestId" default:"-"`
// SecurityHeaders contains configuration for security headers middleware.
SecurityHeaders *HttpInterSecurityHeadersConfig `yaml:"securityHeaders" default:"-"`
// Tracing contains configuration for distributed tracing middleware.
Tracing *HttpInterTracingConfig `yaml:"tracing" default:"-"`
}
MiddlewaresConfig defines the configuration for HTTP middlewares. Contains settings for various middleware components in the HTTP server pipeline.
func DefaultMiddlewaresConfig ¶
func DefaultMiddlewaresConfig() MiddlewaresConfig
DefaultMiddlewaresConfig returns a MiddlewaresConfig with default values for all middlewares. All middlewares are disabled by default.
func (*MiddlewaresConfig) Validate ¶
func (c *MiddlewaresConfig) Validate() error
Validate performs validation of the MiddlewaresConfig. Returns an error if validation fails, nil otherwise.
type MongoAuthMechanismType ¶
type MongoAuthMechanismType string
MongoAuthMechanismType represents the authentication mechanism type for MongoDB. MongoDB supports several authentication mechanisms for different security requirements.
const ( // MongoAuthMechanismTypePLAIN uses PLAIN (LDAP) authentication. Requires TLS. MongoAuthMechanismTypePLAIN MongoAuthMechanismType = "PLAIN" // MongoAuthMechanismTypeX509 uses X.509 certificate authentication. // The [Mongodb.TLS] field must be configured when this mechanism is selected. MongoAuthMechanismTypeX509 MongoAuthMechanismType = "MONGODB-X509" // MongoAuthMechanismTypeSCRAMSHA256 uses SCRAM-SHA-256 (default, recommended). MongoAuthMechanismTypeSCRAMSHA256 MongoAuthMechanismType = "SCRAM-SHA-256" // MongoAuthMechanismTypeSCRAMSHA1 uses the legacy SCRAM-SHA-1 mechanism. MongoAuthMechanismTypeSCRAMSHA1 MongoAuthMechanismType = "SCRAM-SHA-1" )
func (MongoAuthMechanismType) String ¶
func (mt MongoAuthMechanismType) String() string
String returns the string representation of the authentication mechanism type.
type MongoCompressionType ¶
type MongoCompressionType string
MongoCompressionType represents the compression algorithm type for MongoDB connections. MongoDB supports multiple compression algorithms to reduce network traffic.
const ( // MongoCompressionTypeSnappy uses Snappy compression (fast, moderate ratio). MongoCompressionTypeSnappy MongoCompressionType = "snappy" // MongoCompressionTypeZlib uses zlib compression (configurable level via ZlibCompressionLevel). MongoCompressionTypeZlib MongoCompressionType = "zlib" // MongoCompressionTypeZstd uses Zstandard compression (high ratio, good speed). MongoCompressionTypeZstd MongoCompressionType = "zstd" )
func (MongoCompressionType) String ¶
func (ct MongoCompressionType) String() string
String returns the string representation of the compression type.
type MongoCompressionTypes ¶
type MongoCompressionTypes []MongoCompressionType
MongoCompressionTypes represents a slice of compression types. It provides utility methods for converting to string slices.
func (MongoCompressionTypes) StringsSlice ¶
func (cts MongoCompressionTypes) StringsSlice() []string
StringsSlice converts the compression types to a slice of strings. This is useful for passing to MongoDB driver functions.
type MongoEncryption ¶
type MongoEncryption struct {
VaultDatabase *string `yaml:"vaultDatabase"`
VaultCollection string `yaml:"vaultCollection" default:"__keyVault"`
KMS *MongoKMS `yaml:"kms"`
Type MongoEncryptionType `yaml:"type" default:"auto"`
}
MongoEncryption represents the client-side field level encryption configuration for MongoDB. It contains settings for the key vault, KMS provider, and encryption mode. Client-side encryption provides an additional layer of security by encrypting sensitive data before it leaves the application.
func (*MongoEncryption) Validate ¶
func (m *MongoEncryption) Validate() error
Validate validates the MongoDB encryption configuration. It ensures the vault collection name, KMS configuration, and encryption type are valid.
Returns an error if any validation rules fail.
type MongoEncryptionType ¶
type MongoEncryptionType string
MongoEncryptionType represents the type of client-side field level encryption. MongoDB supports both automatic and manual encryption modes.
const ( // MongoEncryptionTypeManual requires the application to explicitly encrypt and // decrypt each field using the encryption client API. MongoEncryptionTypeManual MongoEncryptionType = "manual" // MongoEncryptionTypeAuto lets the MongoDB driver transparently encrypt and // decrypt fields based on a JSON schema or encryption rules. MongoEncryptionTypeAuto MongoEncryptionType = "auto" )
type MongoKMS ¶
type MongoKMS struct {
Provider MongoKMSProvider `yaml:"provider"`
Local *MongoKMSLocal `yaml:"local" default:"-"`
Amazon *MongoKMSAmazon `yaml:"amazon" default:"-"`
Azure *MongoKMSAzure `yaml:"azure" default:"-"`
Google *MongoKMSGoogle `yaml:"google" default:"-"`
}
MongoKMS represents the Key Management Service configuration for MongoDB encryption. It contains provider-specific settings for managing encryption keys. Only the configuration matching the specified provider is required.
type MongoKMSAmazon ¶
type MongoKMSAmazon struct {
AccessKeyId string `yaml:"accessKeyId"`
SecretAccessKey Secret `yaml:"secretAccessKey"`
SessionToken *string `yaml:"sessionToken"`
Key string `yaml:"key"`
Region *string `yaml:"region"`
Endpoint *string `yaml:"endpoint"`
TLS *TlsClient `yaml:"tls" default:"-"`
}
MongoKMSAmazon represents the AWS Key Management Service provider configuration. It contains all necessary credentials and settings for using AWS KMS for MongoDB client-side field level encryption.
func (*MongoKMSAmazon) Validate ¶
func (m *MongoKMSAmazon) Validate() error
Validate validates the AWS KMS provider options. It ensures all required AWS credentials and key information are provided.
Returns an error if any validation rules fail.
type MongoKMSAzure ¶
type MongoKMSAzure struct {
ClientId string `yaml:"clientId"`
ClientSecret Secret `yaml:"clientSecret"`
TenantId string `yaml:"tenantId"`
KeyName string `yaml:"keyName"`
KeyVersion *string `yaml:"keyVersion"`
KeyVaultEndpoint *string `yaml:"keyVaultEndpoint"`
TLS *TlsClient `yaml:"tls" default:"-"`
}
MongoKMSAzure represents the Azure Key Vault provider configuration. It contains all necessary credentials and settings for using Azure Key Vault for MongoDB client-side field level encryption.
func (*MongoKMSAzure) Validate ¶
func (m *MongoKMSAzure) Validate() error
Validate validates the Azure KMS provider options. It ensures all required Azure credentials and key vault information are provided.
Returns an error if any validation rules fail.
type MongoKMSGoogle ¶
type MongoKMSGoogle struct {
Endpoint *string `yaml:"endpoint"`
ProjectId string `yaml:"projectId"`
Email string `yaml:"email"`
AuthenticationEndpoint *string `yaml:"authenticationEndpoint"`
PrivateKey Secret `yaml:"privateKey"`
Location string `yaml:"location"`
KeyRing string `yaml:"keyRing"`
KeyName string `yaml:"keyName"`
KeyVersion *string `yaml:"keyVersion"`
TLS *TlsClient `yaml:"tls" default:"-"`
}
MongoKMSGoogle represents the Google Cloud KMS provider configuration. It contains all necessary credentials and settings for using Google Cloud KMS for MongoDB client-side field level encryption.
func (*MongoKMSGoogle) Validate ¶
func (m *MongoKMSGoogle) Validate() error
Validate validates the GCP KMS provider options. It ensures all required Google Cloud credentials and key information are provided.
Returns an error if any validation rules fail.
type MongoKMSLocal ¶
type MongoKMSLocal struct {
// A 96-byte long base64-encoded string. Locally managed keys do not require additional setup,
// but are not recommended for production applications.
MasterKey Secret `yaml:"masterKey"`
MasterKeyFile string `yaml:"masterKeyFile"`
}
MongoKMSLocal represents the local Key Management Service provider. Local KMS uses locally managed keys and does not require external services. Not recommended for production environments due to security considerations.
func (*MongoKMSLocal) Validate ¶
func (m *MongoKMSLocal) Validate() error
Validate validates the local KMS provider options. It ensures either a master key or master key file is provided, and validates the master key length if specified directly.
Returns an error if any validation rules fail.
type MongoKMSProvider ¶
type MongoKMSProvider string
MongoKMSProvider represents the type of Key Management Service provider for MongoDB client-side field level encryption (CSFLE).
const ( // MongoKMSProviderLocal is the local key provider. The local key service can be any component that assigns the key to // it. It can be integrated with local key vaults or API fetch using stores like Hashicrop and HSM. MongoKMSProviderLocal MongoKMSProvider = "local" // MongoKMSProviderAzure is the Azure Key Vault provider. MongoKMSProviderAzure MongoKMSProvider = "azure" // MongoKMSProviderAmazon is the AWS Key Management Service provider. MongoKMSProviderAmazon MongoKMSProvider = "amazon" // MongoKMSProviderGoogle is the Google Cloud KMS provider. MongoKMSProviderGoogle MongoKMSProvider = "google" )
type MongoPLAINCredentials ¶
type MongoPLAINCredentials struct {
Username string `yaml:"username"`
Password Secret `yaml:"password"`
}
MongoPLAINCredentials represents the credentials for the PLAIN authentication mechanism. PLAIN authentication sends credentials as plain text and should only be used over secure connections (TLS).
func (*MongoPLAINCredentials) Validate ¶
func (m *MongoPLAINCredentials) Validate() error
Validate validates the credentials for the PLAIN authentication mechanism. It ensures both username and password are provided.
Returns an error if any validation rules fail.
type MongoSCRAMCredentials ¶
type MongoSCRAMCredentials struct {
Username string `yaml:"username"`
Password Secret `yaml:"password"`
AuthSource string `yaml:"authSource" default:"admin"`
}
MongoSCRAMCredentials represents the credentials for the SCRAM authentication mechanism. SCRAM (Salted Challenge Response Authentication Mechanism) is the default and recommended authentication mechanism for MongoDB.
func (*MongoSCRAMCredentials) Validate ¶
func (m *MongoSCRAMCredentials) Validate() error
Validate validates the credentials for the SCRAM authentication mechanism. It ensures username, password, and authentication source are provided.
Returns an error if any validation rules fail.
type Mongodb ¶
type Mongodb struct {
// DirectConnection forces a direct connection to the specified host.
// When true, bypasses automatic discovery of replica set topology.
// Defaults to false.
DirectConnection bool `yaml:"directConnection" default:"false"` //+
// ConnectionURI is a full MongoDB connection string (e.g. "mongodb://user:pass@host:27017/db").
// When set, it replaces Hosts, Credentials, ReplicaSet, DirectConnection, and Compressors.
// Mutually exclusive with Credentials.
ConnectionURI Secret `yaml:"connectionUri"`
// Credentials contains optional authentication credentials.
// If nil, the connection will attempt to connect without authentication.
Credentials *MongodbCredentials `yaml:"credentials" default:"-"` //+
// TLS contains optional TLS configuration for secure connections.
// Required when using X.509 certificate authentication.
TLS *TlsClient `yaml:"tls" default:"-"` //+
// Database specifies the default database name.
Database string `yaml:"database"`
// ReplicaSet specifies the replica set name for replica set connections.
// Leave empty for standalone server connections.
ReplicaSet string `yaml:"replicaSet"` //+
// Compressors specifies the list of compression algorithms to use.
// Supported values: snappy, zlib, zstd.
Compressors MongoCompressionTypes `yaml:"compressors"` //+
// Hosts is the list of MongoDB server addresses.
// Defaults to ["localhost:27017"].
Hosts []string `yaml:"hosts" default:"localhost:27017"` //+
// MaxPoolSize is the maximum number of connections in the connection pool.
// Defaults to 100.
MaxPoolSize uint64 `yaml:"maxPoolSize" default:"100"` //+
// MinPoolSize is the minimum number of connections in the connection pool.
// Defaults to 0.
MinPoolSize uint64 `yaml:"minPoolSize" default:"0"` //+
// ConnectTimeout is the maximum time to wait for a connection to be established.
// Defaults to 30 seconds.
ConnectTimeout time.Duration `yaml:"connectTimeout" default:"30s"` //+
// MaxIdleTimeout is the maximum time a connection can be idle before being closed.
// Set to 0 for no timeout (default).
MaxIdleTimeout time.Duration `yaml:"maxIdleTimeout" default:"0"` //+
// ZlibCompressionLevel specifies the compression level for zlib compression.
// Valid range: -1 to 9, where -1 is default compression (default).
ZlibCompressionLevel int `yaml:"zlibCompressionLevel" default:"-1"` //+
// RetryReads enables automatic retrying of read operations.
// Defaults to true.
RetryReads bool `yaml:"retryReads" default:"true"` //+
// RetryWrites enables automatic retrying of write operations.
// Defaults to true.
RetryWrites bool `yaml:"retryWrites" default:"true"` //+
// Encryption contains optional client-side field level encryption settings.
// If nil, no client-side encryption is used.
Encryption *MongoEncryption `yaml:"encryption" default:"-"`
}
Mongodb represents the configuration for MongoDB database connections. It contains all necessary parameters for connecting to MongoDB including authentication, TLS, connection pooling, timeouts, and encryption settings.
When ConnectionURI is set it takes priority over Hosts and Credentials. Fields not expressible through the URI (pool sizes, timeouts, TLS certificates, encryption) are applied on top. Database is always required.
Example:
mongo := &config.Mongodb{
Database: "myapp",
Hosts: []string{"mongo1:27017", "mongo2:27017"},
}
func DefaultMongodb ¶
func DefaultMongodb() Mongodb
DefaultMongodb returns a Mongodb configuration with default values. Note: Database is left as zero value since it is a required field.
func (*Mongodb) UseConnectionURI ¶
UseConnectionURI reports whether ConnectionURI is set and should be used instead of Hosts and Credentials.
func (*Mongodb) Validate ¶
Validate performs comprehensive validation on the MongoDB configuration. It validates hosts, direct connection settings, timeouts, compression types, database name, and ensures TLS is configured when using X.509 authentication.
When ConnectionURI is set, Hosts are not required and Credentials must not be set (conflict error). Database is always required.
Returns an error if any validation rules fail.
type MongodbCredentials ¶
type MongodbCredentials struct {
AuthMechanism MongoAuthMechanismType `yaml:"authMechanism" default:"SCRAM-SHA-256"`
Plain *MongoPLAINCredentials `yaml:"plain" default:"-"`
Scram *MongoSCRAMCredentials `yaml:"scram" default:"-"`
}
MongodbCredentials represents the credentials for the MongoDB connection. It contains the authentication mechanism type and corresponding credential details. Only the credentials matching the specified mechanism are required.
func (*MongodbCredentials) Validate ¶
func (m *MongodbCredentials) Validate() error
Validate validates the credentials for the MongoDB connection. It ensures the authentication mechanism is valid and that the corresponding credential fields are properly configured.
Returns an error if any validation rules fail.
type Nats ¶
type Nats struct {
// TLS contains optional TLS configuration for secure connections.
// If nil, the connection will be made without TLS encryption.
TLS *TlsClient `yaml:"tls" default:"-"`
// ConnectionURI is a full NATS connection string (e.g. "nats://user:pass@host:4222").
// When set, it replaces Hosts and authentication fields.
// Mutually exclusive with Username, Password, Token, and NkeySeed.
ConnectionURI Secret `yaml:"connectionUri"`
// Username is the username for NATS authentication.
// Used with password-based authentication.
Username string `yaml:"username"`
// Token is the authentication token for NATS.
// Alternative to username/password authentication.
Token Secret `yaml:"token"`
// Password is the password for NATS authentication.
// Used with username-based authentication.
Password Secret `yaml:"password"`
// NkeySeed is the NKey seed (private key) for NKey-based authentication.
// The seed is used to derive the public key and sign server challenges.
// Mutually exclusive with Token and Username/Password authentication.
NkeySeed Secret `yaml:"nkeySeed"`
// ClientName is an optional name for the NATS client connection.
// Useful for debugging and monitoring purposes.
ClientName string `yaml:"clientName"`
// Hosts is the list of NATS server URLs to connect to.
// Defaults to ["nats://localhost:4222"].
// The client will attempt to connect to servers in order.
Hosts []string `yaml:"hosts" default:"nats://localhost:4222"`
// ConnectTimeout is the maximum time to wait for a connection to be established.
// Defaults to 5 seconds.
ConnectTimeout time.Duration `yaml:"connectTimeout" default:"5s"`
// ReconnectWait is the time to wait between reconnection attempts.
// Defaults to 10 seconds.
ReconnectWait time.Duration `yaml:"reconnectWait" default:"10s"`
// PingInterval is the interval between ping messages to keep the connection alive.
// Defaults to 10 seconds.
PingInterval time.Duration `yaml:"pingInterval" default:"10s"`
// MaxReconnect is the maximum number of reconnection attempts.
// Set to 0 for unlimited reconnection attempts (default).
// Set to -1 to disable reconnection.
MaxReconnect int `yaml:"maxReconnect" default:"0"`
// MaxPingsOut is the maximum number of ping messages that can be sent
// without receiving a pong response before the connection is considered dead.
// Defaults to 3.
MaxPingsOut int `yaml:"maxPingsOut" default:"3"`
// Consumers is a collection of consumer configurations keyed by consumer name.
// Each consumer defines how messages are consumed from NATS JetStream.
// The key serves as the durable consumer name in NATS.
Consumers NatsConsumers `yaml:"consumers"`
// Recovery contains configuration for automatic stream/consumer recovery.
// If nil, recovery is disabled.
Recovery *NatsRecovery `yaml:"recovery" default:"-"`
}
Nats represents the configuration for NATS messaging system connections. It contains all necessary parameters for connecting to NATS servers including authentication, TLS settings, connection timeouts, and reconnection behavior.
When ConnectionURI is set it takes priority over Hosts and authentication fields (Username, Password, Token, NkeySeed). Fields not expressible through the URI (TLS certificates, timeouts, consumers, recovery) are applied on top.
Example:
nats := &config.Nats{
Hosts: []string{"nats://nats1:4222", "nats://nats2:4222"},
ConnectTimeout: 5 * time.Second,
}
func DefaultNats ¶
func DefaultNats() Nats
DefaultNats returns a Nats configuration with default values.
func (*Nats) GetConsumerByName ¶
func (n *Nats) GetConsumerByName(name string) (*NatsConsumer, bool)
GetConsumerByName returns the consumer configuration for the specified name. Returns the consumer configuration and true if found, nil and false otherwise.
func (*Nats) HasConsumers ¶
HasConsumers returns true if there are any consumers configured.
func (*Nats) RecoveryEnabled ¶
RecoveryEnabled returns true if recovery is configured and enabled.
func (*Nats) UseConnectionURI ¶
UseConnectionURI reports whether ConnectionURI is set and should be used instead of Hosts and individual authentication fields.
func (*Nats) Validate ¶
Validate performs validation on the NATS configuration. It validates hosts, TLS configuration, timeout durations, ping settings, and all configured consumers to ensure they meet NATS client requirements.
When ConnectionURI is set, Hosts are not required and authentication fields (Username, Password, Token, NkeySeed) must not be set (conflict error).
Returns an error if any validation rules fail.
type NatsConsumer ¶
type NatsConsumer struct {
// Description is an optional description of the consumer.
Description string `yaml:"description"`
// DurableName is the durable name for the consumer.
// If not specified, the consumer name from the configuration map key is used.
// Durable consumers maintain their state across restarts and reconnections.
DurableName string `yaml:"durableName"`
// DeliverPolicy defines the point in the stream to start delivering messages.
// Defaults to "all" which delivers all available messages.
DeliverPolicy DeliverPolicy `yaml:"deliverPolicy" default:"all"`
// OptStartSeq is the sequence number to start from when DeliverPolicy is "by_start_sequence".
// Must be greater than 0 when used.
OptStartSeq uint64 `yaml:"optStartSeq"`
// OptStartTime is the time to start from when DeliverPolicy is "by_start_time".
// Format: RFC3339 timestamp.
OptStartTime *time.Time `yaml:"optStartTime"`
// AckPolicy defines how messages should be acknowledged.
// Defaults to "explicit" which requires explicit ack for each message.
AckPolicy AckPolicy `yaml:"ackPolicy" default:"explicit"`
// AckWait is the duration to wait for acknowledgement before redelivery.
// Defaults to 30 seconds.
AckWait time.Duration `yaml:"ackWait" default:"30s"`
// MaxDeliver is the maximum number of delivery attempts for a message.
// After this, the message is considered permanently failed.
// Set to -1 for unlimited attempts. Defaults to -1.
MaxDeliver int `yaml:"maxDeliver" default:"-1"`
// BackOff is a custom backoff schedule for message redelivery.
// If not specified, uses exponential backoff.
// Each duration in the slice represents the delay before the next redelivery attempt.
// Example: [1s, 5s, 30s, 2m, 5m] means:
// - 1st retry after 1 second
// - 2nd retry after 5 seconds
// - 3rd retry after 30 seconds
// - 4th retry after 2 minutes
// - 5th retry after 5 minutes
// After exhausting the backoff schedule, the last duration is used for subsequent retries.
BackOff []time.Duration `yaml:"backOff"`
// FilterSubject is an optional subject filter for the consumer.
// Only messages matching this subject will be delivered.
FilterSubjects []string `yaml:"filterSubject"`
// ReplayPolicy defines how messages are replayed from the stream.
// Defaults to "instant" which replays as fast as possible.
ReplayPolicy ReplayPolicy `yaml:"replayPolicy" default:"instant"`
// MaxAckPending is the maximum number of messages that can be outstanding
// (delivered but not yet acknowledged) at any time.
// Defaults to 1000.
MaxAckPending int `yaml:"maxAckPending" default:"1000"`
// MaxWaiting is the maximum number of waiting pull requests.
// Only applicable for pull-based consumers.
// Defaults to 512.
MaxWaiting int `yaml:"maxWaiting" default:"512"`
// InactiveThreshold is the duration of inactivity before the consumer is removed.
// Set to 0 to disable automatic removal.
// Defaults to 0 (disabled).
InactiveThreshold time.Duration `yaml:"inactiveThreshold" default:"0s"`
}
NatsConsumer represents the configuration for a NATS JetStream consumer. Consumers are clients that consume messages from a stream with specific delivery and acknowledgement policies.
func (*NatsConsumer) Validate ¶
func (nc *NatsConsumer) Validate() error
Validate performs validation on the NatsConsumer configuration. It validates delivery policies, acknowledgement settings, timeout durations, and backoff schedules to ensure they meet NATS JetStream consumer requirements.
Returns an error if any validation rules fail.
type NatsConsumers ¶
type NatsConsumers map[string]*NatsConsumer
NatsConsumers represents a collection of NATS JetStream consumer configurations. It is a map where keys are consumer names (durable names) and values are consumer configurations.
func (NatsConsumers) GetByName ¶
func (nc NatsConsumers) GetByName(name string) (*NatsConsumer, bool)
GetByName returns the consumer configuration for the specified name. Returns the consumer configuration and true if found, nil and false otherwise.
type NatsRecovery ¶
type NatsRecovery struct {
// Enabled determines whether recovery is enabled.
// Defaults to true.
Enabled bool `yaml:"enabled" default:"true"`
// HealthCheckSchedule defines the cron schedule for health checks.
// Acts as fallback detection when advisory events are missed.
// Supports cron expressions and intervals (e.g., "@every 5m", "0 */5 * * * *").
// Defaults to "@every 5m".
HealthCheckSchedule string `yaml:"healthCheckSchedule" default:"@every 5m"`
// MaxRecoveryAttempts defines the maximum number of recovery attempts before giving up.
// Must be between 1 and 100.
// Defaults to 3.
MaxRecoveryAttempts int `yaml:"maxRecoveryAttempts" default:"3"`
// RecoveryBackoff defines the base backoff duration between recovery attempts.
// Actual backoff is calculated as backoff * attemptNumber.
// Defaults to 5 seconds.
RecoveryBackoff time.Duration `yaml:"recoveryBackoff" default:"5s"`
// StaleRecoveryTimeout defines how long a recovery mark can exist before
// being considered stale and cleared. This prevents permanent blocking
// of recovery operations due to crashes or bugs.
// Defaults to 20 minutes.
StaleRecoveryTimeout time.Duration `yaml:"staleRecoveryTimeout" default:"20m"`
// StaleRecoveryCleanupSchedule defines the cron schedule for stale recovery cleanup.
// Supports cron expressions and intervals (e.g., "@every 1m", "0 * * * * *").
// Defaults to "@every 1m".
StaleRecoveryCleanupSchedule string `yaml:"staleRecoveryCleanupSchedule" default:"@every 1m"`
}
NatsRecovery defines configuration for automatic NATS JetStream stream/consumer recovery.
func DefaultNatsRecovery ¶
func DefaultNatsRecovery() NatsRecovery
DefaultNatsRecovery returns a NatsRecovery configuration with default values.
func (NatsRecovery) Validate ¶
func (c NatsRecovery) Validate() error
Validate performs validation of the NatsRecovery configuration.
type Node ¶
type Node struct {
// Unique identifier for the service node
// Must contain only alphanumeric characters, underscores, and hyphens
Id *string `yaml:"id"`
}
Node represents the configuration for a service node. It contains identification information for the service instance.
Example:
node := &config.Node{Id: ptr.Wrap("node-1")}
node.Normalize() // converts to uppercase
type OIDC ¶
type OIDC struct {
// DiscoveryUrl is the URL of the OpenID Connect discovery endpoint
DiscoveryUrl string `yaml:"discoveryUrl"`
// ClockSkew is the acceptable time difference when validating timestamps
ClockSkew time.Duration `yaml:"clockSkew" default:"10s"`
// Cache contains optional token caching settings
Cache *OIDCCache `yaml:"cache" default:"-"`
// Validation contains optional token validation settings
Validation *OIDCValidation `yaml:"validation" default:"-"`
// ServiceAccount contains optional service-to-service authentication credentials
ServiceAccount *OIDCServiceAccount `yaml:"serviceAccount" default:"-"`
// JWKS contains optional JWKS-specific settings
JWKS *OIDCJwks `yaml:"jwks" default:"-"`
// Introspection contains optional RFC 7662 token introspection settings
Introspection *OIDCIntrospection `yaml:"introspection" default:"-"`
// Presets contains optional validation presets configuration
Presets *OIDCPresets `yaml:"presets" default:"-"`
// Revocation contains optional token/key revocation settings
Revocation *OIDCRevocation `yaml:"revocation" default:"-"`
}
OIDC represents the configuration for OpenID Connect authentication. It contains all necessary parameters for OIDC provider integration including token validation, service account credentials, and OIDCJwks management.
func DefaultOIDC ¶
func DefaultOIDC() OIDC
DefaultOIDC returns an OIDC configuration with default values. Note: DiscoveryUrl is left as zero value since it is a required field.
func (*OIDC) IsCacheConfigured ¶
IsCacheConfigured returns true if cache settings are configured.
func (*OIDC) IsIntrospectionConfigured ¶
IsIntrospectionConfigured returns true if introspection settings are configured.
func (*OIDC) IsJWKSConfigured ¶
IsJWKSConfigured returns true if OIDCJwks settings are configured.
func (*OIDC) IsPresetsConfigured ¶
IsPresetsConfigured returns true if presets settings are configured.
func (*OIDC) IsRevocationConfigured ¶
IsRevocationConfigured returns true if revocation settings are configured.
func (*OIDC) IsServiceAccountConfigured ¶
IsServiceAccountConfigured returns true if service account credentials are configured.
func (*OIDC) IsValidationConfigured ¶
IsValidationConfigured returns true if validation settings are configured.
type OIDCCache ¶
type OIDCCache struct {
// Enabled enables caching of token validation results
Enabled bool `yaml:"enabled" default:"false"`
// TokensKeyPrefix is the prefix for validated token cache keys
TokensKeyPrefix string `yaml:"tokensKeyPrefix" default:"tokens:"`
// RevokedTokensKeyPrefix is the prefix for revoked token cache keys
RevokedTokensKeyPrefix string `yaml:"revokedTokensKeyPrefix" default:"revoked-tokens:"`
}
OIDCCache represents token caching configuration. It controls caching behavior for validated and revoked tokens.
func DefaultOIDCCache ¶
func DefaultOIDCCache() OIDCCache
DefaultOIDCCache returns an OIDCCache configuration with default values.
type OIDCClaims ¶
type OIDCClaims struct {
// Required is the list of claims that must be present in the token
Required []string `yaml:"required"`
// Expected defines exact values that specific claims must have
Expected map[string]string `yaml:"expected"`
// Ignored is the list of claims to skip during validation
Ignored []string `yaml:"ignored"`
// Audience is the expected audience claim in the token
Audience []string `yaml:"audience"`
// AllowedClientIds is the whitelist of client_id values for service-to-service calls
AllowedClientIds []string `yaml:"allowedClientIds"`
// RequiredScopes is the list of required scopes for service tokens
RequiredScopes []string `yaml:"requiredScopes"`
// RequireAuthorizedParty requires the 'azp' (authorized party) claim
RequireAuthorizedParty bool `yaml:"requireAuthorizedParty"`
// AllowedAuthorizedParties is the whitelist of allowed 'azp' claim values
AllowedAuthorizedParties []string `yaml:"allowedAuthorizedParties"`
// AllowMissingSubject permits tokens without 'sub' claim
AllowMissingSubject bool `yaml:"allowMissingSubject"`
}
OIDCClaims represents JWT token claims validation configuration. It defines requirements for validating claims in OIDC tokens including required claims, expected values, audience, scopes, and authorized parties.
func (*OIDCClaims) Validate ¶
func (c *OIDCClaims) Validate() error
Validate performs validation on the OIDCClaims configuration. It validates that required fields are not empty and that authorized parties are provided when RequireAuthorizedParty is enabled.
Returns an error if any validation rules fail.
type OIDCExpression ¶
type OIDCExpression struct {
// Expression is the CEL expression to evaluate (required)
Expression string `yaml:"expression"`
// Name is the rule identifier used in error messages (optional)
Name string `yaml:"name"`
}
OIDCExpression represents a CEL expression for custom token validation. It allows defining custom validation logic with optional name and error message.
func (*OIDCExpression) Validate ¶
func (e *OIDCExpression) Validate() error
Validate performs validation on the OIDCExpression configuration. It validates that the expression is not empty.
Returns an error if any validation rules fail.
type OIDCIntrospection ¶
type OIDCIntrospection struct {
// ClientId is the OAuth2 client identifier for introspection endpoint authentication
ClientId string `yaml:"clientId"`
// ClientSecret is the OAuth2 client secret for introspection endpoint authentication
ClientSecret Secret `yaml:"clientSecret"`
}
OIDCIntrospection represents RFC 7662 token introspection configuration. It enables checking token revocation status with the authorization server.
func (*OIDCIntrospection) Validate ¶
func (i *OIDCIntrospection) Validate() error
Validate performs validation on the OIDCIntrospection configuration. It validates that required client credentials are present.
Returns an error if any validation rules fail.
type OIDCJwks ¶
type OIDCJwks struct {
// RefreshEnabled enables proactive JWKS refresh via an external scheduler.
RefreshEnabled bool `yaml:"refreshEnabled" default:"true"`
// RefreshSchedule is the cron expression for periodic JWKS refresh.
RefreshSchedule string `yaml:"refreshSchedule" default:"0 0 * * * *"`
// HTTPTimeout is the timeout for JWKS HTTP requests
HTTPTimeout time.Duration `yaml:"httpTimeout" default:"30s"`
}
OIDCJwks represents OIDCJwks-specific configuration. It controls the refresh behavior for JSON Web Key Sets used in token signature verification.
func DefaultOIDCJwks ¶
func DefaultOIDCJwks() OIDCJwks
DefaultOIDCJwks returns an OIDCJwks configuration with default values.
type OIDCPreset ¶
type OIDCPreset struct {
// Name is the unique preset identifier
Name string `yaml:"name"`
// Issuer is the expected issuer claim (iss) for this preset
Issuer *string `yaml:"issuer"`
// MaxTokenLifetime is the maximum acceptable token lifetime for this preset
MaxTokenLifetime time.Duration `yaml:"maxTokenLifetime"`
// Expression is a CEL expression for custom token validation logic
Expression *OIDCExpression `yaml:"expression" default:"-"`
// Claims contains optional requirements for JWT token claims validation
Claims *OIDCClaims `yaml:"claims" default:"-"`
}
OIDCPreset represents a named validation preset. Each preset defines a complete set of validation rules that can be applied to tokens.
func (*OIDCPreset) IsClaimsConfigured ¶
func (p *OIDCPreset) IsClaimsConfigured() bool
IsClaimsConfigured returns true if claims validation is configured.
func (*OIDCPreset) Validate ¶
func (p *OIDCPreset) Validate() error
Validate performs validation on the OIDCPreset configuration. It validates the preset name, issuer, and claims configuration.
Returns an error if any validation rules fail.
type OIDCPresets ¶
type OIDCPresets struct {
// List is the list of named validation presets
List []OIDCPreset `yaml:"list"`
// Selectors is the list of rules for automatic preset selection
Selectors []OIDCSelector `yaml:"selectors"`
}
OIDCPresets represents validation presets configuration. It allows defining multiple validation rule sets that can be dynamically selected based on token claims or custom logic.
func (*OIDCPresets) Validate ¶
func (p *OIDCPresets) Validate() error
Validate performs validation on the OIDCPresets configuration. It validates the list of presets and selectors, ensuring they are used together. Both presets.list and presets.selectors must be configured together or both must be empty.
Returns an error if any validation rules fail.
type OIDCRevocation ¶
type OIDCRevocation struct {
// Enabled enables revocation checking.
Enabled bool `yaml:"enabled" default:"false"`
// SyncEnabled enables periodic synchronization of the revocation storage
// via an external scheduler.
SyncEnabled bool `yaml:"syncEnabled" default:"true"`
// SyncSchedule is the cron expression for periodic revocation synchronization.
SyncSchedule string `yaml:"syncSchedule" default:"0 0 * * * *"`
// ItemType specifies what items are being revoked: "token", "jti", or "kid"
ItemType string `yaml:"itemType" default:"token"`
// Filter contains configuration for the probabilistic filter used for revocation
Filter *ProbabilisticFilterConfig `yaml:"filter"`
// Source contains configuration for fetching the revocation list
Source *OIDCRevocationSource `yaml:"source"`
}
OIDCRevocation represents token or key revocation configuration.
func DefaultOIDCRevocation ¶
func DefaultOIDCRevocation() OIDCRevocation
DefaultOIDCRevocation returns an OIDCRevocation configuration with default values.
func (*OIDCRevocation) Validate ¶
func (r *OIDCRevocation) Validate() error
Validate performs validation on the OIDCRevocation configuration.
type OIDCRevocationSource ¶
type OIDCRevocationSource struct {
// URL to fetch revoked items from
URL string `yaml:"url"`
// File path to read revoked items from
File string `yaml:"file"`
}
OIDCRevocationSource represents the source for a revocation list.
func (*OIDCRevocationSource) Validate ¶
func (s *OIDCRevocationSource) Validate() error
Validate performs validation on the OIDCRevocationSource configuration.
type OIDCSelector ¶
type OIDCSelector struct {
// Expression is the CEL expression that evaluates to true/false to select this preset
Expression string `yaml:"expression"`
// Priority determines the evaluation order (higher values = higher priority)
Priority int `yaml:"priority"`
// PresetName is the name of the preset to apply when this selector matches
PresetName string `yaml:"presetName"`
}
OIDCSelector represents a rule for automatic preset selection. Selectors are evaluated in priority order to dynamically choose validation presets based on token claims.
func (*OIDCSelector) Validate ¶
func (s *OIDCSelector) Validate() error
Validate performs validation on the OIDCSelector configuration. It validates the CEL expression, priority, and preset name.
Returns an error if any validation rules fail.
type OIDCServiceAccount ¶
type OIDCServiceAccount struct {
// ClientId is the OAuth2 client identifier for the service account
ClientId string `yaml:"clientId"`
// ClientSecret is the OAuth2 client secret for authentication
ClientSecret Secret `yaml:"clientSecret"`
// Scopes defines the OAuth2 scopes to request
Scopes []string `yaml:"scopes"`
}
OIDCServiceAccount represents service account credentials for backend-to-backend authentication. It contains OAuth2 client credentials and token validation rules specific to service accounts.
func (*OIDCServiceAccount) Validate ¶
func (sa *OIDCServiceAccount) Validate() error
Validate performs validation on the OIDCServiceAccount configuration. It validates that required credentials are present and that scopes are not empty.
Returns an error if any validation rules fail.
type OIDCValidation ¶
type OIDCValidation struct {
// Issuer is the expected issuer claim (iss) in the token
Issuer *string `yaml:"issuer"`
// Claims contains optional requirements for JWT token claims validation
Claims *OIDCClaims `yaml:"claims" default:"-"`
// MaxTokenLifetime is the maximum acceptable token lifetime
MaxTokenLifetime time.Duration `yaml:"maxTokenLifetime"`
// Expression is a CEL expression for custom token validation logic
Expression *OIDCExpression `yaml:"expression" default:"-"`
}
OIDCValidation represents token validation settings for OIDC. It contains rules for validating JWT tokens including issuer, claims, and lifetime constraints.
func (*OIDCValidation) IsClaimsConfigured ¶
func (v *OIDCValidation) IsClaimsConfigured() bool
IsClaimsConfigured returns true if claims validation is configured.
func (*OIDCValidation) Validate ¶
func (v *OIDCValidation) Validate() error
Validate performs validation on the OIDCValidation configuration. It validates the issuer URL format, claims configuration, and token lifetime constraints.
Returns an error if any validation rules fail.
type OPA ¶
type OPA struct {
// BundlePath is the filesystem path or URL to the OPA policy bundle.
// Can be a directory path (e.g., "./policies") or bundle URL.
// This field is required.
BundlePath string `yaml:"bundlePath"`
// Query is the Rego query to evaluate for authorization decisions.
// Defaults to "data.profiles.authz.allow".
Query string `yaml:"query" default:"data.profiles.authz.allow"`
// DecisionLogging enables logging of all authorization decisions.
// Useful for auditing and debugging authorization policies.
// Defaults to false.
DecisionLogging bool `yaml:"decisionLogging" default:"false"`
// Cache contains caching configuration for authorization decisions.
// If nil, caching is disabled.
Cache *OPACache `yaml:"cache" default:"-"`
// WatchBundle enables automatic reloading of policies when a bundle changes.
// Uses fsnotify to watch for filesystem changes.
// Useful for development and dynamic policy updates.
// Defaults to false.
WatchBundle bool `yaml:"watchBundle" default:"false"`
// UpdateSchedule is an optional cron schedule for periodic policy updates.
// If set, policies are reloaded according to this schedule regardless of file changes.
// Example: "*/5 * * * * *" for every 5 seconds, "@every 1m" for every minute.
// Defaults to empty (disabled).
UpdateSchedule string `yaml:"updateSchedule" default:""`
// RunOnStart determines whether to run an update cycle when the manager starts.
// Defaults to true.
RunOnStart bool `yaml:"runOnStart" default:"true"`
// FileExtensions specifies the file extensions to include when loading policies.
// Defaults to [".rego"].
FileExtensions []string `yaml:"fileExtensions" default:"[\".rego\"]"`
// IncludeData enables loading .json files as OPA data.
// When enabled, JSON files in the policy directory are loaded into OPA's data store.
// Defaults to false.
IncludeData bool `yaml:"includeData" default:"false"`
}
OPA represents Open Policy Agent configuration for authorization. It defines settings for policy evaluation, caching, and decision logging.
Example:
opa := &config.OPA{
BundlePath: "./policies",
Query: "data.authz.allow",
}
func DefaultOPA ¶
func DefaultOPA() OPA
DefaultOPA returns an OPA configuration with default values. Note: BundlePath is left as zero value since it is a required field.
type OPACache ¶
type OPACache struct {
// Enabled enables caching of authorization decisions.
// Improves performance for repeated authorization checks.
// Defaults to false.
Enabled bool `yaml:"enabled" default:"false"`
// TTL is the time-to-live for cached decisions.
// Defaults to 5 minutes.
TTL time.Duration `yaml:"ttl" default:"5m"`
}
OPACache represents caching configuration for OPA authorization decisions.
func DefaultOPACache ¶
func DefaultOPACache() OPACache
DefaultOPACache returns an OPACache configuration with default values.
type OTLPProtocol ¶
type OTLPProtocol string
OTLPProtocol represents the OTLP transport protocol.
const ( // OTLPProtocolGRPC uses gRPC transport. OTLPProtocolGRPC OTLPProtocol = "grpc" // OTLPProtocolHTTP uses HTTP transport. OTLPProtocolHTTP OTLPProtocol = "http" )
Supported OTLP protocols.
type Observability ¶
type Observability struct {
// Metrics contains configuration for the metrics collection system.
Metrics *Metrics `yaml:"metrics,omitempty" default:"-"`
// Tracing contains configuration for distributed tracing.
Tracing *Tracing `yaml:"tracing,omitempty" default:"-"`
}
Observability represents the configuration for observability features including metrics, tracing, and logging.
Example:
observability:
metrics:
enable: true
type: prometheus
namespace: myapp
tracing:
enable: true
type: otlp
serviceName: myapp
otlp:
endpoint: localhost:4317
func DefaultObservability ¶
func DefaultObservability() Observability
DefaultObservability returns an Observability configuration with default values.
func (Observability) Validate ¶
func (o Observability) Validate() error
Validate performs validation on the Observability configuration.
type Outbox ¶
type Outbox struct {
// Enabled determines whether the outbox is enabled.
// Defaults to true.
Enabled bool `yaml:"enabled" default:"true"`
// DispatchSchedule defines the cron schedule for the dispatcher.
// Example: "*/2 * * * * *" for every 2 seconds.
DispatchSchedule string `yaml:"dispatchSchedule" default:"@every 2s"`
// FetchTimeout defines the timeout for fetching unprocessed events.
// Defaults to 5 seconds.
FetchTimeout time.Duration `yaml:"fetchTimeout" default:"5s"`
// HandleTimeout defines the timeout for processing a batch of events.
// Defaults to 20 seconds.
HandleTimeout time.Duration `yaml:"handleTimeout" default:"20s"`
// UpdateTimeout defines the timeout for updating event status.
// Defaults to 5 seconds.
UpdateTimeout time.Duration `yaml:"updateTimeout" default:"5s"`
// CleanupSchedule defines the cron schedule for the cleanup task.
// Example: "0 */10 * * * *" for every 10 minutes.
CleanupSchedule string `yaml:"cleanupSchedule" default:"@every 10m"`
// UnlockSchedule defines the cron schedule for the unlocker task.
// Example: "*/11 * * * * *" for every 11 seconds.
UnlockSchedule string `yaml:"unlockSchedule" default:"@every 11s"`
// MessagesBatchSize defines the number of events fetched per batch.
// Must be between 1 and 10000 to prevent memory exhaustion.
// Defaults to 200.
MessagesBatchSize uint32 `yaml:"messagesBatchSize" default:"200"`
// RetryMaxAttempts defines the maximum number of publish attempts.
// Must be between 1 and 100 to prevent infinite retry loops.
// Defaults to 10.
RetryMaxAttempts uint32 `yaml:"retryMaxAttempts" default:"10"`
// PublishedEventsLifetime defines how long published events are retained.
// -1 means indefinite. Defaults to -1.
PublishedEventsLifetime time.Duration `yaml:"publishedEventsLifetime" default:"-1"`
// TopicCompaction enables log compaction behavior.
// Defaults to false.
TopicCompaction bool `yaml:"topicCompaction" default:"false"`
}
Outbox defines the configuration for reliable event delivery via the outbox pattern. This configuration is shared by both the generic outbox (data/outbox) and the broker-specific adapter (transport/broker/outbox).
type ProbabilisticFilter ¶
type ProbabilisticFilter struct {
// Defaults contains default settings for all filters.
Defaults *ProbabilisticFilterDefaults `yaml:"defaults"`
// Filters contains named filter configurations.
Filters map[string]*ProbabilisticFilterConfig `yaml:"filters"`
}
ProbabilisticFilter defines the configuration for probabilistic filters. Supports multiple named filters with shared defaults for existence checks optimization.
func DefaultProbabilisticFilter ¶
func DefaultProbabilisticFilter() ProbabilisticFilter
DefaultProbabilisticFilter returns a ProbabilisticFilter configuration with default values.
func (*ProbabilisticFilter) Validate ¶
func (p *ProbabilisticFilter) Validate() error
Validate performs validation of the probabilistic filter configuration. Returns an error if validation fails, nil otherwise.
type ProbabilisticFilterBloomConfig ¶
type ProbabilisticFilterBloomConfig struct {
// Storage defines the storage backend for the filter.
Storage *ProbabilisticFilterStorageType `yaml:"storage,omitempty"`
// ExpectedItems is the expected number of elements in the filter.
ExpectedItems int64 `yaml:"expectedItems"`
// FalsePositiveRate is the target false positive rate.
FalsePositiveRate *float64 `yaml:"falsePositiveRate,omitempty"`
// RebuildCron is the cron expression for periodic filter rebuild.
RebuildCron *string `yaml:"rebuildCron,omitempty"`
// RebuildOnStart enables rebuilding filter on service startup.
RebuildOnStart *bool `yaml:"rebuildOnStart,omitempty"`
// Redis defines Redis-specific configuration.
Redis *StorageRedisConfig `yaml:"redis,omitempty" default:"-"`
}
ProbabilisticFilterBloomConfig defines configuration for a specific Bloom filter.
func (*ProbabilisticFilterBloomConfig) Validate ¶
func (c *ProbabilisticFilterBloomConfig) Validate() error
Validate performs validation of the Bloom filter configuration.
type ProbabilisticFilterBloomDefaults ¶
type ProbabilisticFilterBloomDefaults struct {
// Storage defines the storage backend for the filter.
Storage ProbabilisticFilterStorageType `yaml:"storage" default:"memory"`
// FalsePositiveRate is the target false positive rate (0.01 = 1%).
FalsePositiveRate float64 `yaml:"falsePositiveRate" default:"0.01"`
// RebuildCron is the cron expression for periodic filter rebuild.
RebuildCron string `yaml:"rebuildCron" default:"0 0 * * * *"`
// RebuildOnStart enables rebuilding filter on service startup.
RebuildOnStart bool `yaml:"rebuildOnStart" default:"true"`
}
ProbabilisticFilterBloomDefaults defines default settings for Bloom filters. These values are used when not overridden in specific filter configuration.
func DefaultProbabilisticFilterBloomDefaults ¶
func DefaultProbabilisticFilterBloomDefaults() ProbabilisticFilterBloomDefaults
DefaultProbabilisticFilterBloomDefaults returns a ProbabilisticFilterBloomDefaults with default values.
func (*ProbabilisticFilterBloomDefaults) Validate ¶
func (c *ProbabilisticFilterBloomDefaults) Validate() error
Validate performs validation of the Bloom defaults configuration.
type ProbabilisticFilterConfig ¶
type ProbabilisticFilterConfig struct {
// Type defines the type of probabilistic filter to use.
Type ProbabilisticFilterType `yaml:"type" default:"bloom"`
// Bloom defines Bloom filter-specific configuration.
Bloom *ProbabilisticFilterBloomConfig `yaml:"bloom,omitempty" default:"-"`
// Cuckoo defines Cuckoo filter-specific configuration.
Cuckoo *ProbabilisticFilterCuckooConfig `yaml:"cuckoo,omitempty" default:"-"`
}
ProbabilisticFilterConfig defines configuration for a single named filter.
func (*ProbabilisticFilterConfig) Validate ¶
func (c *ProbabilisticFilterConfig) Validate() error
Validate performs validation of the filter configuration.
type ProbabilisticFilterCuckooConfig ¶
type ProbabilisticFilterCuckooConfig struct {
// Storage defines the storage backend for the filter.
Storage *ProbabilisticFilterStorageType `yaml:"storage,omitempty"`
// Capacity is the initial capacity of the filter.
Capacity int64 `yaml:"capacity"`
// FingerprintSize is the fingerprint size in bits.
FingerprintSize *int `yaml:"fingerprintSize,omitempty"`
// CapacityMultiplier is the multiplier for auto-rebuild on overflow.
CapacityMultiplier *float64 `yaml:"capacityMultiplier,omitempty"`
// MaxCapacity is the maximum capacity limit.
MaxCapacity *int64 `yaml:"maxCapacity,omitempty"`
// Redis defines Redis-specific configuration.
Redis *StorageRedisConfig `yaml:"redis,omitempty" default:"-"`
}
ProbabilisticFilterCuckooConfig defines configuration for a specific Cuckoo filter.
func (*ProbabilisticFilterCuckooConfig) Validate ¶
func (c *ProbabilisticFilterCuckooConfig) Validate() error
Validate performs validation of the Cuckoo filter configuration.
type ProbabilisticFilterCuckooDefaults ¶
type ProbabilisticFilterCuckooDefaults struct {
// Storage defines the storage backend for the filter.
Storage ProbabilisticFilterStorageType `yaml:"storage" default:"memory"`
// FingerprintSize is the fingerprint size in bits (8, 12, or 16).
FingerprintSize int `yaml:"fingerprintSize" default:"12"`
// CapacityMultiplier is the multiplier for auto-rebuild on overflow.
CapacityMultiplier float64 `yaml:"capacityMultiplier" default:"2.0"`
// MaxCapacity is the maximum capacity limit.
MaxCapacity int64 `yaml:"maxCapacity" default:"100000000"`
}
ProbabilisticFilterCuckooDefaults defines default settings for Cuckoo filters. These values are used when not overridden in specific filter configuration.
func DefaultProbabilisticFilterCuckooDefaults ¶
func DefaultProbabilisticFilterCuckooDefaults() ProbabilisticFilterCuckooDefaults
DefaultProbabilisticFilterCuckooDefaults returns a ProbabilisticFilterCuckooDefaults with default values.
func (*ProbabilisticFilterCuckooDefaults) Validate ¶
func (c *ProbabilisticFilterCuckooDefaults) Validate() error
Validate performs validation of the Cuckoo defaults configuration.
type ProbabilisticFilterDefaults ¶
type ProbabilisticFilterDefaults struct {
// Bloom contains default Bloom filter settings.
Bloom *ProbabilisticFilterBloomDefaults `yaml:"bloom"`
// Cuckoo contains default Cuckoo filter settings.
Cuckoo *ProbabilisticFilterCuckooDefaults `yaml:"cuckoo"`
}
ProbabilisticFilterDefaults defines default settings for all filters.
func DefaultProbabilisticFilterDefaults ¶
func DefaultProbabilisticFilterDefaults() ProbabilisticFilterDefaults
DefaultProbabilisticFilterDefaults returns a ProbabilisticFilterDefaults with default values.
func (*ProbabilisticFilterDefaults) Validate ¶
func (c *ProbabilisticFilterDefaults) Validate() error
Validate performs validation of the filter defaults configuration.
type ProbabilisticFilterStorageType ¶
type ProbabilisticFilterStorageType string
ProbabilisticFilterStorageType defines the storage backend for probabilistic filters.
const ( // ProbabilisticFilterStorageTypeMemory represents in-memory storage. ProbabilisticFilterStorageTypeMemory ProbabilisticFilterStorageType = "memory" // ProbabilisticFilterStorageTypeRedis represents Redis storage. ProbabilisticFilterStorageTypeRedis ProbabilisticFilterStorageType = "redis" )
type ProbabilisticFilterType ¶
type ProbabilisticFilterType string
ProbabilisticFilterType defines the type of probabilistic filter to use.
const ( // ProbabilisticFilterTypeBloom represents a Bloom filter. ProbabilisticFilterTypeBloom ProbabilisticFilterType = "bloom" // ProbabilisticFilterTypeCuckoo represents a Cuckoo filter. ProbabilisticFilterTypeCuckoo ProbabilisticFilterType = "cuckoo" )
type Redis ¶
type Redis struct {
// KeysPrefix is an optional prefix to prepend to all Redis keys.
// If nil, no prefix is used.
KeysPrefix *string `yaml:"keysPrefix"`
// ConnectionURI is a full Redis connection string (e.g. "redis://user:pass@host:6379/0").
// When set, it replaces Hosts, Username, Password, and Database.
// Mutually exclusive with Username and Password.
// Supports a single address only; for clusters with multiple seeds use Hosts.
ConnectionURI Secret `yaml:"connectionUri"`
// Username is the username for Redis authentication (Redis 6.0+).
// Leave empty for password-only authentication.
Username string `yaml:"username"`
// Password is the password for Redis authentication.
// Leave empty for no authentication.
Password Secret `yaml:"password"`
// SentinelPassword is the password for Redis Sentinel authentication.
// Used when connecting to Redis through Sentinel.
SentinelPassword Secret `yaml:"sentinelPassword"`
// MasterName is the name of the Redis master when using Sentinel.
// Required for Sentinel-based configurations.
MasterName string `yaml:"masterName"`
// Hosts is the list of Redis server addresses.
// Defaults to ["localhost:6379"].
// For clusters, specify multiple nodes. For Sentinel, specify sentinel addresses.
Hosts []string `yaml:"hosts" default:"localhost:6379"`
// Database is the Redis database number to select.
// Defaults to 0. Only applicable for standalone Redis (not clusters).
Database int `yaml:"database" default:"0,skip_zero"`
// MinIdleConnections is the minimum number of idle connections to maintain.
// Defaults to 5.
MinIdleConnections int `yaml:"minIdleConnections" default:"5"`
// MaxRedirects is the maximum number of redirects for Redis Cluster.
// Defaults to 3.
MaxRedirects int `yaml:"maxRedirects" default:"3"`
// PoolSize is the maximum number of connections in the connection pool.
// Defaults to 100.
PoolSize int `yaml:"poolSize" default:"100"`
// MaxConnectionAge is the maximum lifetime of a connection.
// Set to 0 for no age limit (default).
MaxConnectionAge time.Duration `yaml:"maxConnectionAge" default:"0s"`
// ConnectTimeout is the maximum time to wait for a connection to be established.
// Defaults to 5 seconds.
ConnectTimeout time.Duration `yaml:"connectTimeout" default:"5s"`
// SocketTimeout is the maximum time to wait for socket reads and writes.
// Defaults to 5 seconds.
SocketTimeout time.Duration `yaml:"socketTimeout" default:"5s"`
// IdleTimeout is the maximum time a connection can be idle before being closed.
// Defaults to 5 seconds.
IdleTimeout time.Duration `yaml:"idleTimeout" default:"5s"`
// ReadOnly enables read-only mode for Redis Cluster connections.
// When true, read commands are routed to replica nodes.
ReadOnly bool `yaml:"readOnly"`
// RouteByLatency enables routing to the Redis node with lowest latency.
// Only applicable for Redis Cluster.
RouteByLatency bool `yaml:"routeByLatency"`
// RouteRandomly enables random routing to Redis nodes.
// Only applicable for Redis Cluster.
RouteRandomly bool `yaml:"routeRandomly"`
}
Redis represents the configuration for Redis database connections. It contains all necessary parameters for connecting to Redis including authentication, connection pooling, timeouts, and cluster/sentinel settings.
When ConnectionURI is set it takes priority over Hosts and authentication fields (Username, Password). Fields not expressible through the URI (pool sizes, timeouts, sentinel, routing) are applied on top. Note: ConnectionURI with redis.ParseURL supports a single address only — for multi-node clusters use Hosts instead.
Example:
redis := &config.Redis{
Hosts: []string{"redis1:6379", "redis2:6379"},
Password: "secret",
}
func DefaultRedis ¶
func DefaultRedis() Redis
DefaultRedis returns a Redis configuration with default values.
func (*Redis) UseConnectionURI ¶
UseConnectionURI reports whether ConnectionURI is set and should be used instead of Hosts and individual authentication fields.
func (*Redis) Validate ¶
Validate performs validation on the Redis configuration. It validates hosts, timeout durations, and key prefix settings to ensure they meet Redis client requirements.
When ConnectionURI is set, Hosts are not required and authentication fields (Username, Password) must not be set (conflict error).
Returns an error if any validation rules fail.
type ReplayPolicy ¶
type ReplayPolicy string
ReplayPolicy defines how messages are replayed from the stream.
const ( // ReplayPolicyInstant replays messages as fast as possible. ReplayPolicyInstant ReplayPolicy = "instant" // ReplayPolicyOriginal replays messages at the original rate they were received. ReplayPolicyOriginal ReplayPolicy = "original" )
type RequestsLimiter ¶
type RequestsLimiter struct {
// Rate is the maximum number of requests allowed per period.
// Defaults to 2500 requests per period.
// This represents the sustained request rate over the configured period.
Rate int `yaml:"rate" default:"2500"`
// Period is the time window for the rate limit.
// Defaults to 24 hours.
// The rate limit resets every period.
Period time.Duration `yaml:"period" default:"24h"`
// Burst is the maximum number of requests that can be processed
// in a short burst above the sustained rate.
// Defaults to 100 requests.
// This allows handling traffic spikes while maintaining overall rate limits.
Burst int `yaml:"burst" default:"100"`
}
RequestsLimiter represents the configuration for rate limiting HTTP requests. It implements a token bucket algorithm to control the rate of incoming requests and prevent system overload while allowing burst traffic.
func DefaultRequestsLimiter ¶
func DefaultRequestsLimiter() RequestsLimiter
DefaultRequestsLimiter returns a RequestsLimiter configuration with default values.
func (*RequestsLimiter) Validate ¶
func (l *RequestsLimiter) Validate() error
Validate performs validation on the RequestsLimiter configuration. It ensures that rate, period, and burst values are properly specified and within acceptable ranges for rate limiting functionality.
Returns an error if any validation rules fail.
type S3 ¶
type S3 struct {
// Endpoint is the S3 service endpoint URL.
// Defaults to "http://localhost:9000" for local MinIO development.
// For AWS S3, use regional endpoints like "https://s3.us-west-2.amazonaws.com".
Endpoint string `yaml:"endpoint" default:"http://localhost:9000"`
// AccessKey is the access key ID for S3 authentication.
// This is required and should be kept secure.
AccessKey Secret `yaml:"accessKey"`
// SecretKey is the secret access key for S3 authentication.
// This is required and should be kept secure.
SecretKey Secret `yaml:"secretKey"`
// PathStyle enables path-style addressing instead of virtual-hosted-style.
// Use for MinIO or S3-compatible services that do not support virtual-hosted-style URLs.
PathStyle bool `yaml:"pathStyle"`
// Region is the AWS region for the S3 bucket (e.g. "us-east-1", "eu-west-1").
// This is required for proper request signing and endpoint resolution.
Region string `yaml:"region"`
}
S3 represents the configuration for Amazon S3 or S3-compatible storage services. It contains the necessary authentication and connection details for accessing S3-compatible object storage.
Example:
s3 := &config.S3{
Endpoint: "https://s3.amazonaws.com",
AccessKey: "$__secret{s3:accessKey}",
SecretKey: "$__secret{s3:secretKey}",
}
type STS ¶
type STS struct {
// MaxAge specifies how long browsers should enforce HTTPS-only access
// Default is 8760h (1 year)
MaxAge time.Duration `yaml:"maxAge" default:"8760h"`
}
STS configures Http Strict Transport Security (HSTS) headers. HSTS instructs browsers to only access the site over HTTPS for a specified duration.
type SamplerType ¶
type SamplerType string
SamplerType represents the type of trace sampler.
const ( // SamplerTypeAlwaysOn samples all traces. SamplerTypeAlwaysOn SamplerType = "always_on" // SamplerTypeAlwaysOff samples no traces. SamplerTypeAlwaysOff SamplerType = "always_off" // SamplerTypeTraceIDRatio samples a fraction of traces based on trace ID. SamplerTypeTraceIDRatio SamplerType = "trace_id_ratio" // SamplerTypeParentBased defers to parent span's sampling decision. SamplerTypeParentBased SamplerType = "parent_based" )
Supported sampler types.
type Scheduler ¶
type Scheduler struct {
// TickInterval is the interval for the scheduler loop to check for tasks.
// Defaults to 1 second if not specified.
TickInterval time.Duration `yaml:"tickInterval" default:"1s"`
// HistoryRetention is the duration to keep task history before cleanup.
// Defaults to 7 days (168h) if not specified.
HistoryRetention time.Duration `yaml:"historyRetention" default:"168h"`
// MaxConcurrentTasks is the maximum number of tasks that can run concurrently.
// Zero means unlimited.
// Defaults to 0 (unlimited) if not specified.
MaxConcurrentTasks int `yaml:"maxConcurrentTasks" default:"0"`
// ReservedHighPrioritySlots is the number of concurrency slots reserved for
// high priority tasks. These slots cannot be used by normal/low priority tasks.
// Defaults to 2 if not specified.
ReservedHighPrioritySlots int `yaml:"reservedHighPrioritySlots" default:"2"`
// StaleTaskTimeout is the duration after which a task stuck in Running status
// is considered stale and will be reset to Active. This handles recovery from
// process crashes where tasks were left in Running state.
// Defaults to 30 minutes if not specified.
StaleTaskTimeout time.Duration `yaml:"staleTaskTimeout" default:"30m"`
// Storage defines the storage backend configuration.
// If nil, defaults to in-memory storage.
Storage *SchedulerStorageConfig `yaml:"storage" default:"-"`
}
Scheduler configures the task scheduler service. Controls scheduler behavior including tick interval, history retention, and concurrency.
Example:
sched := &config.Scheduler{
TickInterval: time.Second,
HistoryRetention: 7 * 24 * time.Hour,
MaxConcurrentTasks: 10,
ReservedHighPrioritySlots: 2,
Storage: &config.SchedulerStorageConfig{
Type: config.SchedulerStorageTypeMongodb,
},
}
func DefaultScheduler ¶
func DefaultScheduler() Scheduler
DefaultScheduler returns a Scheduler configuration with default values.
type SchedulerStorageConfig ¶
type SchedulerStorageConfig struct {
// Type defines the storage backend type.
// Must be one of: mongodb, redis, memory.
// Defaults to "memory" if not specified.
Type SchedulerStorageType `yaml:"type" default:"memory"`
// Mongodb defines MongoDB-specific configuration.
// Required when Type is "mongodb", ignored otherwise.
Mongodb *SchedulerStorageMongoConfig `yaml:"mongodb" default:"-"`
// Redis defines Redis-specific configuration.
// Required when Type is "redis", ignored otherwise.
Redis *SchedulerStorageRedisConfig `yaml:"redis" default:"-"`
// Memory defines in-memory storage configuration.
// Optional when Type is "memory", ignored otherwise.
Memory *SchedulerStorageMemoryConfig `yaml:"memory" default:"-"`
}
SchedulerStorageConfig configures the scheduler storage backend.
Example:
storage := &config.SchedulerStorageConfig{
Type: config.SchedulerStorageTypeMongodb,
Mongodb: &config.SchedulerStorageMongoConfig{
TasksCollection: "my_tasks",
HistoryCollection: "my_history",
},
}
func DefaultSchedulerStorageConfig ¶
func DefaultSchedulerStorageConfig() SchedulerStorageConfig
DefaultSchedulerStorageConfig returns a SchedulerStorageConfig with default values.
func (*SchedulerStorageConfig) Validate ¶
func (c *SchedulerStorageConfig) Validate() error
Validate performs validation of the scheduler storage configuration. Ensures type is valid and corresponding configuration is provided when required. Returns an error if validation fails, nil otherwise.
type SchedulerStorageMemoryConfig ¶
type SchedulerStorageMemoryConfig struct {
// MaxHistoryPerTask is the maximum number of history entries kept per task.
// Defaults to 1000 if not specified.
MaxHistoryPerTask int `yaml:"maxHistoryPerTask" default:"1000"`
}
SchedulerStorageMemoryConfig contains in-memory storage settings for the scheduler.
func DefaultSchedulerStorageMemoryConfig ¶
func DefaultSchedulerStorageMemoryConfig() SchedulerStorageMemoryConfig
DefaultSchedulerStorageMemoryConfig returns a SchedulerStorageMemoryConfig with default values.
type SchedulerStorageMongoConfig ¶
type SchedulerStorageMongoConfig struct {
// TasksCollection is the MongoDB collection name for task states.
// Defaults to "scheduler_tasks" if not specified.
TasksCollection string `yaml:"tasksCollection" default:"scheduler_tasks"`
// HistoryCollection is the MongoDB collection name for task history.
// Defaults to "scheduler_history" if not specified.
HistoryCollection string `yaml:"historyCollection" default:"scheduler_history"`
}
SchedulerStorageMongoConfig contains MongoDB-specific settings for the scheduler storage.
func DefaultSchedulerStorageMongoConfig ¶
func DefaultSchedulerStorageMongoConfig() SchedulerStorageMongoConfig
DefaultSchedulerStorageMongoConfig returns a SchedulerStorageMongoConfig with default values.
type SchedulerStorageRedisConfig ¶
type SchedulerStorageRedisConfig struct {
// KeyPrefix is the Redis key prefix for scheduler data.
// Defaults to "scheduler" if not specified.
KeyPrefix string `yaml:"keyPrefix" default:"scheduler"`
// HistoryTTL is the TTL for history entries in Redis.
// Set to 0 to disable TTL (history cleaned by CleanupHistory only).
// Defaults to 0 (disabled).
HistoryTTL time.Duration `yaml:"historyTtl" default:"-"`
// MaxHistoryPerTask is the maximum number of history entries kept per task.
// Defaults to 1000 if not specified.
MaxHistoryPerTask int `yaml:"maxHistoryPerTask" default:"1000"`
}
SchedulerStorageRedisConfig contains Redis-specific settings for the scheduler storage.
func DefaultSchedulerStorageRedisConfig ¶
func DefaultSchedulerStorageRedisConfig() SchedulerStorageRedisConfig
DefaultSchedulerStorageRedisConfig returns a SchedulerStorageRedisConfig with default values.
type SchedulerStorageType ¶
type SchedulerStorageType string
SchedulerStorageType defines the storage backend type for the scheduler.
const ( // SchedulerStorageTypeMongodb represents MongoDB storage backend. SchedulerStorageTypeMongodb SchedulerStorageType = "mongodb" // SchedulerStorageTypeRedis represents Redis storage backend. SchedulerStorageTypeRedis SchedulerStorageType = "redis" // SchedulerStorageTypeMemory represents in-memory storage backend. SchedulerStorageTypeMemory SchedulerStorageType = "memory" )
type Secret ¶
type Secret string
Secret is a named string type for credential fields that redacts its value in all common output contexts (fmt, JSON, YAML, slog) to prevent accidental exposure.
Because Secret has underlying kind reflect.String, the config loader infrastructure (secret expander, reflection setter, YAML v3 decoder) works without modification.
Use Expose() when the plain-text value is intentionally needed (e.g., passing to a client library).
func (Secret) Expose ¶
Expose returns the underlying plain-text credential. Use this only when the actual value is required (e.g., passing to a client library).
func (Secret) MarshalJSON ¶
MarshalJSON implements json.Marshaler, returning a redacted JSON string.
func (Secret) MarshalText ¶
MarshalText implements encoding.TextMarshaler, returning a redacted value.
func (Secret) MarshalYAML ¶
MarshalYAML implements yaml.Marshaler, returning a redacted value.
func (Secret) SecureString ¶
func (s Secret) SecureString() *corestrings.SecureString
SecureString converts the secret into a pooled SecureString with memory zeroing. The caller must call Clear() on the returned value when done.
type Secrets ¶
type Secrets struct {
// Provider is the type of secrets storage to use.
Provider SecretsProvider `yaml:"provider" default:"memory"`
// UpdateSchedule is the cron schedule for cache updates.
// Example: "0 */5 * * * *" (every 5 minutes)
UpdateSchedule string `yaml:"updateSchedule" default:"0 */5 * * * *"`
// RunOnStart triggers an immediate update cycle when starting.
RunOnStart bool `yaml:"runOnStart" default:"true"`
// Cache contains cache configuration.
Cache SecretsCache `yaml:"cache"`
// Retry contains retry configuration for storage operations.
Retry SecretsRetry `yaml:"retry"`
// Vault contains Vault-specific configuration.
// Required when Provider is "vault".
Vault *SecretsVault `yaml:"vault"`
// GCP contains GCP Secret Manager-specific configuration.
// Required when Provider is "gcp".
GCP *SecretsGCP `yaml:"gcp"`
// Lockbox contains Yandex Cloud Lockbox-specific configuration.
// Required when Provider is "lockbox".
Lockbox *SecretsLockbox `yaml:"lockbox"`
}
Secrets defines the configuration for secrets management. Supports multiple storage providers with provider-specific settings.
Example:
secrets := &config.Secrets{
Provider: config.SecretsProviderVault,
Vault: &config.SecretsVault{MountPath: "kv", SecretPath: "myapp"},
}
func DefaultSecrets ¶
func DefaultSecrets() Secrets
DefaultSecrets returns a Secrets configuration with default values.
type SecretsCache ¶
type SecretsCache struct {
// MaxSize is the maximum number of cached entries.
// 0 means use default (1000).
MaxSize int `yaml:"maxSize" default:"1000"`
// ShardCount is the number of shards for sharded cache.
// 0 means use standard (non-sharded) cache.
ShardCount int `yaml:"shardCount" default:"0"`
}
SecretsCache configures the secrets cache behavior.
func (*SecretsCache) Validate ¶
func (c *SecretsCache) Validate() error
Validate performs validation of the SecretsCache configuration.
type SecretsGCP ¶
type SecretsGCP struct {
// ProjectID is the GCP project ID.
ProjectID string `yaml:"projectId"`
// ServiceAccountPath is the path to service account JSON file.
ServiceAccountPath string `yaml:"serviceAccountPath"`
// Labels filters secrets by GCP labels.
Labels map[string]string `yaml:"labels"`
// IgnoreInvalidKeys skips keys that fail to decode instead of returning error.
IgnoreInvalidKeys bool `yaml:"ignoreInvalidKeys" default:"false"`
}
SecretsGCP contains GCP Secret Manager-specific configuration.
func (*SecretsGCP) Validate ¶
func (g *SecretsGCP) Validate() error
Validate performs validation of the SecretsGCP configuration.
type SecretsLockbox ¶
type SecretsLockbox struct {
// FolderID is the Yandex Cloud folder ID.
FolderID string `yaml:"folderId"`
// KeyID is the service account key ID.
KeyID string `yaml:"keyId"`
// ServiceKeyID is the service account ID.
ServiceKeyID string `yaml:"serviceKeyId"`
// PrivateKeyPath is the path to the private key PEM file.
PrivateKeyPath string `yaml:"privateKeyPath"`
// Labels filters secrets by Yandex Cloud labels.
Labels map[string]string `yaml:"labels"`
// IgnoreInvalidKeys skips keys that fail to decode instead of returning error.
IgnoreInvalidKeys bool `yaml:"ignoreInvalidKeys" default:"false"`
}
SecretsLockbox contains Yandex Cloud Lockbox-specific configuration.
func (*SecretsLockbox) Validate ¶
func (l *SecretsLockbox) Validate() error
Validate performs validation of the SecretsLockbox configuration.
type SecretsProvider ¶
type SecretsProvider string
SecretsProvider defines the type of secrets storage provider.
const ( // SecretsProviderMemory uses in-memory storage (for testing/development). SecretsProviderMemory SecretsProvider = "memory" // SecretsProviderVault uses HashiCorp Vault KV v2 engine. SecretsProviderVault SecretsProvider = "vault" // SecretsProviderGCP uses Google Cloud Secret Manager. SecretsProviderGCP SecretsProvider = "gcp" // SecretsProviderLockbox uses Yandex Cloud Lockbox. SecretsProviderLockbox SecretsProvider = "lockbox" )
type SecretsRetry ¶
type SecretsRetry struct {
// MaxAttempts is the maximum number of retry attempts.
MaxAttempts int `yaml:"maxAttempts" default:"3"`
// BaseDelay is the initial delay between retries.
BaseDelay time.Duration `yaml:"baseDelay" default:"1s"`
// MaxDelay is the maximum delay between retries.
MaxDelay time.Duration `yaml:"maxDelay" default:"1m"`
// Multiplier is the exponential backoff factor.
Multiplier float64 `yaml:"multiplier" default:"2.0"`
}
SecretsRetry configures retry behavior for failed storage operations.
func (*SecretsRetry) Validate ¶
func (r *SecretsRetry) Validate() error
Validate performs validation of the SecretsRetry configuration.
type SecretsVault ¶
type SecretsVault struct {
// MountPath is the mount path for Vault KV v2 engine.
MountPath string `yaml:"mountPath" default:"kv"`
// SecretPath is the base path for secrets within the KV engine.
SecretPath string `yaml:"secretPath" default:"blitz"`
// CAS enables Check-and-Set operations for atomic updates.
CAS bool `yaml:"cas" default:"false"`
}
SecretsVault contains Vault-specific secrets provider configuration.
func DefaultSecretsVault ¶
func DefaultSecretsVault() SecretsVault
DefaultSecretsVault returns a SecretsVault configuration with default values.
type StorageMemoryConfig ¶
type StorageMemoryConfig struct {
// CleanupSchedule defines the cron schedule for the cleanup task.
// Supports standard cron format with seconds: "sec min hour day month weekday"
// (e.g., "0 */5 * * * *") or descriptor format (e.g., "@every 5m").
CleanupSchedule string `yaml:"cleanupSchedule" default:"@every 5m"`
}
StorageMemoryConfig defines common in-memory storage configuration. Contains settings for memory-based storage with cleanup schedule.
func (*StorageMemoryConfig) Validate ¶
func (c *StorageMemoryConfig) Validate() error
Validate performs validation of the memory storage configuration.
type StorageNATSConfig ¶
type StorageNATSConfig struct {
// Bucket is the name of the NATS KeyValue bucket.
// If empty, a default bucket name will be generated based on service name.
Bucket string `yaml:"bucket,omitempty"`
// Replicas defines the number of replicas for NATS KeyValue storage.
// Higher values provide better availability but increase storage overhead.
Replicas int `yaml:"replicas" default:"3"`
}
StorageNATSConfig defines common NATS-specific configuration for storage backends. Contains settings for NATS KeyValue bucket creation and replication strategy.
func (*StorageNATSConfig) Validate ¶
func (c *StorageNATSConfig) Validate() error
Validate performs validation of the NATS storage configuration. Ensures bucket names and replica counts are within acceptable limits.
type StorageRedisConfig ¶
type StorageRedisConfig struct {
// KeysPrefix is a prefix for all keys in storage.
// Useful for namespacing when sharing storage between multiple services.
KeysPrefix string `yaml:"keysPrefix,omitempty"`
}
StorageRedisConfig defines common Redis-specific configuration for storage backends. Contains Redis-specific settings for key prefixes and storage behavior.
func (*StorageRedisConfig) Validate ¶
func (c *StorageRedisConfig) Validate() error
Validate performs validation of the Redis storage configuration.
type TlsClient ¶
type TlsClient struct {
// Certificate is the path to the client certificate file.
// Used for mutual Tls authentication.
Certificate string `yaml:"certificate"`
// PrivateKey is the path to the client private key file.
// Must correspond to the client certificate.
PrivateKey string `yaml:"privateKey"`
// PrivateKeyPassword is the password for encrypted private key files.
// Leave empty if the private key is not encrypted.
PrivateKeyPassword Secret `yaml:"privateKeyPassword"`
// CACerts is a list of paths to Certificate Authority certificate files.
// Used to verify the server's certificate.
CACerts []string `yaml:"caCerts"`
// ServerName is the expected server name for certificate verification.
// Used to verify the server's certificate matches the expected hostname.
ServerName string `yaml:"serverName"`
// SkipVerify disables server certificate verification.
// WARNING: Setting this to true makes connections insecure.
// Defaults to false.
SkipVerify bool `yaml:"skipVerifyServerName" default:"false"`
}
TlsClient represents the configuration for Tls client connections. It contains certificates, private keys, and CA certificates needed for establishing secure Tls connections as a client.
type TlsClientAuth ¶
type TlsClientAuth struct {
// CACerts is a list of paths to Certificate Authority certificate files.
// Used to verify client certificates during mutual Tls authentication.
CACerts []string `yaml:"caCerts"`
// AllowCertAuth enables client certificate authentication.
// When true, clients must present valid certificates signed by the configured CAs.
AllowCertAuth bool `yaml:"allowCertAuth"`
}
TlsClientAuth represents the configuration for client certificate authentication. It defines how the server should authenticate client certificates in mutual Tls scenarios.
func (*TlsClientAuth) Normalize ¶
func (c *TlsClientAuth) Normalize()
Normalize processes the Tls client auth configuration by resolving CA certificate file paths. It attempts to locate CA certificate files using the findFile helper. This method should be called after loading configuration.
func (*TlsClientAuth) Validate ¶
func (c *TlsClientAuth) Validate() error
Validate performs validation on the Tls client auth configuration. It verifies that all CA certificate files exist.
Returns an error if any validation rules fail.
type TlsProvider ¶
type TlsProvider struct {
// File contains file-based certificate provider settings.
// Used when certificates are loaded from local files.
File *TlsProviderFile `yaml:"file" default:"-"`
// LetsEncrypt contains Let's Encrypt ACME provider settings.
// Used for automatic certificate provisioning via ACME protocol.
LetsEncrypt *TlsProviderLetsEncrypt `yaml:"letsencrypt" default:"-"`
// Vault contains HashiCorp Vault provider settings.
// Used for certificate provisioning via Vault PKI backend.
Vault *TlsProviderVault `yaml:"vault" default:"-"`
}
TlsProvider represents the configuration for Tls certificate providers. It contains provider-specific settings for obtaining Tls certificates. Only the configuration matching the specified provider type is required.
func (*TlsProvider) Validate ¶
func (c *TlsProvider) Validate() error
Validate performs validation on the Tls provider configuration. It ensures that provider-specific configurations are valid when present.
Returns an error if any validation rules fail.
type TlsProviderFile ¶
type TlsProviderFile struct {
// Certificate file path containing the PEM-encoded certificate
Certificate string `yaml:"certificate"`
// PrivateKey file path containing the PEM-encoded private key
PrivateKey string `yaml:"privateKey"`
// PrivateKeyPassword for encrypted private keys (optional)
PrivateKeyPassword Secret `yaml:"privateKeyPassword"`
}
TlsProviderFile configures file-based Tls certificate provider. It loads certificates and private keys from the filesystem, suitable for static certificate deployments where certificates are managed externally. Supports password-protected private keys for enhanced security.
func (*TlsProviderFile) Validate ¶
func (c *TlsProviderFile) Validate() error
Validate checks that the file provider configuration is valid. It ensures that both certificate and private key file paths are provided and that the files exist and are accessible.
Returns an error if validation fails.
type TlsProviderLetsEncrypt ¶
type TlsProviderLetsEncrypt struct {
// Email address for Let's Encrypt account registration and notifications
Email string `yaml:"email"`
// Domain names to include in the certificate (first domain becomes the common name)
Domain []string `yaml:"domain"`
// RenewBefore specifies when to renew the certificate before expiration
RenewBefore time.Duration `yaml:"renewBefore" default:"30m"`
// StartInternalServer enables automatic Http server for ACME challenge handling
StartInternalServer bool `yaml:"startInternalServer"`
// ListenAddress specifies the address for the internal ACME challenge server
ListenAddress *string `yaml:"listenAddress" default:"0.0.0.0:8080"`
}
TlsProviderLetsEncrypt configures Let's Encrypt ACME certificate provider. It automatically obtains and renews Tls certificates from Let's Encrypt using domain validation. Supports automatic Http server for ACME challenge handling.
func (*TlsProviderLetsEncrypt) Validate ¶
func (l *TlsProviderLetsEncrypt) Validate() error
Validate checks that the Let's Encrypt provider configuration is valid. It ensures that required fields (email, domains) are provided, validates email format, domain format, and listen address when internal server is enabled.
Returns an error if validation fails.
type TlsProviderType ¶
type TlsProviderType string
TlsProviderType defines the type of Tls certificate provider. Different providers offer different methods for obtaining and managing Tls certificates.
const ( // TlsProviderTypeFile loads certificates from local PEM files. TlsProviderTypeFile TlsProviderType = "file" // TlsProviderTypeLetsEncrypt obtains certificates automatically via the ACME protocol. TlsProviderTypeLetsEncrypt TlsProviderType = "letsencrypt" // TlsProviderTypeVault provisions certificates from a HashiCorp Vault PKI backend. TlsProviderTypeVault TlsProviderType = "vault" )
type TlsProviderVault ¶
type TlsProviderVault struct {
// CommonName sets the certificate's common name (primary domain or service name)
CommonName string `yaml:"commonName"`
// Role specifies the PKI role in Vault that defines certificate constraints and policies
Role string `yaml:"role"`
// RenewBefore specifies when to renew the certificate before expiration
RenewBefore time.Duration `yaml:"renewBefore" default:"30m"`
// SubjectAlternativeNames contains additional DNS names for the certificate
SubjectAlternativeNames []string `yaml:"subjectAlternativeNames"`
// IPSubjectAlternativeNames contains IP addresses to include in the certificate
IPSubjectAlternativeNames []string `yaml:"ipSubjectAlternativeNames"`
}
TlsProviderVault configures HashiCorp Vault PKI certificate provider. It integrates with Vault's PKI secrets engine to dynamically generate and manage certificates with automatic renewal. Supports Subject Alternative Names (SANs) for multi-domain and IP-based certificates.
func (*TlsProviderVault) Validate ¶
func (l *TlsProviderVault) Validate() error
Validate checks that the Vault provider configuration is valid. It ensures that required fields (role, common name) are provided and validates that IP addresses in Subject Alternative Names are properly formatted.
Returns an error if validation fails.
type TlsServer ¶
type TlsServer struct {
// ProviderType specifies how Tls certificates are obtained.
// Defaults to "file" for file-based certificates.
// Supported types: file, letsencrypt, vault.
ProviderType TlsProviderType `yaml:"providerType" default:"file"`
// MinTLSVersion specifies the minimum Tls version to accept.
// Defaults to "1.2". Supported values: "1.2", "1.3".
MinTLSVersion string `yaml:"minVersion" default:"1.2"`
}
TlsServer represents the configuration for Tls server settings. It defines the certificate provider and minimum Tls version for server connections.
type Tracing ¶
type Tracing struct {
// Enable determines whether tracing is enabled.
// Defaults to false.
Enable bool `yaml:"enable" default:"false"`
// Type specifies the tracing backend type.
// Valid values: "otlp", "console", "noop".
// Defaults to "otlp".
Type TracingType `yaml:"type" default:"otlp"`
// ServiceName identifies the service in traces.
// This is a required field when tracing is enabled.
ServiceName string `yaml:"serviceName"`
// ServiceVersion is the version of the service.
// Optional but recommended for identifying deployments.
ServiceVersion string `yaml:"serviceVersion"`
// Environment identifies the deployment environment (e.g., "production", "staging").
// Optional but recommended for filtering traces.
Environment string `yaml:"environment"`
// Sampler contains sampling configuration.
// Controls which traces are recorded and exported.
Sampler *TracingSampler `yaml:"sampler,omitempty" default:"-"`
// Adapters contains adapter-specific configurations.
Adapters *TracingAdapters `yaml:"adapters,omitempty" default:"-"`
}
Tracing represents the configuration for the tracing system.
Example:
tracing:
enable: true
type: otlp
serviceName: myapp
serviceVersion: 1.0.0
sampler:
type: parent_based
ratio: 0.1
adapters:
otlp:
endpoint: localhost:4317
insecure: true
func DefaultTracing ¶
func DefaultTracing() Tracing
DefaultTracing returns a Tracing configuration with default values.
type TracingAdapters ¶
type TracingAdapters struct {
// OTLP contains OTLP-specific configuration.
// Only used when Type is "otlp".
OTLP *TracingOTLP `yaml:"otlp,omitempty" default:"-"`
// Console contains console-specific configuration.
// Only used when Type is "console".
Console *TracingConsole `yaml:"console,omitempty" default:"-"`
}
TracingAdapters contains configurations for different tracing adapters.
func DefaultTracingAdapters ¶
func DefaultTracingAdapters() TracingAdapters
DefaultTracingAdapters returns a TracingAdapters with default values.
func (*TracingAdapters) Validate ¶
func (a *TracingAdapters) Validate() error
Validate performs validation on the TracingAdapters configuration.
type TracingConsole ¶
type TracingConsole struct {
// PrettyPrint enables indented JSON output.
// Defaults to true.
PrettyPrint bool `yaml:"prettyPrint" default:"true"`
// Timestamps includes timestamps in output.
// Defaults to true.
Timestamps bool `yaml:"timestamps" default:"true"`
}
TracingConsole contains console output configuration.
func DefaultTracingConsole ¶
func DefaultTracingConsole() TracingConsole
DefaultTracingConsole returns a TracingConsole with default values.
func (*TracingConsole) Validate ¶
func (c *TracingConsole) Validate() error
Validate performs validation on the TracingConsole configuration.
type TracingOTLP ¶
type TracingOTLP struct {
// Endpoint is the OTLP collector endpoint.
// For gRPC, this is typically "host:4317".
// For HTTP, this is typically "host:4318".
// Defaults to "localhost:4317".
Endpoint string `yaml:"endpoint" default:"localhost:4317"`
// Protocol specifies the transport protocol.
// Valid values: "grpc", "http".
// Defaults to "grpc".
Protocol OTLPProtocol `yaml:"protocol" default:"grpc"`
// Insecure disables TLS.
// Use for development or when connecting to a local collector.
// Defaults to false.
Insecure bool `yaml:"insecure" default:"false"`
// Headers are custom headers to send with requests.
// Useful for authentication (e.g., API keys).
Headers map[string]string `yaml:"headers,omitempty"`
// Compression enables gzip compression.
// Defaults to true.
Compression bool `yaml:"compression" default:"true"`
}
TracingOTLP contains OTLP-specific configuration.
func DefaultTracingOTLP ¶
func DefaultTracingOTLP() TracingOTLP
DefaultTracingOTLP returns a TracingOTLP with default values.
func (*TracingOTLP) Validate ¶
func (o *TracingOTLP) Validate() error
Validate performs validation on the TracingOTLP configuration.
type TracingSampler ¶
type TracingSampler struct {
// Type specifies the sampler type.
// Valid values: "always_on", "always_off", "trace_id_ratio", "parent_based".
// Defaults to "parent_based".
Type SamplerType `yaml:"type" default:"parent_based"`
// Ratio specifies the sampling ratio for trace_id_ratio and parent_based samplers.
// Must be between 0.0 and 1.0.
// 1.0 = sample all, 0.0 = sample none, 0.1 = sample 10%.
// Defaults to 1.0.
Ratio float64 `yaml:"ratio" default:"1.0"`
}
TracingSampler contains sampling configuration.
func DefaultTracingSampler ¶
func DefaultTracingSampler() TracingSampler
DefaultTracingSampler returns a TracingSampler with default values.
func (*TracingSampler) Validate ¶
func (s *TracingSampler) Validate() error
Validate performs validation on the TracingSampler configuration.
type TracingType ¶
type TracingType string
TracingType represents the type of tracing backend.
const ( // TracingTypeOTLP exports traces via OTLP protocol. TracingTypeOTLP TracingType = "otlp" // TracingTypeConsole outputs traces to console (for development). TracingTypeConsole TracingType = "console" // TracingTypeNoop disables tracing. TracingTypeNoop TracingType = "noop" )
Supported tracing types.
type Vault ¶
type Vault struct {
Auth *VaultAuth `yaml:"auth" default:"-"`
// TLS indicates we should use a secure connection while talking to Vault.
TLS *TlsClient `yaml:"tls" default:"-"`
// Host is the address of the Vault server. It may be an IP or FQDN.
Address string `yaml:"address" default:"http://localhost:8200"`
}
Vault represents the configuration for connecting to a HashiCorp Vault server. It includes authentication settings, TLS configuration, and server address.
Example:
vault := &config.Vault{
Address: "https://vault.example.com:8200",
Auth: &config.VaultAuth{Method: config.VaultAuthMethodToken, Token: ptr.Wrap("s.secret")},
}
func DefaultVault ¶
func DefaultVault() Vault
DefaultVault returns a Vault configuration with default values. Note: Auth is left as nil since it is a required field that must be configured.
type VaultAuth ¶
type VaultAuth struct {
Method VaultAuthMethod `yaml:"method" default:"token"`
Token *Secret `yaml:"token" default:"-"`
Approle *VaultAuthApprole `yaml:"approle" default:"-"`
Userpass *VaultAuthUserpass `yaml:"userpass" default:"-"`
}
VaultAuth configures authentication settings for connecting to Vault. Only one authentication method should be configured based on the Method field.
func DefaultVaultAuth ¶
func DefaultVaultAuth() VaultAuth
DefaultVaultAuth returns a VaultAuth configuration with default values. Note: Token is left as nil since it is required when using token auth method.
type VaultAuthApprole ¶
type VaultAuthApprole struct {
RoleId string `yaml:"roleId"`
SecretId Secret `yaml:"secretId"`
MountPath *string `yaml:"mountPath" default:"-"`
}
VaultAuthApprole represents the AppRole authentication method.
type VaultAuthMethod ¶
type VaultAuthMethod string
VaultAuthMethod represents the authentication method used to authenticate with Vault.
const ( // VaultAuthMethodToken uses a Vault token for authentication. VaultAuthMethodToken VaultAuthMethod = "token" // VaultAuthMethodAppRole uses AppRole authentication for machine-to-machine authentication. VaultAuthMethodAppRole VaultAuthMethod = "approle" // VaultAuthMethodUserPass uses username/password authentication for user authentication. VaultAuthMethodUserPass VaultAuthMethod = "userpass" )
type VaultAuthUserpass ¶
type VaultAuthUserpass struct {
Username string `yaml:"username"`
Password Secret `yaml:"password"`
MountPath *string `yaml:"mountPath" default:"-"`
}
VaultAuthUserpass represents the Userpass authentication method.
Source Files
¶
- auth.go
- auth_oidc.go
- broker.go
- broker_inprogress.go
- broker_outbox.go
- broker_recovery.go
- common.go
- dlock.go
- doc.go
- grpc.go
- grpc_interceptor_auth.go
- grpc_interceptor_base.go
- grpc_interceptor_cache.go
- grpc_interceptor_health.go
- grpc_interceptor_idempotency.go
- grpc_interceptor_limiter.go
- grpc_interceptor_logger.go
- grpc_interceptor_prometheus.go
- grpc_interceptor_realip.go
- grpc_interceptor_recovery.go
- grpc_interceptor_requestid.go
- grpc_interceptor_tracing.go
- grpc_interceptors.go
- health.go
- helpers.go
- http.go
- http_middleware_base.go
- http_middleware_bodylimit.go
- http_middleware_cors.go
- http_middleware_idempotency.go
- http_middleware_limiter.go
- http_middleware_logger.go
- http_middleware_prometheus.go
- http_middleware_realip.go
- http_middleware_recovery.go
- http_middleware_requestid.go
- http_middleware_securityheaders.go
- http_middleware_tracing.go
- http_middlewares.go
- http_tls.go
- idempotency.go
- leader_election.go
- limiter.go
- logger.go
- metrics.go
- mongo.go
- mongo_cred.go
- mongo_enc.go
- nats.go
- nats_consumer.go
- node.go
- observability.go
- opa.go
- probabilistic_filter.go
- redis.go
- requests_limiter.go
- s3.go
- scheduler.go
- secret.go
- secrets.go
- storage_validation.go
- tls_client.go
- tls_provider.go
- tls_provider_file.go
- tls_provider_letsencrypt.go
- tls_provider_vault.go
- tls_server.go
- tracing.go
- validation_helper.go
- vault.go
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
utils
Package utils provides internal utilities for the config package.
|
Package utils provides internal utilities for the config package. |
|
validators
Package validators provides custom validation rules for configuration fields.
|
Package validators provides custom validation rules for configuration fields. |
|
Package loader provides multi-source configuration loading with YAML/TOML backends and environment variable mapping.
|
Package loader provides multi-source configuration loading with YAML/TOML backends and environment variable mapping. |
|
backend
Package backend defines interfaces for configuration file backends.
|
Package backend defines interfaces for configuration file backends. |
|
backend/toml
Package toml provides a TOML backend for the configuration parser.
|
Package toml provides a TOML backend for the configuration parser. |
|
backend/yaml3
Package yaml3 provides a YAML backend for the configuration parser.
|
Package yaml3 provides a YAML backend for the configuration parser. |
|
secrets
Package secrets provides secret expansion functionality for configuration loading.
|
Package secrets provides secret expansion functionality for configuration loading. |