config

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 26 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 loads remora's runtime settings from the environment.

Index

Constants

View Source
const (
	EnvListen        = "REMORA_LISTEN"
	EnvDrainTimeout  = "REMORA_DRAIN_TIMEOUT"
	EnvData          = "REMORA_DATA"
	EnvAdminPassword = "REMORA_ADMIN_PASSWORD" //nolint:gosec // G101: a variable name, not a credential.
	EnvLogLevel      = "REMORA_LOG_LEVEL"
	EnvEngineDir     = "REMORA_ENGINE_DIR"
	EnvMasterKey     = "REMORA_MASTER_KEY"
	EnvPortRouter    = "REMORA_PORT_ROUTER"
	EnvPortAccounts  = "REMORA_PORT_ACCOUNTS"
	EnvPortSpeech    = "REMORA_PORT_SPEECH"

	EnvSonioxBaseURL       = "REMORA_SONIOX_BASE_URL"
	EnvSonioxPollInterval  = "REMORA_SONIOX_POLL_INTERVAL"
	EnvSonioxDeadline      = "REMORA_SONIOX_DEADLINE"
	EnvSonioxSweepInterval = "REMORA_SONIOX_SWEEP_INTERVAL"
	EnvCooling429Count     = "REMORA_COOLING_429_COUNT"
	EnvCooling429Window    = "REMORA_COOLING_429_WINDOW"
	EnvCoolingDefault      = "REMORA_COOLING_DEFAULT"
	EnvCoolingPoll         = "REMORA_COOLING_POLL"

	EnvCoolingSubscriptionDefault = "REMORA_COOLING_SUBSCRIPTION_DEFAULT"
	EnvPprofAddr                  = "REMORA_PPROF_ADDR"
	EnvLogContent                 = "REMORA_LOG_CONTENT"
	EnvQuotaInterval              = "REMORA_QUOTA_INTERVAL"
	EnvQuotaBaseURL               = "REMORA_TEST_QUOTA_BASE_URL"
	EnvStatsBackfillPace          = "REMORA_STATS_BACKFILL_PACE"
)

Environment variables read by Load.

View Source
const (
	DefaultListen       = ":8080"
	DefaultDrainTimeout = 5 * time.Second
	DefaultDataDir      = "/data"
	DefaultEngineDir    = "/usr/local/lib/remora/engines"
	DefaultPortRouter   = 18080
	DefaultPortAccounts = 18317
	DefaultPortSpeech   = 18090

	DefaultSonioxBaseURL       = "https://api.soniox.com"
	DefaultSonioxPollInterval  = time.Second
	DefaultSonioxDeadline      = 30 * time.Minute
	DefaultSonioxSweepInterval = 10 * time.Minute
	DefaultCooling429Count     = 3
	DefaultCooling429Window    = 60 * time.Second
	DefaultCoolingDefault      = 5 * time.Minute
	DefaultCoolingPoll         = time.Second

	DefaultCoolingSubscriptionDefault = 30 * time.Second
	// DefaultQuotaInterval and MinQuotaInterval equal quota.DefaultInterval and quota.MinInterval; quota imports
	// accounts, whose tests import config, so config cannot import quota.
	DefaultQuotaInterval = 15 * time.Minute
	MinQuotaInterval     = 5 * time.Minute
)

Defaults applied when a variable is unset or empty.

Variables

View Source
var ErrInvalid = errors.New("remora.yaml")

ErrInvalid marks a document that cannot be planned against the store, such as a new resource whose secret is not set. Its text is meant for the caller.

Functions

func EnvName

func EnvName(provider, key string) string

EnvName names the environment variable that holds a secret: a provider key is "REMORA_PROVIDER_<PROVIDER>_<KEY>", a client key (provider "") is "REMORA_KEY_<NAME>". Letters are upper-cased and every other character that is not a letter or digit becomes "_".

func Marshal

func Marshal(f File) ([]byte, error)

Marshal writes f as YAML in a stable order: every list sorted by name (provider keys by name within their provider); alias members keep their order, which is the fallback order. f itself is not changed.

func PlanHash added in v0.3.0

func PlanHash(prune bool, want File, sec Secrets, current File) string

PlanHash binds a plan to both what it would write and what it was planned against: the hex sha256 of the canonical JSON of {prune, want (normalised), secrets (name → sha256 of the value, never the value), current (the store exported as a File, normalised)}. A different document, secret or prune flag, or any store change since planning, gives a different hash.

func SecretRef

func SecretRef(v string) (string, error)

SecretRef returns NAME for a value "env:NAME", and "" with an error naming the expected form otherwise.

Types

type AccountStrategies added in v0.3.0

type AccountStrategies interface {
	Strategies(ctx context.Context) (map[string]alias.Strategy, error) // every subscription provider, round-robin by default
	SetStrategy(ctx context.Context, provider string, st alias.Strategy) error
	Reconcile(ctx context.Context) error
}

AccountStrategies reads and sets each subscription provider's account strategy. SetStrategy called under a Batch context writes on the batch's transaction; Reconcile then applies the committed strategies to the engine.

type Aliases

type Aliases interface {
	List(ctx context.Context) ([]alias.Alias, error)
	Get(ctx context.Context, name string) (alias.Alias, error)
	Put(ctx context.Context, a alias.Alias, create bool) (alias.Alias, error)
	Delete(ctx context.Context, name string) error
	Chain(ctx context.Context, name string) ([]alias.Target, error)     // compiled, before cooling
	Compile(ctx context.Context, a alias.Alias) ([]alias.Target, error) // an unsaved alias against the stored ones; stores nothing
	Cooling(ctx context.Context) ([]CoolingMember, error)
}

Aliases manages aliases. alias.ErrCycle, ErrDepth and ErrUnknownMember pass through.

type ApplyError

type ApplyError struct {
	Change Change
	Err    error
}

ApplyError is the failure of one change during Apply.

func (*ApplyError) Error

func (e *ApplyError) Error() string

func (*ApplyError) Unwrap

func (e *ApplyError) Unwrap() error

type Batch added in v0.2.0

type Batch func(ctx context.Context, fn func(ctx context.Context) error) error

Batch runs fn so that the port writes made under the context it gets are committed together or not at all.

type Change

type Change struct {
	Op, Kind, Name string
	Fields         []string
	Value          string
}

Change is one difference between a document and the store. Op is "create", "update" or "delete"; Kind is "provider", "alias", "key" or "account_strategy"; Fields lists the fields an update changes ("members", "allow", "keys", "base_url", ...) and is empty, not nil, for create and delete. Value is set only on a client key that Apply created with a generated value, so that it can be shown once.

type Config

type Config struct {
	Listen        string        // REMORA_LISTEN, default ":8080"
	DataDir       string        // REMORA_DATA, default "/data"
	AdminPassword string        // REMORA_ADMIN_PASSWORD, "" = generate at first boot
	LogLevel      slog.Level    // REMORA_LOG_LEVEL, default info
	EngineDir     string        // REMORA_ENGINE_DIR, default "/usr/local/lib/remora/engines"
	MasterKey     string        // REMORA_MASTER_KEY, "" = $REMORA_DATA/master.key
	Ports         Ports         // REMORA_PORT_ROUTER, REMORA_PORT_ACCOUNTS, REMORA_PORT_SPEECH
	DrainTimeout  time.Duration // REMORA_DRAIN_TIMEOUT, default 5s

	// The speech-to-text adapter.
	SonioxAddr          string        // "127.0.0.1:" + Ports.Soniox
	SonioxBaseURL       string        // REMORA_SONIOX_BASE_URL, default "https://api.soniox.com"
	SonioxPollInterval  time.Duration // REMORA_SONIOX_POLL_INTERVAL, default 1s
	SonioxDeadline      time.Duration // REMORA_SONIOX_DEADLINE, default 30m
	SonioxSweepInterval time.Duration // REMORA_SONIOX_SWEEP_INTERVAL, default 10m
	Cooling             Cooling       // REMORA_COOLING_*

	PprofAddr         string        // REMORA_PPROF_ADDR, "" = off: a loopback host:port that serves net/http/pprof
	LogContent        bool          // REMORA_LOG_CONTENT, default false: keep request and response bodies in the request log
	StatsBackfillPace time.Duration // REMORA_STATS_BACKFILL_PACE, default 500ms between historical pages

	QuotaInterval time.Duration // REMORA_QUOTA_INTERVAL, default 15m, at least 5m, 0 = background checks off
	QuotaBaseURL  string        // REMORA_TEST_QUOTA_BASE_URL, "" = the providers; tests point quota checks at a fake
	// MemoryLimit is the container's memory limit in bytes, 0 = none. serve fills it from the cgroup; it is not read
	// from the environment.
	MemoryLimit int64
}

Config is remora's runtime configuration.

func Load

func Load(getenv func(string) string) (Config, error)

Load reads the configuration through getenv. Every error names its variable.

func (Config) DBPath

func (c Config) DBPath() string

DBPath is the path of the SQLite store.

func (Config) StopTimeout added in v0.7.0

func (c Config) StopTimeout() time.Duration

StopTimeout bounds shutdown, including the time reserved for cleanup after the drain.

type Cooling

type Cooling struct {
	Count429  int           // REMORA_COOLING_429_COUNT, default 3: 429s within Window429 that cool a member
	Window429 time.Duration // REMORA_COOLING_429_WINDOW, default 60s
	Default   time.Duration // REMORA_COOLING_DEFAULT, default 5m: cooldown when the upstream gave no retry hint
	Poll      time.Duration // REMORA_COOLING_POLL, default 1s: how often the front door's log is read
	// SubscriptionDefault is the cooldown of a subscription member without a retry hint: the accounts behind it come
	// back within seconds. REMORA_COOLING_SUBSCRIPTION_DEFAULT, default 30s.
	SubscriptionDefault time.Duration
}

Cooling tunes when an alias member that keeps failing is left out of its chains, and how often the front door's log is read for failures.

type CoolingMember

type CoolingMember struct {
	Target alias.Target
	Until  time.Time
	Reason string
}

CoolingMember is a target that is cooling down after failures.

type File

type File struct {
	Version   int            `yaml:"version,omitempty"` // 1; 0 is read as 1
	Providers []FileProvider `yaml:"providers"`
	Aliases   []FileAlias    `yaml:"aliases"`
	Keys      []FileKey      `yaml:"keys"`
	// AccountStrategies is the routing strategy per subscription provider; an omitted provider is round-robin.
	AccountStrategies map[string]string `yaml:"account_strategies,omitempty"`
}

File is the one remora.yaml format: the providers, aliases and client keys `remora apply -f` makes the store match. Plan 05 extends it (export, diff, a JSON Schema) without a second set of types.

func Parse

func Parse(b []byte) (File, error)

Parse decodes a remora.yaml and validates it, against Validate's rules and the published JSON Schema (api/remora.schema.json). An unknown field is an error naming its line and field; every other error names the field's path, such as "keys[0].value". An empty document is an empty File.

func (File) Validate

func (f File) Validate() error

Validate checks what can be checked without the store or the environment. Each error names the field's path.

type FileAlias

type FileAlias struct {
	Name          string   `yaml:"name"`
	Kind          string   `yaml:"kind"`
	Members       []string `yaml:"members"`
	Capabilities  []string `yaml:"capabilities,omitempty"`
	ContextWindow int      `yaml:"context_window,omitempty"`
	Strategy      string   `yaml:"strategy,omitempty"` // one of alias.Strategies; omitted is priority
}

FileAlias is an alias and its ordered members (aliases or "<provider>/<model>").

type FileKey

type FileKey struct {
	Name    string   `yaml:"name"`
	Value   string   `yaml:"value,omitempty"`
	Allow   []string `yaml:"allow"`
	Enabled *bool    `yaml:"enabled,omitempty"` // default true
}

FileKey is a client key. Value is "env:NAME"; when it is omitted on a new key, apply generates one and prints it once.

type FileProvider

type FileProvider struct {
	Name                string          `yaml:"name"`
	Kind                string          `yaml:"kind"`           // builtin | openai-compatible | typesafe-compatible | soniox
	Type                string          `yaml:"type,omitempty"` // builtin only, e.g. openrouter
	BaseURL             string          `yaml:"base_url,omitempty"`
	AllowPrivateNetwork bool            `yaml:"allow_private_network,omitempty"`
	Keys                []FileSecretKey `yaml:"keys"`
}

FileProvider is an upstream provider and its keys.

type FileSecretKey

type FileSecretKey struct {
	Name  string `yaml:"name"`
	Value string `yaml:"value"`
}

FileSecretKey is one provider key. Value must be "env:NAME": a secret never sits in the file.

type Key

type Key struct {
	ID, Name, Prefix string
	Allow            []string
	Enabled          bool
	CreatedAt        time.Time
}

Key is a client key for /v1. Its value is shown once, at creation.

type KeyPatch

type KeyPatch struct {
	Name    *string
	Allow   *[]string
	Enabled *bool
}

KeyPatch changes the fields that are set.

type Keys

type Keys interface {
	List(ctx context.Context) ([]Key, error)
	Get(ctx context.Context, id string) (Key, error)
	Create(ctx context.Context, name string, allow []string, value string, enabled bool) (Key, string, error) // value "" → generated; returns the value
	Update(ctx context.Context, id string, p KeyPatch) (Key, error)
	SetValue(ctx context.Context, id, value string) error // apply/import replacing a key's value
	MatchesValue(ctx context.Context, id, value string) (bool, error)
	Delete(ctx context.Context, id string) error
}

Keys manages client keys.

type PlanMismatchError added in v0.3.0

type PlanMismatchError struct {
	Changes []Change // the fresh plan
	Hash    string   // PlanHash over the same inputs and the current store
}

PlanMismatchError is ApplyPlanned's answer when the store no longer plans to the wanted hash: nothing was applied.

func (*PlanMismatchError) Error added in v0.3.0

func (e *PlanMismatchError) Error() string

type Ports

type Ports struct {
	Bifrost     int // REMORA_PORT_ROUTER
	CLIProxyAPI int // REMORA_PORT_ACCOUNTS
	Soniox      int // REMORA_PORT_SPEECH
}

Ports are the loopback ports of the internal processes. The Go fields name the engines; the variables that set them are neutral.

type Provider

type Provider struct {
	Name, Kind, Type, BaseURL string
	AllowPrivateNetwork       bool
	Keys                      []ProviderKey
}

Provider is an upstream reached with API keys.

type ProviderKey

type ProviderKey struct{ Name, Value string }

ProviderKey is one credential of a provider. Value is never serialised by handlers.

type ProviderTest

type ProviderTest struct {
	OK      bool
	Latency time.Duration
	Message string
}

ProviderTest is the result of a provider connectivity test.

type Providers

type Providers interface {
	List(ctx context.Context) ([]Provider, error)
	Get(ctx context.Context, name string) (Provider, error)
	Create(ctx context.Context, p Provider) (Provider, error)
	Update(ctx context.Context, p Provider) (Provider, error) // empty Keys = keep stored keys
	Delete(ctx context.Context, name string) error
	Test(ctx context.Context, name string) (ProviderTest, error)
}

Providers manages providers. Engine failures roll the store back and are returned.

type Secrets

type Secrets map[string]string

Secrets holds the values of a document's "env:NAME" references, by NAME.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service plans and applies remora.yaml documents and exports the store as one, through the management ports.

func NewService

func NewService(p Providers, a Aliases, k Keys, as AccountStrategies, batch Batch) *Service

NewService returns a Service over the provider, alias, client key and account strategy ports; Apply makes its writes in one batch.

func (*Service) Apply

func (s *Service) Apply(ctx context.Context, want File, sec Secrets, prune bool) ([]Change, error)

Apply makes the store match want, change by change in Plan's order (see Plan for matching, secrets and prune), and returns the changes it made. The changes are made in one Batch: when one fails, none is kept, and the error is an *ApplyError naming the change that failed. A client key created without a value gets a generated one, returned once in its Change's Value.

func (*Service) ApplyPlanned added in v0.3.0

func (s *Service) ApplyPlanned(ctx context.Context, want File, sec Secrets, prune bool, wantHash string) ([]Change, error)

ApplyPlanned is Apply with a guard: when wantHash is not "", the plan is made inside the apply's Batch, which holds the store's write lock until commit, and if its PlanHash differs nothing is written and the error is a *PlanMismatchError.

func (*Service) Export

func (s *Service) Export(ctx context.Context) (File, error)

Export returns the store as a document: every provider with its keys as env:NAME references (EnvName), every alias, and every client key without its value. A provider whose kind a document cannot hold is left out.

func (*Service) Plan

func (s *Service) Plan(ctx context.Context, want File, sec Secrets, prune bool) ([]Change, error)

Plan returns the changes that would make the store match want, in the order Apply makes them; it changes nothing. Providers are matched by name, provider keys by provider and key name, aliases and client keys by name. A secret "env:NAME" is sec[NAME]: when NAME is absent the stored secret is kept, and a resource that does not exist yet is an ErrInvalid error naming it. With prune, what the store has and want does not is deleted; without it nothing is deleted, not even a provider key want leaves out.

Jump to

Keyboard shortcuts

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