config

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 11 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"

	// 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

	DefaultRequestBodyLimit = 20 * 1024 * 1024 // 20 MB

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

	DefaultCheckinCron          = "0 8 * * *"
	DefaultCheckinIntervalHours = 6
	DefaultBalanceRefreshCron   = "0 * * * *"
	DefaultLogCleanupCron       = "0 6 * * *"

	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

	DefaultProxyDebugRetentionHours = 24
	DefaultProxyDebugMaxBodyBytes   = 262144

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

Variables

This section is empty.

Functions

func IsCritical

func IsCritical(err error) bool

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

func MaxInt

func MaxInt(a, b int) int

MaxInt 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.

Types

type CodexHeaderDefaults

type CodexHeaderDefaults struct {
	UserAgent    string
	BetaFeatures string
}

CodexHeaderDefaults holds Codex-specific HTTP header defaults.

type Config

type Config struct {
	// Auth (5 fields)
	AuthToken               string
	ProxyToken              string
	DeployHelperToken       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

	// 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

	// 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

	// 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

	// Proxy: Core (2 fields)
	RequestBodyLimit        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

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

	// Proxy: Session (4 fields)
	ProxySessionChannelConcurrencyLimit int
	ProxySessionChannelQueueWaitMs      int
	ProxySessionChannelLeaseTtlMs       int
	ProxySessionChannelLeaseKeepaliveMs int

	// Proxy: Misc (6 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

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

	// Model Probe (4 fields)
	ModelAvailabilityProbeEnabled     bool
	ModelAvailabilityProbeIntervalMs  int
	ModelAvailabilityProbeTimeoutMs   int
	ModelAvailabilityProbeConcurrency int

	// Retention (6 fields)
	ProxyLogRetentionDays                       int
	ProxyLogRetentionPruneIntervalMinutes       int
	ProxyFileRetentionDays                      int
	ProxyFileRetentionPruneIntervalMinutes      int
	ProxyVideoTaskRetentionDays                 int
	ProxyVideoTaskRetentionPruneIntervalMinutes 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 Load

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

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

func (c *Config) PostgresSSLMode() 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.

Jump to

Keyboard shortcuts

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