feat: add bounded observability and verified SLO incident alerts

This commit is contained in:
Vladislav Agapov
2026-10-29 18:01:11 +03:00
parent 470d9d6f1e
commit 6c7601802d
325 changed files with 24988 additions and 44 deletions
+53
View File
@@ -0,0 +1,53 @@
// Package config loads and validates the environment configuration of the application.
package config
import "fmt"
// Config groups settings by the component that consumes them.
type Config struct {
// HTTP configures the listener, request limits and shutdown deadline.
HTTP *Controller
// Memory configures the capacity of the process-local store.
Memory *Memory
// Logger configures structured process logging.
Logger *Logger
}
// Default returns independent configuration sections with the documented defaults.
func Default() *Config {
return &Config{
HTTP: defaultController(),
Memory: defaultMemory(),
Logger: &Logger{Level: "info"},
}
}
// New loads environment overrides and rejects invalid settings before startup.
func New() (*Config, error) {
cfg := Default()
if err := cfg.HTTP.loadEnvironment(); err != nil {
return nil, err
}
if err := cfg.Memory.loadEnvironment(); err != nil {
return nil, err
}
cfg.Logger.loadEnvironment()
if err := cfg.Validate(); err != nil {
return nil, err
}
return cfg, nil
}
// Validate verifies the presence and invariants of each configuration section.
func (cfg *Config) Validate() error {
if cfg == nil || cfg.HTTP == nil || cfg.Memory == nil || cfg.Logger == nil {
return fmt.Errorf("HTTP, Memory and Logger configuration sections are required")
}
if err := cfg.HTTP.Validate(); err != nil {
return err
}
if err := cfg.Memory.Validate(); err != nil {
return err
}
return cfg.Logger.Validate()
}
+241
View File
@@ -0,0 +1,241 @@
package config
import "testing"
// TestConfig_New checks individual environment overrides and invalid settings.
func TestConfig_New(t *testing.T) {
t.Run("Positive: APP_PORT override", func(t *testing.T) {
// Arrange.
t.Setenv("APP_PORT", "18080")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.Port != 18080 {
t.Fatalf("APP_PORT=%v, want=%v", cfg.HTTP.Port, 18080)
}
})
t.Run("Positive: REQUEST_TIMEOUT_SECONDS override", func(t *testing.T) {
// Arrange.
t.Setenv("REQUEST_TIMEOUT_SECONDS", "4")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.TimeoutSeconds != 4 {
t.Fatalf("REQUEST_TIMEOUT_SECONDS=%v, want=%v", cfg.HTTP.TimeoutSeconds, 4)
}
})
t.Run("Positive: MAX_MESSAGES override", func(t *testing.T) {
// Arrange.
t.Setenv("MAX_MESSAGES", "25")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.Memory.MaxMessages != 25 {
t.Fatalf("MAX_MESSAGES=%v, want=%v", cfg.Memory.MaxMessages, 25)
}
})
t.Run("Positive: REQUESTS_PER_SECOND override", func(t *testing.T) {
// Arrange.
t.Setenv("REQUESTS_PER_SECOND", "12")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.HTTP.Admission.RequestsPerSecond != 12 {
t.Fatalf("REQUESTS_PER_SECOND=%v, want=%v", cfg.HTTP.Admission.RequestsPerSecond, 12)
}
})
t.Run("Positive: LOG_LEVEL override", func(t *testing.T) {
// Arrange.
t.Setenv("LOG_LEVEL", "debug")
// Act.
cfg, err := New()
// Assert.
if err != nil {
t.Fatal(err)
}
if cfg.Logger.Level != "debug" {
t.Fatalf("LOG_LEVEL=%v, want=%v", cfg.Logger.Level, "debug")
}
})
cases := []struct {
name string
key string
value string
}{
{"port exceeds TCP range", "APP_PORT", "65536"},
{"zero message capacity", "MAX_MESSAGES", "0"},
{"nonnumeric body limit", "MAX_BODY_BYTES", "bad"},
{"shutdown deadline exceeds bound", "SHUTDOWN_TIMEOUT_SECONDS", "10"},
{"hostname instead of bind IP", "APP_HOST", "hostname"},
}
for _, tc := range cases {
t.Run("Negative: "+tc.name, func(t *testing.T) {
// Arrange.
t.Setenv(tc.key, tc.value)
// Act.
cfg, err := New()
// Assert.
if err == nil || cfg != nil {
t.Fatalf("invalid %s=%q returned config=%+v, error=%v", tc.key, tc.value, cfg, err)
}
})
}
}
// TestConfig_Validate rejects one missing section or invalid component per scenario.
func TestConfig_Validate(t *testing.T) {
t.Run("Negative: nil config", func(t *testing.T) {
// Arrange.
var cfg *Config
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "nil config")
}
})
t.Run("Negative: missing HTTP", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.HTTP = nil
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "missing HTTP")
}
})
t.Run("Negative: missing Memory", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Memory = nil
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "missing Memory")
}
})
t.Run("Negative: missing Logger", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Logger = nil
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "missing Logger")
}
})
t.Run("Negative: unknown log level", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Logger.Level = "unknown"
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "unknown log level")
}
})
t.Run("Negative: zero storage capacity", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.Memory.MaxUsers = 0
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "zero storage capacity")
}
})
t.Run("Negative: zero concurrency", func(t *testing.T) {
// Arrange.
cfg := Default()
cfg.HTTP.Admission.MaxInFlight = 0
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatalf("accepted %s", "zero concurrency")
}
})
}
// TestLogger_Validate rejects an absent logging section without panicking.
func TestLogger_Validate(t *testing.T) {
// Arrange.
var cfg *Logger
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatal("nil logger accepted")
}
}
// TestMemory_Validate rejects absent storage settings without panicking.
func TestMemory_Validate(t *testing.T) {
// Arrange.
var cfg *Memory
// Act.
err := cfg.Validate()
// Assert.
if err == nil {
t.Fatal("nil memory configuration accepted")
}
}
+160
View File
@@ -0,0 +1,160 @@
package config
import (
"fmt"
"net"
"os"
"strconv"
"time"
)
const (
maxTCPPort = 65535
maxShutdownTimeoutSeconds = 9
maxRequestTimeoutSeconds = 15
)
// Controller contains settings owned exclusively by the HTTP transport.
type Controller struct {
// InstanceID identifies this API process to the load balancer diagnostics.
InstanceID string
// Host is the IP address on which the listener binds.
Host string
// Port is the TCP port, in the range 1..65535.
Port int
// TimeoutSeconds limits request reads, response writes and idle connections.
TimeoutSeconds int
// ShutdownTimeoutSeconds bounds draining of active requests; it must not exceed nine seconds.
ShutdownTimeoutSeconds int
// MaxBodyBytes is the maximum accepted request body size before decoding.
MaxBodyBytes int
// MaxConnections bounds simultaneous connections handled by fasthttp.
MaxConnections int
// Admission controls business request throughput and execution concurrency.
Admission Admission
}
// Admission defines shared request policies; health endpoints bypass them.
type Admission struct {
// MaxInFlight is the maximum number of executing requests, with no waiting queue.
MaxInFlight int
// RequestsPerSecond is the token refill rate for the global admission bucket.
RequestsPerSecond int
// Burst is the bucket capacity and maximum immediate request burst.
Burst int
// AuthRate limits public registration/login attempts per second.
AuthRate int
// AuthSlots bounds concurrent password KDF work globally.
AuthSlots int
// UserRate limits each authenticated account across all groups.
UserRate int
// UserSlots bounds concurrency across one account's groups.
UserSlots int
// UserWriteRate limits one account's write attempts per second.
UserWriteRate int
// UserWriteSlots bounds one account's concurrent writes.
UserWriteSlots int
// UserAuthRate limits session-management operations per account.
UserAuthRate int
// UserAuthSlots bounds one account's session-management concurrency.
UserAuthSlots int
}
// defaultController returns the default listener, timeout and admission settings.
func defaultController() *Controller {
return &Controller{
Host: "0.0.0.0",
Port: 8080,
TimeoutSeconds: 3,
ShutdownTimeoutSeconds: 5,
MaxBodyBytes: 10 << 20,
MaxConnections: 16,
Admission: Admission{
MaxInFlight: 32,
RequestsPerSecond: 1000,
Burst: 100,
AuthRate: 100,
AuthSlots: 4,
UserRate: 100,
UserSlots: 8,
UserWriteRate: 50,
UserWriteSlots: 4,
UserAuthRate: 20,
UserAuthSlots: 2,
},
}
}
// loadEnvironment applies environment overrides to this configuration section.
func (cfg *Controller) loadEnvironment() error {
cfg.InstanceID = os.Getenv("INSTANCE_ID")
if host, exists := os.LookupEnv("APP_HOST"); exists {
cfg.Host = host
}
return loadIntegers(
integerSetting{"APP_PORT", &cfg.Port},
integerSetting{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds},
integerSetting{"SHUTDOWN_TIMEOUT_SECONDS", &cfg.ShutdownTimeoutSeconds},
integerSetting{"MAX_BODY_BYTES", &cfg.MaxBodyBytes},
integerSetting{"MAX_CONNECTIONS", &cfg.MaxConnections},
integerSetting{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight},
integerSetting{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond},
integerSetting{"REQUEST_BURST", &cfg.Admission.Burst},
integerSetting{"AUTH_RATE", &cfg.Admission.AuthRate},
integerSetting{"AUTH_SLOTS", &cfg.Admission.AuthSlots},
integerSetting{"USER_RATE", &cfg.Admission.UserRate},
integerSetting{"USER_SLOTS", &cfg.Admission.UserSlots},
integerSetting{"USER_WRITE_RATE", &cfg.Admission.UserWriteRate},
integerSetting{"USER_WRITE_SLOTS", &cfg.Admission.UserWriteSlots},
integerSetting{"USER_AUTH_RATE", &cfg.Admission.UserAuthRate},
integerSetting{"USER_AUTH_SLOTS", &cfg.Admission.UserAuthSlots},
)
}
// Validate checks listener addresses, timeouts and admission bounds.
func (cfg *Controller) Validate() error {
if cfg == nil {
return fmt.Errorf("HTTP configuration is required")
}
if cfg.TimeoutSeconds > maxRequestTimeoutSeconds {
return fmt.Errorf("REQUEST_TIMEOUT_SECONDS must not exceed %d", maxRequestTimeoutSeconds)
}
if net.ParseIP(cfg.Host) == nil {
return fmt.Errorf("APP_HOST must be an IP address")
}
if cfg.Port < 1 || cfg.Port > maxTCPPort {
return fmt.Errorf("APP_PORT must be 1..%d", maxTCPPort)
}
if cfg.ShutdownTimeoutSeconds < 1 || cfg.ShutdownTimeoutSeconds > maxShutdownTimeoutSeconds {
return fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..%d", maxShutdownTimeoutSeconds)
}
settings := []integerSetting{
{"REQUEST_TIMEOUT_SECONDS", &cfg.TimeoutSeconds},
{"MAX_BODY_BYTES", &cfg.MaxBodyBytes},
{"MAX_CONNECTIONS", &cfg.MaxConnections},
{"MAX_IN_FLIGHT", &cfg.Admission.MaxInFlight},
{"REQUESTS_PER_SECOND", &cfg.Admission.RequestsPerSecond},
{"REQUEST_BURST", &cfg.Admission.Burst},
}
for _, setting := range settings {
if err := validatePositive(setting.name, *setting.target); err != nil {
return err
}
}
return nil
}
// Bind returns the listener address, including brackets for IPv6 hosts.
func (cfg *Controller) Bind() string {
return net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port))
}
// Timeout returns the configured read, write and idle timeout.
func (cfg *Controller) Timeout() time.Duration {
return time.Duration(cfg.TimeoutSeconds) * time.Second
}
// ShutdownTimeout returns the maximum time allowed to drain active requests.
func (cfg *Controller) ShutdownTimeout() time.Duration {
return time.Duration(cfg.ShutdownTimeoutSeconds) * time.Second
}
+41
View File
@@ -0,0 +1,41 @@
package config
import (
"fmt"
"os"
"strconv"
)
const maxConfiguredInteger = 1 << 30
type integerSetting struct {
name string
target *int
}
// loadIntegers parses configured integer overrides and reports invalid values.
func loadIntegers(settings ...integerSetting) error {
for _, setting := range settings {
raw, exists := os.LookupEnv(setting.name)
if !exists {
continue
}
value, err := strconv.Atoi(raw)
if err != nil {
return fmt.Errorf("%s must be an integer", setting.name)
}
if err := validatePositive(setting.name, value); err != nil {
return err
}
*setting.target = value
}
return nil
}
// validatePositive checks that a setting is positive and within the supported range.
func validatePositive(name string, value int) error {
if value < 1 || value > maxConfiguredInteger {
return fmt.Errorf("%s must be between 1 and %d", name, maxConfiguredInteger)
}
return nil
}
+32
View File
@@ -0,0 +1,32 @@
package config
import (
"fmt"
"os"
)
// Logger configures the minimum severity written as structured JSON to stderr.
type Logger struct {
// Level is one of debug, info, warn or error; the default is info.
Level string
}
// loadEnvironment applies environment overrides to this configuration section.
func (cfg *Logger) loadEnvironment() {
if level, exists := os.LookupEnv("LOG_LEVEL"); exists {
cfg.Level = level
}
}
// Validate rejects unsupported levels rather than silently changing verbosity.
func (cfg *Logger) Validate() error {
if cfg == nil {
return fmt.Errorf("Logger configuration is required")
}
switch cfg.Level {
case "debug", "info", "warn", "error":
return nil
default:
return fmt.Errorf("LOG_LEVEL must be debug, info, warn or error")
}
}
+54
View File
@@ -0,0 +1,54 @@
package config
import "fmt"
// Memory defines logical capacity limits; MaxStateBytes is not a measurement of RSS.
type Memory struct {
// MaxUsers limits the number of registered users.
MaxUsers int
// MaxChats limits the number of immutable chats.
MaxChats int
// MaxMessages limits the total number of messages across all chats.
MaxMessages int
// MaxStateBytes limits the logical storage budget, including estimated record overhead.
MaxStateBytes int
}
// defaultMemory returns the default storage capacity limits.
func defaultMemory() *Memory {
return &Memory{
MaxUsers: 10000,
MaxChats: 10000,
MaxMessages: 100000,
MaxStateBytes: 32 << 20,
}
}
// loadEnvironment applies environment overrides to this configuration section.
func (cfg *Memory) loadEnvironment() error {
return loadIntegers(
integerSetting{"MAX_USERS", &cfg.MaxUsers},
integerSetting{"MAX_CHATS", &cfg.MaxChats},
integerSetting{"MAX_MESSAGES", &cfg.MaxMessages},
integerSetting{"MAX_STATE_BYTES", &cfg.MaxStateBytes},
)
}
// Validate rejects disabled, negative and excessively large storage limits.
func (cfg *Memory) Validate() error {
if cfg == nil {
return fmt.Errorf("Memory configuration is required")
}
settings := []integerSetting{
{"MAX_USERS", &cfg.MaxUsers},
{"MAX_CHATS", &cfg.MaxChats},
{"MAX_MESSAGES", &cfg.MaxMessages},
{"MAX_STATE_BYTES", &cfg.MaxStateBytes},
}
for _, setting := range settings {
if err := validatePositive(setting.name, *setting.target); err != nil {
return err
}
}
return nil
}
+35
View File
@@ -0,0 +1,35 @@
package config
import (
"fmt"
"os"
)
// ObjectStore contains only the S3 adapter's connection settings.
type ObjectStore struct {
// Endpoint is host:port, without a URL scheme.
Endpoint string
// Bucket is the private application bucket.
Bucket string
// AccessKey is the restricted service identity.
AccessKey string
// SecretKey is supplied by the runtime secret provider.
SecretKey string
// Secure enables certificate-verified TLS.
Secure bool
}
// NewObjectStore validates S3 settings independently of their use.
func NewObjectStore() (*ObjectStore, error) {
cfg := &ObjectStore{
Endpoint: os.Getenv("S3_ENDPOINT"),
Bucket: os.Getenv("S3_BUCKET"),
AccessKey: os.Getenv("S3_ACCESS_KEY"),
SecretKey: os.Getenv("S3_SECRET_KEY"),
Secure: os.Getenv("S3_TLS") != "false",
}
if cfg.Endpoint == "" || cfg.Bucket == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
return nil, fmt.Errorf("S3 endpoint, bucket and scoped credentials required")
}
return cfg, nil
}
+24
View File
@@ -0,0 +1,24 @@
package config
import "testing"
// TestObjectStoreConfiguration verifies mandatory credentials and opt-in local plaintext.
func TestObjectStoreConfiguration(t *testing.T) {
t.Run("missing credentials", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "")
if _, err := NewObjectStore(); err == nil {
t.Fatal("missing endpoint accepted")
}
})
t.Run("local configuration", func(t *testing.T) {
t.Setenv("S3_ENDPOINT", "localhost:9000")
t.Setenv("S3_BUCKET", "attachments")
t.Setenv("S3_ACCESS_KEY", "test")
t.Setenv("S3_SECRET_KEY", "synthetic-only")
t.Setenv("S3_TLS", "false")
cfg, err := NewObjectStore()
if err != nil || cfg.Secure || cfg.Bucket != "attachments" {
t.Fatalf("invalid result: %v", err)
}
})
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"fmt"
"os"
"strings"
)
// Persistence contains database, cache and session settings.
type Persistence struct {
// CursorKey is the shared base64 signing key supplied through a secret.
CursorKey string
// DatabaseURL identifies the PostgreSQL database.
DatabaseURL string
// Shards maps stable identities to Valkey addresses.
Shards map[string]string
// Coordinator names the stable global admission shard.
Coordinator string
// PoolSize bounds connections per dependency.
PoolSize int
// TimeoutMilliseconds bounds each dependency operation.
TimeoutMilliseconds int
// SessionTTLSeconds sets the absolute session lifetime.
SessionTTLSeconds int
}
// NewPersistence loads dependency settings separately from HTTP configuration.
func NewPersistence() (*Persistence, error) {
cfg := &Persistence{
CursorKey: os.Getenv("CURSOR_SIGNING_KEY"),
DatabaseURL: os.Getenv("DATABASE_URL"),
Coordinator: os.Getenv("VALKEY_COORDINATOR"),
Shards: make(map[string]string),
PoolSize: 8,
TimeoutMilliseconds: 1000,
SessionTTLSeconds: 3600,
}
if cfg.Coordinator == "" {
cfg.Coordinator = "shard0"
}
for _, entry := range strings.Split(os.Getenv("VALKEY_SHARDS"), ",") {
id, address, ok := strings.Cut(entry, "=")
if !ok || id == "" || address == "" || cfg.Shards[id] != "" {
return nil, fmt.Errorf("VALKEY_SHARDS requires unique id=address entries")
}
cfg.Shards[id] = address
}
if cfg.DatabaseURL == "" || cfg.Shards[cfg.Coordinator] == "" {
return nil, fmt.Errorf("DATABASE_URL and a configured VALKEY_COORDINATOR are required")
}
if err := loadIntegers(integerSetting{"DEPENDENCY_POOL_SIZE", &cfg.PoolSize}, integerSetting{"DEPENDENCY_TIMEOUT_MS", &cfg.TimeoutMilliseconds}, integerSetting{"SESSION_TTL_SECONDS", &cfg.SessionTTLSeconds}); err != nil {
return nil, err
}
return cfg, nil
}
+34
View File
@@ -0,0 +1,34 @@
package config
import "testing"
// TestPersistenceConfiguration validates independent environment configurations.
func TestPersistenceConfiguration(t *testing.T) {
cases := []struct {
name string
database string
shards string
coordinator string
ttl string
valid bool
}{
{"defaults", "postgres://localhost/test", "shard0=localhost:6379", "", "3600", true},
{"missing database", "", "shard0=localhost:6379", "", "3600", false},
{"missing coordinator", "postgres://localhost/test", "shard1=localhost:6379", "shard0", "3600", false},
{"duplicate shard", "postgres://localhost/test", "shard0=a,shard0=b", "", "3600", false},
{"invalid topology", "postgres://localhost/test", "wrong", "", "3600", false},
{"invalid ttl", "postgres://localhost/test", "shard0=a", "", "no", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("DATABASE_URL", tc.database)
t.Setenv("VALKEY_SHARDS", tc.shards)
t.Setenv("VALKEY_COORDINATOR", tc.coordinator)
t.Setenv("SESSION_TTL_SECONDS", tc.ttl)
_, err := NewPersistence()
if (err == nil) != tc.valid {
t.Fatalf("unexpected validation result: %v", err)
}
})
}
}
+47
View File
@@ -0,0 +1,47 @@
package config
import (
"fmt"
"math"
"net/url"
"os"
"strconv"
"github.com/google/uuid"
)
// Telemetry holds validated SDK settings; absence of Endpoint disables export.
type Telemetry struct {
// Endpoint is the private Collector OTLP HTTP base URL.
Endpoint string
// Service distinguishes API and worker resource identity.
Service string
// Version identifies the application build.
Version string
// Instance is stable for one process lifetime.
Instance string
// SampleRatio is bounded to [0,1].
SampleRatio float64
}
// NewTelemetry validates explicit export settings without contacting the backend.
func NewTelemetry(service string) (*Telemetry, error) {
cfg := &Telemetry{Endpoint: os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"), Service: service, Version: os.Getenv("APP_VERSION"), Instance: uuid.NewString(), SampleRatio: 1}
if cfg.Version == "" {
cfg.Version = "lab6"
}
if raw := os.Getenv("OTEL_SAMPLE_RATIO"); raw != "" {
value, err := strconv.ParseFloat(raw, 64)
if err != nil || math.IsNaN(value) || value < 0 || value > 1 {
return nil, fmt.Errorf("OTEL_SAMPLE_RATIO must be in [0,1]")
}
cfg.SampleRatio = value
}
if cfg.Endpoint != "" {
u, err := url.Parse(cfg.Endpoint)
if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" {
return nil, fmt.Errorf("OTLP endpoint must be an HTTP(S) base URL without credentials")
}
}
return cfg, nil
}
+36
View File
@@ -0,0 +1,36 @@
package config
import "testing"
// TestTelemetryConfiguration validates bounded sampling and credential-free Collector addresses.
func TestTelemetryConfiguration(t *testing.T) {
for _, tc := range []struct {
name string
endpoint string
ratio string
wantError bool
}{
{"disabled", "", "", false},
{"enabled", "http://collector:4318", "0.5", false},
{"bad ratio", "", "bad", true},
{"NaN", "", "NaN", true},
{"negative", "", "-0.1", true},
{"over one", "", "1.1", true},
{"credentials", "http://user:pass@collector:4318", "", true},
{"query", "http://collector:4318?token=x", "", true},
{"bad scheme", "ftp://collector", "", true},
{"relative", "collector:4318", "", true},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", tc.endpoint)
t.Setenv("OTEL_SAMPLE_RATIO", tc.ratio)
cfg, err := NewTelemetry("messenger-api")
if (err != nil) != tc.wantError {
t.Fatalf("configuration: %v", err)
}
if err == nil && (cfg.Instance == "" || cfg.Version == "" || cfg.Service != "messenger-api") {
t.Fatal("resource identity missing")
}
})
}
}
+25
View File
@@ -0,0 +1,25 @@
package config
import (
"fmt"
"os"
"github.com/google/uuid"
)
// Worker contains the broker address and a process-unique consumer identity.
type Worker struct {
// BrokerAddress is a private Valkey Streams endpoint.
BrokerAddress string
// Consumer is never used as an unbounded metric label.
Consumer string
}
// NewWorker requires an explicit broker separate from the admission shards.
func NewWorker() (*Worker, error) {
address := os.Getenv("BROKER_ADDRESS")
if address == "" {
return nil, fmt.Errorf("BROKER_ADDRESS is required")
}
return &Worker{BrokerAddress: address, Consumer: uuid.NewString()}, nil
}
+24
View File
@@ -0,0 +1,24 @@
package config
import "testing"
// TestWorkerConfiguration requires a broker and gives each process an independent consumer ID.
func TestWorkerConfiguration(t *testing.T) {
t.Run("missing", func(t *testing.T) {
t.Setenv("BROKER_ADDRESS", "")
if _, err := NewWorker(); err == nil {
t.Fatal("missing broker accepted")
}
})
t.Run("configured", func(t *testing.T) {
t.Setenv("BROKER_ADDRESS", "broker:6379")
first, err := NewWorker()
if err != nil {
t.Fatal(err)
}
second, err := NewWorker()
if err != nil || first.Consumer == second.Consumer || first.BrokerAddress != "broker:6379" {
t.Fatal("invalid consumer configuration")
}
})
}