config

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2026 License: AGPL-3.0 Imports: 17 Imported by: 0

README

Configuration Package

This package provides a comprehensive configuration system for Starport with support for:

  • Environment variables
  • .env files (with local.env taking precedence)
  • Type-safe configuration with validation
  • Hot reload for rate limit rules

Configuration Loading

The configuration is loaded in the following order of precedence:

  1. Environment variables
  2. local.env file (if exists)
  3. .env file (if exists)
  4. Default values

Configuration Structure

The main configuration struct includes:

  • Server: HTTP server settings (port, timeouts, etc.)
  • Storage: Storage backend configuration (Badger or Valkey)
  • Providers: LLM provider settings (OpenAI, Anthropic, Google AI Studio, Vertex AI, Groq, Mistral, Azure, Ollama)
  • RateLimiting: Rate limiting configuration with hot reload support
  • Security: Security settings (TLS, CORS, JWT)
  • Logging: Logging configuration

Environment Variables

All configuration can be set via environment variables with the STARPORT_ prefix:

STARPORT_SERVER_PORT=8080
STARPORT_STORAGE_MODE=badger
STARPORT_LOGGING_LEVEL=info

See .env.example for a complete list of available variables.

Hot Reload

Rate limit rules can be hot-reloaded from a YAML file without restarting the server:

# config/rate_limits.yaml
version: "1.0"
rules:
  "sk-premium-key":
    requests_per_minute: 600
    tokens_per_minute: 1000000
models:
  "gpt-4":
    requests_per_minute: 20
    tokens_per_minute: 40000

Enable hot reload by setting:

STARPORT_RATE_LIMITING_ENABLE_HOT_RELOAD=true
STARPORT_RATE_LIMITING_CONFIG_PATH=./config/rate_limits.yaml

Usage

// Load configuration
cfg, err := config.LoadWithDefaults(ctx)
if err != nil {
    log.Fatal(err)
}

// Initialize hot reloader if enabled
if cfg.RateLimiting.EnableHotReload {
    hotReloader, err := config.NewHotReloader(
        cfg.RateLimiting.ConfigPath,
        cfg.RateLimiting.ReloadCheckInterval,
    )
    if err == nil {
        hotReloader.Start(ctx)
        defer hotReloader.Stop()
    }
}

Validation

All configuration is validated on load. The validation includes:

  • Port numbers must be between 1-65535
  • Timeouts must be positive
  • Storage modes must be "badger" or "valkey"
  • Log levels must be valid (trace, debug, info, warn, error, fatal, panic)
  • TLS certificate paths must exist if TLS is enabled
  • Rate limit values must be non-negative

Documentation

Overview

Package config provides configuration management for Starport. It supports loading configuration from environment variables and .env files, with comprehensive validation and hot reload capabilities for rate limiting rules.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BadgerConfig

type BadgerConfig struct {
	Path           string        `env:"PATH,default=./data/starport"`
	SyncWrites     bool          `env:"SYNC_WRITES,default=false"`
	Compression    string        `env:"COMPRESSION,default=snappy"`
	GCInterval     time.Duration `env:"GC_INTERVAL,default=5m"`
	GCDiscardRatio float64       `env:"GC_DISCARD_RATIO,default=0.5"`
}

BadgerConfig defines Badger DB settings

func (*BadgerConfig) Validate

func (c *BadgerConfig) Validate() error

Validate validates BadgerConfig

type CacheConfig

type CacheConfig struct {
	Enabled bool `env:"ENABLED,default=true"`
}

CacheConfig defines cache settings

type CatalogConfig

type CatalogConfig struct {
	WorkspacePath   string        `env:"WORKSPACE_PATH"`
	RefreshOnStart  bool          `env:"REFRESH_ON_START,default=false"`
	RefreshInterval time.Duration `env:"REFRESH_INTERVAL,default=0s"`
	RefreshTimeout  time.Duration `env:"REFRESH_TIMEOUT,default=2m"`
}

CatalogConfig defines Starmap acquisition and tenant workspace settings. Acquisition credentials remain in Starmap's provider environment contract.

func (*CatalogConfig) Validate

func (c *CatalogConfig) Validate() error

Validate validates Starmap catalog acquisition settings.

type ChatUIConfig

type ChatUIConfig struct {
	Enabled bool   `env:"ENABLED,default=false"`
	Title   string `env:"TITLE,default=Starport Chat"`
	Theme   string `env:"THEME,default=light"`
}

ChatUIConfig defines settings for the embedded chat UI

func (*ChatUIConfig) Validate

func (c *ChatUIConfig) Validate() error

Validate validates ChatUIConfig

type Config

type Config struct {
	Server       ServerConfig       `env:",prefix=SERVER_"`
	Storage      StorageConfig      `env:",prefix=STORAGE_"`
	Catalog      CatalogConfig      `env:",prefix=CATALOG_"`
	Providers    ProvidersConfig    `env:",prefix=PROVIDERS_"`
	RateLimiting RateLimitingConfig `env:",prefix=RATE_LIMITING_"`
	Security     SecurityConfig     `env:",prefix=SECURITY_"`
	Logging      LoggingConfig      `env:",prefix=LOGGING_"`
	Cache        CacheConfig        `env:",prefix=CACHE_"`
	ChatUI       ChatUIConfig       `env:",prefix=CHATUI_"`
}

Config represents the complete application configuration

func LoadWithDefaults

func LoadWithDefaults(ctx context.Context) (*Config, error)

LoadWithDefaults loads configuration with default settings

func MustLoad

func MustLoad(ctx context.Context) *Config

MustLoad loads configuration and panics on error

func (*Config) Validate

func (c *Config) Validate() error

Validate performs validation on the configuration

type HotReloader

type HotReloader struct {
	// contains filtered or unexported fields
}

HotReloader manages hot-reloading of configuration files

func NewHotReloader

func NewHotReloader(configPath string, checkInterval time.Duration) (*HotReloader, error)

NewHotReloader creates a new hot reloader

func (*HotReloader) GetRateLimitRules

func (h *HotReloader) GetRateLimitRules() *RateLimitRules

GetRateLimitRules returns the current rate limit rules

func (*HotReloader) GetRuleForKey

func (h *HotReloader) GetRuleForKey(keyID string) (*RateLimitRule, bool)

GetRuleForKey returns the rate limit rule for a specific API key

func (*HotReloader) GetRuleForModel

func (h *HotReloader) GetRuleForModel(model string) (*RateLimitRule, bool)

GetRuleForModel returns the rate limit rule for a specific model

func (*HotReloader) OnUpdate

func (h *HotReloader) OnUpdate(callback func(*RateLimitRules))

OnUpdate registers a callback to be called when configuration is updated

func (*HotReloader) Start

func (h *HotReloader) Start(ctx context.Context) error

Start begins the hot reload monitoring

func (*HotReloader) Stop

func (h *HotReloader) Stop()

Stop stops the hot reloader

type Loader

type Loader struct {
	// contains filtered or unexported fields
}

Loader handles configuration loading from multiple sources

func NewLoader

func NewLoader() *Loader

NewLoader creates a new configuration loader

func (*Loader) Load

func (l *Loader) Load(ctx context.Context) (*Config, error)

Load loads configuration from environment variables and .env files

func (*Loader) WithEnvFiles

func (l *Loader) WithEnvFiles(files ...string) *Loader

WithEnvFiles sets custom env files to load (in order of precedence)

func (*Loader) WithPrefix

func (l *Loader) WithPrefix(prefix string) *Loader

WithPrefix sets a custom environment variable prefix

type LoggingConfig

type LoggingConfig struct {
	Level      string `env:"LEVEL,default=info"`
	Format     string `env:"FORMAT,default=json"`
	Output     string `env:"OUTPUT,default=stdout"`
	FilePath   string `env:"FILE_PATH"`
	MaxSize    int    `env:"MAX_SIZE,default=100"`
	MaxBackups int    `env:"MAX_BACKUPS,default=3"`
	MaxAge     int    `env:"MAX_AGE,default=7"`
	Compress   bool   `env:"COMPRESS,default=true"`
}

LoggingConfig defines logging settings

func (*LoggingConfig) Validate

func (c *LoggingConfig) Validate() error

Validate validates LoggingConfig

type ProviderConfig

type ProviderConfig struct {
	BaseURL        string        `env:"BASE_URL"`
	APIKey         string        `env:"API_KEY"`
	Timeout        time.Duration `env:"TIMEOUT,default=30s"`
	MaxConnections int           `env:"MAX_CONNECTIONS,default=100"`
	Enabled        bool          `env:"ENABLED"` // Used for optional providers like Ollama
	ProjectID      string        `env:"PROJECT_ID"`
	Location       string        `env:"LOCATION"`
}

ProviderConfig defines settings for a single LLM provider

func (*ProviderConfig) Validate

func (c *ProviderConfig) Validate() error

Validate validates ProviderConfig

type ProviderEntry

type ProviderEntry struct {
	ProviderID catalogs.ProviderID
	Config     ProviderConfig
}

ProviderEntry binds external operator configuration to one exact Starmap provider ID.

type ProvidersConfig

type ProvidersConfig struct {
	OpenAI         ProviderConfig `env:",prefix=OPENAI_"`
	Anthropic      ProviderConfig `env:",prefix=ANTHROPIC_"`
	GoogleAIStudio ProviderConfig `env:",prefix=GOOGLE_AI_STUDIO_"`
	GoogleVertexAI ProviderConfig `env:",prefix=GOOGLE_VERTEX_"`
	Groq           ProviderConfig `env:",prefix=GROQ_"`
	Mistral        ProviderConfig `env:",prefix=MISTRAL_"`
	Azure          ProviderConfig `env:",prefix=AZURE_OPENAI_"`
	Ollama         ProviderConfig `env:",prefix=OLLAMA_"`
}

ProvidersConfig defines LLM provider settings

func (ProvidersConfig) Entries

func (c ProvidersConfig) Entries() []ProviderEntry

Entries returns all supported external configuration slots. Adapter semantics and provider membership remain outside the configuration package.

func (*ProvidersConfig) Validate

func (c *ProvidersConfig) Validate() error

Validate validates each active provider configuration.

type RateLimitRule

type RateLimitRule struct {
	Name              string  `yaml:"name"`
	RequestsPerMinute int     `yaml:"requests_per_minute"`
	RequestsPerHour   int     `yaml:"requests_per_hour"`
	TokensPerMinute   int     `yaml:"tokens_per_minute"`
	TokensPerHour     int     `yaml:"tokens_per_hour"`
	BurstMultiplier   float64 `yaml:"burst_multiplier"`
}

RateLimitRule represents a rate limit configuration that can be hot-reloaded

type RateLimitRules

type RateLimitRules struct {
	Version string                   `yaml:"version"`
	Rules   map[string]RateLimitRule `yaml:"rules"`
	Models  map[string]RateLimitRule `yaml:"models"`
}

RateLimitRules represents the hot-reloadable rate limit configuration

type RateLimitingConfig

type RateLimitingConfig struct {
	// Global limits
	GlobalRequestsPerSecond int     `env:"GLOBAL_REQUESTS_PER_SECOND,default=10000"`
	GlobalBurstMultiplier   float64 `env:"GLOBAL_BURST_MULTIPLIER,default=2.0"`

	// Default key limits
	DefaultRequestsPerMinute int `env:"DEFAULT_REQUESTS_PER_MINUTE,default=60"`
	DefaultRequestsPerHour   int `env:"DEFAULT_REQUESTS_PER_HOUR,default=1000"`
	DefaultTokensPerMinute   int `env:"DEFAULT_TOKENS_PER_MINUTE,default=100000"`
	DefaultTokensPerHour     int `env:"DEFAULT_TOKENS_PER_HOUR,default=1000000"`
	DefaultBurst             int `env:"DEFAULT_BURST,default=10"`

	// Rate limit window
	WindowSize      time.Duration `env:"WINDOW_SIZE,default=1m"`
	SyncInterval    time.Duration `env:"SYNC_INTERVAL,default=5s"`
	CleanupInterval time.Duration `env:"CLEANUP_INTERVAL,default=10m"`

	// Hot reload settings
	EnableHotReload     bool          `env:"ENABLE_HOT_RELOAD,default=true"`
	ConfigPath          string        `env:"CONFIG_PATH,default=./config/rate_limits.yaml"`
	ReloadCheckInterval time.Duration `env:"RELOAD_CHECK_INTERVAL,default=10s"`
}

RateLimitingConfig defines rate limiting settings

func (*RateLimitingConfig) Validate

func (c *RateLimitingConfig) Validate() error

Validate validates RateLimitingConfig

type SecurityConfig

type SecurityConfig struct {
	MasterKey          string `env:"MASTER_KEY"`
	BootstrapAPIKey    string `env:"BOOTSTRAP_API_KEY"`
	TLSCertPath        string `env:"TLS_CERT_PATH"`
	TLSKeyPath         string `env:"TLS_KEY_PATH"`
	EnableTLS          bool   `env:"ENABLE_TLS,default=false"`
	AllowedOrigins     string `env:"ALLOWED_ORIGINS,default=*"`
	EnableCORS         bool   `env:"ENABLE_CORS,default=true"`
	JWTSecret          string `env:"JWT_SECRET"`
	APIKeyHeader       string `env:"API_KEY_HEADER,default=Authorization"`
	EnableRateLimiting bool   `env:"ENABLE_RATE_LIMITING,default=true"`
}

SecurityConfig defines security settings

func (*SecurityConfig) Validate

func (c *SecurityConfig) Validate() error

Validate validates SecurityConfig

type ServerConfig

type ServerConfig struct {
	Port              int           `env:"PORT,default=8080"`
	Host              string        `env:"HOST,default=0.0.0.0"`
	ReadTimeout       time.Duration `env:"READ_TIMEOUT,default=30s"`
	WriteTimeout      time.Duration `env:"WRITE_TIMEOUT,default=30s"`
	IdleTimeout       time.Duration `env:"IDLE_TIMEOUT,default=120s"`
	RequestTimeout    time.Duration `env:"REQUEST_TIMEOUT,default=60s"`
	MaxRequestSize    int64         `env:"MAX_REQUEST_SIZE,default=10485760"`
	MaxHeaderBytes    int           `env:"MAX_HEADER_BYTES,default=1048576"`
	ShutdownTimeout   time.Duration `env:"SHUTDOWN_TIMEOUT,default=30s"`
	EnableProfiling   bool          `env:"ENABLE_PROFILING,default=false"`
	EnableHealthCheck bool          `env:"ENABLE_HEALTH_CHECK,default=true"`
}

ServerConfig defines HTTP server settings

func (*ServerConfig) Validate

func (c *ServerConfig) Validate() error

Validate validates ServerConfig

type StorageConfig

type StorageConfig struct {
	Mode   string       `env:"MODE,default=badger"`
	Badger BadgerConfig `env:",prefix=BADGER_"`
	Valkey ValkeyConfig `env:",prefix=VALKEY_"`
}

StorageConfig defines storage backend settings

func (*StorageConfig) Validate

func (c *StorageConfig) Validate() error

Validate validates StorageConfig

type ValkeyConfig

type ValkeyConfig struct {
	URL            string        `env:"URL,default=valkey://localhost:6379"`
	MaxConnections int           `env:"MAX_CONNECTIONS,default=50"`
	MinIdleConns   int           `env:"MIN_IDLE_CONNS,default=10"`
	DialTimeout    time.Duration `env:"DIAL_TIMEOUT,default=5s"`
	ReadTimeout    time.Duration `env:"READ_TIMEOUT,default=3s"`
	WriteTimeout   time.Duration `env:"WRITE_TIMEOUT,default=3s"`
	IdleTimeout    time.Duration `env:"IDLE_TIMEOUT,default=5m"`
	ClusterMode    bool          `env:"CLUSTER_MODE,default=false"`
	Password       string        `env:"PASSWORD"`
}

ValkeyConfig defines Valkey/Redis settings

func (*ValkeyConfig) Validate

func (c *ValkeyConfig) Validate() error

Validate validates ValkeyConfig

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL