Documentation
¶
Overview ¶
Package store provides database initialization and models.
Index ¶
- Constants
- Variables
- func AllModels() []any
- func AutoMigrate(db *gorm.DB) error
- func Close(db *gorm.DB) error
- func Open(cfg *config.Config) (*gorm.DB, error)
- func OpenPostgres(dsn string) (*gorm.DB, error)
- func OpenSQLite(path string) (*gorm.DB, error)
- type APIKey
- type APIKeyStore
- func (s *APIKeyStore) CountByStatus(ctx context.Context) (total, active, inactive, expired, rateLimited int, err error)
- func (s *APIKeyStore) Create(ctx context.Context, ak *APIKey) error
- func (s *APIKeyStore) Delete(ctx context.Context, id uint) error
- func (s *APIKeyStore) GetByID(ctx context.Context, id uint) (*APIKey, error)
- func (s *APIKeyStore) GetByKey(ctx context.Context, key string) (*APIKey, error)
- func (s *APIKeyStore) IncrementUsage(ctx context.Context, id uint) error
- func (s *APIKeyStore) List(ctx context.Context, page, pageSize int, status string) ([]*APIKey, int64, error)
- func (s *APIKeyStore) Regenerate(ctx context.Context, id uint) (string, error)
- func (s *APIKeyStore) ResetDailyUsage(ctx context.Context) error
- func (s *APIKeyStore) Update(ctx context.Context, ak *APIKey) error
- type APIKeyUsage
- type BatchUpdateRequest
- type ConfigEntry
- type ConfigStore
- func (s *ConfigStore) Delete(key string) error
- func (s *ConfigStore) Get(key string) (string, error)
- func (s *ConfigStore) GetAll() (map[string]string, error)
- func (s *ConfigStore) GetJSON(key string, dest any) error
- func (s *ConfigStore) Set(key, value string) error
- func (s *ConfigStore) SetJSON(key string, value any) error
- func (s *ConfigStore) SetMany(kvs map[string]string) error
- type HourlyUsage
- type ModelUsage
- type StringSlice
- type Token
- type TokenFilter
- type TokenSnapshotData
- type TokenStore
- func (s *TokenStore) BatchUpdateTokens(ctx context.Context, req BatchUpdateRequest) (int, error)
- func (s *TokenStore) CreateToken(ctx context.Context, token *Token) error
- func (s *TokenStore) DeleteToken(ctx context.Context, id uint) error
- func (s *TokenStore) GetToken(ctx context.Context, id uint) (*Token, error)
- func (s *TokenStore) ListTokenIDs(ctx context.Context, filter TokenFilter) ([]uint, error)
- func (s *TokenStore) ListTokens(ctx context.Context) ([]*Token, error)
- func (s *TokenStore) ListTokensFiltered(ctx context.Context, filter TokenFilter) ([]*Token, error)
- func (s *TokenStore) UpdateToken(ctx context.Context, token *Token) error
- func (s *TokenStore) UpdateTokenSnapshots(ctx context.Context, snapshots []TokenSnapshotData) error
- type TokenTotals
- type UsageLog
- type UsageLogListParams
- type UsageLogStore
- func (s *UsageLogStore) BatchInsert(ctx context.Context, logs []*UsageLog) error
- func (s *UsageLogStore) HourlyBreakdown(ctx context.Context, hours int) ([]HourlyUsage, error)
- func (s *UsageLogStore) ListLogs(ctx context.Context, p UsageLogListParams) ([]UsageLogWithKeyName, int64, error)
- func (s *UsageLogStore) PeriodUsage(ctx context.Context, period string) (*UsagePeriodResult, error)
- func (s *UsageLogStore) Record(ctx context.Context, log *UsageLog) error
- func (s *UsageLogStore) TodayCountByEndpoint(ctx context.Context) (map[string]int, error)
- func (s *UsageLogStore) TodayTokenTotals(ctx context.Context) (*TokenTotals, error)
- func (s *UsageLogStore) YesterdayCountByEndpoint(ctx context.Context) (map[string]int, error)
- type UsageLogWithKeyName
- type UsagePeriodResult
Constants ¶
const ( TokenStatusActive = "active" TokenStatusDisabled = "disabled" TokenStatusExpired = "expired" TokenStatusCooling = "cooling" )
Token status constants.
Variables ¶
var ErrConflict = errors.New("request name conflict")
ErrConflict is returned when a derived request name conflicts with existing models.
var ErrInvalidInput = errors.New("invalid input")
ErrInvalidInput is returned when a request violates model definition rules.
var ErrNotFound = errors.New("record not found")
ErrNotFound is returned when a record is not found.
Functions ¶
func OpenPostgres ¶
OpenPostgres opens a PostgreSQL database.
Types ¶
type APIKey ¶
type APIKey struct {
ID uint `gorm:"primaryKey" json:"id"`
Key string `gorm:"uniqueIndex;size:128" json:"key"`
Name string `gorm:"size:128" json:"name"`
Status string `gorm:"index;size:32;default:active" json:"status"`
ModelWhitelist StringSlice `gorm:"type:text" json:"model_whitelist"`
RateLimit int `gorm:"default:60" json:"rate_limit"`
DailyLimit int `gorm:"default:1000" json:"daily_limit"`
DailyUsed int `gorm:"default:0" json:"daily_used"`
TotalUsed int `gorm:"default:0" json:"total_used"`
LastUsedAt *time.Time `json:"last_used_at"`
ExpiresAt *time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
APIKey represents an API key for authenticating /v1/* requests.
type APIKeyStore ¶
type APIKeyStore struct {
// contains filtered or unexported fields
}
APIKeyStore handles API key persistence and queries.
func NewAPIKeyStore ¶
func NewAPIKeyStore(db *gorm.DB) *APIKeyStore
NewAPIKeyStore creates a new APIKeyStore.
func (*APIKeyStore) CountByStatus ¶
func (s *APIKeyStore) CountByStatus(ctx context.Context) (total, active, inactive, expired, rateLimited int, err error)
CountByStatus returns counts of API keys grouped by status.
func (*APIKeyStore) Create ¶
func (s *APIKeyStore) Create(ctx context.Context, ak *APIKey) error
Create creates a new API key, generating the key value.
func (*APIKeyStore) Delete ¶
func (s *APIKeyStore) Delete(ctx context.Context, id uint) error
Delete soft-deletes an API key by ID.
func (*APIKeyStore) IncrementUsage ¶
func (s *APIKeyStore) IncrementUsage(ctx context.Context, id uint) error
IncrementUsage atomically increments daily_used and total_used, and updates last_used_at.
func (*APIKeyStore) List ¶
func (s *APIKeyStore) List(ctx context.Context, page, pageSize int, status string) ([]*APIKey, int64, error)
List returns paginated API keys with optional status filter, ordered by created_at DESC.
func (*APIKeyStore) Regenerate ¶
Regenerate generates a new key value for an existing API key, returns the new key.
func (*APIKeyStore) ResetDailyUsage ¶
func (s *APIKeyStore) ResetDailyUsage(ctx context.Context) error
ResetDailyUsage resets daily_used to 0 for all non-deleted API keys.
type APIKeyUsage ¶
type APIKeyUsage struct {
APIKeyName string `json:"api_key_name"`
Requests int `json:"requests"`
TokensInput int `json:"tokens_input"`
TokensOutput int `json:"tokens_output"`
}
APIKeyUsage represents per-API-key usage stats.
type BatchUpdateRequest ¶
BatchUpdateRequest holds parameters for batch updating tokens.
type ConfigEntry ¶
type ConfigEntry struct {
ID uint `gorm:"primaryKey" json:"id"`
Key string `gorm:"uniqueIndex;size:128" json:"key"`
Value string `gorm:"type:text" json:"value"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
ConfigEntry stores configuration key-value pairs in database.
type ConfigStore ¶
type ConfigStore struct {
// contains filtered or unexported fields
}
ConfigStore handles configuration persistence via config_entries table.
func NewConfigStore ¶
func NewConfigStore(db *gorm.DB) *ConfigStore
NewConfigStore creates a new ConfigStore.
func (*ConfigStore) Delete ¶
func (s *ConfigStore) Delete(key string) error
Delete removes a config entry by key.
func (*ConfigStore) Get ¶
func (s *ConfigStore) Get(key string) (string, error)
Get returns the value for a config key, or empty string if not found.
func (*ConfigStore) GetAll ¶
func (s *ConfigStore) GetAll() (map[string]string, error)
GetAll returns all config entries as a map.
func (*ConfigStore) GetJSON ¶
func (s *ConfigStore) GetJSON(key string, dest any) error
GetJSON reads a config key and unmarshals JSON value into dest.
func (*ConfigStore) Set ¶
func (s *ConfigStore) Set(key, value string) error
Set upserts a config key-value pair.
type HourlyUsage ¶
type HourlyUsage struct {
Hour string `json:"hour"`
Endpoint string `json:"endpoint"`
Count int `json:"count"`
}
HourlyUsage represents usage count for a specific hour and endpoint.
type ModelUsage ¶
type ModelUsage struct {
Requests int `json:"requests"`
TokensInput int `json:"tokens_input"`
TokensOutput int `json:"tokens_output"`
}
ModelUsage represents per-model usage stats.
type StringSlice ¶
type StringSlice []string
StringSlice is a custom type for JSON-encoded []string in SQLite.
func (*StringSlice) Scan ¶
func (s *StringSlice) Scan(src any) error
Scan implements sql.Scanner for reading from database.
type Token ¶
type Token struct {
ID uint `gorm:"primaryKey" json:"id"`
Token string `gorm:"uniqueIndex;size:512" json:"token"`
Pool string `gorm:"index;size:32" json:"pool"` // canonical: ssoBasic, ssoSuper, ssoHeavy
Status string `gorm:"index;size:32" json:"status"` // active, disabled, expired, cooling
ChatQuota int `json:"chat_quota"`
InitialChatQuota int `gorm:"default:0" json:"-"`
ImageQuota int `json:"image_quota"`
InitialImageQuota int `gorm:"default:0" json:"-"`
VideoQuota int `json:"video_quota"`
InitialVideoQuota int `gorm:"default:0" json:"-"`
FailCount int `json:"fail_count"`
CoolUntil *time.Time `json:"cool_until,omitempty"`
LastUsed *time.Time `json:"last_used,omitempty"`
Remark string `gorm:"type:text" json:"remark,omitempty"`
NsfwEnabled bool `gorm:"default:false;index" json:"nsfw_enabled"`
StatusReason string `gorm:"size:256" json:"status_reason,omitempty"`
Priority int `gorm:"default:0;index" json:"priority"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
Token represents a Grok authentication token.
type TokenFilter ¶
TokenFilter holds filter criteria for listing tokens.
type TokenSnapshotData ¶
type TokenSnapshotData struct {
ID uint
Status string
StatusReason string
ChatQuota int
InitialChatQuota int
ImageQuota int
InitialImageQuota int
VideoQuota int
InitialVideoQuota int
FailCount int
CoolUntil *time.Time
LastUsed *time.Time
}
TokenSnapshotData holds the mutable fields of a token for batch updates. This mirrors token.TokenSnapshot to avoid circular imports.
type TokenStore ¶
type TokenStore struct {
// contains filtered or unexported fields
}
TokenStore provides CRUD operations for Token.
func NewTokenStore ¶
func NewTokenStore(db *gorm.DB) *TokenStore
NewTokenStore creates a new TokenStore.
func (*TokenStore) BatchUpdateTokens ¶
func (s *TokenStore) BatchUpdateTokens(ctx context.Context, req BatchUpdateRequest) (int, error)
BatchUpdateTokens updates multiple tokens in a transaction.
func (*TokenStore) CreateToken ¶
func (s *TokenStore) CreateToken(ctx context.Context, token *Token) error
CreateToken creates a new token.
func (*TokenStore) DeleteToken ¶
func (s *TokenStore) DeleteToken(ctx context.Context, id uint) error
DeleteToken soft-deletes a token by ID.
func (*TokenStore) ListTokenIDs ¶
func (s *TokenStore) ListTokenIDs(ctx context.Context, filter TokenFilter) ([]uint, error)
ListTokenIDs returns token IDs matching the filter criteria.
func (*TokenStore) ListTokens ¶
func (s *TokenStore) ListTokens(ctx context.Context) ([]*Token, error)
ListTokens returns all active tokens.
func (*TokenStore) ListTokensFiltered ¶
func (s *TokenStore) ListTokensFiltered(ctx context.Context, filter TokenFilter) ([]*Token, error)
ListTokensFiltered returns tokens matching the filter criteria.
func (*TokenStore) UpdateToken ¶
func (s *TokenStore) UpdateToken(ctx context.Context, token *Token) error
UpdateToken updates an existing token.
func (*TokenStore) UpdateTokenSnapshots ¶
func (s *TokenStore) UpdateTokenSnapshots(ctx context.Context, snapshots []TokenSnapshotData) error
UpdateTokenSnapshots batch updates token snapshots.
type TokenTotals ¶
type TokenTotals struct {
Input int `json:"input"`
Output int `json:"output"`
Cache int `json:"cache"`
Total int `json:"total"`
}
TokenTotals holds today's aggregated token usage.
type UsageLog ¶
type UsageLog struct {
ID uint `gorm:"primaryKey" json:"id"`
TokenID uint `gorm:"index" json:"token_id"`
APIKeyID uint `gorm:"index;default:0" json:"api_key_id"`
Model string `gorm:"size:64" json:"model"`
Endpoint string `gorm:"size:128" json:"endpoint"`
Status int `gorm:"index:idx_created_status,priority:2" json:"status"`
DurationMs int64 `gorm:"column:duration_ms" json:"duration_ms"`
TTFTMs int `gorm:"default:0" json:"ttft_ms"`
CacheTokens int `gorm:"default:0" json:"cache_tokens"`
TokensInput int `gorm:"default:0" json:"tokens_input"`
TokensOutput int `gorm:"default:0" json:"tokens_output"`
Estimated bool `gorm:"default:false" json:"estimated"`
CreatedAt time.Time `gorm:"index;index:idx_created_status,priority:1" json:"created_at"`
}
UsageLog records token usage history.
type UsageLogListParams ¶
type UsageLogListParams struct {
Page int
PageSize int
SortBy string
SortDir string
Model string // partial match
Period string
Status string // partial match on status code (e.g. "4" matches 400,401...)
APIKeyName string // partial match on api_keys.name
}
UsageLogListParams holds parameters for ListLogs pagination, filtering, sorting.
type UsageLogStore ¶
type UsageLogStore struct {
// contains filtered or unexported fields
}
UsageLogStore handles usage log persistence and queries.
func NewUsageLogStore ¶
func NewUsageLogStore(db *gorm.DB) *UsageLogStore
NewUsageLogStore creates a new UsageLogStore.
func (*UsageLogStore) BatchInsert ¶
func (s *UsageLogStore) BatchInsert(ctx context.Context, logs []*UsageLog) error
BatchInsert inserts multiple usage log records in batches of 100.
func (*UsageLogStore) HourlyBreakdown ¶
func (s *UsageLogStore) HourlyBreakdown(ctx context.Context, hours int) ([]HourlyUsage, error)
HourlyBreakdown returns usage counts grouped by hour and endpoint for the past N hours. Uses CASE expression to support both SQLite (substr) and PostgreSQL (to_char).
func (*UsageLogStore) ListLogs ¶
func (s *UsageLogStore) ListLogs(ctx context.Context, p UsageLogListParams) ([]UsageLogWithKeyName, int64, error)
ListLogs returns paginated usage logs with api_key_name resolved via LEFT JOIN.
func (*UsageLogStore) PeriodUsage ¶
func (s *UsageLogStore) PeriodUsage(ctx context.Context, period string) (*UsagePeriodResult, error)
PeriodUsage returns aggregated usage stats for the given period.
func (*UsageLogStore) Record ¶
func (s *UsageLogStore) Record(ctx context.Context, log *UsageLog) error
Record inserts a usage log record.
func (*UsageLogStore) TodayCountByEndpoint ¶
TodayCountByEndpoint returns success request counts grouped by endpoint for today. Only counts requests with status < 400.
func (*UsageLogStore) TodayTokenTotals ¶
func (s *UsageLogStore) TodayTokenTotals(ctx context.Context) (*TokenTotals, error)
TodayTokenTotals returns aggregated token totals for today (success only).
func (*UsageLogStore) YesterdayCountByEndpoint ¶
YesterdayCountByEndpoint returns success request counts grouped by endpoint for yesterday. Only counts requests with status < 400.
type UsageLogWithKeyName ¶
UsageLogWithKeyName embeds UsageLog with resolved API key name via JOIN.
type UsagePeriodResult ¶
type UsagePeriodResult struct {
Requests int `json:"requests"`
TokensInput int `json:"tokens_input"`
TokensOutput int `json:"tokens_output"`
CacheTokens int `json:"cache_tokens"`
Errors int `json:"errors"`
ByModel map[string]ModelUsage `json:"by_model"`
ByAPIKey []APIKeyUsage `json:"by_api_key"`
}
UsagePeriodResult holds aggregated usage stats for a time period.