settings

package
v0.10.4 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: Apache-2.0 Imports: 19 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 settings is the typed-sectioned config layer.

Each known section is a Go type with a Validate() method, registered statically in this package's init via Register(). The DB stores one row per section in the `settings` table; the value is opaque JSONB, the typed struct enforces shape on read and write.

Adding a new section: create <section>.go with the typed struct, implement Validate() error, call Register() from its init().

Hot-path consumers read from the in-memory Cache populated by the catalog reconciler; the Store is admin-plane only.

Index

Constants

View Source
const (
	SectionGovernanceProvider = "governance:provider"
	SectionGovernanceHost     = "governance:host"
	SectionGovernanceModel    = "governance:model"
	SectionGovernancePolicy   = "governance:policy"
)

Governance section keys. Colon-namespaced so they double as future RBAC permission targets (governance:<resource>). Only the catalog-managed kinds need a section; purely user-owned kinds fall through to the user tier in Governs.

View Source
const AuthOIDCSection = "auth:oidc"

AuthOIDCSection is the section name.

View Source
const AuthTokensSection = "auth:tokens"

AuthTokensSection is the section name.

View Source
const DefaultKeyRotateMaxGrace = 24 * 60 * 60

DefaultKeyRotateMaxGrace is the cap applied when the section leaves KeyRotateMaxGrace unset.

View Source
const DefaultPayloadRetentionDays = 30

DefaultPayloadRetentionDays applies when payload-logging sets no retentionDays.

View Source
const DefaultVerifyCacheSize = 10000

DefaultVerifyCacheSize is the verified-claims cache bound when the section names none.

View Source
const OAuthSectionPrefix = "oauth:"

OAuthSectionPrefix namespaces per-provider OAuth sections (oauth:anthropic, oauth:openai, …), mirroring the governance:<kind> convention.

View Source
const SectionAudit = "audit"

SectionAudit is the section key for the admin audit log's retention window. Read live by the audit emitter's hourly prune, so a change takes effect without a restart.

View Source
const SectionCatalogSource = "catalog-source"

SectionCatalogSource is the section key for the catalog-source marker — the record of which public-catalog version the DB's template rows were last seeded from.

View Source
const SectionInference = "inference"

SectionInference is the section key for normal-mode inference behavior knobs — settings that affect /v1/* traffic served via an authenticated Key. Distinct from proxy-mode (BYO-creds), which has its own section.

View Source
const SectionLicense = "license"

SectionLicense holds the inline license value pasted through the admin UI, so a deployment can install a key without a redeploy. The RELAY_LICENSE_FILE / RELAY_LICENSE environment still wins when set.

View Source
const SectionOTLPReceiver = "otlp-receiver"

SectionOTLPReceiver is the section key for the OpenTelemetry receiver on the inference listener.

View Source
const SectionParsing = "parsing"

SectionParsing is the section key for request-parsing behavior knobs — how much structure the relay extracts from inbound request bodies before dispatch. Applies across flows (authenticated /v1/* and proxy-mode), so it is its own section rather than living under inference or proxy-mode.

View Source
const SectionPayloadLogging = "payload-logging"

SectionPayloadLogging is the section key for the request/response body capture observer's runtime config. Mutable at runtime via the settings API — the payload observer reconciles the live value and hot-swaps its sink (toggle, backend, bucket, credentials) without a restart.

View Source
const SectionProxyMode = "proxy-mode"

SectionProxyMode is the section key for the proxy-mode settings — the singleton that gates anonymous-key (BYO upstream creds) inference traffic served by the future app/proxy flow.

View Source
const SectionUsageLogging = "usage-logging"

SectionUsageLogging is the section key for the log (usage) event sink's backend selection. The log observer reconciles the live value and hot-swaps its sink + reader without a restart. Mirrors payload-logging, minus the per-request opt-in (logging is constant — every request).

Connection-level config (DSNs) stays bootstrap-tier (boot env), the same way the PG DSN does: you need a connection before you can read settings. Only the backend selection + safe per-backend knobs live here.

Variables

View Source
var ErrSecretRefNotAllowed = errors.New("secret reference not allowed")

ErrSecretRefNotAllowed marks a section value that would resolve a secret outside the section's scope or send one without TLS.

GovernanceSections lists every registered governance:<kind> section key.

Functions

func AdminOnly added in v0.10.1

func AdminOnly(section string) bool

AdminOnly reports whether writing section requires an admin caller.

func Governs

func Governs(r Reader, op Op, kind, ownerKind string, admin bool) error

Governs decides whether op may be applied to a row of the given kind with the given ownerKind. It is the single source of truth for mutation governance; httpapi calls it and maps a non-nil result to 403.

Owner tiers are hardcoded invariants (not operator-toggleable):

  • system → edited or deleted only by an admin (the admin role or the admin token). A delete is still refused while anything references the row; that check lives with the references, not here.
  • user / team / project → always allowed (the row belongs to a tenant, not to the catalog). RBAC will later add an owner match here.
  • else (provider/host-owned, i.e. catalog-managed) → consult the kind's governance:<kind> section; absent or unregistered ⇒ the safe default (edit allowed, delete denied).

admin reports whether the caller holds the admin identity (authz.IsAdmin); it only widens the system tier.

func Names

func Names() []string

Names returns all registered section names in lexical order. Used by the list endpoint and the cache to enumerate sections.

func OAuthSection added in v0.4.2

func OAuthSection(provider string) string

OAuthSection returns the settings section name for a provider.

func Register

func Register(sec Section)

Register adds sec to the section registry. Called from each section's init(). Panics on duplicate registration — the typo would otherwise be silent.

func RegisterOAuthProvider added in v0.4.2

func RegisterOAuthProvider(provider string)

RegisterOAuthProvider registers the oauth:<provider> settings section so its config can be seeded and edited via the settings API. Call once per provider (e.g. from a vendor wiring file in the composition root) before settings are seeded or served. Panics on duplicate registration.

func SecretRefs added in v0.10.1

func SecretRefs(v any) map[string]secret.Ref

SecretRefs returns the secret refs a section value holds, keyed by field path, so deleting a stored secret can tell whether a section still names it. A section with a secret.Ref field must be listed here.

func SeedDir

func SeedDir(ctx context.Context, store *Store, dir string) ([]string, error)

SeedDir loads settings from manifest YAML in dir and upserts each section that has NO existing DB row — **seed-if-absent**. It never clobbers a runtime change or a prior seed, so a live `PUT /settings/...` stays authoritative. This is the first-boot / airgapped path; managed deployments are configured at runtime via the settings API.

Settings use the same Kubernetes-style manifest envelope as every other catalog resource — `apiVersion` + `kind: Setting` + `metadata.name` (the section key) + `spec` (the section's typed value). Files may hold multiple `---`-separated docs. metadata.name selecting an unregistered section, a spec that fails the section's Decode, or a non-Setting kind in the tree are all hard errors (fail fast on a typo). A missing dir is a no-op.

Returns the section names actually seeded, lexically sorted.

func SetLicenseGate added in v0.10.0

func SetLicenseGate(c license.Checker)

SetLicenseGate installs the Checker gated sections consult. Called once by the composition root before the first settings decode; until then every gated feature reads as unlicensed.

func SetSchemaRef

func SetSchemaRef(name, ref string)

SetSchemaRef records the OpenAPI component name for section's typed value. Called by the HTTP layer right after huma registers the typed GET/PUT pair, so the per-section schema id is discoverable via the list / sections endpoints.

Types

type Audit added in v0.10.0

type Audit struct {
	// RetentionDays is how long audit rows are kept. 0 disables pruning —
	// deliberate, for deployments that archive the table externally.
	RetentionDays int `json:"retentionDays"`
}

Audit configures the admin audit log.

func (*Audit) Validate added in v0.10.0

func (a *Audit) Validate() error

Validate is enforced before any write.

type AuthOIDC added in v0.7.0

type AuthOIDC struct {
	Enabled bool `json:"enabled"`

	// Issuer is the provider's issuer URL; endpoints are discovered from
	// its metadata document.
	Issuer   string `json:"issuer,omitempty"`
	ClientID string `json:"clientId,omitempty"`

	// ClientSecretEnv names the env var holding the client secret; it must
	// start with RELAY_OIDC_ (or WYOLET_OIDC_). Indirection keeps the secret
	// out of the settings row (world-readable to any authenticated operator).
	ClientSecretEnv string `json:"clientSecretEnv,omitempty"`

	// RedirectURL is this relay's public callback,
	// e.g. https://relay.example.com/api/auth/oidc/callback.
	RedirectURL string `json:"redirectUrl,omitempty"`

	// Scopes defaults to ["openid", "profile", "email"].
	Scopes []string `json:"scopes,omitempty"`

	// AuthParams are extra authorization-URL query params some providers
	// require beyond the OIDC standard set (e.g. WorkOS AuthKit needs
	// {"provider": "authkit"}). Provider-specific values live here in
	// config, never in code.
	AuthParams map[string]string `json:"authParams,omitempty"`

	// GroupsClaim names the id-token claim carrying the user's IdP groups
	// (default "groups"); empty after an explicit "" write means the
	// provider asserts none.
	GroupsClaim *string `json:"groupsClaim,omitempty"`

	// Registration gates first-login auto-provisioning: "open" creates a
	// user row on first successful OIDC login; "closed" (default) rejects
	// subjects with no existing user row.
	Registration string `json:"registration,omitempty"`

	// PostLoginURL is where the callback sends the browser after minting
	// the session. Empty means "/" — correct when the admin UI is embedded
	// (same origin as the callback). Set it to the UI's origin when the UI
	// is served from a different hostname than the control API, so a login
	// doesn't strand the user on the API origin.
	PostLoginURL string `json:"postLoginUrl,omitempty"`
}

AuthOIDC is the auth:oidc settings section: inbound OpenID Connect login for the control plane. Disabled by default — the zero value changes nothing about a deployment. When enabled, GET /auth/oidc/start redirects to the provider and /auth/oidc/callback exchanges the code and mints a normal relay session, so everything downstream of login is unchanged.

The provider is generic OIDC: any issuer publishing a discovery document (RFC 8414 / OpenID discovery) works. The client secret is referenced by env var name, never stored in the section value.

func AuthOIDCEnv added in v0.9.9

func AuthOIDCEnv() (*AuthOIDC, error)

AuthOIDCEnv reads the WYOLET_* environment overlay. WYOLET_AUTH_MODE=oidc returns a fully-formed enabled section that short-circuits the DB-backed one — deployment env is the platform's config channel, and turning SSO on must not require a live DB write. Any other mode value (including the platform-contract "insecure-dev", which relay covers with password login) returns (nil, nil): overlay inactive. A malformed active overlay returns an error; callers on the boot path should treat it as fatal.

func AuthOIDCFrom added in v0.7.0

func AuthOIDCFrom(r Reader) *AuthOIDC

AuthOIDCFrom reads the typed section from a settings Reader, tolerating absent or mistyped values (returns the zero value → disabled).

func EffectiveAuthOIDC added in v0.9.9

func EffectiveAuthOIDC(r Reader) *AuthOIDC

EffectiveAuthOIDC is what handlers obey: the env overlay when active, else the DB-backed section. A malformed overlay resolves to the DB path here — the boot path has already fatal'd on it, so a running process never carries one.

func (*AuthOIDC) EffectiveGroupsClaim added in v0.10.0

func (c *AuthOIDC) EffectiveGroupsClaim() string

EffectiveGroupsClaim returns the id-token claim to read groups from, or "" when the deployment has explicitly opted out.

func (*AuthOIDC) EffectiveScopes added in v0.7.0

func (c *AuthOIDC) EffectiveScopes() []string

EffectiveScopes returns Scopes or the OIDC default set.

func (*AuthOIDC) OpenRegistration added in v0.7.0

func (c *AuthOIDC) OpenRegistration() bool

OpenRegistration reports whether first-login auto-provisioning is on.

func (*AuthOIDC) Validate added in v0.7.0

func (c *AuthOIDC) Validate() error

Validate enforces shape only when enabled — a disabled section may be sparse or empty. The secret reference and issuer are checked whenever present.

type AuthTokens added in v0.10.0

type AuthTokens struct {
	Enabled bool `json:"enabled"`

	// DefaultTTL applies when a mint request names no ttl; MaxTTL caps what
	// a request may ask for. Both are time.Duration — nanoseconds on the
	// wire, as everywhere Go durations are serialized.
	DefaultTTL time.Duration `json:"defaultTTL"`
	MaxTTL     time.Duration `json:"maxTTL"`

	// SigningKey points at the stored Ed25519 seed. Empty means "not
	// generated yet": boot mints one, stores it through the master-key path,
	// and writes the ref back here.
	SigningKey secret.Ref `json:"signingKey,omitempty"`

	// PreviousSigningKey is the ref rotation replaced. Tokens minted under
	// it still verify, so a rotation is not a fleet-wide logout — every pod
	// loads both refs at boot, not just the one it happened to rotate.
	PreviousSigningKey secret.Ref `json:"previousSigningKey,omitempty"`

	// VerifyCacheSize bounds how many verified tokens the data plane keeps
	// so a repeat request skips the Ed25519 verify. 0 uses the default;
	// negative disables the cache.
	VerifyCacheSize int `json:"verifyCacheSize,omitempty"`
}

AuthTokens is the auth:tokens settings section: short-lived, relay-signed inference tokens a logged-in user mints for a project. Enabled by default, but a deployment with no master key has nowhere to keep the signing key and stays token-less until one is configured.

func AuthTokensFrom added in v0.10.0

func AuthTokensFrom(r Reader) *AuthTokens

AuthTokensFrom reads the typed section from a settings Reader, tolerating absent or mistyped values (returns the defaults).

func (*AuthTokens) EffectiveVerifyCacheSize added in v0.10.0

func (a *AuthTokens) EffectiveVerifyCacheSize() int

EffectiveVerifyCacheSize resolves the configured bound, 0 meaning "disabled".

func (*AuthTokens) Validate added in v0.10.0

func (a *AuthTokens) Validate() error

Validate is enforced before any write.

type CatalogSource added in v0.5.0

type CatalogSource struct {
	// Version is the catalog ref (tag) the last versioned seed ran from,
	// e.g. "v0.1.0". Empty when the catalog was seeded without a version
	// (local dir / embedded first-boot seed) or never seeded.
	Version string `json:"version,omitempty"`

	// SeededAt is when that seed completed (RFC 3339).
	SeededAt string `json:"seededAt,omitempty"`
}

CatalogSource records the provenance of the seeded catalog. Written by the bootstrap seeder after a successful versioned seed; compared against RELAY_CATALOG_VERSION at boot to decide whether a re-seed is due. An operator can blank Version via the settings API to force a re-seed on the next boot. Re-seeds only touch pristine template rows: operator- edited (dirty) rows are skipped and overlays re-merge at snapshot load, so user changes survive.

func (*CatalogSource) Validate added in v0.5.0

func (c *CatalogSource) Validate() error

type Governance

type Governance struct {
	AllowEdit   bool `json:"allowEdit"`
	AllowDelete bool `json:"allowDelete"`
}

Governance is the per-resource mutation policy: whether a catalog-managed row of a given kind may be edited or deleted through the generic control CRUD API. One value type is shared by every governance:<kind> section so the shape — and the decision logic in Governs — stays uniform.

These toggles are a speed-bump against accidental mutation, not a wall: editing catalog rows is rare but safe (the router self-heals; nothing hard-depends on a specific row surviving), so AllowEdit defaults true. Deleting is the click-around risk, so AllowDelete defaults false and an operator flips it on when they actually mean to prune.

func (*Governance) Validate

func (g *Governance) Validate() error

type Inference

type Inference struct {
	// AllowMissingPolicy permits a Key with an empty Spec.PolicyID
	// to reach inference endpoints. The request bypasses the per-policy
	// authorization gate: any model served by any host the relay has
	// hostkeys for is reachable, with no policy-level rate limits (system
	// ratelimits still apply). When false, requests from such keys are
	// rejected with 403.
	//
	// Read only under single-user authorization (RELAY_AUTHZ=single).
	// Under rbac a credential's grants are the whole access model, so a
	// key with no policy is rejected whatever this says.
	//
	// Default false. Turn on only for self-hosted setups where the
	// operator is the caller (single-tenant) and wants a god-mode key.
	AllowMissingPolicy bool `json:"allowMissingPolicy"`

	// KeyRotateMaxGrace caps, in seconds, how long a rotated key's previous
	// hash keeps authenticating. Zero means the default below; rotation
	// requests above the cap are rejected.
	KeyRotateMaxGrace int `json:"keyRotateMaxGrace"`
}

Inference controls authenticated-flow behavior.

func (*Inference) MaxRotateGrace added in v0.10.0

func (i *Inference) MaxRotateGrace() int

MaxRotateGrace resolves the configured cap, falling back to the default.

func (*Inference) Validate

func (i *Inference) Validate() error

type License added in v0.10.0

type License struct {
	// Value is the signed license file, verbatim. Empty is a community
	// deployment.
	Value string `json:"value,omitempty"`
}

License is the license settings section.

func LicenseFrom added in v0.10.0

func LicenseFrom(r Reader) *License

LicenseFrom reads the typed section from a settings Reader, tolerating absent or mistyped values (returns the zero value → community).

func (*License) Validate added in v0.10.0

func (l *License) Validate() error

Validate accepts any value: only the verifier in the composition root can tell a good license from a bad one, and it runs before this is written (PUT /license) rather than here.

type MutationError

type MutationError struct {
	Op        Op
	Kind      string
	OwnerKind string
	Reason    string
}

MutationError is returned by Governs when an operation is not permitted. The control layer maps it to a 403.

func (*MutationError) Error

func (e *MutationError) Error() string

type OAuthProvider added in v0.4.2

type OAuthProvider struct {
	oauth.ProviderConfig
}

OAuthProvider is the typed value of an oauth:<provider> settings section: the flow config (authorize/token endpoints, client id, scopes, authorize params) used to acquire and refresh that provider's OAuth credentials.

The relay core ships only this generic shape. Concrete provider values are operator/community config — register a provider's section with RegisterOAuthProvider and supply the values via the settings API or a config/settings/oauth-<provider>.yaml. No provider is registered by default.

func (*OAuthProvider) Validate added in v0.4.2

func (c *OAuthProvider) Validate() error

Validate enforces the minimum a flow + refresh needs.

type OTLPReceiver added in v0.10.3

type OTLPReceiver struct {
	// Enabled accepts exports at POST /otlp/v1/traces and /otlp/v1/logs. Off by default: reported usage is self-declared by the client and is recorded, never enforced.
	Enabled bool `json:"enabled"`
	// CaptureContent stores the message content a client reports with a call (instructions, input and output messages, tool definitions) in the payload store. It takes effect only while payload logging is enabled, and a policy governing the reporting credential must allow payload logging. Off by default: content is the client's data and the largest part of an export.
	CaptureContent bool `json:"captureContent,omitempty"`
}

OTLPReceiver configures the endpoints that accept telemetry clients report about model calls relay did not carry.

func OTLPReceiverFrom added in v0.10.3

func OTLPReceiverFrom(r Reader) *OTLPReceiver

OTLPReceiverFrom reads the typed section from a settings Reader, tolerating absent or mistyped values (returns the zero value: disabled).

func (*OTLPReceiver) Validate added in v0.10.3

func (o *OTLPReceiver) Validate() error

Validate is enforced before any write.

type Op

type Op string

Op is a mutating operation subject to the governance check.

const (
	OpEdit   Op = "edit"
	OpDelete Op = "delete"
)

type Parsing

type Parsing struct {
	// RichParsing extracts per-request metadata and messages from the
	// body (for attribution / observability). When false the relay
	// reads only the minimal fields needed to route (model, stream),
	// leaving metadata and messages unparsed — lower CPU on the hot
	// path, no body-level observability.
	//
	// Default true. Hot-swappable: a change takes effect on the next
	// request within a reconcile interval, no restart.
	RichParsing bool `json:"richParsing"`
}

Parsing controls inbound request-body parsing depth.

func (*Parsing) Validate

func (p *Parsing) Validate() error

type PayloadClickHouse

type PayloadClickHouse struct {
	// WALDir overrides the local WAL segment directory; empty uses the
	// boot default.
	WALDir string `json:"walDir,omitempty"`

	// Dedup stores each distinct message, tool list and system prompt once
	// and request bodies as references to them. Rows written either way
	// stay readable.
	Dedup bool `json:"dedup,omitempty"`
}

PayloadClickHouse configures the ClickHouse backend (Langfuse-style: text bodies as ZSTD String columns, queryable). The DSN is NOT stored here — it reuses the relay's boot CH connection (RELAY_CH_DSN, the same cluster the usage sink uses), so no credentials live in this row. Only the per-backend knobs that are safe to hot-swap live here.

type PayloadFile

type PayloadFile struct {
	Path string `json:"path"`
}

PayloadFile configures the JSONL file backend.

type PayloadLogging

type PayloadLogging struct {
	// Enabled is the global master switch. When false the observer
	// produces nothing regardless of per-request opt-in.
	Enabled bool `json:"enabled"`

	// Backend selects the sink: "file" (default), "s3", or "clickhouse".
	Backend string `json:"backend"`

	// MaxBytes caps each stored body, measured on the DECODED plaintext
	// (compressed upstream bodies are decoded before capture); 0 = unlimited.
	MaxBytes int `json:"maxBytes"`

	// RetentionDays bounds how long captured bodies are kept by the
	// clickhouse backend; 0 keeps them forever. A stored row without the
	// field decodes to DefaultPayloadRetentionDays, not to keep-forever.
	RetentionDays int `json:"retentionDays"`

	File PayloadFile       `json:"file"`
	S3   PayloadS3         `json:"s3"`
	CH   PayloadClickHouse `json:"clickhouse"`
}

PayloadLogging configures the payloadlog observer. Off by default; the per-request opt-in (policy/key) still gates capture on top of Enabled. Credentials are secret.Refs resolved via pkg/secret, so they can live in env, encrypted-PG, or a future external backend — never as plaintext in this row.

func (*PayloadLogging) Validate

func (p *PayloadLogging) Validate() error

Validate is enforced before any write. Only meaningful when Enabled — a disabled section can hold partial config (e.g. while an operator fills in S3 details before flipping it on). The S3 credentials and transport are checked regardless: the log reader builds from this section whatever the toggle says.

type PayloadS3

type PayloadS3 struct {
	Endpoint  string     `json:"endpoint"`
	Bucket    string     `json:"bucket"`
	Region    string     `json:"region,omitempty"`
	Prefix    string     `json:"prefix,omitempty"`
	UseSSL    bool       `json:"useSSL"`
	AccessKey secret.Ref `json:"accessKey"`
	SecretKey secret.Ref `json:"secretKey"`
}

PayloadS3 configures the object-store backend. AccessKey/SecretKey are secret.Refs resolved at sink-build time: env names under RELAY_PAYLOAD_S3_ or stored ids under "payload-logging:".

type ProxyMode

type ProxyMode struct {
	// Enabled turns the proxy flow on. When false, requests without a
	// valid relay key get 401, regardless of any other field below.
	Enabled bool `json:"enabled"`

	// AllowUnauthenticated lets proxy callers reach the upstream with
	// no relay-side auth — the inbound Authorization header is forwarded
	// as-is. When false, the proxy flow still requires a relay key
	// (proxied traffic gets logged against that key) but the upstream
	// credential comes from the caller.
	AllowUnauthenticated bool `json:"allowUnauthenticated"`
}

ProxyMode controls whether the relay accepts inference requests where the caller brings their own upstream provider key instead of a relay key. The flow lives in app/proxy (not yet built); this section gates the dispatch at the inference handler.

func (*ProxyMode) Validate

func (p *ProxyMode) Validate() error

type Reader

type Reader interface {
	Setting(section string) (any, bool)
}

Reader is the narrow read surface Governs needs — satisfied by *catalog.Catalog. Settings cache reads are lock-free and total (a registered section always returns at least its Defaults).

type Row

type Row struct {
	Section   string
	Value     any
	UpdatedAt time.Time
}

Row is a single settings row, decoded into a typed value via its section's Decode func. UpdatedAt is informational.

type Section

type Section struct {
	Name        string
	Description string
	Defaults    func() any
	Decode      func([]byte) (any, error)
	SchemaRef   string
}

Section describes one known settings section. Defaults returns a fresh zero-value instance; Decode parses raw JSON into a typed value and validates it; SchemaRef is the OpenAPI component name of the typed value's schema (set automatically by the per-section registerSettingsSection helper); Description is operator-facing prose explaining the section's purpose.

func Lookup

func Lookup(name string) (Section, bool)

Lookup returns the registered section by name. ok=false means the caller asked for an unknown section — handler returns 404.

type SectionName

type SectionName string

SectionName is a typed string whose OpenAPI schema is a string enum of every registered section. Use it in handler request/response types instead of bare `string` so the generated spec carries the closed set of valid section keys.

func (SectionName) Schema

func (SectionName) Schema(_ huma.Registry) *huma.Schema

Schema implements huma.SchemaProvider — huma calls this when registering any type that embeds SectionName, snapshotting the current registry into the OpenAPI components.

type Store

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

Store is the data-access layer for settings rows.

func NewStore

func NewStore(q *gen.Queries) *Store

func (*Store) Get

func (s *Store) Get(ctx context.Context, section string) (*Row, error)

Get returns the typed value for section. When no row exists, the section's Defaults() is returned with UpdatedAt zero — so the read path is total: every registered section always has a value.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]*Row, error)

List returns one Row per registered section, falling back to Defaults for sections without a DB row.

func (*Store) Upsert

func (s *Store) Upsert(ctx context.Context, section string, raw json.RawMessage) (*Row, error)

Upsert writes value as the typed section. The Decode round-trip validates input before any DB write.

type UsageClickHouse

type UsageClickHouse struct {
	WALDir string `json:"walDir,omitempty"`
}

UsageClickHouse holds the safe-to-hot-swap CH knobs. The DSN reuses the boot CH connection (bootstrap-tier), so no credentials live in this row.

type UsageFile

type UsageFile struct {
	Path string `json:"path,omitempty"`
}

UsageFile configures the JSONL file backend.

type UsageLogging

type UsageLogging struct {
	// Backend selects the sink+reader: "file" (default), "clickhouse",
	// "postgres", or "valkey".
	Backend string `json:"backend"`

	// RetentionDays bounds how long usage events are kept by the clickhouse
	// and postgres backends; 0 keeps them forever. Applied to the existing
	// table on change, so shortening it deletes history.
	RetentionDays int `json:"retentionDays"`

	File UsageFile       `json:"file"`
	CH   UsageClickHouse `json:"clickhouse"`
}

UsageLogging selects and tunes the log/usage event backend. Per the config direction (minimize env), the backend choice lives here, not in env; the legacy RELAY_EVENTLOG_BACKEND is honored only as an interim fallback when this section is unset, until the YAML→DB settings seed lands.

func (*UsageLogging) Validate

func (u *UsageLogging) Validate() error

Validate enforces the backend enum + non-negative knobs.

Jump to

Keyboard shortcuts

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