store

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2026 License: MIT Imports: 17 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.

Index

Constants

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

Dialect name constants.

Variables

This section is empty.

Functions

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, 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.

func AutoMigrate

func AutoMigrate(db *DB) error

AutoMigrate creates all 28 tables with indexes, unique constraints, foreign keys, and check constraints. Uses CREATE TABLE IF NOT EXISTS for idempotency. After the base bootstrap it runs ApplyAdditiveMigrations (schema_migrations bookkeeping + ordered enterprise steps). Run on startup after Open().

func CloseDatabase

func CloseDatabase() error

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

func EnsureColumn

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

This is the primary primitive SC2 uses for enterprise columns.

func EnsureDataDir

func EnsureDataDir(dataDir string) error

EnsureDataDir creates the data directory if it does not exist.

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) 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 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 LoadRuntimeSettings

func LoadRuntimeSettings(cfg *config.Config) error

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

func Migrate

func Migrate(cfg *config.Config) error

Migrate is a backward-compatible entry point for the P0 stub API. AutoMigrate (called from EnsureRuntimeDatabase) already runs the 28-table bootstrap plus ApplyAdditiveMigrations. This entry point re-runs additive steps only — useful when GetDB() is already open and callers want an explicit compatibility pass without re-executing full CREATE TABLE DDL.

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 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 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. Update config in-place (dialect, URL, SSL). 3. Open new connection + run auto-migration. 4. On failure: close new connection, restore old config, re-open old connection.

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            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"`
}

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

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 AdminSnapshot

type AdminSnapshot struct {
	ID          int64  `db:"id" json:"id"`
	Namespace   string `db:"namespace" json:"namespace"`
	SnapshotKey string `db:"snapshot_key" json:"snapshotKey"`
	Payload     string `db:"payload" json:"payload"`
	GeneratedAt string `db:"generated_at" json:"generatedAt"`
	ExpiresAt   string `db:"expires_at" json:"expiresAt"`
	StaleUntil  string `db:"stale_until" json:"staleUntil"`
	CreatedAt   string `db:"created_at" json:"createdAt"`
	UpdatedAt   string `db:"updated_at" json:"updatedAt"`
}

---- Table 20: admin_snapshots ----

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 DownstreamAPIKey

type DownstreamAPIKey struct {
	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 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 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 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            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"`
	CreatedAt            string  `db:"created_at" json:"createdAt"`
	UpdatedAt            string  `db:"updated_at" json:"updatedAt"`
}

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

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 ProxyDebugAttempt

type ProxyDebugAttempt struct {
	ID                  int64   `db:"id" json:"id"`
	TraceID             int64   `db:"trace_id" json:"traceId"`
	AttemptIndex        int64   `db:"attempt_index" json:"attemptIndex"`
	Endpoint            string  `db:"endpoint" json:"endpoint"`
	RequestPath         string  `db:"request_path" json:"requestPath"`
	TargetURL           string  `db:"target_url" json:"targetUrl"`
	RuntimeExecutor     *string `db:"runtime_executor" json:"runtimeExecutor"`
	RequestHeadersJSON  *string `db:"request_headers_json" json:"requestHeadersJson"`
	RequestBodyJSON     *string `db:"request_body_json" json:"requestBodyJson"`
	ResponseStatus      *int64  `db:"response_status" json:"responseStatus"`
	ResponseHeadersJSON *string `db:"response_headers_json" json:"responseHeadersJson"`
	ResponseBodyJSON    *string `db:"response_body_json" json:"responseBodyJson"`
	RawErrorText        *string `db:"raw_error_text" json:"rawErrorText"`
	RecoverApplied      bool    `db:"recover_applied" json:"recoverApplied"`
	DowngradeDecision   bool    `db:"downgrade_decision" json:"downgradeDecision"`
	DowngradeReason     *string `db:"downgrade_reason" json:"downgradeReason"`
	MemoryWriteJSON     *string `db:"memory_write_json" json:"memoryWriteJson"`
	CreatedAt           string  `db:"created_at" json:"createdAt"`
}

---- Table 16: proxy_debug_attempts ----

type ProxyDebugTrace

type ProxyDebugTrace struct {
	ID                       int64   `db:"id" json:"id"`
	DownstreamPath           string  `db:"downstream_path" json:"downstreamPath"`
	ClientKind               *string `db:"client_kind" json:"clientKind"`
	SessionID                *string `db:"session_id" json:"sessionId"`
	TraceHint                *string `db:"trace_hint" json:"traceHint"`
	RequestedModel           *string `db:"requested_model" json:"requestedModel"`
	DownstreamAPIKeyID       *int64  `db:"downstream_api_key_id" json:"downstreamApiKeyId"`
	RequestHeadersJSON       *string `db:"request_headers_json" json:"requestHeadersJson"`
	RequestBodyJSON          *string `db:"request_body_json" json:"requestBodyJson"`
	StickySessionKey         *string `db:"sticky_session_key" json:"stickySessionKey"`
	StickyHitChannelID       *int64  `db:"sticky_hit_channel_id" json:"stickyHitChannelId"`
	SelectedChannelID        *int64  `db:"selected_channel_id" json:"selectedChannelId"`
	SelectedRouteID          *int64  `db:"selected_route_id" json:"selectedRouteId"`
	SelectedAccountID        *int64  `db:"selected_account_id" json:"selectedAccountId"`
	SelectedSiteID           *int64  `db:"selected_site_id" json:"selectedSiteId"`
	SelectedSitePlatform     *string `db:"selected_site_platform" json:"selectedSitePlatform"`
	EndpointCandidatesJSON   *string `db:"endpoint_candidates_json" json:"endpointCandidatesJson"`
	EndpointRuntimeStateJSON *string `db:"endpoint_runtime_state_json" json:"endpointRuntimeStateJson"`
	DecisionSummaryJSON      *string `db:"decision_summary_json" json:"decisionSummaryJson"`
	FinalStatus              *string `db:"final_status" json:"finalStatus"`
	FinalHTTPStatus          *int64  `db:"final_http_status" json:"finalHttpStatus"`
	FinalUpstreamPath        *string `db:"final_upstream_path" json:"finalUpstreamPath"`
	FinalResponseHeadersJSON *string `db:"final_response_headers_json" json:"finalResponseHeadersJson"`
	FinalResponseBodyJSON    *string `db:"final_response_body_json" json:"finalResponseBodyJson"`
	CreatedAt                string  `db:"created_at" json:"createdAt"`
	UpdatedAt                string  `db:"updated_at" json:"updatedAt"`
}

---- Table 15: proxy_debug_traces ----

type ProxyFile

type ProxyFile struct {
	ID            int64   `db:"id" json:"id"`
	PublicID      string  `db:"public_id" json:"publicId"`
	OwnerType     string  `db:"owner_type" json:"ownerType"`
	OwnerID       string  `db:"owner_id" json:"ownerId"`
	Filename      string  `db:"filename" json:"filename"`
	MimeType      string  `db:"mime_type" json:"mimeType"`
	Purpose       *string `db:"purpose" json:"purpose"`
	ByteSize      int64   `db:"byte_size" json:"byteSize"`
	SHA256        string  `db:"sha256" json:"sha256"`
	ContentBase64 string  `db:"content_base64" json:"contentBase64"`
	CreatedAt     string  `db:"created_at" json:"createdAt"`
	UpdatedAt     string  `db:"updated_at" json:"updatedAt"`
	DeletedAt     *string `db:"deleted_at" json:"deletedAt"`
}

---- Table 18: proxy_files ----

type ProxyLog

type ProxyLog struct {
	ID                 int64    `db:"id" json:"id"`
	RouteID            *int64   `db:"route_id" json:"routeId"`
	ChannelID          *int64   `db:"channel_id" json:"channelId"`
	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"`
	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 {
	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"`
	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             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"`
}

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

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 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                            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"`
}

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

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.
	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 ----

Jump to

Keyboard shortcuts

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