config

package
v0.30.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 12 Imported by: 0 modules, 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 centralizes all RELAY_* env var parsing for the relay binary. It is the single source of truth for the env contract; grep here to learn what env vars Relay reads.

Load() validates inputs at boot (master key shape, cluster-mode enum, etc.) so subsystem constructors can trust the fields they receive. Subsystems do NOT read env vars themselves — they accept values via their own typed configs.

Index

Constants

View Source
const (
	AuthzSingle = "single"
	AuthzRBAC   = "rbac"
)

Authorizer modes for RELAY_AUTHZ.

View Source
const (
	DefaultRedisPoolSizePerCPU           = 25
	DefaultRedisPostFlightPoolSizePerCPU = 25
	// A larger queue brings back the pool-wait latency the cap exists to stop; a smaller one refuses load the pool would serve.
	DefaultRedisPoolMaxWaitersPerConn = 2
)

Pool sizes scale with GOMAXPROCS, since a pod's request rate and so its concurrent Valkey round trips grow with its CPUs. Under load requests queue for a free connection long before Valkey or relay CPU is busy, so both pools sit well above the round trips a pod has in flight at sub-millisecond latency. A served request makes about one round trip on each (the reserve before the upstream call, the commit after), so they get the same size.

View Source
const (
	DefaultRedisPostFlightPoolTimeout = time.Second
	DefaultRedisPostFlightReadTimeout = time.Second
)

Post-flight client wait bounds. A command waits at most pool + write + read (2.5 s with the default write bound), plus one dial on a pool miss, which stays inside the 5 s deadline a served request's post-flight runs under.

View Source
const (
	DefaultRedisPostFlightBatchSize  = 64
	DefaultRedisPostFlightBatchDelay = 2 * time.Millisecond
	DefaultRedisPostFlightQueueSize  = 4096
)

Settle queue defaults. A 2 ms wait gathers 10–20 settles per round trip at 5–10k requests a second per pod and delays only post-flight work and a concurrency slot's release. 64 caps one pipeline at some 130–190 commands while catching up after a stall. 4096 queued settles absorb about 400 ms of stalled Valkey at 10k a second before settles go direct.

Variables

View Source
var DefaultCatalogVersion = ""

DefaultCatalogVersion is the catalog release `make build` stamps from versions.env (-X ...config.DefaultCatalogVersion=<tag>); it stands in for RELAY_CATALOG_VERSION when neither that nor RELAY_CATALOG_DIR is set, so a binary without a bundled tree still seeds.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Cluster
	ClusterMode bool

	// Backends
	CatalogBackend  string
	StateBackend    string
	EventlogBackend string

	// Connections
	PGDSN         string
	PGMaxConns    int // RELAY_PG_MAX_CONNS; 0 = storage default (10)
	PGMinConns    int // RELAY_PG_MIN_CONNS warm floor; 0 = storage default (2)
	RedisAddr     string
	RedisPassword string // RELAY_REDIS_PASSWORD; empty = no AUTH
	// RedisPoolSize / RedisMinIdleConns tune the shared go-redis client pool.
	// Pool defaults to DefaultRedisPoolSizePerCPU × GOMAXPROCS; idle floor 0
	// = none. A warm floor keeps connections pre-dialed so request bursts
	// never pay cold-dial (TCP + uncached DNS) latency inside a request
	// budget — same rationale as the PG warm floor above.
	RedisPoolSize     int // RELAY_REDIS_POOL_SIZE
	RedisMinIdleConns int // RELAY_REDIS_MIN_IDLE_CONNS
	// RELAY_REDIS_{DIAL,READ,WRITE,POOL}_TIMEOUT_MS and RELAY_REDIS_MAX_RETRIES. Defaults are kv.Default*; retries default to 0 because a resent reserve script can count one request twice.
	RedisDialTimeout  time.Duration
	RedisReadTimeout  time.Duration
	RedisWriteTimeout time.Duration
	RedisPoolTimeout  time.Duration
	RedisMaxRetries   int
	// RELAY_REDIS_POOL_MAX_WAITERS: calls that may wait for a shared-pool connection before admission is refused at once rather than after the pool wait; default twice RedisPoolSize.
	RedisPoolMaxWaiters int
	// RELAY_REDIS_POSTFLIGHT_{POOL_SIZE,POOL_TIMEOUT_MS,READ_TIMEOUT_MS}: the second client that settles served requests after the response; dial and write bounds and retries are the shared ones.
	RedisPostFlightPoolSize    int
	RedisPostFlightPoolTimeout time.Duration
	RedisPostFlightReadTimeout time.Duration
	// RELAY_REDIS_POSTFLIGHT_{BATCH_SIZE,BATCH_DELAY_MS,QUEUE_SIZE}: the queue that coalesces served requests' settles into shared round trips on that client; a queue size of 0 turns it off.
	RedisPostFlightBatchSize  int
	RedisPostFlightBatchDelay time.Duration
	RedisPostFlightQueueSize  int
	CHDSN                     string
	OTLPEndpoint              string

	// PublicURL is the deployment's externally reachable control-plane
	// origin (RELAY_PUBLIC_URL). Exported manifests reference the schema
	// endpoint under it; empty renders the reference relative.
	PublicURL string

	// Auth
	AdminToken string
	MasterKey  []byte // already parsed via crypto.ParseMasterKey; nil if unset
	// MasterKeyExtra are further key-encryption keys (RELAY_MASTER_KEY_EXTRA,
	// comma-separated), held while changing the master key.
	MasterKeyExtra [][]byte

	// Authz selects the control-plane authorizer. "single" (the default)
	// grants every authenticated caller every action; "rbac" evaluates the
	// caller's RoleBindings against each row's scope chain.
	Authz string

	// MigrateOnBoot runs the pending up-migrations at startup
	// (RELAY_MIGRATE_ON_BOOT, default true). Set it false while rolling the
	// schema back, so a restarting pod doesn't re-apply what was just undone.
	MigrateOnBoot bool

	// MigrateLockTimeout bounds how long a migration statement waits for a table lock (RELAY_MIGRATE_LOCK_TIMEOUT_S, default 10s; 0 waits indefinitely). A migration queued behind a long transaction holds every later query on that table behind it, logins included.
	MigrateLockTimeout time.Duration

	// Behavior knobs
	AutoSeedIfEmpty bool
	ConfigDir       string
	CatalogDir      string
	CatalogVersion  string
	CatalogURL      string
	CatalogIndexURL string
	// CatalogPollInterval is how often a relay on RELAY_CATALOG_VERSION=latest
	// re-checks the catalog index while running (RELAY_CATALOG_POLL_INTERVAL,
	// default 1h; 0 disables the timer).
	CatalogPollInterval time.Duration
	// CatalogAllowDowngrade lets this boot seed a release older than the one
	// the database holds (RELAY_CATALOG_ALLOW_DOWNGRADE=1).
	CatalogAllowDowngrade bool
	// CatalogWebhookURL is this relay's public inference base the catalog
	// server sends release webhooks to (RELAY_CATALOG_WEBHOOK_URL); empty
	// registers none.
	CatalogWebhookURL string
	// CatalogPrune runs the prune of detached catalog rows after every
	// versioned reseed and on a following relay's checks (RELAY_CATALOG_PRUNE,
	// default on).
	CatalogPrune bool
	// CatalogPruneIdle is how long a detached model or host binding must have
	// served no request to be pruned (RELAY_CATALOG_PRUNE_IDLE, default 720h).
	CatalogPruneIdle time.Duration
	InstanceID       string
	EventlogDir      string
	// UsageQueueSize is how many usage events wait in memory for the sink before new ones are dropped (RELAY_USAGE_QUEUE_SIZE); 0 = usagelog.DefaultQueueSize.
	UsageQueueSize int
	// UsageRefusedQueueSize is the same for events of requests that never reached an upstream (RELAY_USAGE_REFUSED_QUEUE_SIZE); 0 = usagelog.DefaultRefusedQueueSize.
	UsageRefusedQueueSize int
	// PayloadQueueBytes bounds the memory captured payload records hold while they wait for the sink (RELAY_PAYLOAD_QUEUE_BYTES); 0 = sized from the memory limit.
	PayloadQueueBytes int
	// PayloadRefusedQueueBytes is the same for records of requests that never reached an upstream (RELAY_PAYLOAD_REFUSED_QUEUE_BYTES); 0 = payloadlog.DefaultRefusedQueueBytes.
	PayloadRefusedQueueBytes int
	MaxRequestBytes          int64 // 0 = use httpmw.DefaultMaxRequestBytes
	MaxInflight              int   // RELAY_MAX_INFLIGHT per-pod in-flight cap; 0 = derived from the memory limit at boot

	// InflightSchedP99 is the scheduler latency p99 above which the effective in-flight limit is lowered (RELAY_INFLIGHT_SCHED_P99, default 20ms, acting after three consecutive windows above it); 0 = the hard cap only.
	InflightSchedP99 time.Duration

	// UpstreamMaxIdlePerHost caps idle keep-alive connections the upstream
	// transport pools per host (RELAY_UPSTREAM_MAX_IDLE_PER_HOST); 0 = the
	// in-flight cap, so every request in flight can return its connection to the pool.
	UpstreamMaxIdlePerHost int

	// UpstreamDialTimeout bounds the TCP connect to an upstream (RELAY_UPSTREAM_DIAL_TIMEOUT_S, default 10s).
	UpstreamDialTimeout time.Duration

	// MaxConns caps the open connections the inference listener accepts (RELAY_MAX_CONNS); 0 = derived from the memory limit at boot.
	MaxConns int
	// ConnQueue is how many connections past MaxConns wait for a slot (RELAY_CONN_QUEUE, default 1024; 0 = refuse them at once), each for at most ConnQueueTimeout (RELAY_CONN_QUEUE_TIMEOUT, default 1s).
	ConnQueue        int
	ConnQueueTimeout time.Duration
	// ConnCloseIdle closes an idle keep-alive connection for each queued one (RELAY_CONN_CLOSE_IDLE, default off).
	ConnCloseIdle bool

	// KeyBreakerThreshold and KeyBreakerWindow set how many upstream server or network errors within the window open a host key's breaker (RELAY_KEY_BREAKER_THRESHOLD, RELAY_KEY_BREAKER_WINDOW_S); 0 = keypool defaults. 401 and 403 open it at once.
	KeyBreakerThreshold int
	KeyBreakerWindow    time.Duration

	// Limiter names the limiter that counts rate limits and budgets (RELAY_LIMITER): "hybrid" (default) counts in pod memory, synced every LimiterSync (RELAY_LIMITER_SYNC_MS, default 1000), and reserves in the store only counters near their cap; "lua" reserves every request in the store.
	Limiter     string
	LimiterSync time.Duration

	// PlanCellIdle is how long runtime state no published plan links any more (a rotated credential's breaker copy, a deleted pool's rotation) is kept before it is dropped (RELAY_PLAN_CELL_IDLE_S, default 600). A plan that links it again within the window gets it back.
	PlanCellIdle time.Duration

	// PlanResync is how often the plans are listed again from Postgres and compared with what they hold (RELAY_PLAN_RESYNC_S, default 600; 0 disables), the safety net for a catalog notification that never arrived. It publishes only when a row differs.
	PlanResync time.Duration

	// StreamKeepAlive is the silence interval after which relay emits the inbound wire shape's own no-op SSE frame on a streamed response (RELAY_STREAM_KEEPALIVE_S, default 15s; 0 disables). Upstreams send nothing during long prompt processing or thinking, and coding-agent clients abort a stream after a few minutes without bytes.
	StreamKeepAlive time.Duration

	// ProxyBodyIdle is how long a proxy-mode request body may go without a byte before relay answers 408 and aborts the forward (RELAY_PROXY_BODY_IDLE_S, default 30s; 0 disables). The body streams upstream while the request holds an in-flight slot, a rate-limit lease and an upstream connection, and the listener has no read timeout of its own.
	ProxyBodyIdle time.Duration

	// AccountDomain is the parent domain of the per-account inference hosts (RELAY_ACCOUNT_DOMAIN): a request to <account-name>.<AccountDomain> runs in that account. Empty turns host selection off.
	AccountDomain string

	// StreamUsage makes same-shape streamed requests ask the upstream for token usage when the wire shape reports it only on request (RELAY_STREAM_USAGE, default on). The extra usage frame is removed from the caller's stream unless the caller asked for it.
	StreamUsage bool

	// LastUsed records when each relay key and host key last served a request (RELAY_LAST_USED, default on).
	LastUsed bool

	// BatchMaxItems caps the items in one batch submission (RELAY_BATCH_MAX_ITEMS, default 50000).
	BatchMaxItems int

	// StreamIdleTimeout ends a streamed upstream call that has sent no bytes for this long (RELAY_STREAM_IDLE_TIMEOUT_S, default 600s; 0 disables). Deliberately above the clients' own silence watchdogs so relay is never the first to give up. Streams have no total deadline; buffered calls do.
	StreamIdleTimeout time.Duration

	HealthzDeadlineMS int
	ShutdownDeadlineS int

	// DevTrustEventTime makes the inference edge honor the X-WR-Event-Time
	// header as the usage Event timestamp (RELAY_DEV_TRUST_EVENT_TIME=1).
	// Dev/replay tooling only — never enable in production.
	DevTrustEventTime bool

	// Port is the inference listener's port (RELAY_PORT, default 8080).
	Port string

	// ControlPort is the listener port for the control-plane HTTP server.
	// Empty disables the control listener entirely (data plane only).
	ControlPort string

	// ListenHost is the address the inference listener binds (RELAY_LISTEN_HOST) and the control listener's default. Empty binds every interface.
	ListenHost string

	// ControlListenHost is the address the control listener binds (RELAY_CONTROL_LISTEN_HOST, default ListenHost), so the admin plane can stay private while inference is reachable.
	ControlListenHost string

	// PprofAddr is the host:port the runtime profiling listener binds (RELAY_PPROF_ADDR). Empty disables it.
	PprofAddr string

	// PprofMutexFraction and PprofBlockRate turn on the mutex and block profiles (RELAY_PPROF_MUTEX_FRACTION, RELAY_PPROF_BLOCK_RATE; 0 = off). They take effect only with PprofAddr set.
	PprofMutexFraction int
	PprofBlockRate     int

	// ControlAllowOrigins is the CORS allowlist for the control API. Comma-
	// separated list of exact origin strings (no wildcards — credentialed
	// CORS forbids them). Empty disables CORS entirely.
	ControlAllowOrigins []string

	// UIDisable suppresses serving the embedded admin UI on the control
	// listener (RELAY_UI_DISABLE=1). Off by default; the UI is same-origin
	// and adds no surface beyond the control API it already fronts.
	UIDisable bool

	// Runtime is the public, unauthenticated runtime config the embedded admin
	// UI fetches at boot via GET /config.json. Public values only — it is
	// world-readable. All fields are optional; empty URL fields make the UI
	// fall back to its own origin (which is correct for controlApiUrl in the
	// single-binary case, but NOT for inferenceApiUrl when the data plane is a
	// separate origin — hence RELAY_INFERENCE_API_URL).
	Runtime RuntimeConfig
}

Config holds every RELAY_* setting parsed and validated at startup.

func Load

func Load() (*Config, error)

Load reads every RELAY_* environment variable, validates them, and returns a fully-populated *Config. Returns a descriptive error on the first validation failure.

func (*Config) ControlAddr added in v0.10.8

func (c *Config) ControlAddr() string

ControlAddr is the address the control listener binds.

func (*Config) InferenceAddr added in v0.10.8

func (c *Config) InferenceAddr() string

InferenceAddr is the address the inference listener binds.

func (*Config) MasterKeys added in v0.11.6

func (c *Config) MasterKeys() [][]byte

MasterKeys is the key-encryption key set, RELAY_MASTER_KEY first; nil without a master key.

type RuntimeConfig added in v0.2.0

type RuntimeConfig struct {
	ControlAPIURL   string // RELAY_CONTROL_API_URL   (empty ⇒ UI uses its origin)
	InferenceAPIURL string // RELAY_INFERENCE_API_URL (empty ⇒ UI prompts; no safe origin default)
	Mode            string // RELAY_MODE ("oss" | "cloud"); default "oss"
	SentryDSN       string // RELAY_UI_SENTRY_DSN        (public client-side DSN)
	TelemetryEnv    string // RELAY_UI_TELEMETRY_ENV
	DocsURL         string // RELAY_UI_DOCS_URL
	SupportURL      string // RELAY_UI_SUPPORT_URL
}

RuntimeConfig carries the deployment-specific values surfaced to the browser via GET /config.json. Mirrors the JSON the UI reads; see config_json.go.

Jump to

Keyboard shortcuts

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