store

package
v0.1.0-beta Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: MIT Imports: 16 Imported by: 0 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 database initialization and models.

Index

Constants

View Source
const (
	TokenStatusActive   = "active"
	TokenStatusDisabled = "disabled"
	TokenStatusExpired  = "expired"
	TokenStatusCooling  = "cooling"
)

Token status constants.

Variables

View Source
var ErrNotFound = errors.New("record not found")

ErrNotFound is returned when a record is not found.

Functions

func AllModels

func AllModels() []any

AllModels returns all models for AutoMigrate.

func AutoMigrate

func AutoMigrate(db *gorm.DB) error

AutoMigrate runs GORM AutoMigrate for all models and handles data migrations.

func Close

func Close(db *gorm.DB) error

Close closes the database connection.

func MigrateUsageLog

func MigrateUsageLog(db *gorm.DB) error

MigrateUsageLog handles UsageLog schema changes that AutoMigrate cannot do (column rename from "latency" to "duration_ms").

func Open

func Open(cfg *config.Config) (*gorm.DB, error)

Open opens a database based on configuration.

func OpenPostgres

func OpenPostgres(dsn string) (*gorm.DB, error)

OpenPostgres opens a PostgreSQL database.

func OpenSQLite

func OpenSQLite(path string) (*gorm.DB, error)

OpenSQLite opens a SQLite database with WAL mode enabled.

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

func (s *APIKeyStore) GetByID(ctx context.Context, id uint) (*APIKey, error)

GetByID returns an API key by ID.

func (*APIKeyStore) GetByKey

func (s *APIKeyStore) GetByKey(ctx context.Context, key string) (*APIKey, error)

GetByKey returns an API key by key string.

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

func (s *APIKeyStore) Regenerate(ctx context.Context, id uint) (string, error)

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.

func (*APIKeyStore) Update

func (s *APIKeyStore) Update(ctx context.Context, ak *APIKey) error

Update saves changes to an existing API key.

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

type BatchUpdateRequest struct {
	IDs          []uint
	Status       *string
	StatusReason *string
	NsfwEnabled  *bool
}

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.

func (*ConfigStore) SetJSON

func (s *ConfigStore) SetJSON(key string, value any) error

SetJSON marshals value to JSON and stores it.

func (*ConfigStore) SetMany

func (s *ConfigStore) SetMany(kvs map[string]string) error

SetMany upserts multiple config key-value pairs in a single transaction.

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.

func (StringSlice) Value

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

Value implements driver.Valuer for database storage.

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"`   // ssoBasic or ssoSuper
	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

type TokenFilter struct {
	Status      *string
	NsfwEnabled *bool
}

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

func (s *TokenStore) GetToken(ctx context.Context, id uint) (*Token, error)

GetToken returns 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       `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" 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

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

func (s *UsageLogStore) TodayCountByEndpoint(ctx context.Context) (map[string]int, error)

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

func (s *UsageLogStore) YesterdayCountByEndpoint(ctx context.Context) (map[string]int, error)

YesterdayCountByEndpoint returns success request counts grouped by endpoint for yesterday. Only counts requests with status < 400.

type UsageLogWithKeyName

type UsageLogWithKeyName struct {
	UsageLog
	APIKeyName string `json:"api_key_name"`
}

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.

Jump to

Keyboard shortcuts

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