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 MaxInt(a, b int) int
- func MaxInt64(a, b int64) int64
- func ParseJsonValue(value string) any
- func Set(cfg *Config)
- func SlogLevel(logLevel string) slog.Level
- func ValidateCronExpr(expr string) bool
- type CodexHeaderDefaults
- type Config
- type RoutingWeights
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" 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" 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 (models.dev official list prices) cold-start cost signal. DefaultPricingCatalogEnabled = true DefaultPricingCatalogRefreshMin = 60 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 TokenRouterFailureCooldownMaxSecCeiling = 30 * 24 * 60 * 60 // 30 days DefaultCheckinCron = "0 8 * * *" DefaultCheckinIntervalHours = 6 DefaultBalanceRefreshCron = "0 * * * *" DefaultLogCleanupCron = "0 6 * * *" // Site & Branding defaults. Empty means the embedded frontend branding and // login-page copy are used unchanged. DefaultSystemName = "" DefaultLogo = "" DefaultAbout = "" DefaultHomePageContent = "" 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 (1 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 = 1 << 20 // 1 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 )
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 MaxInt64 ¶ added in v0.12.0
MaxInt64 returns the larger of a and b. Exported for use by other packages.
func ParseJsonValue ¶
ParseJsonValue parses a JSON string into an any value. Returns nil on empty input or parse error.
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 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 CodexHeaderDefaults ¶
CodexHeaderDefaults holds Codex-specific HTTP header defaults.
type Config ¶
type Config struct {
// Auth (4 fields)
AuthToken string
ProxyToken string
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
DbType string
DbUrl string
DbSsl bool
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
// 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
LogCleanupCron string
// Site & Branding (6 fields) - empty defaults keep the embedded frontend
// branding and login-page copy unchanged.
SystemName string
Logo string
About string
HomePageContent string
ServerAddress string
// Log Cleanup (4 fields)
LogCleanupUsageLogsEnabled bool
LogCleanupProgramLogsEnabled bool
LogCleanupRetentionDays int
LogCleanupConfigured bool
// 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
// 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
// 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
// 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
// RedisURL enables optional shared admission counters.
RedisURL string
// Admin (3 fields)
AdminIpAllowlist []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
// 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
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
TokenRouterCacheTtlMs int
// PricingCatalog (models.dev official list prices) feeds the cold-start
// catalog cost signal for cost-aware routing.
// PRICING_CATALOG_ENABLED — default true
// PRICING_CATALOG_REFRESH_MIN — refresh period in minutes (default 60)
// PRICING_CATALOG_URL — dataset URL (default https://models.dev/api.json)
PricingCatalogEnabled bool
PricingCatalogRefreshMin int
PricingCatalogURL string
// Proxy: Channel (3 fields)
ProxyMaxChannelAttempts int
ProxyStickySessionEnabled bool
ProxyStickySessionTtlMs int
// Proxy: Session (4 fields)
ProxySessionChannelConcurrencyLimit int
ProxySessionChannelQueueWaitMs int
ProxySessionChannelLeaseTtlMs int
ProxySessionChannelLeaseKeepaliveMs int
// Proxy: Misc (7 fields)
CodexUpstreamWebsocketEnabled bool
ResponsesCompactFallbackToResponsesEnabled bool
DisableCrossProtocolFallback bool
ProxyEmptyContentFailEnabled bool
// 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
ProxyErrorKeywords []string
GlobalBlockedBrands []string
GlobalAllowedModels []string
// 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
// Proxy: Debug (9 fields)
ProxyDebugTraceEnabled bool
ProxyDebugCaptureHeaders bool
ProxyDebugCaptureBodies bool
ProxyDebugCaptureStreamChunks bool
ProxyDebugTargetSessionId string
ProxyDebugTargetClientKind string
ProxyDebugTargetModel string
ProxyDebugRetentionHours int
ProxyDebugMaxBodyBytes int
// Codex-specific (3 fields)
CodexResponsesWebsocketBeta string
CodexHeaderDefaults CodexHeaderDefaults
// Model Probe (4 fields)
ModelAvailabilityProbeEnabled bool
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
// Routing Weights (5 fields)
RoutingWeights RoutingWeights
// Payload Rules (2 JSON fields)
PayloadRules any
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 Load ¶
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 (*Config) PostgresSSLMode ¶
PostgresSSLMode returns the explicit DB_SSLMODE setting, or the legacy DB_SSL=true behavior mapped to sslmode=require.