config

package
v0.16.21 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 12 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package config loads and validates all server configuration from environment variables.

Index

Constants

View Source
const (
	DefaultAuthToken             = "change-me-admin-token"
	DefaultProxyToken            = "change-me-proxy-sk-token"
	DefaultCodexClientId         = "CODEX_CLIENT_ID_PLACEHOLDER"
	DefaultClaudeClientId        = "CLAUDE_CLIENT_ID_PLACEHOLDER"
	DefaultGeminiCliClientId     = "GEMINI_CLI_CLIENT_ID_PLACEHOLDER"
	DefaultGeminiCliClientSecret = "GEMINI_CLI_CLIENT_SECRET_PLACEHOLDER"

	DefaultPort    = 4000
	DefaultDataDir = "./data"
	DefaultDbType  = "sqlite"

	// DefaultLogLevel is the slog threshold applied at startup when LOG_LEVEL
	// is unset or invalid. "info" preserves the pre-config behavior so the
	// hot-path Debug downgrades stay silent unless an operator opts in.
	DefaultLogLevel = "info"

	// DbProfile selects PostgreSQL pool presets. Explicit DB_MAX_* env vars
	// always override the profile numbers. Dedicated/large-DB users can set
	// DB_PROFILE=dedicated or raise DB_MAX_OPEN_CONNS freely.
	//
	// shared-tiny — multi-tenant / role LIMIT 1–3 (e.g. shared managed PostgreSQL B1ms-class)
	// normal — default; small-to-medium single service
	// dedicated — large exclusive PostgreSQL (legacy 20/5)
	DefaultDbProfile = "normal"

	DefaultDbMaxOpenConnsSharedTiny = 2
	DefaultDbMaxIdleConnsSharedTiny = 1
	DefaultDbMaxOpenConnsNormal     = 10
	DefaultDbMaxIdleConnsNormal     = 3
	DefaultDbMaxOpenConnsDedicated  = 20
	DefaultDbMaxIdleConnsDedicated  = 5

	DefaultDbConnMaxLifetimeSec = 1800
	DefaultDbConnMaxIdleTimeSec = 300

	// RequestBodyLimit / FileUploadLimit. Parsed from MB env vars in Load:
	//   REQUEST_BODY_LIMIT_MB  (default 20, clamped [1, 200])
	//   FILE_UPLOAD_LIMIT_MB   (default 100, clamped [1, 1000])
	// DefaultRequestBodyLimit is kept as the byte equivalent of 20 MB for
	// backward-compatible struct literals in tests and callers that don't
	// run Load().
	DefaultRequestBodyLimitMB = 20
	DefaultFileUploadLimitMB  = 100
	DefaultRequestBodyLimit   = DefaultRequestBodyLimitMB * 1024 * 1024 // 20 MB

	// Per-IP rate limiting for /v1 proxy routes. Default 60 RPM per IP.
	// 0 disables the per-IP limiter entirely.
	DefaultProxyRateLimitRPM = 60

	// Pricing catalog (model data source registry: llm-metadata primary +
	// models.dev fallback by default) cold-start cost signal + marketplace
	// hydration. Refresh cadence is 12h — the primary upstream dataset is
	// rebuilt daily, so the old 60min cadence wasted bandwidth.
	// PRICING_CATALOG_URL is honored as a legacy single-source override and
	// migrated into the registry as the top-priority custom source.
	DefaultPricingCatalogEnabled    = true
	DefaultPricingCatalogRefreshMin = 720
	DefaultPricingCatalogURL        = "https://models.dev/api.json"

	// Admin/OAuth per-IP token-bucket rate limits. These mirror the original
	// hardcoded router values so existing deployments are unchanged without
	// env overrides.
	DefaultAdminRateLimitRPS   = 100
	DefaultAdminRateLimitBurst = 200
	DefaultOAuthRateLimitRPS   = 10
	DefaultOAuthRateLimitBurst = 20
	// /api/auth/* (login/logout/session/ws-ticket) gets the same strict
	// defaults as OAuth: it is the only surface that accepts the master
	// token (#1034 session model).
	DefaultAuthRateLimitRPS   = 10
	DefaultAuthRateLimitBurst = 20

	// Admin UI session defaults (#1034). 720 minutes = 12h sliding TTL,
	// matching the legacy client-side session window; the credential now
	// lives server-side (HttpOnly cookie) instead of localStorage.
	DefaultAdminSessionTTLMinutes = 720
	// "auto" sets the Secure flag based on the request protocol so local
	// plain-HTTP dev works while HTTPS deployments stay protected.
	DefaultAdminSessionCookieSecure = "auto"

	TokenRouterFailureCooldownMaxSecCeiling = 30 * 24 * 60 * 60 // 30 days

	DefaultCheckinCron          = "0 8 * * *"
	DefaultCheckinIntervalHours = 6
	DefaultBalanceRefreshCron   = "0 * * * *"
	// DefaultModelSyncCron drives the periodic upstream model-list sync
	// (MODEL_SYNC_CRON env / settings key model_sync_cron). Daily 04:00 by
	// default; operators can widen to weekly etc. via env or the settings API.
	DefaultModelSyncCron  = "0 4 * * *"
	DefaultLogCleanupCron = "0 6 * * *"

	// Site & Branding defaults. Empty means the embedded frontend branding and
	// login-page copy are used unchanged.
	DefaultSystemName    = ""
	DefaultFooter        = ""
	DefaultAbout         = ""
	DefaultServerAddress = ""

	DefaultNotifyCooldownSec = 300
	DefaultSmtpPort          = 587

	DefaultTokenRouterCacheTtlMs               = 1500
	DefaultProxyMaxChannelAttempts             = 3
	DefaultProxyStickySessionTtlMs             = 30 * 60 * 1000 // 30 minutes
	DefaultProxySessionChannelConcurrencyLimit = 2
	DefaultProxySessionChannelQueueWaitMs      = 1500
	DefaultProxySessionChannelLeaseTtlMs       = 90000
	DefaultProxySessionChannelLeaseKeepaliveMs = 15000

	DefaultModelAvailabilityProbeIntervalMs  = 30 * 60 * 1000 // 30 minutes
	DefaultModelAvailabilityProbeTimeoutMs   = 15000
	DefaultModelAvailabilityProbeConcurrency = 1

	DefaultProxyLogRetentionDays                  = 30
	DefaultProxyLogRetentionPruneIntervalMinutes  = 30
	DefaultProxyFileRetentionDays                 = 30
	DefaultProxyFileRetentionPruneIntervalMinutes = 60
	// Video task mappings: default 0 = retention disabled (no silent mass delete).
	DefaultProxyVideoTaskRetentionDays                 = 0
	DefaultProxyVideoTaskRetentionPruneIntervalMinutes = 60

	// Proxy log batch writer (async INSERT batching). Default async=true so
	// production gets the latency/lock-contention win automatically; tests and
	// e2e suites set PROXY_LOG_ASYNC=false for write-through visibility.
	DefaultProxyLogAsync           = true
	DefaultProxyLogBatchSize       = 50
	DefaultProxyLogFlushIntervalMs = 1000

	DefaultProxyDebugRetentionHours = 24
	DefaultProxyDebugMaxBodyBytes   = 262144

	// DefaultProxyMaxStreamResponseBytes caps the total bytes relayed for a
	// single SSE stream before a controlled termination (64 MB). Parsed from
	// PROXY_MAX_STREAM_RESPONSE_BYTES; 0/negative/invalid falls back to this
	// default. Read once at startup via config.Load — the stream handler reads
	// the resolved value from the config singleton, not os.Getenv per request.
	DefaultProxyMaxStreamResponseBytes = 64 << 20 // 64 MB

	// DefaultProxyMaxBufferedResponseBytes caps the total bytes read for a
	// single non-streaming upstream response before a controlled termination
	// (20 MB). Parsed from PROXY_MAX_BUFFERED_RESPONSE_BYTES; 0/negative/invalid
	// falls back to this default. Read once at startup via config.Load so the
	// buffered-response hot path reads a struct field instead of re-parsing
	// os.Getenv + strconv.ParseInt on every proxied request.
	DefaultProxyMaxBufferedResponseBytes int64 = 20 << 20 // 20 MB

	TelegramApiBaseUrl = "https://api.telegram.org"

	// DefaultLDOHBaseURL is the upstream LDOH (LdoHub) dashboard URL proxied
	// by the /monitor-proxy/ldoh/* admin surface. Parsed from LDOH_BASE_URL
	// so operators can point the monitor iframe at a self-hosted LDOH
	// instance without rebuilding the binary.
	DefaultLDOHBaseURL = "https://ldoh.105117.xyz"

	// DefaultLDOHProxyTimeoutSec is the per-request timeout for the LDOH
	// upstream HTTP client used by the /monitor-proxy/ldoh/* admin surface.
	// Parsed from LDOH_PROXY_TIMEOUT_SEC; 0/negative/invalid falls back to
	// this default. Matches the previous hardcoded 30s so existing
	// deployments are unchanged without an env override.
	DefaultLDOHProxyTimeoutSec = 30

	// Default outbound proxy / upstream HTTP timeouts in seconds (#1009).
	// Parsed from the PROXY_*_TIMEOUT_SEC env vars; 0/negative/invalid falls
	// back to these defaults at Load time. Values match the timeouts that were
	// hardcoded in platform/site_proxy.go before #1009, so deployments without
	// env overrides keep identical behavior.
	DefaultProxyConnectTimeoutSec        = 2  // TCP dial (connect) timeout
	DefaultProxyTLSHandshakeTimeoutSec   = 10 // TLS handshake timeout
	DefaultProxyResponseHeaderTimeoutSec = 30 // wait for upstream response headers
	DefaultProxyIdleConnTimeoutSec       = 90 // idle keep-alive connection TTL
	DefaultProxyRequestTimeoutSec        = 30 // whole-request http.Client timeout
	// DefaultProxyStreamIdleTimeoutSec bounds the gap between SSE chunks on a
	// flowing stream (each relayed chunk resets the window). 300 aligns with
	// new-api's STREAMING_TIMEOUT; the timeout distinguishes a stalled stream
	// from a long-but-healthy one, which the whole-request timeout cannot.
	DefaultProxyStreamIdleTimeoutSec = 300
)

Variables

This section is empty.

Functions

func ClampInt added in v0.12.0

func ClampInt(v, lo, hi int) int

ClampInt clamps v to [lo, hi].

func IsCritical

func IsCritical(err error) bool

IsCritical returns true if the error represents a fatal config issue.

func IsWarning added in v0.13.0

func IsWarning(err error) bool

IsWarning returns true if the error represents a non-fatal config warning. It is the complement of IsCritical for config errors produced by Validate.

func Load

func Load(env map[string]string) (*Config, *RuntimeSettings)

Load reads environment variables from the given map and returns a fully populated Config. The caller (main.go) is responsible for loading.env files via godotenv before calling Load.

func MaxInt

func MaxInt(a, b int) int

MaxInt returns the larger of a and b. Exported for use by other packages.

func MaxInt64 added in v0.12.0

func MaxInt64(a, b int64) int64

MaxInt64 returns the larger of a and b. Exported for use by other packages.

func ParseJsonValue

func ParseJsonValue(value string) any

ParseJsonValue parses a JSON string into an any value. Returns nil on empty input or parse error.

func Set

func Set(cfg *Config)

Set stores the global config singleton. The published Config is static: every field is frozen at boot before this call. Fields that may change at runtime live in RuntimeSettings (see SetRuntime/UpdateRuntime).

func SetRuntime added in v0.16.20

func SetRuntime(rt *RuntimeSettings)

SetRuntime publishes the initial runtime snapshot. Composition-root only (boot, after DB settings hydration) plus tests. A nil argument clears the singleton (test teardown parity with Set(nil)).

func SlogLevel added in v0.13.0

func SlogLevel(logLevel string) slog.Level

SlogLevel maps a canonical log-level string to the matching slog.Level. Callers (e.g. cmd/server/main.go) use this at startup to configure the default slog handler threshold from config.LogLevel. Unknown values fall back to LevelInfo, matching normalizeLogLevel's "info" default.

func UpdateRuntime added in v0.16.20

func UpdateRuntime(mutate func(*RuntimeSettings))

UpdateRuntime is the sole gate for runtime mutation. It copies the current snapshot, hands the private draft to mutate, and atomically publishes the result. mutate must only reassign fields on the draft it is given (wholesale replacement for slices/maps/any) and must not retain the draft pointer.

func ValidateCronExpr added in v0.12.0

func ValidateCronExpr(expr string) bool

ValidateCronExpr checks if a cron expression is parseable. Auto-normalizes 5-field expressions (minute hour dom month dow) to 6-field (second...) for compatibility with cron.WithSeconds(), matching the scheduler behavior. This is the canonical cron validation used by both config.Validate and scheduler.ValidateCronExpr.

Types

type CodexHeaderDefaults

type CodexHeaderDefaults struct {
	UserAgent    string
	BetaFeatures string
}

CodexHeaderDefaults holds Codex-specific HTTP header defaults.

type Config

type Config struct {
	AccountCredentialSecret string
	CodexClientId           string

	// OAuth Clients (4 fields)
	ClaudeClientId        string
	ClaudeClientSecret    string
	GeminiCliClientId     string
	GeminiCliClientSecret string

	// Server (7 fields)
	Port       int
	ListenHost string
	DataDir    string
	DbSslMode  string
	// PostgreSQL pool budget. Production operators must size MaxOpenConns no
	// higher than the database role CONNECTION LIMIT.
	// DbProfile is a convenience preset (shared-tiny|normal|dedicated);
	// explicit DB_MAX_* values always win when set.
	DbProfile            string
	DbMaxOpenConns       int
	DbMaxIdleConns       int
	DbConnMaxLifetimeSec int
	DbConnMaxIdleTimeSec int
	// DbApplicationName is injected into the PostgreSQL DSN as
	// application_name (default metapi-<hostname>) for pg_stat_activity.
	DbApplicationName string
	Tz                string

	// LogLevel controls the slog threshold applied at startup (env LOG_LEVEL).
	// Accepted values: debug, info, warn, error. Default "info". Raising the
	// threshold silences per-request / SSE / WS Debug-downgraded hot-path logs
	// that are already observable via Prometheus metrics, cutting log volume in
	// production without losing Warn/Error signal.
	LogLevel string

	LogCleanupConfigured bool

	// Resin sticky proxy pool (3 fields, env-only — no DDL for Tier 1).
	// RESIN_URL carries the base URL + token, e.g. http://resin.local:2260/my-token.
	// RESIN_PLATFORM_NAME is the Platform identity (falls back to site.Platform).
	// RESIN_ENABLED is the global opt-in (default false).
	ResinURL          string
	ResinPlatformName string
	ResinEnabled      bool

	// uTLS TLS fingerprint masking (1 field, env-only — no DDL for Tier 1).
	// UTLS_ENABLED is the global opt-in (default false). When true, all
	// outbound platform requests use a uTLS Chrome-ClientHello transport
	// instead of Go's default crypto/tls ClientHello, masking the JA3/JA4
	// fingerprint that Cloudflare and similar WAFs use to block automated
	// traffic. Per-site use_utls overrides this flag (see service.UTLSEnabled).
	UTLSEnabled bool

	// Outbound proxy / upstream HTTP timeouts (5 fields, env-only — no DDL).
	// Integer seconds applied to every outbound site-proxy / upstream request
	// (platform.SiteProxy, DoWithProxy, pooled transports). Parsed from the
	// PROXY_*_TIMEOUT_SEC env vars; 0/negative/invalid falls back to the
	// Default* constants at Load time, which match the pre-#1009 hardcoded
	// values so unset deployments keep identical behavior.
	ProxyConnectTimeoutSec        int // dial / TCP connect
	ProxyTLSHandshakeTimeoutSec   int // TLS handshake
	ProxyResponseHeaderTimeoutSec int // wait for upstream response headers
	ProxyIdleConnTimeoutSec       int // idle keep-alive connection TTL
	ProxyRequestTimeoutSec        int // whole-request http.Client timeout
	// ProxyStreamIdleTimeoutSec bounds the gap between SSE chunks once a
	// stream is flowing: each relayed chunk resets the window, and expiry
	// aborts the stalled stream. Parsed from PROXY_STREAM_IDLE_TIMEOUT_SEC;
	// 0/negative/invalid falls back to DefaultProxyStreamIdleTimeoutSec.
	// Unlike the five transport timeouts above this applies to the relayed
	// body phase only — non-streaming responses never see it.
	ProxyStreamIdleTimeoutSec int

	// LDOHBaseURL is the upstream LDOH dashboard URL proxied through
	// /monitor-proxy/ldoh/* (env-only — no DDL). Parsed from LDOH_BASE_URL;
	// defaults to DefaultLDOHBaseURL so operators can redirect the monitor
	// iframe at a self-hosted LDOH instance without a code change.
	LDOHBaseURL string
	// LDOHProxyTimeoutSec is the per-request timeout for the LDOH upstream
	// HTTP client used by the /monitor-proxy/ldoh/* admin surface (env-only —
	// no DDL). Parsed from LDOH_PROXY_TIMEOUT_SEC (default 30). Previously
	// hardcoded to 30s in handler/admin/monitor.go; making it configurable
	// lets operators raise the budget for slow LDOH instances or tighten it
	// to fail fast. 0/negative/invalid falls back to the default at Load time.
	LDOHProxyTimeoutSec int

	// UpdateCenterEnabled gates the residual update-center scheduler
	// (scheduler.UpdateCenterScheduler). The scheduler is a log-only no-op
	// today (no remote registry / version discovery), so it is disabled by
	// default to avoid a 15-min lease heartbeat with no product value.
	// METAPI_ENABLE_UPDATE_CENTER=true re-enables it for operators who want
	// the periodic log line while a real helper/registry client is wired.
	UpdateCenterEnabled bool

	// RedisURL enables optional shared admission counters.
	RedisURL string

	AdminCorsAllowedOrigins []string
	TrustedProxyCidrs       []string
	// AdminRateLimitRPS / AdminRateLimitBurst control the per-IP token bucket
	// for /api/* admin routes. Parsed from ADMIN_RATE_LIMIT_RPS (default 100)
	// and ADMIN_RATE_LIMIT_BURST (default 200). A burst of 0 means the bucket
	// never refills above the RPS rate; values <= 0 disable the limiter.
	AdminRateLimitRPS   int
	AdminRateLimitBurst int
	// OAuthRateLimitRPS / OAuthRateLimitBurst control the stricter per-IP
	// token bucket applied to /api/oauth/* routes. Parsed from
	// OAUTH_RATE_LIMIT_RPS (default 10) and OAUTH_RATE_LIMIT_BURST (default 20).
	OAuthRateLimitRPS   int
	OAuthRateLimitBurst int
	// AuthRateLimitRPS / AuthRateLimitBurst control the stricter per-IP
	// token bucket applied to /api/auth/* routes (login is the only place
	// the master token is presented, so brute-force protection matters).
	// Parsed from AUTH_RATE_LIMIT_RPS (default 10) and AUTH_RATE_LIMIT_BURST
	// (default 20).
	AuthRateLimitRPS   int
	AuthRateLimitBurst int
	// AdminSessionTTLMinutes is the sliding lifetime of a server-side admin
	// UI session (#1034). Every authenticated request refreshes the expiry;
	// the raw master token never reaches the browser. Parsed from
	// ADMIN_SESSION_TTL_MINUTES (default 720 = 12h, matching the legacy
	// client-side session window). Values < 1 clamp to 1.
	AdminSessionTTLMinutes int
	// AdminSessionCookieSecure controls the Secure flag of the session
	// cookie: "auto" (default; Secure when the request is HTTPS), "true"
	// (always Secure -- use behind a TLS terminator), or "false" (never
	// Secure -- plain-HTTP dev only). Parsed from ADMIN_SESSION_COOKIE_SECURE.
	AdminSessionCookieSecure string

	// Proxy: Core (5 fields)
	RequestBodyLimit int
	// FileUploadLimitBytes is the higher body limit applied to multipart upload
	// routes (/v1/files, /v1/images/*) so large uploads are not rejected by the
	// general RequestBodyLimit. Parsed from FILE_UPLOAD_LIMIT_MB.
	FileUploadLimitBytes int
	// ProxyRateLimitRPM is the per-IP request-per-minute cap for /v1 proxy
	// routes. Parsed from PROXY_RATE_LIMIT_RPM (default 60; 0 = disabled).
	ProxyRateLimitRPM int
	// ProxyGlobalTokenRPM caps the global PROXY_TOKEN across all IPs. Parsed
	// from PROXY_GLOBAL_TOKEN_RPM (default 0 = unlimited). Safety net: even if
	// the token leaks, upstream spend is bounded.
	ProxyGlobalTokenRPM int

	TokenRouterCacheTtlMs int

	// PricingCatalog (model data source registry) feeds the cold-start
	// catalog cost signal for cost-aware routing and hydrates the models
	// marketplace.
	//   PRICING_CATALOG_ENABLED      — default true
	//   PRICING_CATALOG_REFRESH_MIN  — auto-sync period in minutes (default 720 = 12h)
	//   PRICING_CATALOG_URL          — legacy single-source dataset URL; migrated
	//                                  into the registry as the top custom source
	PricingCatalogEnabled    bool
	PricingCatalogRefreshMin int
	PricingCatalogURL        string

	// Proxy: Channel (3 fields)
	ProxyMaxChannelAttempts   int
	ProxyStickySessionEnabled bool
	ProxyStickySessionTtlMs   int

	ProxySessionChannelLeaseTtlMs       int
	ProxySessionChannelLeaseKeepaliveMs int

	// ProxyMaxStreamResponseBytes caps the total bytes relayed for a single
	// SSE stream before a controlled termination (default 1 MB). Parsed once
	// at startup from PROXY_MAX_STREAM_RESPONSE_BYTES so the hot stream path
	// reads a struct field instead of calling os.Getenv per request.
	ProxyMaxStreamResponseBytes int
	// ProxyMaxBufferedResponseBytes caps the total bytes read for a single
	// non-streaming upstream response before a controlled termination
	// (default 20 MB). Parsed once at startup from
	// PROXY_MAX_BUFFERED_RESPONSE_BYTES so the buffered-response hot path
	// (upstream.go / upstream_stream.go / executor.go) reads a struct field
	// instead of re-parsing os.Getenv + strconv.ParseInt on every proxied
	// request. 0/negative/invalid falls back to the default at Load time.
	ProxyMaxBufferedResponseBytes int

	// Prompt Filter (OAuth account pool protection, #681).
	// PROMPT_FILTER_ENABLED gates a pre-upstream pattern-based safety filter
	// that blocks jailbreak/exfiltration prompts before they reach shared OAuth
	// accounts. Default false — opt-in only. PROMPT_FILTER_DENY_PATTERNS is a
	// comma-separated list of extra substring patterns appended to the seed list.
	PromptFilterEnabled      bool
	PromptFilterDenyPatterns []string

	// Codex-specific (3 fields)
	CodexResponsesWebsocketBeta string
	CodexHeaderDefaults         CodexHeaderDefaults

	// Model Probe (3 fields; ModelAvailabilityProbeEnabled is runtime-mutable
	// and lives in RuntimeSettings)
	ModelAvailabilityProbeIntervalMs  int
	ModelAvailabilityProbeTimeoutMs   int
	ModelAvailabilityProbeConcurrency int

	// RouteRebuildProbeFilterEnabled gates the route-rebuild probe filter (#625).
	// Default false keeps the legacy non-probe rebuild path byte-for-byte.
	RouteRebuildProbeFilterEnabled       bool
	RouteRebuildProbeFilterIncludeModels []string
	RouteRebuildProbeFilterExcludeModels []string

	// Retention (6 fields)
	ProxyLogRetentionDays                       int
	ProxyLogRetentionPruneIntervalMinutes       int
	ProxyFileRetentionDays                      int
	ProxyFileRetentionPruneIntervalMinutes      int
	ProxyVideoTaskRetentionDays                 int
	ProxyVideoTaskRetentionPruneIntervalMinutes int

	// Proxy Log Batch Writer (3 fields). PROXY_LOG_ASYNC (default true) routes
	// proxy_logs INSERTs through a background batch writer that decouples the
	// hot proxy path from DB write latency / SQLite write-lock contention.
	// Set false for tests/e2e that need write-through visibility. BATCH_SIZE
	// (default 50) is the row count that triggers a flush; FLUSH_INTERVAL_MS
	// (default 1000) is the max time between flushes.
	ProxyLogAsync           bool
	ProxyLogBatchSize       int
	ProxyLogFlushIntervalMs int

	OpenAiServiceTierRules any
}

Config holds ALL configuration fields for the Metapi server. Field names use Go exported (PascalCase) but each maps 1:1 to a TS config field as documented in section 3.

func Get

func Get() *Config

Get returns the global config singleton. Panics if config has not been loaded.

func GetSafe added in v0.11.0

func GetSafe() *Config

GetSafe returns the global config singleton, or nil when it has not been loaded yet. Prefer Get() in the composition root; GetSafe is for optional callbacks that may run before (or without) config initialization.

func (*Config) PostgresSSLMode

func (c *Config) PostgresSSLMode(dbSsl bool) string

PostgresSSLMode returns the explicit DB_SSLMODE setting, or the legacy DB_SSL=true behavior mapped to sslmode=require.

func (*Config) Validate

func (c *Config) Validate() []error

Validate checks Config fields and returns all validation errors. Callers should treat these as a single report — log warnings for non-fatal issues and exit on critical ones before binding the port.

type RoutingWeights

type RoutingWeights struct {
	BaseWeightFactor float64
	ValueScoreFactor float64
	CostWeight       float64
	BalanceWeight    float64
	UsageWeight      float64
}

RoutingWeights holds the weight factors for the routing algorithm.

type RuntimeSettings added in v0.16.20

type RuntimeSettings struct {
	// Auth (4 fields)
	AuthToken  string
	ProxyToken string
	DbType     string
	DbUrl      string
	DbSsl      bool
	// Cron (5 fields)
	CheckinCron          string
	CheckinScheduleMode  string
	CheckinIntervalHours int
	// window mode — random HH:mm inside [start, end]
	// re-rolled per start/setting change (load spreading + anti-fingerprint).
	CheckinWindowStart string
	CheckinWindowEnd   string
	BalanceRefreshCron string
	// Global kill switches for the two always-on periodic jobs that touch
	// upstream accounts (check-in, balance refresh) — issue #1027. Defaults
	// preserve historical behavior (both jobs on); operators turn either job
	// off via env (CHECKIN_ENABLED / BALANCE_REFRESH_ENABLED) or the runtime
	// settings of the same camelCase names. Stored inverted (zero value =
	// enabled) so bare config literals keep the default-on behavior.
	CheckinDisabled        bool
	BalanceRefreshDisabled bool
	ModelSyncCron          string
	LogCleanupCron         string
	// Site & Branding (5 fields) - empty defaults keep the embedded frontend
	// branding and login-page copy unchanged. homePageContent was removed
	// (Wave 8 Lane D): the value was stored but never rendered anywhere.
	SystemName    string
	Footer        string
	About         string
	ServerAddress string
	// Log Cleanup (4 fields)
	LogCleanupUsageLogsEnabled   bool
	LogCleanupProgramLogsEnabled bool
	LogCleanupRetentionDays      int
	// Notify: Webhook (2 fields)
	WebhookUrl     string
	WebhookEnabled bool
	// Notify: Bark (2 fields)
	BarkUrl     string
	BarkEnabled bool
	// Notify: ServerChan (2 fields)
	ServerChanKey     string
	ServerChanEnabled bool
	// Notify: Telegram (6 fields)
	TelegramEnabled         bool
	TelegramApiBaseUrl      string
	TelegramBotToken        string
	TelegramChatId          string
	TelegramUseSystemProxy  bool
	TelegramMessageThreadId string
	// Notify: SMTP (8 fields)
	SmtpEnabled bool
	SmtpHost    string
	SmtpPort    int
	SmtpSecure  bool
	SmtpUser    string
	SmtpPass    string
	SmtpFrom    string
	SmtpTo      string
	// Notify: Feishu (3 fields) —
	FeishuEnabled bool
	FeishuWebhook string
	FeishuSecret  string
	// Notify: DingTalk (3 fields) —
	DingtalkEnabled bool
	DingtalkWebhook string
	DingtalkSecret  string
	// Notify: WeCom (2 fields) —
	WecomEnabled bool
	WecomWebhook string
	// Notify: Ntfy (4 fields) —
	NtfyEnabled bool
	NtfyUrl     string
	NtfyTopic   string
	NtfyToken   string
	// Notify: General (2 fields)
	NotifyCooldownSec int
	SystemProxyUrl    string
	// ProxyRetryStatusRanges / ProxyDisableStatusRanges carry the
	// operator-tunable status-code range specs (routing.StatusRange policy,
	// competitor-study-2026-08 P1-2): retry decides which upstream statuses
	// count as retryable channel faults; disable decides which auto-disable
	// the failing channel. Runtime settings only (settings table +
	// PUT /api/settings/runtime, rehydrated at startup); blank keeps the
	// defaults, which reproduce the historical behavior exactly.
	ProxyRetryStatusRanges   string
	ProxyDisableStatusRanges string
	// NotifyTaskToggles gates per-alert-type notifications.
	// Keys are alert task slugs ("token_expired", "low_balance", "proxy_all_failed").
	// Default nil = all enabled (backward-compatible). When a key is present and
	// false, SendNotification skips that task type so operators can mute, e.g.,
	// low_balance while still receiving token_expired alerts.
	NotifyTaskToggles map[string]bool
	// Admin (3 fields)
	AdminIpAllowlist        []string
	RoutingFallbackUnitCost float64
	// CacheRatioDefault / CacheRatioClaude override the prompt-cache ratio
	// fallbacks used when an upstream pricing row omits cache_ratio. 0/missing =
	// use the code defaults (DefaultCacheRatio=1.0, ClaudeCacheRatio=0.1).
	CacheRatioDefault float64
	CacheRatioClaude  float64
	// ProxyFirstByteTimeoutSec is the operator-facing first-byte / first-token
	// timeout in SECONDS (env PROXY_FIRST_BYTE_TIMEOUT_SEC). Internal dispatch
	// converts to milliseconds via proxy.FirstByteTimeoutMs (sec * 1000).
	// 0 disables observed first-byte timeout.
	ProxyFirstByteTimeoutSec int
	// Proxy: Token Router (2 fields)
	TokenRouterFailureCooldownMaxSec int
	// Proxy: Session (4 fields)
	ProxySessionChannelConcurrencyLimit int
	ProxySessionChannelQueueWaitMs      int
	// Proxy: Misc (7 fields)
	CodexUpstreamWebsocketEnabled              bool
	ResponsesCompactFallbackToResponsesEnabled bool
	DisableCrossProtocolFallback               bool
	ProxyEmptyContentFailEnabled               bool
	ProxyErrorKeywords                         []string
	GlobalBlockedBrands                        []string
	GlobalAllowedModels                        []string
	// Proxy: Debug (9 fields)
	ProxyDebugTraceEnabled        bool
	ProxyDebugCaptureHeaders      bool
	ProxyDebugCaptureBodies       bool
	ProxyDebugCaptureStreamChunks bool
	ProxyDebugTargetSessionId     string
	ProxyDebugTargetClientKind    string
	ProxyDebugTargetModel         string
	ProxyDebugRetentionHours      int
	ProxyDebugMaxBodyBytes        int
	// Routing Weights (5 fields)
	// Model availability probe kill switch (settings toggle hot-applies the
	// running ticker, scheduler/model_probe.go SetEnabled).
	ModelAvailabilityProbeEnabled bool

	RoutingWeights RoutingWeights
	// Payload Rules (2 JSON fields)
	PayloadRules any
}

RuntimeSettings carries every configuration value that may change while the server is running: admin runtime-settings updates (PUT /api/settings/runtime), auth-token rotation, scheduler schedule write-backs, and the runtime database switch.

Concurrency contract (Wave 18 config-race fix, Milestone C1):

  • Readers take the current immutable snapshot via Runtime() / RuntimeSafe() and must treat it as strictly read-only. The pointer load is atomic, so hot paths (proxy auth, admin auth, routing status ranges) never lock and can never observe a torn value.
  • The ONLY write path is UpdateRuntime, which copies the current snapshot, applies the mutation to the private draft, and atomically publishes the copy. Inside the mutation, slice/map/any fields must be replaced wholesale — never mutated in place — because published snapshots share those references with earlier snapshots.
  • Everything left on Config is static (frozen at boot before config.Set), so long-lived components may keep reading cached *Config pointers safely.

func Runtime added in v0.16.20

func Runtime() *RuntimeSettings

Runtime returns the current immutable runtime-settings snapshot. Panics when called before boot publication — the same contract as Get().

func RuntimeSafe added in v0.16.20

func RuntimeSafe() *RuntimeSettings

RuntimeSafe returns the current runtime snapshot, or nil before publication. Prefer Runtime() on request paths; RuntimeSafe is for optional callbacks that may run before (or without) config publication.

func (*RuntimeSettings) Validate added in v0.16.20

func (r *RuntimeSettings) Validate() []error

Validate checks the runtime-mutable settings and returns all validation errors. Boot-time call path mirrors Config.Validate: warnings for non-fatal issues, exit on critical ones before binding the port.

Jump to

Keyboard shortcuts

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