config

package
v1.0.3 Latest Latest
Warning

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

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

README

Configuration package

The configuration package owns source precedence, platform paths, decoding, and validation. Loading reads process state but does not change it.

Source precedence

Starport resolves each value in this order:

  1. A STARPORT_ process environment variable.
  2. The first environment file that defines the value.
  3. A built-in default.

The standard loader reads one platform file named config.env. It uses these locations:

Platform File
Linux and other Unix systems $XDG_CONFIG_HOME/starport/config.env, or $HOME/.config/starport/config.env when XDG_CONFIG_HOME is empty
macOS $HOME/Library/Application Support/starport/config.env
Windows %AppData%\starport\config.env

os.UserConfigDir supplies the platform root. Tests can inject a different root and environment map without changing global process state.

Managed paths

The platform configuration directory owns these defaults:

Concept Relative path
Environment file config.env
Badger data data/badger
Rate-limit rules rate_limits.yaml

Starport resolves a configured relative path from the platform configuration directory. An absolute path remains unchanged. This rule makes file behavior independent of the directory that starts the process.

Secure local defaults

The HTTP server listens on 127.0.0.1:8080. CORS and rate-limit hot reload are off until an operator enables them. A supplied credential master key must contain at least 32 bytes.

starport init --provider openai and starport init --provider ollama create the standard local file with mode 0600. Initialization creates the credential master key and the first named identity. It does not replace an existing file or identity store.

The container image explicitly listens on 0.0.0.0 because publishing a container port is an operator action. It also stores Badger data under /var/lib/starport/data/badger. Its writable configuration root is /var/lib/starport/config.

Environment variables

All external fields use the STARPORT_ prefix. For example:

STARPORT_SERVER_PORT=8080
STARPORT_STORAGE_MODE=badger
STARPORT_LOGGING_LEVEL=info

Use the configuration reference for the complete field list. Starmap acquisition credentials stay separate from Starport inference credentials.

Provider credential references

The active Starmap catalog defines each provider field. Without an explicit reference, Starport checks its conventional environment names first. It then checks the derived STARPORT_<PROVIDER>_<FIELD> value.

Set STARPORT_<PROVIDER>_<FIELD>_REFERENCE to select an explicit env:, file:, Google Cloud Secret Manager, Azure Key Vault, AWS Secrets Manager, Vault KV v2, or OpenBao KV v2 source. The reference precedes ambient values. Set the matching _REFERENCE_FALLBACK_AMBIENT value to true only when a typed not_configured result can use ambient discovery. Other source failures stay terminal.

The credential resolver owns initial resolution, caching, single-flight work, refresh, revocation, and expiry. Secret-store network access does not occur on a warmed cache hit. Direct-source material has a five-minute refresh interval by default. Set STARPORT_CREDENTIAL_SOURCES_REMOTE_REFRESH_INTERVAL to a different positive duration.

Inspection

Use these commands to inspect the resolved configuration:

starport config paths
starport config show
starport config validate

config show uses the configuration schema to replace each secret and URL with <redacted>. Loader errors report only the failed loading stage. These commands never show configured values in an error and never change process or file state. With --json, validation writes valid: false and a safe loading stage before it returns a nonzero status.

starport doctor uses the same loader. Passive diagnosis does not open storage. It does not send provider inference.

A selected cloud identity can use its authentication network during credential resolution. A selected direct secret reference can do the same. starport doctor --probe opens configured storage through a write-blocking adapter and checks the stored catalog and identity state. If Badger needs writable recovery, the probe skips storage inspection and gives recovery instructions. It also skips this inspection on platforms where Badger does not support read-only mode.

Rate-limit reload

To enable rule reload, set both values:

STARPORT_RATE_LIMITING_ENABLE_HOT_RELOAD=true
STARPORT_RATE_LIMITING_CONFIG_PATH=/absolute/path/to/rate_limits.yaml

Starport requires the rules file after an operator enables reload. The hot reloader watches its directory and also checks the file at the configured interval.

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

View Source
var (
	// ErrCredentialAliasCollision reports an ambiguous catalog-derived
	// environment name. Validation completes before any value lookup.
	ErrCredentialAliasCollision = errors.New("provider credential environment alias is ambiguous")
)

Functions

func OperatorError added in v1.0.1

func OperatorError(err error) error

OperatorError returns an error that is safe to show without configured values. It preserves the original error for programmatic inspection.

func Redacted added in v1.0.1

func Redacted(cfg *Config) map[string]any

Redacted returns an inspectable configuration tree without secret values.

Types

type BadgerConfig

type BadgerConfig struct {
	Path           string        `env:"PATH,overwrite"`
	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"`
	// contains filtered or unexported fields
}

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"`
	RemoteURL                string        `env:"REMOTE_URL" redact:"url"`
	RemoteAPIKey             string        `env:"REMOTE_API_KEY" secret:"true"`
	RemoteActivationInterval time.Duration `env:"REMOTE_ACTIVATION_INTERVAL,default=250ms"`
}

CatalogConfig selects local Starmap acquisition or one verified remote Starmap publication source. 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_"`
	CredentialSources CredentialSourcesConfig `env:",prefix=CREDENTIAL_SOURCES_"`
	Providers         ProvidersConfig
	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_"`
	// contains filtered or unexported fields
}

Config represents the complete application configuration

func LoadDevelopment added in v1.0.3

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

LoadDevelopment loads process environment settings without a configuration file and applies the guarded development runtime contract.

func LoadWithDefaults

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

LoadWithDefaults loads configuration from the standard sources.

func MustLoad

func MustLoad(ctx context.Context) *Config

MustLoad loads configuration and panics if loading fails.

func (*Config) ConfigureDevelopmentRuntime added in v1.0.3

func (c *Config) ConfigureDevelopmentRuntime()

ConfigureDevelopmentRuntime selects process-local settings that cannot expose a development gateway or create persistent state.

func (*Config) EnableProvider added in v1.0.2

func (c *Config) EnableProvider(providerID catalogs.ProviderID)

EnableProvider marks one exact catalog provider for operator credential resolution. Catalog membership and adapter activation remain independent.

func (*Config) ResolveProviderRuntime added in v1.0.3

func (c *Config) ResolveProviderRuntime(
	ctx context.Context,
	provider catalogs.Provider,
	explicit ProviderConfig,
	refresh bool,
) (ProviderConfig, bool, error)

ResolveProviderRuntime resolves one catalog provider. Refresh bypasses a fresh cache entry but preserves valid cached material after a transient source failure.

func (*Config) ResolveProviderSet added in v1.0.2

func (c *Config) ResolveProviderSet(
	ctx context.Context,
	providers catalogs.ProvidersReader,
	settings ProvidersConfig,
) (ProvidersConfig, error)

ResolveProviderSet resolves one deployment-owned provider configuration against an exact catalog without changing the supplied settings.

func (*Config) ResolveProviderSetLocalIsolated added in v1.0.3

func (c *Config) ResolveProviderSetLocalIsolated(
	ctx context.Context,
	providers catalogs.ProvidersReader,
	settings ProvidersConfig,
) (ProvidersConfig, []ProviderResolutionFailure, error)

ResolveProviderSetLocalIsolated resolves startup-local environment fields without contacting a remote secret source or cloud identity endpoint. The background reconciler owns external source discovery.

func (*Config) ResolveProviders added in v1.0.2

func (c *Config) ResolveProviders(ctx context.Context, providers catalogs.ProvidersReader) error

ResolveProviders resolves named inference material from the active Starmap provider collection. It validates the complete alias namespace before the first environment read.

func (*Config) Validate

func (c *Config) Validate() error

Validate performs validation on the configuration

func (*Config) ValidateProviderCredentialContracts added in v1.0.3

func (c *Config) ValidateProviderCredentialContracts(
	providers []catalogs.Provider,
) error

ValidateProviderCredentialContracts validates the catalog-wide inference credential namespace before any source access.

type CredentialReference added in v1.0.2

type CredentialReference struct {
	Reference       string `json:"reference"`
	FallbackAmbient bool   `json:"fallback_ambient,omitempty"`
}

CredentialReference selects one explicit source for a catalog credential field. Ambient fallback applies only to a not-configured source result.

type CredentialSourcesConfig added in v1.0.2

type CredentialSourcesConfig struct {
	RemoteRefreshInterval time.Duration `env:"REMOTE_REFRESH_INTERVAL,default=5m"`
	ReconcileInterval     time.Duration `env:"RECONCILE_INTERVAL,default=1m"`
	ReconcileTimeout      time.Duration `env:"RECONCILE_TIMEOUT,default=10s"`
}

CredentialSourcesConfig defines direct inference secret-source lifecycle.

func (*CredentialSourcesConfig) Validate added in v1.0.2

func (c *CredentialSourcesConfig) Validate() error

Validate validates the direct inference secret-source lifecycle.

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 reads configuration without changing process state.

func NewLoader

func NewLoader() *Loader

NewLoader creates a loader for the process environment and platform paths.

func (*Loader) Load

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

Load resolves configuration sources, applies defaults, and validates the result.

func (*Loader) LoadDevelopment added in v1.0.3

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

LoadDevelopment reads process settings, applies the guarded development runtime contract, and validates the result.

func (*Loader) WithEnvFiles

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

WithEnvFiles sets environment files in descending precedence order. An empty list disables file loading.

func (*Loader) WithEnvironment added in v1.0.1

func (l *Loader) WithEnvironment(values map[string]string) *Loader

WithEnvironment replaces the process environment source.

func (*Loader) WithPaths added in v1.0.1

func (l *Loader) WithPaths(paths Paths) *Loader

WithPaths replaces platform path resolution.

func (*Loader) WithPrefix

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

WithPrefix sets the 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 Paths added in v1.0.1

type Paths struct {
	ConfigDir      string `json:"config_dir"`
	ConfigFile     string `json:"config_file"`
	DataDir        string `json:"data_dir"`
	BadgerDir      string `json:"badger_dir"`
	RateLimitsFile string `json:"rate_limits_file"`
}

Paths contains the platform-owned files and directories that Starport uses.

func PathsForConfigDir added in v1.0.1

func PathsForConfigDir(configDir string) Paths

PathsForConfigDir derives all managed paths from one configuration directory.

func PlatformPaths added in v1.0.1

func PlatformPaths() (Paths, error)

PlatformPaths resolves the current user's Starport paths.

type ProviderConfig

type ProviderConfig struct {
	BaseURL              string                                                     `redact:"url"`
	CredentialReferences map[catalogs.ProviderCredentialFieldID]CredentialReference `json:"credential_references,omitempty"`
	Material             credentials.Material                                       `json:"-"`
	CredentialSource     credentials.MaterialSource                                 `json:"-"`
	Timeout              time.Duration                                              `json:"timeout"`
	MaxConnections       int                                                        `json:"max_connections"`
	Enabled              bool                                                       `json:"enabled"`
}

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 ProviderResolutionFailure added in v1.0.3

type ProviderResolutionFailure struct {
	ProviderID catalogs.ProviderID
	Err        error
}

ProviderResolutionFailure identifies one provider whose inference material could not be resolved. It contains no credential material.

type ProvidersConfig

type ProvidersConfig map[catalogs.ProviderID]ProviderConfig

ProvidersConfig stores inference settings by exact Starmap provider ID. Provider membership comes from the active catalog, not this map.

func CloneProvidersConfig added in v1.0.2

func CloneProvidersConfig(source ProvidersConfig) ProvidersConfig

CloneProvidersConfig returns a caller-owned copy of deployment provider settings. Material and source values are immutable handles.

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=false"`
	ConfigPath          string        `env:"CONFIG_PATH,overwrite"`
	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" secret:"true"`
	TLSCertPath        string `env:"TLS_CERT_PATH"`
	TLSKeyPath         string `env:"TLS_KEY_PATH"`
	EnableTLS          bool   `env:"ENABLE_TLS,default=false"`
	AllowedOrigins     string `env:"ALLOWED_ORIGINS"`
	EnableCORS         bool   `env:"ENABLE_CORS,default=false"`
	JWTSecret          string `env:"JWT_SECRET" secret:"true"`
	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=127.0.0.1"`
	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) RuntimeStorage added in v1.0.1

func (c StorageConfig) RuntimeStorage() storage.Config

RuntimeStorage projects external storage settings into the storage adapter contract.

func (*StorageConfig) Validate

func (c *StorageConfig) Validate() error

Validate validates StorageConfig

type ValkeyConfig

type ValkeyConfig struct {
	URL            string        `env:"URL,default=valkey://localhost:6379" redact:"url"`
	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" secret:"true"`
}

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