store

package
v0.27.2 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: AGPL-3.0 Imports: 32 Imported by: ? 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 store provides the database layer with SQLite and PostgreSQL dual-dialect support.

Package store's migrate_runner.go is the callable form of the metapi-migrate CLI: it transfers all application tables between a SQLite database and a PostgreSQL database (either direction). cmd/migrate/main.go is now a thin wrapper around RunMigration, and handler/admin/settings_database.go queues RunMigration as an admin background task.

The migration matches the TS databaseMigrationService.ts behaviour: - Per-column type coercion with fallback defaults - JSON column serialization (14 columns across 6 tables) - FK-safe DELETE order during overwrite - PostgreSQL sequence synchronization after insert (PG targets only; SQLite AUTOINCREMENT handles itself) - Single-transaction boundary with rollback on error - Settings key filtering (skips db_type, db_url, db_ssl)

ts_schema_detect.go implements startup-time reverse-drift detection for the TS→Go migration: a SQLite database produced by a NEWER TypeScript build may carry columns (or __drizzle_migrations journal entries) this Go build has never seen. Without detection the old binary boots fine and only crashes later, at SELECT time, with "no such column" (the hb0730 failure mode).

Detection is deliberately warn-only. Unknown columns may be harmless, and blocking startup would brick the older binary against any future TS migration — the Go server must keep serving even when the TS side has moved ahead.

Index

Constants

View Source
const (
	DirectCredentialAPIKey = "api_key"
	DirectCredentialOAuth  = "oauth"
	DirectCredentialNone   = "none"
	// DirectCredentialGCPServiceAccount: durable material is the service-account
	// JSON in upstream_credentials.gcp_service_account; secret holds the latest
	// exchanged access token (single-owner token contract unchanged).
	DirectCredentialGCPServiceAccount = "gcp_service_account"
)
View Source
const (
	DirectAuthBearer = "bearer"
	DirectAuthAPIKey = "x-api-key"
	DirectAuthGoogle = "x-goog-api-key"
	DirectAuthNone   = "none"
)
View Source
const (
	DirectProtocolChat                      = 1 << 1
	DirectProtocolResponses                 = 1 << 2
	DirectProtocolMessages                  = 1 << 3
	DirectProtocolGemini                    = 1 << 4
	DirectProtocolCompletions               = 1 << 5
	DirectProtocolEmbeddings                = 1 << 6
	DirectProtocolRerank                    = 1 << 7
	DirectProtocolImageGeneration           = 1 << 8
	DirectProtocolImageEdit                 = 1 << 9
	DirectProtocolImageVariation            = 1 << 10
	DirectProtocolAudioSpeech               = 1 << 11
	DirectProtocolAudioTranscription        = 1 << 12
	DirectProtocolAudioTranslation          = 1 << 13
	DirectProtocolModerations               = 1 << 14
	DirectProtocolVideo                     = 1 << 15
	DirectProtocolGeminiEmbeddings          = 1 << 16
	DirectProtocolJinaEmbeddings            = 1 << 17
	DirectProtocolModelScopeImageGeneration = 1 << 18
	DirectProtocolSeedanceVideo             = 1 << 19
	DirectProtocolZenmuxVideo               = 1 << 20
	DirectProtocolOllama                    = 1 << 21
	DirectProtocolSystemOne                 = 1 << 22
	DirectProtocolAlphaSearch               = 1 << 23
	DirectStandardGenerationProtocols       = DirectProtocolChat | DirectProtocolResponses | DirectProtocolMessages | DirectProtocolGemini
	DirectGenerationProtocols               = DirectStandardGenerationProtocols | DirectProtocolOllama
	DirectVideoProtocols                    = DirectProtocolVideo | DirectProtocolSeedanceVideo | DirectProtocolZenmuxVideo
	DirectAllProtocols                      = (1 << 24) - 2
)

These persisted bits are shared by endpoint configuration, grants and route member restrictions. Existing bits are never reassigned.

View Source
const (
	DialectSQLite   = "sqlite"
	DialectPostgres = "postgres"
)

Dialect name constants.

View Source
const GatewayRequestTimeLayout = "2006-01-02T15:04:05.000000000Z"

GatewayRequestTimeLayout keeps TEXT timestamps chronologically sortable at fractional-second boundaries and across client time-zone offsets.

View Source
const GatewayUserDirectoryLimit = 1000

GatewayUserDirectoryLimit caps the initial administrator directories until they have a paginated API. Route grants are not truncated authorization data.

View Source
const LegacyProxyTokenMigrationKey = "downstream.root_token_migrated_v1"
View Source
const UserKeyResourceOwnerPrefix = "user-key:"

Distinguishes user-Key-owned files/tasks even in portable row payloads.

Variables

View Source
var (
	ErrGatewayUserInvalid     = errors.New("invalid gateway user input")
	ErrGatewayUserUnavailable = errors.New("gateway user store unavailable")
)
View Source
var (
	ErrUserBudgetExceeded = errors.New("user budget exhausted or reserved")
	ErrUserBudgetUnknown  = errors.New("user budget accounting unresolved")
	ErrUserBudgetConflict = errors.New("user budget request identity conflict")
)

Functions

func AllTableNames added in v0.12.0

func AllTableNames() []string

AllTableNames returns the application tables transferred between dialects by cmd/migrate, ordered parents-before-children so inserts satisfy foreign keys. It is derived from the schema registry minus migrationExcludedTables; this is the single source of truth for the migration table set and cmd/migrate must not maintain its own copy.

func ApplyAdditiveMigrations

func ApplyAdditiveMigrations(db *DB) error

ApplyAdditiveMigrations ensures the bookkeeping table exists, then runs any pending enterpriseAdditiveSteps in registry order. Safe on fresh and old DBs.

func ApplyRuntimeSettings

func ApplyRuntimeSettings(cfg *config.Config, rt *config.RuntimeSettings, settingsMap map[string]string)

Mirrors TS runtime settings application logic. Settings stored in the settings table are JSON-encoded; this function parses and applies them. Numeric keys are clamped exactly like the env path in config.Load, so a value persisted through the admin API cannot bypass a floor the same value would hit when it arrives through env.

func AutoMigrate

func AutoMigrate(db *DB) error

AutoMigrate creates every table in the schema registry (store/tablesets.go) with indexes, unique constraints, foreign keys, and check constraints. Uses CREATE TABLE IF NOT EXISTS for idempotency. After the base bootstrap it runs the additive enterprise steps (schema_migrations bookkeeping + ordered ALTER TABLE upgrades) and logs a one-line summary when legacy-schema convergence actually happened. Run on startup after Open().

func BackupExcludedTables added in v0.17.1

func BackupExcludedTables() map[string]string

BackupExcludedTables returns a copy of the backup exclusion set: table name to the reason it is not carried. Callers surface it to operators (metadata.excluded_tables in the export payload) and the drift guard checks it against the registry, so an exclusion can never be silent or orphaned.

func BackupTableNames added in v0.17.1

func BackupTableNames() []string

BackupTableNames returns the tables a backup export carries, ordered parents-before-children so an import can replay the payload in one pass without violating a foreign key. It is the schema registry minus backupExcludedTables; service/backup must not keep its own copy of the list.

func ClearTableNames added in v0.12.0

func ClearTableNames() []string

ClearTableNames returns the same table set in FK-safe delete order (children before parents): the reverse of AllTableNames, which is topologically parents-first. Used to wipe a target database before a re-insert.

func CloseDatabase

func CloseDatabase() error

CloseDatabase closes the active database connection and resets the initialized flag so EnsureRuntimeDatabase can be called again.

func DirectProviderAllowsAnonymous added in v0.24.0

func DirectProviderAllowsAnonymous(provider string) bool

func DirectVideoTaskOwner added in v0.26.0

func DirectVideoTaskOwner(source, token string, keyID *int64) string

DirectVideoTaskOwner keeps durable video ownership stable across key rotation.

func EnsureColumn

func EnsureColumn(db *DB, table, column, sqliteType, pgType, defaultClause string) error

This is the primary primitive SC2 uses for enterprise columns.

func EnsureIndex

func EnsureIndex(db *DB, name, createSQL string) error

EnsureIndex creates a non-unique index if missing. Both dialects support CREATE INDEX IF NOT EXISTS.

func EnsureRuntimeDatabase

func EnsureRuntimeDatabase(cfg *config.Config, rt *config.RuntimeSettings) error

EnsureRuntimeDatabase creates the data directory, opens the database, and runs auto-migration. This replaces the P0 stub. Mirrors TS initDb() module-level singleton behavior.

func FactoryReset added in v0.17.0

func FactoryReset(db *sqlx.DB) (map[string]int64, error)

FactoryReset wipes every business table and restarts the auto-increment sequences, which is what the admin "restore factory settings" operation promises. The table set is FactoryResetTableNames(): derived from the schema registry (the same single source of truth AutoMigrate and cmd/migrate use) minus an explicit exclusion map, so a table added to the schema is wiped by a factory reset until someone deliberately excludes it with a reason.

admin_sessions is part of the set on purpose. Session validation reads the table on every authenticated request, so wiping it invalidates every cookie issued before the reset — without it, an operator who reset the system left pre-reset admin sessions able to write to an otherwise empty database.

It returns the per-table row count deleted, for the API response and audit log. Deletion happens in one transaction in FK-safe order (children before parents) so a failure leaves the database untouched rather than half wiped. The handle is the plain *sqlx.DB rather than *store.DB because the admin endpoint that calls it is registered with the same handle the router already carries; nothing else in the operation needs the dialect field (see isPostgresConn).

func FactoryResetTableNames added in v0.17.0

func FactoryResetTableNames() []string

FactoryResetTableNames returns every table a factory reset must wipe, in FK-safe delete order, derived from the same registry that drives AutoMigrate and cmd/migrate minus factoryResetExcludedTables. Deriving it (instead of reusing the backup export list) is what makes admin_sessions, admin_audit_logs and the other previously-missed tables part of the reset: a pre-reset admin cookie must not survive "restore factory settings".

func HasExplicitLogCleanupSettings

func HasExplicitLogCleanupSettings(settingsMap map[string]string) bool

HasExplicitLogCleanupSettings checks whether log cleanup was explicitly configured via the settings table. Mirrors TS behavior: checks for specific setting keys that indicate user-intended log cleanup config.

func InsertGatewayRequest added in v0.25.0

func InsertGatewayRequest(ctx context.Context, db *DB, entry GatewayRequest) error

InsertGatewayRequest persists a terminal observation once. Repeated completion calls must not overwrite the first outcome, including after cancellation.

func InsertGatewayRequests added in v0.25.0

func InsertGatewayRequests(ctx context.Context, db *DB, entries []GatewayRequest) error

InsertGatewayRequests shares validation and wire layout with the single-row path. The bounded log writer uses one INSERT per batch in either dialect.

func LoadRuntimeSettings

func LoadRuntimeSettings(cfg *config.Config, rt *config.RuntimeSettings) error

LoadRuntimeSettings reads the settings table and applies runtime overrides to the config. Mirrors TS runtimeSettingsHydration behavior.

func MigrateLegacyProxyToken added in v0.26.0

func MigrateLegacyProxyToken(db *DB, rt *config.RuntimeSettings, rpm int) error

MigrateLegacyProxyToken imports the effective old root key once. Claiming the marker, creating the key, and transferring video ownership are one transaction. Existing keys retain their permissions and enabled state.

func OverrideDB

func OverrideDB(db *DB)

OverrideDB replaces the active database singleton with the given DB. Intended for tests that need to inject a pre-configured connection.

func PruneProxyRequestLogs added in v0.25.0

func PruneProxyRequestLogs(db *DB, cutoff string) (int64, error)

PruneProxyRequestLogs shares the existing usage-log retention window. Remove linked attempts with their expired request in one transaction; legacy attempts retain their original created_at policy. No foreign key is used because attempt writes precede terminal request persistence, which is intentionally best-effort.

func RecordAccountPricingFailure added in v0.26.0

func RecordAccountPricingFailure(ctx context.Context, db *sqlx.DB, accountID int64, at, code string) error

func ResolveSQLitePath

func ResolveSQLitePath(dbURL string, dataDir string) string

ResolveSQLitePath resolves the SQLite database file path. Mirrors TS index.ts resolveSqlitePath() behavior: - ":memory:" stays ":memory:" - empty DB_URL defaults to {DATA_DIR}/hub.db - "file://..." / "sqlite://..." prefixes are stripped - Other values are treated as file paths (resolved against cwd).

func ResyncPGIDSequences added in v0.19.0

func ResyncPGIDSequences(exec sequenceExecer) error

ResyncPGIDSequences advances every serial id sequence that is behind the largest id now stored, for the tables that have one. It never rewinds a sequence that is already ahead of MAX(id), including watermarks left by deleted rows or allocated ids.

Bulk writers that insert explicit ids leave PostgreSQL's sequences behind: the migrator copying a SQLite database over, a backup import restoring rows with the ids they were exported with, and legacy databases whose sequence was already below an occupied id before this repair existed. The next ordinary INSERT then asks the sequence for a value the restore just occupied and fails with a duplicate key — a deployment in that state works until its first write, which is the worst moment to discover it, and the error names a constraint rather than a sequence so nothing points back here.

SQLite needs no help: AUTOINCREMENT updates sqlite_sequence on an explicit insert, and a plain INTEGER PRIMARY KEY derives max+1 by itself.

Table names come from the schema registry (AllTableNames filtered by tableHasSerialID), never from a payload, which is why they are interpolated; the migrator has always built this statement the same way.

Failures are collected and returned together rather than aborting on the first, so a caller running against a possibly-incomplete schema can report every table it could not resync. The migrator warns and continues, because its target may not have run every migration; a backup import and AutoMigrate treat the same error as fatal, because there the schema was just migrated and a silently un-advanced sequence is exactly the bug this prevents.

func SaveAccountPricing added in v0.26.0

func SaveAccountPricing(ctx context.Context, db *sqlx.DB, row AccountPricingSnapshot) error

func SaveSiteAnnouncementRevision added in v0.26.0

func SaveSiteAnnouncementRevision(tx *sqlx.Tx, announcement SiteAnnouncement) error

SaveSiteAnnouncementRevision preserves the previous version in the same transaction that replaces its current content.

func SchemaTableNames added in v0.17.0

func SchemaTableNames() []string

SchemaTableNames returns every application table AutoMigrate creates, in registry order. It is the authoritative table set; the measured table count of a migrated database must equal len(SchemaTableNames()).

func SwitchDatabase

func SwitchDatabase(cfg *config.Config, nextDialect, nextDsn string, nextSsl bool) error

SwitchDatabase closes the old database connection pool and opens a new one with the given dialect and DSN. On failure, it rolls back to the original config values and re-opens the original connection.

Mirrors TS index.ts switchRuntimeDatabase() behavior:

  1. Close all existing connections.
  2. Publish the new connection settings (dialect, URL, SSL) through the atomic RuntimeSettings snapshot.
  3. Open new connection + run auto-migration.
  4. On failure: close new connection, restore old settings, re-open old connection.

The new connection honors cfg.DbSslMode (DB_SSLMODE) and the runtime PostgreSQL pool profile, so a switch can never silently downgrade an explicit sslmode or the configured pool budget.

func TrackUserBudgetRequest added in v0.27.0

func TrackUserBudgetRequest(requestID string) func()

TrackUserBudgetRequest is owned by the ingress lifecycle. It blocks local reconciliation while a request is actually running. It is not a distributed lease: operators must still verify termination on every serving instance.

func ValidDirectProtocol added in v0.24.0

func ValidDirectProtocol(bit int) bool

Types

type Account

type Account struct {
	ID          int64   `db:"id" json:"id"`
	SiteID      int64   `db:"site_id" json:"siteId"`
	Username    *string `db:"username" json:"username"`
	AccessToken string  `db:"access_token" json:"accessToken"`
	APIToken    *string `db:"api_token" json:"apiToken"`
	// Balance/BalanceUsed/Quota/ValueScore are nullable in the accounts table
	// (DEFAULT 0 without NOT NULL): rows migrated from the TS version, or never
	// refreshed, carry NULL. Keep them as pointers so a NULL column scans to nil
	// (JSON null) instead of failing with "converting NULL to float64". Readers
	// that need a numeric default use the OrZero helpers below.
	Balance            *float64 `db:"balance" json:"balance"`
	BalanceUsed        *float64 `db:"balance_used" json:"balanceUsed"`
	Quota              *float64 `db:"quota" json:"quota"`
	UnitCost           *float64 `db:"unit_cost" json:"unitCost"`
	ValueScore         *float64 `db:"value_score" json:"valueScore"`
	Status             string   `db:"status" json:"status"`
	IsPinned           bool     `db:"is_pinned" json:"isPinned"`
	SortOrder          int64    `db:"sort_order" json:"sortOrder"`
	CheckinEnabled     bool     `db:"checkin_enabled" json:"checkinEnabled"`
	LastCheckinAt      *string  `db:"last_checkin_at" json:"lastCheckinAt"`
	LastBalanceRefresh *string  `db:"last_balance_refresh" json:"lastBalanceRefresh"`
	OAuthProvider      *string  `db:"oauth_provider" json:"oauthProvider"`
	OAuthAccountKey    *string  `db:"oauth_account_key" json:"oauthAccountKey"`
	OAuthProjectID     *string  `db:"oauth_project_id" json:"oauthProjectId"`
	ExtraConfig        *string  `db:"extra_config" json:"extraConfig"`
	CreatedAt          string   `db:"created_at" json:"createdAt"`
	UpdatedAt          string   `db:"updated_at" json:"updatedAt"`
	// Tags holds a JSON array of operator labels.
	// NULL/empty means no tags; JSON array text like ["prod","priority"].
	Tags *string `db:"tags" json:"tags"`
	// Remark holds a free-form human-readable note (e.g. account source,
	// expiry, donor). NULL means no remark. Complements the machine-readable
	// Tags column; surfaced via PUT /api/accounts/{id}.
	//
	// Do not store access tokens, passwords, or other secrets here. Unlike
	// accessToken/apiToken (masked in list views), remark is returned in
	// plaintext on admin list/search responses.
	Remark *string `db:"remark" json:"remark"`
}

---- Table 4: accounts ----

func (Account) BalanceOrZero added in v0.16.8

func (a Account) BalanceOrZero() float64

OrZero helpers coerce the nullable numeric account columns for callers that need a numeric default (routing weights, balance aggregation, refresh results). Callers that must preserve the unknown/nil semantics (e.g. the daily low-balance check, JSON display) should read the pointer directly.

func (Account) BalanceUsedOrZero added in v0.16.8

func (a Account) BalanceUsedOrZero() float64

func (Account) QuotaOrZero added in v0.16.8

func (a Account) QuotaOrZero() float64

func (Account) ValueScoreOrZero added in v0.16.8

func (a Account) ValueScoreOrZero() float64

type AccountPricingSnapshot added in v0.26.0

type AccountPricingSnapshot struct {
	AccountID   int64  `db:"account_id" json:"accountId"`
	Payload     string `db:"payload" json:"-"`
	FetchedAt   string `db:"fetched_at" json:"fetchedAt"`
	AttemptedAt string `db:"attempted_at" json:"attemptedAt"`
	LastError   string `db:"last_error" json:"lastError"`
}

AccountPricingSnapshot contains only normalized public pricing, never credentials.

type AccountToken

type AccountToken struct {
	ID          int64   `db:"id" json:"id"`
	AccountID   int64   `db:"account_id" json:"accountId"`
	Name        string  `db:"name" json:"name"`
	Token       string  `db:"token" json:"token"`
	TokenGroup  *string `db:"token_group" json:"tokenGroup"`
	ValueStatus string  `db:"value_status" json:"valueStatus"`
	Source      string  `db:"source" json:"source"`
	Enabled     bool    `db:"enabled" json:"enabled"`
	IsDefault   bool    `db:"is_default" json:"isDefault"`
	CreatedAt   string  `db:"created_at" json:"createdAt"`
	UpdatedAt   string  `db:"updated_at" json:"updatedAt"`
}

---- Table 5: account_tokens ----

type AdditiveStep

type AdditiveStep struct {
	// Version is the primary key stored in schema_migrations.
	Version string
	// Description is a short human-readable note for operators and logs.
	Description string
	// Apply performs the DDL/DML for this step. It should be idempotent where
	// practical (e.g. EnsureColumn) so a crash between DDL and bookkeeping
	// does not break the next startup.
	Apply func(db *DB) error
}

Version IDs are stable strings (not integers) so SC2+ can insert descriptive IDs such as "sc2_001_downstream_proxy_url" without renumbering history.

type AdminAuditLog

type AdminAuditLog struct {
	ID        int64  `db:"id" json:"id"`
	Actor     string `db:"actor" json:"actor"`
	Method    string `db:"method" json:"method"`
	Path      string `db:"path" json:"path"`
	Status    int    `db:"status" json:"status"`
	RequestID string `db:"request_id" json:"requestId"`
	RemoteIP  string `db:"remote_ip" json:"remoteIp"`
	CreatedAt string `db:"created_at" json:"createdAt"`
}

---- Table 34: admin_audit_logs ---- One row per authenticated admin write operation (POST/PUT/PATCH/DELETE). actor is a sha256 prefix of the admin bearer token; the raw token is never stored. status 0 means the handler panicked before writing (recoverer catches it — the row is still useful as evidence the request arrived).

type AdminBackgroundTask

type AdminBackgroundTask struct {
	ID         int64   `db:"id" json:"id"`
	TaskID     string  `db:"task_id" json:"taskId"`
	Type       string  `db:"type" json:"type"`
	Title      string  `db:"title" json:"title"`
	Status     string  `db:"status" json:"status"`
	Message    *string `db:"message" json:"message"`
	Error      *string `db:"error" json:"error"`
	ResultJSON *string `db:"result_json" json:"resultJson"`
	DedupeKey  *string `db:"dedupe_key" json:"dedupeKey"`
	CreatedAt  string  `db:"created_at" json:"createdAt"`
	UpdatedAt  string  `db:"updated_at" json:"updatedAt"`
	StartedAt  *string `db:"started_at" json:"startedAt"`
	FinishedAt *string `db:"finished_at" json:"finishedAt"`
	LogsJSON   *string `db:"logs_json" json:"logsJson"`
}

---- Table 27: events ---- ---- Table 28: admin_background_tasks ----

type AnalyticsProjectionCheckpoint

type AnalyticsProjectionCheckpoint struct {
	ProjectorKey         string  `db:"projector_key" json:"projectorKey"`
	TimeZone             string  `db:"time_zone" json:"timeZone"`
	LastProxyLogID       int64   `db:"last_proxy_log_id" json:"lastProxyLogId"`
	WatermarkCreatedAt   *string `db:"watermark_created_at" json:"watermarkCreatedAt"`
	LeaseOwner           *string `db:"lease_owner" json:"leaseOwner"`
	LeaseToken           *string `db:"lease_token" json:"leaseToken"`
	LeaseExpiresAt       *string `db:"lease_expires_at" json:"leaseExpiresAt"`
	RecomputeFromID      *int64  `db:"recompute_from_id" json:"recomputeFromId"`
	RecomputeRequestedAt *string `db:"recompute_requested_at" json:"recomputeRequestedAt"`
	RecomputeReason      *string `db:"recompute_reason" json:"recomputeReason"`
	RecomputeStartedAt   *string `db:"recompute_started_at" json:"recomputeStartedAt"`
	RecomputeCompletedAt *string `db:"recompute_completed_at" json:"recomputeCompletedAt"`
	LastProjectedAt      *string `db:"last_projected_at" json:"lastProjectedAt"`
	LastSuccessfulAt     *string `db:"last_successful_at" json:"lastSuccessfulAt"`
	LastError            *string `db:"last_error" json:"lastError"`
	CreatedAt            string  `db:"created_at" json:"createdAt"`
	UpdatedAt            string  `db:"updated_at" json:"updatedAt"`
}

---- Table 21: analytics_projection_checkpoints (text PK) ----

type AnnouncementDismissal

type AnnouncementDismissal struct {
	AnnouncementID int64  `db:"announcement_id" json:"announcementId"`
	DismissedAt    string `db:"dismissed_at" json:"dismissedAt"`
}

---- Table 32: announcement_dismissals ----

type BalanceHistory

type BalanceHistory struct {
	ID          int64   `db:"id" json:"id"`
	AccountID   int64   `db:"account_id" json:"accountId"`
	Balance     float64 `db:"balance" json:"balance"`
	BalanceUsed float64 `db:"balance_used" json:"balanceUsed"`
	Quota       float64 `db:"quota" json:"quota"`
	LocalDay    string  `db:"local_day" json:"localDay"`
	CapturedAt  string  `db:"captured_at" json:"capturedAt"`
	CreatedAt   string  `db:"created_at" json:"createdAt"`
}

---- Table 29: balance_history ---- One snapshot per account per UTC day (UPSERT on local_day+account_id). Captured by RefreshBalance on success so operators get a balance trend without a separate capture job. Replaces the "current balance only" gap.

type CheckinLog

type CheckinLog struct {
	ID            int64   `db:"id" json:"id"`
	AccountID     int64   `db:"account_id" json:"accountId"`
	Status        string  `db:"status" json:"status"`
	Message       *string `db:"message" json:"message"`
	Reward        *string `db:"reward" json:"reward"`
	FailureReason *string `db:"failure_reason" json:"failureReason"`
	CreatedAt     string  `db:"created_at" json:"createdAt"`
}

---- Table 6: checkin_logs ---- FailureReason holds the JSON-serialized FailureReason struct produced by service/checkin/failure_reason.go ClassifyFailureReason. NULL for success or unclassified rows. Surfaced to the API as a parsed `failureReason` object by handler/admin/checkin_routes.go getLogs.

type DB

type DB struct {
	*sqlx.DB
	Dialect string
}

DB wraps a *sqlx.DB connection pool and provides convenience methods. Query helpers override sqlx.DB methods to rebind ? placeholders to $N for PostgreSQL before queries reach pgx.

func GetDB

func GetDB() *DB

GetDB returns the current active database connection. Returns nil if the database has not been initialized.

func Open

func Open(dialect string, dsn string, sslMode bool) (*DB, error)

Open opens a database connection pool for the given dialect and DSN. - "sqlite" uses modernc.org/sqlite (pure Go, no CGO). - "postgres" uses jackc/pgx/v5.

SQLite connections are configured with WAL journal mode and foreign_keys=ON.

func OpenWithPostgresSSLMode

func OpenWithPostgresSSLMode(dialect string, dsn string, sslMode string) (*DB, error)

OpenWithPostgresSSLMode opens a database connection pool and, for PostgreSQL, applies an explicit sslmode without duplicating existing DSN parameters.

func OpenWithPostgresSSLModeAndPool

func OpenWithPostgresSSLModeAndPool(
	dialect string,
	dsn string,
	sslMode string,
	pool PostgresPoolConfig,
) (*DB, error)

OpenWithPostgresSSLModeAndPool opens a database connection pool and applies an explicit PostgreSQL budget. SQLite ignores the PostgreSQL pool settings.

func (*DB) Exec

func (db *DB) Exec(query string, args ...any) (sql.Result, error)

Exec executes a query that does not return rows. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) ExecContext

func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)

ExecContext executes a query that does not return rows, honoring the request context. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution so callers never branch on dialect.

func (*DB) Get

func (db *DB) Get(dest any, query string, args ...any) error

Get loads one row into dest. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) GetContext

func (db *DB) GetContext(ctx context.Context, dest any, query string, args ...any) error

GetContext loads one row into dest, honoring the request context. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution so callers never branch on dialect.

func (*DB) Query

func (db *DB) Query(query string, args ...any) (*sql.Rows, error)

Query executes a query that returns rows. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) QueryRow

func (db *DB) QueryRow(query string, args ...any) *sql.Row

QueryRow executes a query that returns at most one row. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) QueryRowx

func (db *DB) QueryRowx(query string, args ...any) *sqlx.Row

QueryRowx executes a query and returns an sqlx row. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) QueryRowxContext

func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row

QueryRowxContext executes a query and returns an sqlx row, honoring the request context. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) Queryx

func (db *DB) Queryx(query string, args ...any) (*sqlx.Rows, error)

Queryx executes a query and returns sqlx rows. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) QueryxContext

func (db *DB) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)

QueryxContext executes a query and returns sqlx rows, honoring the request context. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) Select

func (db *DB) Select(dest any, query string, args ...any) error

Select loads all rows into dest. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.

func (*DB) SelectContext

func (db *DB) SelectContext(ctx context.Context, dest any, query string, args ...any) error

SelectContext loads all rows into dest, honoring the request context. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution so callers never branch on dialect.

type DirectEndpoint added in v0.24.0

type DirectEndpoint struct {
	URL  string `json:"url"`
	Auth string `json:"auth"`
	// ModelPath appends the native Gemini or Bedrock model/action to its prefix.
	// Custom endpoint URLs remain exact when false.
	ModelPath bool   `json:"modelPath,omitempty"`
	Profile   string `json:"profile,omitempty"`
	// RequestModel is the Responses model used by the Codex image bridge;
	// the grant's model remains the image tool model.
	RequestModel string `json:"requestModel,omitempty"`
	// ModelWireURLs belong to the OpenCode Go Chat adapter. They are internal
	// wire destinations, not additional endpoint permissions or fallbacks.
	ModelWireURLs *DirectModelWireURLs `json:"modelWireUrls,omitempty"`
}

DirectEndpoint is a fully resolved HTTP endpoint. The importer owns source provider URL conventions; execution must not normalize this URL again.

func (*DirectEndpoint) URLFields added in v0.24.0

func (e *DirectEndpoint) URLFields() []*string

URLFields includes every network destination owned by this endpoint. Both validation and preset resolution must visit the same fields.

type DirectEndpointEntry added in v0.24.0

type DirectEndpointEntry struct {
	Key      string
	Protocol int
	Endpoint *DirectEndpoint
}

type DirectEndpoints added in v0.24.0

type DirectEndpoints struct {
	Chat                      *DirectEndpoint `json:"chat,omitempty"`
	Responses                 *DirectEndpoint `json:"responses,omitempty"`
	Messages                  *DirectEndpoint `json:"messages,omitempty"`
	Gemini                    *DirectEndpoint `json:"gemini,omitempty"`
	Completions               *DirectEndpoint `json:"completions,omitempty"`
	Embeddings                *DirectEndpoint `json:"embeddings,omitempty"`
	Rerank                    *DirectEndpoint `json:"rerank,omitempty"`
	ImageGeneration           *DirectEndpoint `json:"imageGeneration,omitempty"`
	ImageEdit                 *DirectEndpoint `json:"imageEdit,omitempty"`
	ImageVariation            *DirectEndpoint `json:"imageVariation,omitempty"`
	AudioSpeech               *DirectEndpoint `json:"audioSpeech,omitempty"`
	AudioTranscription        *DirectEndpoint `json:"audioTranscription,omitempty"`
	AudioTranslation          *DirectEndpoint `json:"audioTranslation,omitempty"`
	Moderations               *DirectEndpoint `json:"moderations,omitempty"`
	Video                     *DirectEndpoint `json:"video,omitempty"`
	GeminiEmbeddings          *DirectEndpoint `json:"geminiEmbeddings,omitempty"`
	JinaEmbeddings            *DirectEndpoint `json:"jinaEmbeddings,omitempty"`
	ModelScopeImageGeneration *DirectEndpoint `json:"modelscopeImageGeneration,omitempty"`
	SeedanceVideo             *DirectEndpoint `json:"seedanceVideo,omitempty"`
	ZenmuxVideo               *DirectEndpoint `json:"zenmuxVideo,omitempty"`
	Ollama                    *DirectEndpoint `json:"ollama,omitempty"`
	SystemOne                 *DirectEndpoint `json:"systemOne,omitempty"`
	AlphaSearch               *DirectEndpoint `json:"alphaSearch,omitempty"`
}

DirectEndpoints is optional for imports that use the original base/path contract. When present, each endpoint owns both its URL and authentication.

func (DirectEndpoints) AnonymousProtocolMask added in v0.24.0

func (e DirectEndpoints) AnonymousProtocolMask() int

AnonymousProtocolMask is deliberately narrower than the endpoint mask. A credential without secret material cannot authorize authenticated slots.

func (DirectEndpoints) Entries added in v0.24.0

func (e DirectEndpoints) Entries() []DirectEndpointEntry

Entries is the single field-to-protocol mapping for the persisted endpoint object. Nil entries remain visible to callers building a configuration form.

func (DirectEndpoints) ForProtocol added in v0.24.0

func (e DirectEndpoints) ForProtocol(bit int) *DirectEndpoint

func (DirectEndpoints) IsConfigured added in v0.24.0

func (e DirectEndpoints) IsConfigured() bool

func (DirectEndpoints) ProtocolMask added in v0.24.0

func (e DirectEndpoints) ProtocolMask() int

func (*DirectEndpoints) Scan added in v0.24.0

func (e *DirectEndpoints) Scan(value any) error

func (DirectEndpoints) Value added in v0.24.0

func (e DirectEndpoints) Value() (driver.Value, error)

type DirectModelWireURLs added in v0.24.0

type DirectModelWireURLs struct {
	Responses string `json:"responses"`
	Messages  string `json:"messages"`
}

type DirectOAuthState added in v0.24.0

type DirectOAuthState struct {
	RefreshToken string `json:"refreshToken,omitempty"`
	ClientID     string `json:"clientId,omitempty"`
	ExpiresAt    int64  `json:"expiresAt,omitempty"` // Unix milliseconds
	IDToken      string `json:"idToken,omitempty"`
	AccountID    string `json:"accountId,omitempty"`
}

DirectOAuthState contains refresh material. It belongs only in credential storage and write inputs, never routing snapshots or inventory responses. The access token has one owner: upstream_credentials.secret.

func (*DirectOAuthState) Scan added in v0.24.0

func (s *DirectOAuthState) Scan(value any) error

func (DirectOAuthState) Value added in v0.24.0

func (s DirectOAuthState) Value() (driver.Value, error)

type DirectProtocolOrder added in v0.24.0

type DirectProtocolOrder []int

DirectProtocolOrder restricts one route item without broadening its shared grant.

func (*DirectProtocolOrder) Scan added in v0.24.0

func (p *DirectProtocolOrder) Scan(value any) error

func (DirectProtocolOrder) Value added in v0.24.0

func (p DirectProtocolOrder) Value() (driver.Value, error)

type DirectUpstreamCandidate added in v0.23.0

type DirectUpstreamCandidate struct {
	GrantID           int64
	RouteID           int64
	GroupID           int64
	GroupMode         string
	ActiveItemID      int64
	ItemID            int64
	ChannelID         int64
	ChannelName       string
	BaseURL           string
	Dialect           string
	Provider          string
	ChatPath          string
	ResponsesPath     string
	AnthropicPath     string
	Endpoints         DirectEndpoints
	ChannelProxy      string
	UseSystemProxy    bool
	CustomHeader      string
	ParamOverride     string
	ModelID           int64
	ModelName         string
	CredentialID      int64
	CredentialName    string
	CredentialKind    string
	Credential        string
	ChannelEnabled    bool
	ModelEnabled      bool
	CredentialEnabled bool
	GrantEnabled      bool
	Protocols         int
	ProtocolOrder     DirectProtocolOrder
}

DirectUpstreamCandidate is the typed source for an Octopus-style grant. It deliberately carries no Site or Account surrogate; selector and executor branches must handle it explicitly rather than treating it as a native row.

func (*DirectUpstreamCandidate) HasAnonymousCredential added in v0.24.0

func (d *DirectUpstreamCandidate) HasAnonymousCredential() bool

type DownstreamAPIKey

type DownstreamAPIKey struct {
	KeyOwnerType string   `db:"key_owner_type" json:"keyOwnerType"`
	OwnerUserID  *int64   `db:"owner_user_id" json:"ownerUserId"`
	AccessPolicy *string  `db:"access_policy" json:"accessPolicy"`
	ID           int64    `db:"id" json:"id"`
	Name         string   `db:"name" json:"name"`
	Key          string   `db:"key" json:"key"`
	Description  *string  `db:"description" json:"description"`
	GroupName    *string  `db:"group_name" json:"groupName"`
	Tags         *string  `db:"tags" json:"tags"`
	Enabled      bool     `db:"enabled" json:"enabled"`
	ExpiresAt    *string  `db:"expires_at" json:"expiresAt"`
	MaxCost      *float64 `db:"max_cost" json:"maxCost"`
	UsedCost     float64  `db:"used_cost" json:"usedCost"`
	MaxRequests  *int64   `db:"max_requests" json:"maxRequests"`
	UsedRequests int64    `db:"used_requests" json:"usedRequests"`
	// MaxRPM / MaxTPM optional soft rate windows. nil = unlimited.
	MaxRPM                 *int64  `db:"max_rpm" json:"maxRpm"`
	MaxTPM                 *int64  `db:"max_tpm" json:"maxTpm"`
	SupportedModels        *string `db:"supported_models" json:"supportedModels"`
	AllowedRouteIDs        *string `db:"allowed_route_ids" json:"allowedRouteIds"`
	SiteWeightMultipliers  *string `db:"site_weight_multipliers" json:"siteWeightMultipliers"`
	ExcludedSiteIDs        *string `db:"excluded_site_ids" json:"excludedSiteIds"`
	ExcludedCredentialRefs *string `db:"excluded_credential_refs" json:"excludedCredentialRefs"`
	// AllowedSiteIDs / AllowedCredentialRefs are optional allow-lists.
	// Empty/NULL means unrestricted (legacy exclude-only semantics).
	// When non-empty, only listed sites/credentials are eligible; exclusions still apply.
	AllowedSiteIDs        *string `db:"allowed_site_ids" json:"allowedSiteIds"`
	AllowedCredentialRefs *string `db:"allowed_credential_refs" json:"allowedCredentialRefs"`
	// KeyWeight is an optional per-downstream-key scalar.
	// NULL means 1.0 (no change). Positive values amplify channel.Weight
	// differences in weighted selection: (channel.weight*keyWeight + 10)*...
	KeyWeight *float64 `db:"key_weight" json:"keyWeight"`
	// ProxyURL is an optional per-key egress proxy override.
	// NULL falls back to site / system proxy — preserves pre-SC2 behavior.
	ProxyURL   *string `db:"proxy_url" json:"proxyUrl"`
	LastUsedAt *string `db:"last_used_at" json:"lastUsedAt"`
	CreatedAt  string  `db:"created_at" json:"createdAt"`
	// IPAllowlist / IPBlocklist: newline/comma-
	// separated CIDR or exact IPs. Empty/NULL = unrestricted. Blocklist wins.
	IPAllowlist *string `db:"ip_allowlist" json:"ipAllowlist"`
	IPBlocklist *string `db:"ip_blocklist" json:"ipBlocklist"`
	UpdatedAt   string  `db:"updated_at" json:"updatedAt"`
}

---- Table 25: downstream_api_keys ----

type DownstreamAccessPolicy added in v0.24.0

type DownstreamAccessPolicy struct {
	AllowedUpstreamChannelIDs *[]int64                 `json:"allowedUpstreamChannelIds,omitempty"`
	ModelIDs                  []string                 `json:"modelIds,omitempty"`
	ModelMappings             []DownstreamModelMapping `json:"modelMappings,omitempty"`
	Quota                     *DownstreamQuota         `json:"quota,omitempty"`
	BlockReason               string                   `json:"blockReason,omitempty"`
}

DownstreamAccessPolicy adds conjunctive restrictions to the existing key policy. A present empty channel list denies every channel; omission imposes no channel restriction. Model IDs are exact and checked after mapping.

func ParseDownstreamAccessPolicy added in v0.24.0

func ParseDownstreamAccessPolicy(raw string) (*DownstreamAccessPolicy, error)

func (*DownstreamAccessPolicy) AllowsModel added in v0.24.0

func (p *DownstreamAccessPolicy) AllowsModel(model string) bool

func (*DownstreamAccessPolicy) AllowsUpstreamChannel added in v0.24.0

func (p *DownstreamAccessPolicy) AllowsUpstreamChannel(id int64) bool

func (*DownstreamAccessPolicy) MapModel added in v0.24.0

func (p *DownstreamAccessPolicy) MapModel(model string) string

func (*DownstreamAccessPolicy) Validate added in v0.24.0

func (p *DownstreamAccessPolicy) Validate() error

type DownstreamModelMapping added in v0.24.0

type DownstreamModelMapping struct {
	From string `json:"from"`
	To   string `json:"to"`
}

type DownstreamQuota added in v0.24.0

type DownstreamQuota struct {
	Requests    *int64                `json:"requests,omitempty"`
	TotalTokens *int64                `json:"totalTokens,omitempty"`
	Cost        *float64              `json:"cost,omitempty"`
	Period      DownstreamQuotaPeriod `json:"period"`
	Timezone    string                `json:"timezone,omitempty"`
	// HistoryMissingBefore bounds an imported history gap. Rolling/calendar
	// windows recover once they no longer overlap the missing history.
	HistoryMissingBefore *int64 `json:"historyMissingBefore,omitempty"`
}

func (*DownstreamQuota) Window added in v0.24.0

func (q *DownstreamQuota) Window(now time.Time) (int64, int64, error)

Window returns inclusive start and exclusive end in Unix milliseconds.

type DownstreamQuotaDuration added in v0.24.0

type DownstreamQuotaDuration struct {
	Value int64  `json:"value,omitempty"`
	Unit  string `json:"unit"`
}

type DownstreamQuotaPeriod added in v0.24.0

type DownstreamQuotaPeriod struct {
	Type             string                   `json:"type"`
	PastDuration     *DownstreamQuotaDuration `json:"pastDuration,omitempty"`
	CalendarDuration *DownstreamQuotaDuration `json:"calendarDuration,omitempty"`
}

type Event

type Event struct {
	ID          int64   `db:"id" json:"id"`
	Type        string  `db:"type" json:"type"`
	Title       string  `db:"title" json:"title"`
	Message     *string `db:"message" json:"message"`
	Level       string  `db:"level" json:"level"`
	Read        bool    `db:"read" json:"read"`
	RelatedID   *int64  `db:"related_id" json:"relatedId"`
	RelatedType *string `db:"related_type" json:"relatedType"`
	CreatedAt   string  `db:"created_at" json:"createdAt"`
}

type GatewayRequest added in v0.25.0

type GatewayRequest struct {
	OwnerUserID          *int64  `db:"owner_user_id" json:"ownerUserId"`
	UserGroupID          *int64  `db:"user_group_id" json:"userGroupId"`
	ID                   string  `db:"id" json:"id"`
	ExternalRequestID    *string `db:"external_request_id" json:"externalRequestId"`
	DownstreamPath       *string `db:"downstream_path" json:"downstreamPath"`
	Transport            string  `db:"transport" json:"transport"`
	ModelRequested       *string `db:"model_requested" json:"modelRequested"`
	DownstreamAPIKeyID   *int64  `db:"downstream_api_key_id" json:"downstreamApiKeyId"`
	TerminalStatus       string  `db:"terminal_status" json:"terminalStatus"`
	AttemptCount         int     `db:"attempt_count" json:"attemptCount"`
	ReasonCode           *string `db:"reason_code" json:"reasonCode"`
	HTTPStatus           *int    `db:"http_status" json:"httpStatus"`
	OutputStarted        bool    `db:"output_started" json:"outputStarted"`
	FirstByteLatencyMs   *int64  `db:"first_byte_latency_ms" json:"firstByteLatencyMs"`
	FirstOutputLatencyMs *int64  `db:"first_output_latency_ms" json:"firstOutputLatencyMs"`
	LatencyMs            int64   `db:"latency_ms" json:"latencyMs"`
	StartedAt            string  `db:"started_at" json:"startedAt"`
	EndedAt              string  `db:"ended_at" json:"endedAt"`
}

GatewayRequest records one gateway-observed HTTP request or WebSocket turn. ExternalRequestID is untrusted client correlation, never its identity.

type GatewayUser added in v0.27.0

type GatewayUser struct {
	ID          int64  `db:"id" json:"id"`
	Username    string `db:"username" json:"username"`
	DisplayName string `db:"display_name" json:"displayName"`
	GroupID     int64  `db:"group_id" json:"groupId"`
	Enabled     bool   `db:"enabled" json:"enabled"`
	CreatedAt   string `db:"created_at" json:"createdAt"`
	UpdatedAt   string `db:"updated_at" json:"updatedAt"`
}

GatewayUser belongs to exactly one current group. This identity foundation contains no login credential, deployment-administrator role or issued Key.

type GatewayUserGroup added in v0.27.0

type GatewayUserGroup struct {
	ID        int64  `db:"id" json:"id"`
	Slug      string `db:"slug" json:"slug"`
	Name      string `db:"name" json:"name"`
	Enabled   bool   `db:"enabled" json:"enabled"`
	CreatedAt string `db:"created_at" json:"createdAt"`
	UpdatedAt string `db:"updated_at" json:"updatedAt"`
}

GatewayUserGroup is an administrator-managed access group for this gateway. It is not an independent organization or an upstream provider pool.

type GatewayUserGroupRouteGrant added in v0.27.0

type GatewayUserGroupRouteGrant struct {
	GroupID   int64  `db:"group_id" json:"groupId"`
	RouteID   int64  `db:"route_id" json:"routeId"`
	CreatedAt string `db:"created_at" json:"createdAt"`
}

type GatewayUserStore added in v0.27.0

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

GatewayUserStore owns persistence, not management authorization. Callers authorize administrator writes separately; client-supplied IDs are selectors.

func NewGatewayUserStore added in v0.27.0

func NewGatewayUserStore(db *DB) *GatewayUserStore

func (*GatewayUserStore) CreateOwnKey added in v0.27.0

func (s *GatewayUserStore) CreateOwnKey(ctx context.Context, userID int64, name, key string, models []string, expires *string, maxCost *float64, maxRequests *int64) (UserKey, error)

func (*GatewayUserStore) CreateUser added in v0.27.0

func (s *GatewayUserStore) CreateUser(ctx context.Context, username, displayName string, groupID int64, enabled bool) (GatewayUser, error)

CreateUser uses the default group when groupID is zero. Creating that group and its first user is atomic, and an existing default group's administrator configuration is never overwritten.

func (*GatewayUserStore) CreateUserGroup added in v0.27.0

func (s *GatewayUserStore) CreateUserGroup(ctx context.Context, slug, name string, enabled bool) (GatewayUserGroup, error)

func (*GatewayUserStore) DeleteOwnKey added in v0.27.0

func (s *GatewayUserStore) DeleteOwnKey(ctx context.Context, userID, keyID int64) error

func (*GatewayUserStore) GetActiveGatewayUser added in v0.27.0

func (s *GatewayUserStore) GetActiveGatewayUser(ctx context.Context, userID int64) (GatewayUser, error)

GetActiveGatewayUser reloads both identity and its current group. Possession of a user ID is not authentication and callers must establish the principal.

func (*GatewayUserStore) GetUser added in v0.27.0

func (s *GatewayUserStore) GetUser(ctx context.Context, userID int64) (GatewayUser, error)

func (*GatewayUserStore) GetUserBudget added in v0.27.0

func (s *GatewayUserStore) GetUserBudget(ctx context.Context, userID int64) (UserBudget, error)

func (*GatewayUserStore) GetUserGroup added in v0.27.0

func (s *GatewayUserStore) GetUserGroup(ctx context.Context, groupID int64) (GatewayUserGroup, error)

func (*GatewayUserStore) GetUserGroupPricing added in v0.27.0

func (s *GatewayUserStore) GetUserGroupPricing(ctx context.Context, groupID int64) (UserGroupPricing, error)

func (*GatewayUserStore) GrantUserGroupRoute added in v0.27.0

func (s *GatewayUserStore) GrantUserGroupRoute(ctx context.Context, groupID, routeID int64) error

func (*GatewayUserStore) ListActiveGatewayUserRouteIDs added in v0.27.0

func (s *GatewayUserStore) ListActiveGatewayUserRouteIDs(ctx context.Context, userID int64) ([]int64, error)

ListActiveGatewayUserRouteIDs reads the user's current group and all enabled states in the same query that returns route grants. Empty means deny-all, never unrestricted; this hard layer is separate from legacy Key policy ORs.

func (*GatewayUserStore) ListOwnKeys added in v0.27.0

func (s *GatewayUserStore) ListOwnKeys(ctx context.Context, userID int64) ([]UserKey, error)

func (*GatewayUserStore) ListOwnRequests added in v0.27.0

func (s *GatewayUserStore) ListOwnRequests(ctx context.Context, userID int64, page, pageSize int) ([]UserRequest, int64, error)

func (*GatewayUserStore) ListOwnRequestsFiltered added in v0.27.0

func (s *GatewayUserStore) ListOwnRequestsFiltered(ctx context.Context, userID int64, page, pageSize int, filter UserRequestFilter) ([]UserRequest, int64, error)

func (*GatewayUserStore) ListUserBudgetHolds added in v0.27.0

func (s *GatewayUserStore) ListUserBudgetHolds(ctx context.Context, userID int64, offset int) ([]UserBudgetHold, error)

Administrator-only caller: ordinary users receive aggregate budget DTOs, never a cross-request operational reconciliation surface.

func (*GatewayUserStore) ListUserGroupRouteGrants added in v0.27.0

func (s *GatewayUserStore) ListUserGroupRouteGrants(ctx context.Context, groupID int64) ([]GatewayUserGroupRouteGrant, error)

func (*GatewayUserStore) ListUserGroups added in v0.27.0

func (s *GatewayUserStore) ListUserGroups(ctx context.Context) ([]GatewayUserGroup, error)

func (*GatewayUserStore) ListUsers added in v0.27.0

func (s *GatewayUserStore) ListUsers(ctx context.Context) ([]GatewayUser, error)

func (*GatewayUserStore) OwnRequest added in v0.27.0

func (s *GatewayUserStore) OwnRequest(ctx context.Context, userID int64, id string) (UserRequest, error)

func (*GatewayUserStore) OwnUsage added in v0.27.0

func (s *GatewayUserStore) OwnUsage(ctx context.Context, userID int64) (UserUsage, error)

func (*GatewayUserStore) ReconcileUserBudget added in v0.27.0

func (s *GatewayUserStore) ReconcileUserBudget(ctx context.Context, userID int64, requestID string, totalTokens int64) error

ReconcileUserBudget is an explicit administrator correction for unresolved holds, including crash-surviving pending entries. It uses the original group multiplier. A caller must supply verified TOTAL tokens, not an increment.

func (*GatewayUserStore) ReserveUserBudget added in v0.27.0

func (s *GatewayUserStore) ReserveUserBudget(ctx context.Context, requestID string, userID, expectedGroupID, estimatedTokens int64) (UserBudgetReservation, error)

ReserveUserBudget reserves a bounded token estimate across every Key. An estimate is not a strict promise about third-party reported usage. A crashed process leaves its durable hold; elapsed wall time never turns an unobserved charge into free credit.

func (*GatewayUserStore) ResolveUserKeyAccess added in v0.27.0

func (s *GatewayUserStore) ResolveUserKeyAccess(ctx context.Context, userID int64) (int64, []int64, error)

ResolveUserKeyAccess takes one database snapshot of identity, group and grants, including active users whose current group has no routes.

func (*GatewayUserStore) RevokeUserGroupRoute added in v0.27.0

func (s *GatewayUserStore) RevokeUserGroupRoute(ctx context.Context, groupID, routeID int64) error

func (*GatewayUserStore) RotateOwnKey added in v0.27.0

func (s *GatewayUserStore) RotateOwnKey(ctx context.Context, userID, keyID int64, key string) (UserKey, error)

RotateOwnKey replaces only the secret of an existing caller-owned Key. Its identity, restrictions, counters and request history stay intact. Once the transaction commits, the old secret cannot authorize another request/WS turn.

func (*GatewayUserStore) SetUserBudget added in v0.27.0

func (s *GatewayUserStore) SetUserBudget(ctx context.Context, userID int64, limit float64, unlimited bool) (UserBudget, error)

func (*GatewayUserStore) SetUserGroupPricing added in v0.27.0

func (s *GatewayUserStore) SetUserGroupPricing(ctx context.Context, groupID int64, multiplier float64) (UserGroupPricing, error)

func (*GatewayUserStore) SettleUserBudget added in v0.27.0

func (s *GatewayUserStore) SettleUserBudget(ctx context.Context, requestID string, tokens *int64, dispatched bool) error

SettleUserBudget is a request/WS-turn operation, NEVER an attempt operation. nil or malformed usage retains the hold and blocks subsequent admissions. Actual charges can exceed a hold: this is truthful debt accounting, not a claim that a third-party model has a strictly bounded cost.

func (*GatewayUserStore) UpdateUser added in v0.27.0

func (s *GatewayUserStore) UpdateUser(ctx context.Context, userID int64, displayName string, groupID int64, enabled bool) error

UpdateUser changes the current group; subsequent active lookups follow that group immediately. No historical group union or per-user grant is retained.

func (*GatewayUserStore) UpdateUserGroup added in v0.27.0

func (s *GatewayUserStore) UpdateUserGroup(ctx context.Context, groupID int64, name string, enabled bool) error

type MigrationSummary added in v0.13.0

type MigrationSummary struct {
	Dialect    string         `json:"dialect"`
	Connection string         `json:"connection"`
	Overwrite  bool           `json:"overwrite"`
	Version    string         `json:"version"`
	Timestamp  int64          `json:"timestamp"`
	Rows       map[string]int `json:"rows"`
}

func RunMigration added in v0.13.0

func RunMigration(opts RunMigrationOptions) (*MigrationSummary, error)

RunMigration transfers all application tables between a SQLite database and a PostgreSQL database (either direction). It is the callable form of the metapi-migrate CLI: cmd/migrate/main.go wraps it for the CLI, and the admin migrate handler queues it as a background task. The migration SQL/logic is unchanged from the original CLI; only the log sink is parameterized via opts.LogWriter so progress can be surfaced through /api/tasks/{id}.

type ModelAvailability

type ModelAvailability struct {
	ID        int64  `db:"id" json:"id"`
	AccountID int64  `db:"account_id" json:"accountId"`
	ModelName string `db:"model_name" json:"modelName"`
	Available *bool  `db:"available" json:"available"`
	IsManual  bool   `db:"is_manual" json:"isManual"`
	LatencyMs *int64 `db:"latency_ms" json:"latencyMs"`
	CheckedAt string `db:"checked_at" json:"checkedAt"`
}

---- Table 7: model_availability ----

type ModelDayUsage

type ModelDayUsage struct {
	ID             int64   `db:"id" json:"id"`
	LocalDay       string  `db:"local_day" json:"localDay"`
	SiteID         int64   `db:"site_id" json:"siteId"`
	Model          string  `db:"model" json:"model"`
	TotalCalls     int64   `db:"total_calls" json:"totalCalls"`
	SuccessCalls   int64   `db:"success_calls" json:"successCalls"`
	FailedCalls    int64   `db:"failed_calls" json:"failedCalls"`
	TotalTokens    int64   `db:"total_tokens" json:"totalTokens"`
	TotalSpend     float64 `db:"total_spend" json:"totalSpend"`
	TotalLatencyMs int64   `db:"total_latency_ms" json:"totalLatencyMs"`
	LatencyCount   int64   `db:"latency_count" json:"latencyCount"`
	CreatedAt      string  `db:"created_at" json:"createdAt"`
	UpdatedAt      string  `db:"updated_at" json:"updatedAt"`
}

---- Table 24: model_day_usage ----

type ModelNameRedirect

type ModelNameRedirect struct {
	ID         int64   `db:"id" json:"id"`
	AccountID  int64   `db:"account_id" json:"accountId"`
	Canonical  string  `db:"canonical" json:"canonical"`
	Actual     string  `db:"actual" json:"actual"`
	Source     string  `db:"source" json:"source"` // sync | manual
	LastSeenAt *string `db:"last_seen_at" json:"lastSeenAt"`
	CreatedAt  string  `db:"created_at" json:"createdAt"`
	UpdatedAt  string  `db:"updated_at" json:"updatedAt"`
}

---- Table 33: model_name_redirects ---- Maps a canonical route model name to the actual upstream name per account (e.g. claude-3-5-sonnet → claude-3-5-sonnet-20241022). source is sync (auto-generated) or manual (operator-authored, never overwritten).

type ModelProbeResult added in v0.11.0

type ModelProbeResult struct {
	ID         int64    `db:"id" json:"id"`
	ChannelID  *int64   `db:"channel_id" json:"channelId"`
	AccountID  int64    `db:"account_id" json:"accountId"`
	SiteID     int64    `db:"site_id" json:"siteId"`
	ModelName  string   `db:"model_name" json:"modelName"`
	Status     string   `db:"status" json:"status"` // success | failure | inconclusive | skipped
	LatencyMs  *float64 `db:"latency_ms" json:"latencyMs"`
	HTTPStatus *int64   `db:"http_status" json:"httpStatus"`
	ErrorText  *string  `db:"error_text" json:"errorText"`
	CreatedAt  string   `db:"created_at" json:"createdAt"`
}

---- Table 35: model_probe_results ----

type ModelVerifyRecord

type ModelVerifyRecord struct {
	ID         int64    `db:"id" json:"id"`
	BatchID    string   `db:"batch_id" json:"batchId"`
	ModelName  string   `db:"model_name" json:"modelName"`
	ChannelID  *int64   `db:"channel_id" json:"channelId"`
	AccountID  *int64   `db:"account_id" json:"accountId"`
	SiteID     *int64   `db:"site_id" json:"siteId"`
	Status     string   `db:"status" json:"status"`
	LatencyMs  *float64 `db:"latency_ms" json:"latencyMs"`
	HTTPStatus *int64   `db:"http_status" json:"httpStatus"`
	ErrorText  *string  `db:"error_text" json:"errorText"`
	CreatedAt  string   `db:"created_at" json:"createdAt"`
}

---- Table 30: model_verify_history ----

type OAuthRouteUnit

type OAuthRouteUnit struct {
	ID        int64  `db:"id" json:"id"`
	SiteID    int64  `db:"site_id" json:"siteId"`
	Provider  string `db:"provider" json:"provider"`
	Name      string `db:"name" json:"name"`
	Strategy  string `db:"strategy" json:"strategy"`
	Enabled   bool   `db:"enabled" json:"enabled"`
	CreatedAt string `db:"created_at" json:"createdAt"`
	UpdatedAt string `db:"updated_at" json:"updatedAt"`
}

---- Table 11: oauth_route_units ----

type OAuthRouteUnitMember

type OAuthRouteUnitMember struct {
	ID        int64 `db:"id" json:"id"`
	UnitID    int64 `db:"unit_id" json:"unitId"`
	AccountID int64 `db:"account_id" json:"accountId"`
	// SortOrder/SuccessCount/FailCount/TotalLatencyMs/TotalCost are nullable
	// in the DDL (DEFAULT 0 without NOT NULL): TS-migrated rows can carry
	// NULL. Keep pointers so NULL scans to nil instead of failing
	// LoadOAuthRouteUnitMembers with "converting NULL to int64". Numeric
	// callers use the OrZero helpers below.
	SortOrder            *int64   `db:"sort_order" json:"sortOrder"`
	SuccessCount         *int64   `db:"success_count" json:"successCount"`
	FailCount            *int64   `db:"fail_count" json:"failCount"`
	TotalLatencyMs       *int64   `db:"total_latency_ms" json:"totalLatencyMs"`
	TotalCost            *float64 `db:"total_cost" json:"totalCost"`
	LastUsedAt           *string  `db:"last_used_at" json:"lastUsedAt"`
	LastSelectedAt       *string  `db:"last_selected_at" json:"lastSelectedAt"`
	LastFailAt           *string  `db:"last_fail_at" json:"lastFailAt"`
	ConsecutiveFailCount int64    `db:"consecutive_fail_count" json:"consecutiveFailCount"`
	CooldownLevel        int64    `db:"cooldown_level" json:"cooldownLevel"`
	CooldownUntil        *string  `db:"cooldown_until" json:"cooldownUntil"`
	// Structured cooldown reason — same contract as RouteChannel.
	CooldownReasonCode *string `db:"cooldown_reason_code" json:"cooldownReasonCode"`
	CooldownReason     *string `db:"cooldown_reason" json:"cooldownReason"`
	CooldownReasonAt   *string `db:"cooldown_reason_at" json:"cooldownReasonAt"`
	CreatedAt          string  `db:"created_at" json:"createdAt"`
	UpdatedAt          string  `db:"updated_at" json:"updatedAt"`
}

---- Table 12: oauth_route_unit_members ----

func (OAuthRouteUnitMember) FailCountOrZero added in v0.16.8

func (m OAuthRouteUnitMember) FailCountOrZero() int64

func (OAuthRouteUnitMember) SortOrderOrZero added in v0.16.8

func (m OAuthRouteUnitMember) SortOrderOrZero() int64

OrZero helpers coerce the nullable numeric member columns for callers that need a numeric default (ordering, success/failure recording).

func (OAuthRouteUnitMember) SuccessCountOrZero added in v0.16.8

func (m OAuthRouteUnitMember) SuccessCountOrZero() int64

func (OAuthRouteUnitMember) TotalCostOrZero added in v0.16.8

func (m OAuthRouteUnitMember) TotalCostOrZero() float64

func (OAuthRouteUnitMember) TotalLatencyMsOrZero added in v0.16.8

func (m OAuthRouteUnitMember) TotalLatencyMsOrZero() int64

type PostgresPoolConfig

type PostgresPoolConfig struct {
	MaxOpenConns    int
	MaxIdleConns    int
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
	ApplicationName string
}

PostgresPoolConfig is the application-side connection budget. MaxOpenConns must not exceed the production role CONNECTION LIMIT. ApplicationName is injected into the PostgreSQL DSN as application_name when the DSN does not already set it (visible in pg_stat_activity).

func DefaultPostgresPoolConfig

func DefaultPostgresPoolConfig() PostgresPoolConfig

DefaultPostgresPoolConfig returns the "normal" profile defaults (10/3). Large exclusive databases should raise MaxOpenConns explicitly or use DB_PROFILE=dedicated (20/5). Shared tiny roles use DB_PROFILE=shared-tiny (2/1).

type ProductAnnouncement

type ProductAnnouncement struct {
	ID        int64   `db:"id" json:"id"`
	Title     string  `db:"title" json:"title"`
	Message   string  `db:"message" json:"message"`
	Severity  string  `db:"severity" json:"severity"` // info | warning | critical
	Link      *string `db:"link" json:"link"`
	Enabled   bool    `db:"enabled" json:"enabled"`
	CreatedAt string  `db:"created_at" json:"createdAt"`
	UpdatedAt string  `db:"updated_at" json:"updatedAt"`
}

---- Table 31: product_announcements ----

type ProxyLog

type ProxyLog struct {
	OwnerUserID           *int64   `db:"owner_user_id" json:"ownerUserId"`
	UserGroupID           *int64   `db:"user_group_id" json:"userGroupId"`
	GatewayRequestID      *string  `db:"gateway_request_id" json:"gatewayRequestId"`
	DownstreamPath        *string  `db:"downstream_path" json:"downstreamPath"`
	UpstreamReportedModel *string  `db:"upstream_reported_model" json:"upstreamReportedModel"`
	ID                    int64    `db:"id" json:"id"`
	RouteID               *int64   `db:"route_id" json:"routeId"`
	ChannelID             *int64   `db:"channel_id" json:"channelId"`
	UpstreamChannelID     *int64   `db:"upstream_channel_id" json:"upstreamChannelId"`
	UpstreamGrantID       *int64   `db:"upstream_grant_id" json:"upstreamGrantId"`
	AccountID             *int64   `db:"account_id" json:"accountId"`
	DownstreamAPIKeyID    *int64   `db:"downstream_api_key_id" json:"downstreamApiKeyId"`
	ModelRequested        *string  `db:"model_requested" json:"modelRequested"`
	ModelActual           *string  `db:"model_actual" json:"modelActual"`
	Status                *string  `db:"status" json:"status"`
	HTTPStatus            *int64   `db:"http_status" json:"httpStatus"`
	IsStream              *bool    `db:"is_stream" json:"isStream"`
	FirstByteLatencyMs    *int64   `db:"first_byte_latency_ms" json:"firstByteLatencyMs"`
	FirstOutputLatencyMs  *int64   `db:"first_output_latency_ms" json:"firstOutputLatencyMs"`
	LatencyMs             *int64   `db:"latency_ms" json:"latencyMs"`
	PromptTokens          *int64   `db:"prompt_tokens" json:"promptTokens"`
	CompletionTokens      *int64   `db:"completion_tokens" json:"completionTokens"`
	TotalTokens           *int64   `db:"total_tokens" json:"totalTokens"`
	EstimatedCost         *float64 `db:"estimated_cost" json:"estimatedCost"`
	BillingDetails        *string  `db:"billing_details" json:"billingDetails"`
	ClientFamily          *string  `db:"client_family" json:"clientFamily"`
	ClientAppID           *string  `db:"client_app_id" json:"clientAppId"`
	ClientAppName         *string  `db:"client_app_name" json:"clientAppName"`
	ClientConfidence      *string  `db:"client_confidence" json:"clientConfidence"`
	ErrorMessage          *string  `db:"error_message" json:"errorMessage"`
	RetryCount            int64    `db:"retry_count" json:"retryCount"`
	// RequestID is the ingress X-Request-Id / chi RequestID shared across retries.
	RequestID *string `db:"request_id" json:"requestId"`
	CreatedAt string  `db:"created_at" json:"createdAt"`
}

---- Table 14: proxy_logs ----

type ProxyVideoTask

type ProxyVideoTask struct {
	AccountingState      *string `db:"accounting_state" json:"accountingState,omitempty"`
	DirectIdentity       *string `db:"direct_identity" json:"directIdentity,omitempty"`
	ID                   int64   `db:"id" json:"id"`
	PublicID             string  `db:"public_id" json:"publicId"`
	UpstreamVideoID      string  `db:"upstream_video_id" json:"upstreamVideoId"`
	SiteURL              string  `db:"site_url" json:"siteUrl"`
	TokenValue           string  `db:"token_value" json:"tokenValue"`
	RequestedModel       *string `db:"requested_model" json:"requestedModel"`
	ActualModel          *string `db:"actual_model" json:"actualModel"`
	ChannelID            *int64  `db:"channel_id" json:"channelId"`
	AccountID            *int64  `db:"account_id" json:"accountId"`
	Owner                *string `db:"owner" json:"owner"`
	StatusSnapshot       *string `db:"status_snapshot" json:"statusSnapshot"`
	UpstreamResponseMeta *string `db:"upstream_response_meta" json:"upstreamResponseMeta"`
	LastUpstreamStatus   *int64  `db:"last_upstream_status" json:"lastUpstreamStatus"`
	LastPolledAt         *string `db:"last_polled_at" json:"lastPolledAt"`
	CreatedAt            string  `db:"created_at" json:"createdAt"`
	UpdatedAt            string  `db:"updated_at" json:"updatedAt"`
}

---- Table 17: proxy_video_tasks ----

type RouteChannel

type RouteChannel struct {
	ID               int64   `db:"id" json:"id"`
	RouteID          int64   `db:"route_id" json:"routeId"`
	AccountID        int64   `db:"account_id" json:"accountId"`
	TokenID          *int64  `db:"token_id" json:"tokenId"`
	OAuthRouteUnitID *int64  `db:"oauth_route_unit_id" json:"oauthRouteUnitId"`
	SourceModel      *string `db:"source_model" json:"sourceModel"`
	// Priority/Weight/SuccessCount/FailCount/TotalLatencyMs/TotalCost are
	// nullable in the DDL (DEFAULT without NOT NULL): TS-migrated rows can
	// carry NULL. Keep pointers so NULL scans to nil instead of failing
	// LoadRouteChannels with "converting NULL to int64" (a single NULL row
	// used to take down the whole routing load). Numeric callers use the
	// OrZero helpers below.
	Priority             *int64   `db:"priority" json:"priority"`
	Weight               *int64   `db:"weight" json:"weight"`
	Enabled              bool     `db:"enabled" json:"enabled"`
	ManualOverride       bool     `db:"manual_override" json:"manualOverride"`
	SuccessCount         *int64   `db:"success_count" json:"successCount"`
	FailCount            *int64   `db:"fail_count" json:"failCount"`
	TotalLatencyMs       *int64   `db:"total_latency_ms" json:"totalLatencyMs"`
	TotalCost            *float64 `db:"total_cost" json:"totalCost"`
	LastUsedAt           *string  `db:"last_used_at" json:"lastUsedAt"`
	LastSelectedAt       *string  `db:"last_selected_at" json:"lastSelectedAt"`
	LastFailAt           *string  `db:"last_fail_at" json:"lastFailAt"`
	ConsecutiveFailCount int64    `db:"consecutive_fail_count" json:"consecutiveFailCount"`
	CooldownLevel        int64    `db:"cooldown_level" json:"cooldownLevel"`
	CooldownUntil        *string  `db:"cooldown_until" json:"cooldownUntil"`
	// Structured reason for the active cooldown: classification code,
	// truncated upstream error summary, and the time the triggering failure was
	// recorded. All NULL for rows that cooled down before this schema existed
	// — the UI renders that honestly as "reason not recorded".
	CooldownReasonCode *string                  `db:"cooldown_reason_code" json:"cooldownReasonCode"`
	CooldownReason     *string                  `db:"cooldown_reason" json:"cooldownReason"`
	CooldownReasonAt   *string                  `db:"cooldown_reason_at" json:"cooldownReasonAt"`
	Direct             *DirectUpstreamCandidate `db:"-" json:"-"`
}

---- Table 13: route_channels ----

func (RouteChannel) FailCountOrZero added in v0.16.8

func (c RouteChannel) FailCountOrZero() int64

func (RouteChannel) PriorityOrZero added in v0.16.8

func (c RouteChannel) PriorityOrZero() int64

OrZero helpers coerce the nullable numeric channel columns for callers that need a numeric default (priority layers, weighted selection, success/failure recording). Callers that must preserve unknown/nil semantics (JSON display, IsChannelRecentlyFailed) read the pointer directly.

func (RouteChannel) SuccessCountOrZero added in v0.16.8

func (c RouteChannel) SuccessCountOrZero() int64

func (RouteChannel) TotalCostOrZero added in v0.16.8

func (c RouteChannel) TotalCostOrZero() float64

func (RouteChannel) TotalLatencyMsOrZero added in v0.16.8

func (c RouteChannel) TotalLatencyMsOrZero() int64

func (RouteChannel) WeightOrZero added in v0.16.8

func (c RouteChannel) WeightOrZero() int64

type RouteGroupSource

type RouteGroupSource struct {
	ID            int64 `db:"id" json:"id"`
	GroupRouteID  int64 `db:"group_route_id" json:"groupRouteId"`
	SourceRouteID int64 `db:"source_route_id" json:"sourceRouteId"`
}

---- Table 10: route_group_sources ----

type RunMigrationOptions added in v0.13.0

type RunMigrationOptions struct {
	// FromPath is the source database: a SQLite path (plain, sqlite://, or
	// file://) or a PostgreSQL URL (postgres:// / postgresql://).
	FromPath string
	// ToURL is the target database (same encoding rules as FromPath).
	ToURL string
	// Overwrite clears target data in FK-safe order before inserting.
	// Defaults to true to match the TS behaviour; --overwrite=false is a no-op gate.
	Overwrite bool
	// DryRun validates and prints the migration plan without writing data.
	DryRun bool
	// Progress emits per-100-row progress lines to LogWriter when true.
	Progress bool
	// Verify computes row-count + hash checksums after migration.
	Verify bool
	// BatchSize groups consecutive same-table rows into multi-row INSERT
	// statements of at most BatchSize rows. <= 0 keeps the row-by-row path
	// (the TS default); the CLI --batch-size flag maps here.
	BatchSize int
	// LogWriter receives structural + progress log lines. nil discards output;
	// the CLI passes os.Stderr, the admin handler passes a task-log-backed writer
	// so /api/tasks/{id} polling surfaces meaningful migration progress.
	LogWriter io.Writer
}

RunMigrationOptions configures a single RunMigration invocation. It is the callable equivalent of the metapi-migrate CLI flags; the CLI constructs it from parsed flags while the admin migrate handler constructs it from the HTTP request plus the live runtime database config.

type Setting

type Setting struct {
	Key   string  `db:"key" json:"key"`
	Value *string `db:"value" json:"value"`
}

---- Table 19: settings (text PK) ----

type SettingsStore

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

SettingsStore provides KV read/write access to the settings table. The settings table uses a TEXT primary key (key), not SERIAL.

func NewSettingsStore

func NewSettingsStore(db *DB) *SettingsStore

NewSettingsStore creates a new SettingsStore backed by the given DB.

func (*SettingsStore) Get

func (s *SettingsStore) Get(key string) (string, error)

Get returns the value for the given key. Returns ("", nil) if the key does not exist.

func (*SettingsStore) GetAll

func (s *SettingsStore) GetAll() (map[string]string, error)

GetAll returns all key-value pairs from the settings table.

func (*SettingsStore) Set

func (s *SettingsStore) Set(key, value string) error

Set upserts a key-value pair into the settings table.

type Site

type Site struct {
	ID                 int64   `db:"id" json:"id"`
	Name               string  `db:"name" json:"name"`
	URL                string  `db:"url" json:"url"`
	ExternalCheckinURL *string `db:"external_checkin_url" json:"externalCheckinUrl"`
	Platform           string  `db:"platform" json:"platform"`
	ProxyURL           *string `db:"proxy_url" json:"proxyUrl"`
	UseSystemProxy     bool    `db:"use_system_proxy" json:"useSystemProxy"`
	CustomHeaders      *string `db:"custom_headers" json:"customHeaders"`
	// CustomHeadersOverrideRequestHeaders: when true, site custom headers
	// overwrite same-name request headers (site-wins). Default false =
	// request-wins (only set when the request lacks that header).
	CustomHeadersOverrideRequestHeaders bool   `db:"custom_headers_override_request_headers" json:"customHeadersOverrideRequestHeaders"`
	Status                              string `db:"status" json:"status"`
	// IsPinned/SortOrder/GlobalWeight are nullable in the sites table
	// (DEFAULT without NOT NULL): rows migrated from the TS version can carry
	// NULL. Keep them as pointers so a NULL column scans to nil (JSON null)
	// instead of failing with "converting NULL to ..." in the routing join
	// scans (channelAccountSiteSelect). Readers that need a numeric default
	// use the OrZero helpers below.
	IsPinned     *bool    `db:"is_pinned" json:"isPinned"`
	SortOrder    *int64   `db:"sort_order" json:"sortOrder"`
	GlobalWeight *float64 `db:"global_weight" json:"globalWeight"`
	APIKey       *string  `db:"api_key" json:"apiKey"`
	// MaxConcurrency caps concurrent upstream calls for this site.
	// 0 (default) means unlimited — preserves pre-SC2 behavior.
	MaxConcurrency                     int64  `db:"max_concurrency" json:"maxConcurrency"`
	PostRefreshProbeEnabled            bool   `db:"post_refresh_probe_enabled" json:"postRefreshProbeEnabled"`
	PostRefreshProbeModel              string `db:"post_refresh_probe_model" json:"postRefreshProbeModel"`
	PostRefreshProbeScope              string `db:"post_refresh_probe_scope" json:"postRefreshProbeScope"`
	PostRefreshProbeLatencyThresholdMs int64  `db:"post_refresh_probe_latency_threshold_ms" json:"postRefreshProbeLatencyThresholdMs"`
	CreatedAt                          string `db:"created_at" json:"createdAt"`
	UpdatedAt                          string `db:"updated_at" json:"updatedAt"`
	// Tags holds a JSON array of operator labels.
	Tags *string `db:"tags" json:"tags"`
	// BrowserUA optionally overrides the global browser User-Agent for this
	// site (used to match the UA of a harvested cf_clearance cookie).
	BrowserUA *string `db:"browser_ua" json:"browserUa"`
	// CfClearance is a per-site Cloudflare clearance cookie injected into
	// outbound requests to bypass CF challenges.
	CfClearance *string `db:"cf_clearance" json:"cfClearance"`
	// ResinEnabled is a per-site Resin sticky-proxy override.
	// nil  = inherit global RESIN_ENABLED flag (default, preserves legacy behavior)
	// true = force-enable Resin for this site even when global is disabled
	// false = force-disable Resin for this site even when global is enabled
	ResinEnabled *bool `db:"resin_enabled" json:"resinEnabled"`
	// UseUTLS is a per-site uTLS TLS fingerprint masking override.
	// nil  = inherit global UTLS_ENABLED flag (default, preserves legacy behavior)
	// true = force-enable uTLS Chrome-ClientHello masking for this site
	// false = force-disable uTLS masking even when global is enabled
	UseUTLS *bool `db:"use_utls" json:"useUtls"`
}

---- Table 1: sites ----

func (Site) GlobalWeightOrZero added in v0.16.8

func (s Site) GlobalWeightOrZero() float64

func (Site) IsPinnedOrFalse added in v0.16.8

func (s Site) IsPinnedOrFalse() bool

OrZero helpers coerce the nullable numeric site columns for callers that need a numeric default (routing weights, ordering). Callers that must preserve the unknown/nil semantics (JSON display) read the pointer directly.

func (Site) SortOrderOrZero added in v0.16.8

func (s Site) SortOrderOrZero() int64

type SiteAPIEndpoint

type SiteAPIEndpoint struct {
	ID                int64   `db:"id" json:"id"`
	SiteID            int64   `db:"site_id" json:"siteId"`
	URL               string  `db:"url" json:"url"`
	Enabled           bool    `db:"enabled" json:"enabled"`
	SortOrder         int64   `db:"sort_order" json:"sortOrder"`
	CooldownUntil     *string `db:"cooldown_until" json:"cooldownUntil"`
	LastSelectedAt    *string `db:"last_selected_at" json:"lastSelectedAt"`
	LastFailedAt      *string `db:"last_failed_at" json:"lastFailedAt"`
	LastFailureReason *string `db:"last_failure_reason" json:"lastFailureReason"`
	CreatedAt         string  `db:"created_at" json:"createdAt"`
	UpdatedAt         string  `db:"updated_at" json:"updatedAt"`
}

---- Table 2: site_api_endpoints ----

type SiteAnnouncement

type SiteAnnouncement struct {
	ID                int64   `db:"id" json:"id"`
	SiteID            int64   `db:"site_id" json:"siteId"`
	Platform          string  `db:"platform" json:"platform"`
	SourceKey         string  `db:"source_key" json:"sourceKey"`
	Title             string  `db:"title" json:"title"`
	Content           string  `db:"content" json:"content"`
	Level             string  `db:"level" json:"level"`
	SourceURL         *string `db:"source_url" json:"sourceUrl"`
	StartsAt          *string `db:"starts_at" json:"startsAt"`
	EndsAt            *string `db:"ends_at" json:"endsAt"`
	UpstreamCreatedAt *string `db:"upstream_created_at" json:"upstreamCreatedAt"`
	UpstreamUpdatedAt *string `db:"upstream_updated_at" json:"upstreamUpdatedAt"`
	FirstSeenAt       string  `db:"first_seen_at" json:"firstSeenAt"`
	LastSeenAt        string  `db:"last_seen_at" json:"lastSeenAt"`
	ReadAt            *string `db:"read_at" json:"readAt"`
	DismissedAt       *string `db:"dismissed_at" json:"dismissedAt"`
	RawPayload        *string `db:"raw_payload" json:"rawPayload"`
}

---- Table 26: site_announcements ----

type SiteDayUsage

type SiteDayUsage struct {
	ID                int64   `db:"id" json:"id"`
	LocalDay          string  `db:"local_day" json:"localDay"`
	SiteID            int64   `db:"site_id" json:"siteId"`
	TotalCalls        int64   `db:"total_calls" json:"totalCalls"`
	SuccessCalls      int64   `db:"success_calls" json:"successCalls"`
	FailedCalls       int64   `db:"failed_calls" json:"failedCalls"`
	TotalTokens       int64   `db:"total_tokens" json:"totalTokens"`
	TotalSummarySpend float64 `db:"total_summary_spend" json:"totalSummarySpend"`
	TotalSiteSpend    float64 `db:"total_site_spend" json:"totalSiteSpend"`
	TotalLatencyMs    int64   `db:"total_latency_ms" json:"totalLatencyMs"`
	LatencyCount      int64   `db:"latency_count" json:"latencyCount"`
	CreatedAt         string  `db:"created_at" json:"createdAt"`
	UpdatedAt         string  `db:"updated_at" json:"updatedAt"`
}

---- Table 22: site_day_usage ----

type SiteDisabledModel

type SiteDisabledModel struct {
	ID        int64  `db:"id" json:"id"`
	SiteID    int64  `db:"site_id" json:"siteId"`
	ModelName string `db:"model_name" json:"modelName"`
	CreatedAt string `db:"created_at" json:"createdAt"`
}

---- Table 3: site_disabled_models ----

type SiteHourUsage

type SiteHourUsage struct {
	ID                int64   `db:"id" json:"id"`
	BucketStartUTC    string  `db:"bucket_start_utc" json:"bucketStartUtc"`
	SiteID            int64   `db:"site_id" json:"siteId"`
	TotalCalls        int64   `db:"total_calls" json:"totalCalls"`
	SuccessCalls      int64   `db:"success_calls" json:"successCalls"`
	FailedCalls       int64   `db:"failed_calls" json:"failedCalls"`
	TotalTokens       int64   `db:"total_tokens" json:"totalTokens"`
	TotalSummarySpend float64 `db:"total_summary_spend" json:"totalSummarySpend"`
	TotalSiteSpend    float64 `db:"total_site_spend" json:"totalSiteSpend"`
	TotalLatencyMs    int64   `db:"total_latency_ms" json:"totalLatencyMs"`
	LatencyCount      int64   `db:"latency_count" json:"latencyCount"`
	CreatedAt         string  `db:"created_at" json:"createdAt"`
	UpdatedAt         string  `db:"updated_at" json:"updatedAt"`
}

---- Table 23: site_hour_usage ----

type TokenModelAvailability

type TokenModelAvailability struct {
	ID        int64  `db:"id" json:"id"`
	TokenID   int64  `db:"token_id" json:"tokenId"`
	ModelName string `db:"model_name" json:"modelName"`
	Available *bool  `db:"available" json:"available"`
	LatencyMs *int64 `db:"latency_ms" json:"latencyMs"`
	CheckedAt string `db:"checked_at" json:"checkedAt"`
}

---- Table 8: token_model_availability ----

type TokenRoute

type TokenRoute struct {
	ID                  int64   `db:"id" json:"id"`
	ModelPattern        string  `db:"model_pattern" json:"modelPattern"`
	DisplayName         *string `db:"display_name" json:"displayName"`
	DisplayIcon         *string `db:"display_icon" json:"displayIcon"`
	RouteMode           string  `db:"route_mode" json:"routeMode"`
	ModelMapping        *string `db:"model_mapping" json:"modelMapping"`
	DecisionSnapshot    *string `db:"decision_snapshot" json:"decisionSnapshot"`
	DecisionRefreshedAt *string `db:"decision_refreshed_at" json:"decisionRefreshedAt"`
	RoutingStrategy     string  `db:"routing_strategy" json:"routingStrategy"`
	// ContextLength is optional route-level context window metadata (tokens).
	// NULL means unknown / no enforcement — preserves pre-SC2 behavior.
	// No dedicated model_catalog table exists; token_routes is the SC0 Option A home.
	ContextLength *int64 `db:"context_length" json:"contextLength"`
	// SortOrder controls admin list order (lower first, then id). Default 0.
	// Nullable in the DDL (DEFAULT 0 without NOT NULL): TS-migrated rows can
	// carry NULL, so keep a pointer — NULL scans to nil instead of failing
	// LoadEnabledRoutes with "converting NULL to int64".
	SortOrder *int64 `db:"sort_order" json:"sortOrder"`
	Enabled   bool   `db:"enabled" json:"enabled"`
	CreatedAt string `db:"created_at" json:"createdAt"`
	UpdatedAt string `db:"updated_at" json:"updatedAt"`
}

---- Table 9: token_routes ----

func (TokenRoute) SortOrderOrZero added in v0.16.8

func (r TokenRoute) SortOrderOrZero() int64

SortOrderOrZero coerces the nullable sort_order for ordering callers.

type UserAuthStore added in v0.27.0

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

UserAuthStore persists opaque credential digests, never plaintext passwords, activation codes or session tokens. No method returns these to an HTTP DTO.

func NewUserAuthStore added in v0.27.0

func NewUserAuthStore(db *DB) *UserAuthStore

func (*UserAuthStore) Activate added in v0.27.0

func (s *UserAuthStore) Activate(ctx context.Context, username, codeHash, passwordHash, version string, now time.Time) error

func (*UserAuthStore) ChangePassword added in v0.27.0

func (s *UserAuthStore) ChangePassword(ctx context.Context, userID int64, oldVersion, passwordHash, version string, now time.Time) error

func (*UserAuthStore) CreateSession added in v0.27.0

func (s *UserAuthStore) CreateSession(ctx context.Context, credential UserCredential, hash string, now, expires, idle time.Time) error

func (*UserAuthStore) Credential added in v0.27.0

func (s *UserAuthStore) Credential(ctx context.Context, username string) (UserCredential, error)

func (*UserAuthStore) IssueActivation added in v0.27.0

func (s *UserAuthStore) IssueActivation(ctx context.Context, userID int64, hash, version string, now, expires time.Time) error

IssueActivation also resets an existing login. Its transaction serializes with password changes and invalidates old login attempts by version.

func (*UserAuthStore) RevokeSession added in v0.27.0

func (s *UserAuthStore) RevokeSession(ctx context.Context, hash string) error

func (*UserAuthStore) ValidateSession added in v0.27.0

func (s *UserAuthStore) ValidateSession(ctx context.Context, hash string, now time.Time, idleTTL time.Duration) (UserSession, error)

type UserBudget added in v0.27.0

type UserBudget struct {
	Limit           float64 `json:"limit"`
	Used            float64 `json:"used"`
	Reserved        float64 `json:"reserved"`
	Unlimited       bool    `json:"unlimited"`
	Frozen          bool    `json:"frozen"`
	UnknownRequests int64   `json:"unknownRequests"`
}

type UserBudgetHold added in v0.27.0

type UserBudgetHold struct {
	RequestID   string  `db:"request_id" json:"requestId"`
	State       string  `db:"state" json:"state"`
	Reserved    float64 `db:"reserved" json:"reserved"`
	TotalTokens *int64  `db:"total_tokens" json:"totalTokens"`
	CreatedAt   string  `db:"created_at" json:"createdAt"`
	Multiplier  float64 `db:"multiplier" json:"multiplier"`
}

type UserBudgetReservation added in v0.27.0

type UserBudgetReservation struct {
	RequestID       string `db:"request_id"`
	UserID          int64  `db:"user_id"`
	GroupID         int64  `db:"group_id"`
	MultiplierUnits int64  `db:"multiplier_units"`
	ReservedUnits   int64  `db:"reserved_units"`
	ChargedUnits    *int64 `db:"charged_units"`
	TotalTokens     *int64 `db:"total_tokens"`
	State           string `db:"state"`
}

type UserCredential added in v0.27.0

type UserCredential struct {
	UserID       int64  `db:"user_id"`
	PasswordHash string `db:"password_hash"`
	Version      string `db:"version"`
}

type UserGroupPricing added in v0.27.0

type UserGroupPricing struct {
	Multiplier float64 `json:"multiplier"`
}

type UserKey added in v0.27.0

type UserKey struct {
	ID              int64    `db:"id" json:"id"`
	Name            string   `db:"name" json:"name"`
	KeyMasked       string   `db:"key_masked" json:"keyMasked"`
	Enabled         bool     `db:"enabled" json:"enabled"`
	ExpiresAt       *string  `db:"expires_at" json:"expiresAt"`
	SupportedModels []string `db:"-" json:"supportedModels"`
	MaxCost         *float64 `db:"max_cost" json:"maxCost"`
	MaxRequests     *int64   `db:"max_requests" json:"maxRequests"`
	UsedCost        float64  `db:"used_cost" json:"usedCost"`
	UsedRequests    int64    `db:"used_requests" json:"usedRequests"`
	CreatedAt       string   `db:"created_at" json:"createdAt"`
}

UserKey and UserRequest are explicit safe projections. Do not replace these with SELECT * or the administrator's credential-bearing records.

type UserRequest added in v0.27.0

type UserRequest struct {
	ID             string            `db:"id" json:"id"`
	ModelRequested *string           `db:"model_requested" json:"modelRequested"`
	TerminalStatus string            `db:"terminal_status" json:"terminalStatus"`
	LatencyMs      int64             `db:"latency_ms" json:"latencyMs"`
	StartedAt      string            `db:"started_at" json:"startedAt"`
	EndedAt        string            `db:"ended_at" json:"endedAt"`
	AttemptCount   int               `db:"attempt_count" json:"attemptCount"`
	Quota          *UserRequestQuota `db:"-" json:"quota"`
}

type UserRequestFilter added in v0.27.0

type UserRequestFilter struct {
	Search     string
	Status     string
	QuotaState string
}

UserRequestFilter searches retained public identifiers, never private upstream reasons or correlation metadata. Both rows and totals use it.

func (UserRequestFilter) Validate added in v0.27.0

func (f UserRequestFilter) Validate() error

type UserRequestQuota added in v0.27.0

type UserRequestQuota struct {
	Unit            string   `json:"unit"`
	State           string   `json:"state"`
	TotalTokens     *int64   `json:"totalTokens"`
	GroupMultiplier float64  `json:"groupMultiplier"`
	Reserved        float64  `json:"reserved"`
	Charged         *float64 `json:"charged"`
}

UserRequestQuota exposes only the request's durable token-credit snapshot, not upstream cost or current group pricing. Nil measurements remain unknown.

type UserSession added in v0.27.0

type UserSession struct {
	TokenHash string `db:"token_hash"`
	UserID    int64  `db:"user_id"`
	ExpiresAt string `db:"expires_at"`
}

type UserUsage added in v0.27.0

type UserUsage struct {
	UsedCost         float64 `db:"used_cost" json:"usedCost"`
	UsedRequests     int64   `db:"used_requests" json:"usedRequests"`
	KeyCount         int64   `db:"key_count" json:"keyCount"`
	RecordedRequests int64   `db:"recorded_requests" json:"recordedRequests"`
}

type VideoTaskAccounting added in v0.24.0

type VideoTaskAccounting struct {
	Version     int            `json:"version"`
	Initialized bool           `json:"initialized"`
	KeyID       int64          `json:"keyId"`
	Usage       VideoTaskUsage `json:"usage"`
	Cost        float64        `json:"cost"`
}

type VideoTaskAccountingResult added in v0.24.0

type VideoTaskAccountingResult struct {
	Delta     VideoTaskUsage
	CostDelta float64
	Legacy    bool
}

func AccountVideoTask added in v0.24.0

func AccountVideoTask(ctx context.Context, db *DB, publicID, owner string, grantID, keyID int64, observed VideoTaskUsage, cumulativeCost float64) (VideoTaskAccountingResult, error)

AccountVideoTask atomically advances the task's high water mark and all durable billing sinks. The no-op UPDATE takes the row/write lock before the read on both PostgreSQL and SQLite; no separate claim/async increment exists.

type VideoTaskUsage added in v0.24.0

type VideoTaskUsage struct {
	Found               bool  `json:"found"`
	PromptTokens        int64 `json:"promptTokens"`
	CompletionTokens    int64 `json:"completionTokens"`
	TotalTokens         int64 `json:"totalTokens"`
	CacheReadTokens     int64 `json:"cacheReadTokens"`
	CacheCreationTokens int64 `json:"cacheCreationTokens"`
	ReasoningTokens     int64 `json:"reasoningTokens"`
}

VideoTaskUsage is a cumulative upstream observation, not a new HTTP charge.

Jump to

Keyboard shortcuts

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