Documentation
¶
Overview ¶
Package config loads and validates all server configuration from environment variables.
Index ¶
- Constants
- func ClampInt(v, lo, hi int) int
- func IsCritical(err error) bool
- func IsWarning(err error) bool
- func Load(env map[string]string) (*Config, *RuntimeSettings)
- func MaxInt(a, b int) int
- func MaxInt64(a, b int64) int64
- func NormalizeTokenRouterFailureCooldownMaxSec(value float64) (int, bool)
- func ParseJsonValue(value string) any
- func Set(cfg *Config)
- func SetRuntime(rt *RuntimeSettings)
- func SlogLevel(logLevel string) slog.Level
- func UpdateRuntime(mutate func(*RuntimeSettings))
- func ValidateCronExpr(expr string) bool
- type Config
- type RoutingWeights
- type RuntimeSettings
Constants ¶
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" // EnvExampleAccountCredentialSecret is the literal shipped on the // ACCOUNT_CREDENTIAL_SECRET line of .env.example. It is deliberately NOT // named Default*: every other constant in this block is a value Load() // falls back to, whereas nothing in the code ever falls back to this one. // It matters because Load() takes any non-empty env value verbatim, so a // deployment that copies .env.example and leaves this value unchanged runs with this // public string as its real credential-encryption key. config.Validate // reports it; TestShippedCredentialSecretPlaceholderIsTheGuardedOne pins // the two files to each other so retyping the placeholder in only one of // them cannot silently disarm that check. EnvExampleAccountCredentialSecret = "REPLACE_WITH_STRONG_RANDOM_SECRET" DefaultPort = 4000 DefaultDataDir = "./data" // DefaultDbType is the dialect used when DB_TYPE is unset/unrecognized and // DB_URL is not a PostgreSQL URL. It is the single in-repo owner of that // fallback: docs/configuration.md documents the same default, and the env // parity gate compares key sets rather than default values (#1237), so this // constant is the only handle on it. The mapped spellings "postgres"/"mysql" // in parseDbType stay literals — the cross-package owner is store.Dialect*, // which config cannot import without a cycle. 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" 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 = "" DefaultLogo = "" DefaultAbout = "" DefaultServerAddress = "" DefaultNotifyCooldownSec = 300 DefaultSmtpPort = 587 DefaultTokenRouterCacheTtlMs = 1500 DefaultProxyMaxChannelAttempts = 3 DefaultProxyStickySessionTtlMs = 30 * 60 * 1000 // 30 minutes DefaultProxySessionChannelConcurrencyLimit = 2 DefaultProxySessionChannelQueueWaitMs = 1500 DefaultModelAvailabilityProbeIntervalMs = 30 * 60 * 1000 // 30 minutes DefaultModelAvailabilityProbeTimeoutMs = 15000 DefaultModelAvailabilityProbeConcurrency = 1 DefaultProxyLogRetentionDays = 30 DefaultProxyLogRetentionPruneIntervalMinutes = 30 // Video task mappings are short-lived id rewrites, so they retire faster // than proxy logs: 7 days. The same knob bounds the process-local // rewrite cache in handler/proxy. <=0 remains an explicit operator opt-out // (retention disabled), it is just no longer the default. DefaultProxyVideoTaskRetentionDays = 7 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 // Usage aggregation projects proxy_logs into the site/model rollups. 5s // keeps admin dashboards near-real-time; small single-node deployments // (2 vCPU class) can relax it to trade freshness for fewer passes. DefaultUsageProjectionIntervalMs = 5000 // 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 // DefaultProxyStreamWriteTimeoutSec bounds one downstream write+flush for // SSE and native media streams. The relay holds the deadline only while // writing and clears it between chunks, so a healthy stream may run forever // while a client that stopped reading is cut off instead of blocking the // relay and its concurrency slot. DefaultProxyStreamWriteTimeoutSec = 60 // DefaultProxyDirectAccountMaxConcurrency caps concurrent dispatches per // direct upstream account (upstream_credentials.id). 0 keeps the // historical unlimited behavior; a positive value opts into per-account // isolation for direct channels, which have no site row to carry // sites.max_concurrency. DefaultProxyDirectAccountMaxConcurrency = 0 )
Variables ¶
This section is empty.
Functions ¶
func IsCritical ¶
IsCritical returns true if the error represents a fatal config issue.
func IsWarning ¶ added in v0.13.0
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 MaxInt64 ¶ added in v0.12.0
MaxInt64 returns the larger of a and b. Exported for use by other packages.
func NormalizeTokenRouterFailureCooldownMaxSec ¶ added in v0.16.23
§1.7 NormalizeTokenRouterFailureCooldownMaxSec: !finite || <= 0 → (0, false); trunc → clamp[1, ceiling] → (int, true). Exported so the settings-table hydration path (store.ApplyRuntimeSettings) clamps a persisted cap exactly like the env path instead of growing a second copy of the rule.
func ParseJsonValue ¶
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
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
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 Config ¶
type Config struct {
AccountCredentialSecret string
CodexClientId string
// OAuth Clients (3 fields)
ClaudeClientId 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 reports whether the log_cleanup regime owns the log
// tables (true) or the legacy PROXY_LOG_RETENTION_DAYS pruner does (false).
// Resolved during startup settings hydration, not by Load.
LogCleanupConfigured bool
// LogCleanupEnvEnabled records that an env toggle explicitly asked for the
// log_cleanup regime: LOG_CLEANUP_USAGE_LOGS_ENABLED=true or
// LOG_CLEANUP_PROGRAM_LOGS_ENABLED=true. Startup hydration ORs it into
// LogCleanupConfigured so an env-driven deployment keeps its intent even
// with an empty settings table.
//
// Deliberately one-directional: neither LOG_CLEANUP_RETENTION_DAYS nor
// LOG_CLEANUP_CRON counts, and an explicit false does not count either.
// Claiming the regime while both toggles are off would run the new scheduler
// (which then skips for want of a target) and disable the legacy pruner, so
// nothing would ever be pruned.
LogCleanupEnvEnabled bool
// Resin sticky proxy pool (3 fields, env-only — no schema change).
// 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 schema change).
// 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
// ProxyStreamWriteTimeoutSec bounds one downstream write+flush for every
// relayed stream: SSE and native audio/video byte streams share it. The
// relay arms it immediately before writing and clears it immediately after,
// so it never limits total stream duration or the wait for the next
// upstream chunk; a client that stops reading cannot pin a relay (and its
// site slot) forever. Parsed from PROXY_STREAM_WRITE_TIMEOUT_SEC, with the
// pre-generalization PROXY_SSE_WRITE_TIMEOUT_SEC accepted as an alias;
// 0/negative/invalid falls back to DefaultProxyStreamWriteTimeoutSec.
ProxyStreamWriteTimeoutSec int
// ProxyDirectAccountMaxConcurrency caps concurrent proxy dispatches per
// direct upstream account, keyed by upstream_credentials.id. Direct
// channels have no site row to carry MaxConcurrency, so this is their
// equivalent isolation knob. Parsed from
// PROXY_DIRECT_ACCOUNT_MAX_CONCURRENCY; 0 (or any non-positive value)
// means unlimited, which is the historical behavior. The cap is
// process-local and read once at startup.
ProxyDirectAccountMaxConcurrency 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
// 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 supplies the initial max_rpm for a migrated root key. 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
PricingCatalogAllowPrivate bool
// Proxy: Channel (2 fields)
ProxyMaxChannelAttempts int
ProxyStickySessionTtlMs 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 (2 fields)
CodexResponsesWebsocketBeta string
// 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 (4 fields)
ProxyLogRetentionDays int
ProxyLogRetentionPruneIntervalMinutes 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
// Usage aggregation (1 field). USAGE_PROJECTION_INTERVAL_MS is the cadence
// of the proxy_logs -> site_day_usage / site_hour_usage / model_day_usage
// projection pass. Clamped to [1000, 3600000] ms.
UsageProjectionIntervalMs 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 ¶
PostgresSSLMode returns the explicit DB_SSLMODE setting, or the legacy DB_SSL=true behavior mapped to sslmode=require.
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 // Legacy startup import only; cleared after migration.
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
// AutoCreateModelRoutes is opt-in and persisted in runtime settings.
// Existing routes, manual channels and downstream grants remain operator-owned.
AutoCreateModelRoutes bool
ModelSyncCron string
LogCleanupCron string
// Site & Branding (5 fields) - empty defaults keep the embedded frontend
// branding and login-page copy unchanged. homePageContent was removed
// long ago: the value was stored but never rendered anywhere.
SystemName string
Logo 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
// SmtpAllowCustomPort permits SMTP ports outside 25/465/587. It exists
// only as an explicit operator escape hatch (SMTP_ALLOW_CUSTOM_PORT);
// without it a session-writable smtpHost/smtpPort cannot turn the
// notification test into an arbitrary-port probe of internal hosts.
SmtpAllowCustomPort bool
// 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):
// 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 (6 fields)
CodexUpstreamWebsocketEnabled bool
DisableCrossProtocolFallback bool
ProxyEmptyContentFailEnabled bool
ProxyErrorKeywords []string
GlobalBlockedBrands []string
GlobalAllowedModels []string
// 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:
- 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.