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
- func AllTableNames() []string
- func ApplyAdditiveMigrations(db *DB) error
- func ApplyRuntimeSettings(cfg *config.Config, rt *config.RuntimeSettings, settingsMap map[string]string)
- func AutoMigrate(db *DB) error
- func BackupExcludedTables() map[string]string
- func BackupTableNames() []string
- func ClearTableNames() []string
- func CloseDatabase() error
- func DirectProviderAllowsAnonymous(provider string) bool
- func DirectVideoTaskOwner(source, token string, keyID *int64) string
- func EnsureColumn(db *DB, table, column, sqliteType, pgType, defaultClause string) error
- func EnsureIndex(db *DB, name, createSQL string) error
- func EnsureRuntimeDatabase(cfg *config.Config, rt *config.RuntimeSettings) error
- func FactoryReset(db *sqlx.DB) (map[string]int64, error)
- func FactoryResetTableNames() []string
- func HasExplicitLogCleanupSettings(settingsMap map[string]string) bool
- func InsertGatewayRequest(ctx context.Context, db *DB, entry GatewayRequest) error
- func InsertGatewayRequests(ctx context.Context, db *DB, entries []GatewayRequest) error
- func LoadRuntimeSettings(cfg *config.Config, rt *config.RuntimeSettings) error
- func MigrateLegacyProxyToken(db *DB, rt *config.RuntimeSettings, rpm int) error
- func OverrideDB(db *DB)
- func PruneProxyRequestLogs(db *DB, cutoff string) (int64, error)
- func RecordAccountPricingFailure(ctx context.Context, db *sqlx.DB, accountID int64, at, code string) error
- func ResolveSQLitePath(dbURL string, dataDir string) string
- func ResyncPGIDSequences(exec sequenceExecer) error
- func SaveAccountPricing(ctx context.Context, db *sqlx.DB, row AccountPricingSnapshot) error
- func SaveSiteAnnouncementRevision(tx *sqlx.Tx, announcement SiteAnnouncement) error
- func SchemaTableNames() []string
- func SwitchDatabase(cfg *config.Config, nextDialect, nextDsn string, nextSsl bool) error
- func ValidDirectProtocol(bit int) bool
- type Account
- type AccountPricingSnapshot
- type AccountToken
- type AdditiveStep
- type AdminAuditLog
- type AdminBackgroundTask
- type AnalyticsProjectionCheckpoint
- type AnnouncementDismissal
- type BalanceHistory
- type CheckinLog
- type DB
- func (db *DB) Exec(query string, args ...any) (sql.Result, error)
- func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
- func (db *DB) Get(dest any, query string, args ...any) error
- func (db *DB) GetContext(ctx context.Context, dest any, query string, args ...any) error
- func (db *DB) Query(query string, args ...any) (*sql.Rows, error)
- func (db *DB) QueryRow(query string, args ...any) *sql.Row
- func (db *DB) QueryRowx(query string, args ...any) *sqlx.Row
- func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row
- func (db *DB) Queryx(query string, args ...any) (*sqlx.Rows, error)
- func (db *DB) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error)
- func (db *DB) Select(dest any, query string, args ...any) error
- func (db *DB) SelectContext(ctx context.Context, dest any, query string, args ...any) error
- type DirectEndpoint
- type DirectEndpointEntry
- type DirectEndpoints
- func (e DirectEndpoints) AnonymousProtocolMask() int
- func (e DirectEndpoints) Entries() []DirectEndpointEntry
- func (e DirectEndpoints) ForProtocol(bit int) *DirectEndpoint
- func (e DirectEndpoints) IsConfigured() bool
- func (e DirectEndpoints) ProtocolMask() int
- func (e *DirectEndpoints) Scan(value any) error
- func (e DirectEndpoints) Value() (driver.Value, error)
- type DirectModelWireURLs
- type DirectOAuthState
- type DirectProtocolOrder
- type DirectUpstreamCandidate
- type DownstreamAPIKey
- type DownstreamAccessPolicy
- type DownstreamModelMapping
- type DownstreamQuota
- type DownstreamQuotaDuration
- type DownstreamQuotaPeriod
- type Event
- type GatewayRequest
- type MigrationSummary
- type ModelAvailability
- type ModelDayUsage
- type ModelNameRedirect
- type ModelProbeResult
- type ModelVerifyRecord
- type OAuthRouteUnit
- type OAuthRouteUnitMember
- type PostgresPoolConfig
- type ProductAnnouncement
- type ProxyLog
- type ProxyVideoTask
- type RouteChannel
- type RouteGroupSource
- type RunMigrationOptions
- type Setting
- type SettingsStore
- type Site
- type SiteAPIEndpoint
- type SiteAnnouncement
- type SiteDayUsage
- type SiteDisabledModel
- type SiteHourUsage
- type TokenModelAvailability
- type TokenRoute
- type VideoTaskAccounting
- type VideoTaskAccountingResult
- type VideoTaskUsage
Constants ¶
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" )
const ( DirectAuthBearer = "bearer" DirectAuthAPIKey = "x-api-key" DirectAuthGoogle = "x-goog-api-key" DirectAuthNone = "none" )
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.
const ( DialectSQLite = "sqlite" DialectPostgres = "postgres" )
Dialect name constants.
const GatewayRequestTimeLayout = "2006-01-02T15:04:05.000000000Z"
GatewayRequestTimeLayout keeps TEXT timestamps chronologically sortable at fractional-second boundaries and across client time-zone offsets.
const LegacyProxyTokenMigrationKey = "downstream.root_token_migrated_v1"
Variables ¶
This section is empty.
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 ¶
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 ¶
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
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 DirectVideoTaskOwner ¶ added in v0.26.0
DirectVideoTaskOwner keeps durable video ownership stable across key rotation.
func EnsureColumn ¶
This is the primary primitive SC2 uses for enterprise columns.
func EnsureIndex ¶
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
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 ¶
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
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 ResolveSQLitePath ¶
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 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 ¶
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:
- Close all existing connections.
- Publish the new connection settings (dialect, URL, SSL) through the atomic RuntimeSettings snapshot.
- Open new connection + run auto-migration.
- 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 ValidDirectProtocol ¶ added in v0.24.0
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
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 (Account) QuotaOrZero ¶ added in v0.16.8
func (Account) ValueScoreOrZero ¶ added in v0.16.8
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Get loads one row into dest. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.
func (*DB) GetContext ¶
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 ¶
Query executes a query that returns rows. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.
func (*DB) QueryRow ¶
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 ¶
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 ¶
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 ¶
Queryx executes a query and returns sqlx rows. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.
func (*DB) QueryxContext ¶
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 ¶
Select loads all rows into dest. For PostgreSQL, the query string is rebound from ? to $N placeholders before execution.
func (*DB) SelectContext ¶
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
type DirectModelWireURLs ¶ added in v0.24.0
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
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
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 {
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 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"`
}
type DownstreamQuotaDuration ¶ added in v0.24.0
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 {
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 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 {
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 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 (Site) IsPinnedOrFalse ¶ added in v0.16.8
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
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 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.
Source Files
¶
- account_pricing.go
- additive.go
- bootstrap.go
- direct_credentials.go
- direct_endpoints.go
- direct_protocols.go
- doc.go
- downstream_policy.go
- factory_reset.go
- gateway_requests.go
- indexes.go
- legacy_proxy_token.go
- migrate.go
- migrate_runner.go
- open.go
- schema.go
- schema_ddl.go
- sequences.go
- setting_store.go
- settings.go
- site_announcement_history.go
- switch.go
- tablesets.go
- ts_schema_detect.go
- ts_timestamp_normalize.go
- upstream_ddl.go
- video_accounting.go