store

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: AGPL-3.0 Imports: 14 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

Index

Constants

This section is empty.

Variables

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

Functions

This section is empty.

Types

type APIKey

type APIKey struct {
	ID int64 `json:"id"`
	// Exactly one of UserID and AdminID is set.
	UserID     *int64     `json:"userId"`
	AdminID    *int64     `json:"adminId"`
	Name       string     `json:"name"`
	Prefix     string     `json:"prefix"`
	Disabled   bool       `json:"disabled"`
	CreatedAt  time.Time  `json:"createdAt"`
	ExpiresAt  *time.Time `json:"expiresAt"`
	LastUsedAt *time.Time `json:"lastUsedAt"`
	// AllowedModels holds glob patterns; empty means every model is allowed.
	AllowedModels    []string `json:"allowedModels"`
	RPMLimit         int      `json:"rpmLimit"`
	DisplayProfileID *int64   `json:"displayProfileId"`
	// DisplayConfig is the key's own quota page view (quota.Profile as JSON); it overrides the
	// profile. Empty when the key has none.
	DisplayConfig json.RawMessage `json:"displayConfig"`
	// ModelRules is the key's own model mapping (routing.KeyRules as JSON).
	ModelRules json.RawMessage `json:"modelRules"`
	// Copyable is true when an encrypted copy of the full key is stored.
	Copyable bool `json:"copyable"`
	// AuditMode overrides the global audit log setting: "" follows it, "on" or "off" force it.
	AuditMode string `json:"auditMode"`
}

type Account

type Account struct {
	ID             int64      `json:"id"`
	Provider       string     `json:"provider"`
	Label          string     `json:"label"`
	Alias          string     `json:"alias"`
	Email          string     `json:"email"`
	ExternalID     string     `json:"externalId"`
	Plan           string     `json:"plan"`
	Credentials    string     `json:"-"`
	Disabled       bool       `json:"disabled"`
	Priority       int        `json:"priority"`
	AutoRedeem     bool       `json:"-"` // superseded by RedeemPolicy
	RedeemPolicy   string     `json:"-"`
	PrimerPolicy   string     `json:"-"`
	Status         string     `json:"status"`
	StatusMessage  string     `json:"statusMessage"`
	CooldownUntil  *time.Time `json:"cooldownUntil"`
	Quota          string     `json:"-"`
	Subscription   string     `json:"-"`
	HasWebSession  bool       `json:"hasWebSession"`
	QuotaUpdatedAt *time.Time `json:"quotaUpdatedAt"`
	LastUsedAt     *time.Time `json:"lastUsedAt"`
	CreatedAt      time.Time  `json:"createdAt"`
	UpdatedAt      time.Time  `json:"updatedAt"`
}

Account is an upstream provider subscription (a Claude or Codex login).

type AccountPatch

type AccountPatch struct {
	Label    *string `json:"label"`
	Alias    *string `json:"alias"`
	Disabled *bool   `json:"disabled"`
	Priority *int    `json:"priority"`
	// RedeemPolicy is the account's banked reset override as JSON ("" clears it).
	RedeemPolicy *string `json:"-"`
	// PrimerPolicy is the account's session primer override as JSON ("" clears it).
	PrimerPolicy *string `json:"-"`
}

type Admin

type Admin struct {
	ID           int64     `json:"id"`
	Username     string    `json:"username"`
	PasswordHash string    `json:"-"`
	CreatedAt    time.Time `json:"createdAt"`
}

type AuditEntry

type AuditEntry struct {
	ID int64 `json:"id"`
	UsageEvent
	ClientIP    string          `json:"clientIp"`
	UserAgent   string          `json:"userAgent"`
	Attempts    json.RawMessage `json:"attempts"`
	PayloadSize int64           `json:"payloadSize"`
	Payload     []byte          `json:"-"`
}

AuditEntry is one fully recorded request. Payload is the gzip-compressed detail (headers and bodies); it is only loaded by GetAudit.

type AuditFilter

type AuditFilter struct {
	Since     time.Time
	Until     time.Time
	Before    int64 // only entries with a smaller id, for paging
	UserID    int64
	KeyID     int64
	AccountID int64
	Model     string
	// Status is "errors", "ok", or a specific status code.
	Status string
	// Search matches the error, endpoint, models, client IP and user agent.
	Search string
}

type AuditStats

type AuditStats struct {
	Entries int64 `json:"entries"`
	Bytes   int64 `json:"bytes"`
}

type DisplayProfile

type DisplayProfile struct {
	ID        int64           `json:"id"`
	Name      string          `json:"name"`
	Config    json.RawMessage `json:"config"`
	CreatedAt time.Time       `json:"createdAt"`
	UpdatedAt time.Time       `json:"updatedAt"`
	KeyCount  int             `json:"keyCount"`
}

type KeyOwner

type KeyOwner struct {
	Key       APIKey
	User      User
	OwnerName string
}

KeyOwner is the result of authenticating a client API key. User is zero for admin-owned keys.

type KeyPatch

type KeyPatch struct {
	Name             *string   `json:"name"`
	Disabled         *bool     `json:"disabled"`
	AllowedModels    *[]string `json:"allowedModels"`
	RPMLimit         *int      `json:"rpmLimit"`
	DisplayProfileID *int64    `json:"displayProfileId"`
	// DisplayConfig sets the key's own view; JSON null removes it.
	DisplayConfig *json.RawMessage `json:"displayConfig"`
	ModelRules    *json.RawMessage `json:"modelRules"`
	AuditMode     *string          `json:"auditMode"`
	// ExpiresAt: absent leaves the expiry alone, null removes it, a time sets it.
	ExpiresAt OptionalTime `json:"expiresAt"`
}

KeyPatch updates only the non-nil fields. DisplayProfileID 0 resets the key to the default profile.

type OptionalTime

type OptionalTime struct {
	Set   bool
	Value *time.Time
}

OptionalTime tells an absent JSON field apart from an explicit null.

func (*OptionalTime) UnmarshalJSON

func (o *OptionalTime) UnmarshalJSON(b []byte) error

type OwnedKey

type OwnedKey struct {
	APIKey
	OwnerType string `json:"ownerType"` // "user" or "admin"
	OwnerName string `json:"ownerName"`
}

OwnedKey is a key with a display name for whoever owns it.

type PrimerRun

type PrimerRun struct {
	ID        int64      `json:"id"`
	AccountID int64      `json:"accountId"`
	Time      time.Time  `json:"time"`
	Trigger   string     `json:"trigger"` // "slot" or "manual"
	PlannedAt *time.Time `json:"plannedAt,omitempty"`
	// Outcome is "started", "sent" (not verified), "skipped" or "failed".
	Outcome  string     `json:"outcome"`
	Message  string     `json:"message"`
	Pings    int        `json:"pings"`
	ResetsAt *time.Time `json:"resetsAt,omitempty"`
}

PrimerRun is one attempt by the session primer to start an account's session window.

type QuotaSample added in v0.8.0

type QuotaSample struct {
	AccountID int64
	WindowID  string
	Kind      string
	Time      time.Time
	Used      float64
	ResetsAt  *time.Time
	Minutes   int
}

QuotaSample is one recorded reading of an account's quota window.

type Store

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

func Open

func Open(ctx context.Context, path string) (*Store, error)

func (*Store) AccountWebSession

func (s *Store) AccountWebSession(ctx context.Context, id int64) (string, error)

func (*Store) AdminBySession

func (s *Store) AdminBySession(ctx context.Context, tokenHash []byte) (*Admin, error)

func (*Store) AdminByUsername

func (s *Store) AdminByUsername(ctx context.Context, username string) (*Admin, error)

func (*Store) AuditStats

func (s *Store) AuditStats(ctx context.Context) (AuditStats, error)

func (*Store) AuthenticateKey

func (s *Store) AuthenticateKey(ctx context.Context, hash []byte) (*KeyOwner, error)

AuthenticateKey returns the key and owner for an active key, or ErrNotFound if the key is unknown, disabled, expired, or belongs to a disabled user.

func (*Store) ClearAudit

func (s *Store) ClearAudit(ctx context.Context, f AuditFilter) (int64, error)

ClearAudit deletes every entry matching f and reports how many went.

func (*Store) ClearKeySecrets

func (s *Store) ClearKeySecrets(ctx context.Context) (int64, error)

ClearKeySecrets deletes every stored key copy, leaving only hashes.

func (*Store) Close

func (s *Store) Close() error

func (*Store) CountAdmins

func (s *Store) CountAdmins(ctx context.Context) (int, error)

func (*Store) CreateAdminKey

func (s *Store) CreateAdminKey(ctx context.Context, adminID int64, name, prefix string, hash, enc []byte, expiresAt *time.Time) (*APIKey, error)

func (*Store) CreateFirstAdmin

func (s *Store) CreateFirstAdmin(ctx context.Context, username, passwordHash string) (*Admin, error)

CreateFirstAdmin inserts an admin only if none exist yet, so concurrent setup requests can't both succeed.

func (*Store) CreateKey

func (s *Store) CreateKey(ctx context.Context, userID int64, name, prefix string, hash, enc []byte, expiresAt *time.Time) (*APIKey, error)

CreateKey stores a new user key. enc is the encrypted full key, or nil to keep only the hash.

func (*Store) CreateProfile

func (s *Store) CreateProfile(ctx context.Context, name string, config json.RawMessage) (*DisplayProfile, error)

func (*Store) CreateSession

func (s *Store) CreateSession(ctx context.Context, tokenHash []byte, adminID int64, ttl time.Duration) error

func (*Store) CreateUser

func (s *Store) CreateUser(ctx context.Context, name, note string) (*User, error)

func (*Store) DeleteAccount

func (s *Store) DeleteAccount(ctx context.Context, id int64) error

func (*Store) DeleteAudit

func (s *Store) DeleteAudit(ctx context.Context, id int64) error

func (*Store) DeleteKey

func (s *Store) DeleteKey(ctx context.Context, id int64) error

func (*Store) DeleteProfile

func (s *Store) DeleteProfile(ctx context.Context, id int64) error

func (*Store) DeleteSession

func (s *Store) DeleteSession(ctx context.Context, tokenHash []byte) error

func (*Store) DeleteUser

func (s *Store) DeleteUser(ctx context.Context, id int64) error

func (*Store) GetAccount

func (s *Store) GetAccount(ctx context.Context, id int64) (*Account, error)

func (*Store) GetAudit

func (s *Store) GetAudit(ctx context.Context, id int64) (*AuditEntry, error)

func (*Store) GetKey

func (s *Store) GetKey(ctx context.Context, id int64) (*APIKey, error)

func (*Store) GetProfile

func (s *Store) GetProfile(ctx context.Context, id int64) (*DisplayProfile, error)

func (*Store) GetSetting

func (s *Store) GetSetting(ctx context.Context, key string, dst any) error

GetSetting decodes the JSON value stored under key into dst, leaving dst untouched if unset.

func (*Store) GetUser

func (s *Store) GetUser(ctx context.Context, id int64) (*User, error)

func (*Store) InsertAudit

func (s *Store) InsertAudit(ctx context.Context, entries []AuditEntry) error

func (*Store) InsertPrimerRun

func (s *Store) InsertPrimerRun(ctx context.Context, r *PrimerRun) error

func (*Store) InsertQuotaSamples added in v0.8.0

func (s *Store) InsertQuotaSamples(ctx context.Context, samples []QuotaSample) error

func (*Store) InsertUsage

func (s *Store) InsertUsage(ctx context.Context, events []UsageEvent) error

func (*Store) KeySecret

func (s *Store) KeySecret(ctx context.Context, id int64) ([]byte, error)

KeySecret returns the encrypted copy of a key, or nil if none is stored.

func (*Store) ListAccounts

func (s *Store) ListAccounts(ctx context.Context) ([]Account, error)

func (*Store) ListAllKeys

func (s *Store) ListAllKeys(ctx context.Context) ([]OwnedKey, error)

ListAllKeys returns every key with its owner's name, newest first.

func (*Store) ListAudit

func (s *Store) ListAudit(ctx context.Context, f AuditFilter, limit int) ([]AuditEntry, error)

func (*Store) ListKeys

func (s *Store) ListKeys(ctx context.Context, userID int64) ([]APIKey, error)

func (*Store) ListProfiles

func (s *Store) ListProfiles(ctx context.Context) ([]DisplayProfile, error)

func (*Store) ListUsers

func (s *Store) ListUsers(ctx context.Context) ([]User, error)

func (*Store) PrimerRuns

func (s *Store) PrimerRuns(ctx context.Context, accountID int64, since time.Time, limit int) ([]PrimerRun, error)

PrimerRuns lists runs newest first, since a time, optionally for one account (0 = all).

func (*Store) PruneAudit

func (s *Store) PruneAudit(ctx context.Context, before time.Time, maxEntries int, maxBytes int64) error

PruneAudit drops entries older than before (unless zero) and all but the newest maxEntries (unless 0), then those beyond maxBytes of payload (unless 0).

func (*Store) PrunePrimerRuns

func (s *Store) PrunePrimerRuns(ctx context.Context, before time.Time) error

func (*Store) PruneQuotaSamples added in v0.8.0

func (s *Store) PruneQuotaSamples(ctx context.Context, before time.Time) error

func (*Store) PruneUsage

func (s *Store) PruneUsage(ctx context.Context, before time.Time) error

func (*Store) PurgeExpiredSessions

func (s *Store) PurgeExpiredSessions(ctx context.Context) error

func (*Store) PutSetting

func (s *Store) PutSetting(ctx context.Context, key string, v any) error

func (*Store) QuotaSamples added in v0.8.0

func (s *Store) QuotaSamples(ctx context.Context, kind string, since, until time.Time) ([]QuotaSample, error)

QuotaSamples returns samples of one window kind in [since, until], oldest first, plus the last sample of each account's window before since so a series can start at since.

func (*Store) RecentUsage

func (s *Store) RecentUsage(ctx context.Context, f UsageFilter, limit int) ([]UsageEvent, error)

func (*Store) RotateKey

func (s *Store) RotateKey(ctx context.Context, id int64, prefix string, hash, enc []byte) (*APIKey, error)

RotateKey replaces a key's secret, keeping its settings. The old secret stops working.

func (*Store) SaveAccountCredentials

func (s *Store) SaveAccountCredentials(ctx context.Context, id int64, creds, plan string) error

func (*Store) SaveAccountQuota

func (s *Store) SaveAccountQuota(ctx context.Context, id int64, quota string, at time.Time) error

func (*Store) SaveAccountStatus

func (s *Store) SaveAccountStatus(ctx context.Context, id int64, status, message string, cooldownUntil *time.Time) error

func (*Store) SaveAccountSubscription

func (s *Store) SaveAccountSubscription(ctx context.Context, id int64, sub string) error

func (*Store) SetAccountWebSession

func (s *Store) SetAccountWebSession(ctx context.Context, id int64, session string) error

SetAccountWebSession stores (or with "" clears) an account's web session cookie.

func (*Store) TouchAccount

func (s *Store) TouchAccount(ctx context.Context, id int64, at time.Time) error

func (*Store) UpdateAccount

func (s *Store) UpdateAccount(ctx context.Context, id int64, p AccountPatch) (*Account, error)

func (*Store) UpdateKey

func (s *Store) UpdateKey(ctx context.Context, id int64, p KeyPatch) (*APIKey, error)

func (*Store) UpdateProfile

func (s *Store) UpdateProfile(ctx context.Context, id int64, name *string, config json.RawMessage) (*DisplayProfile, error)

func (*Store) UpdateUser

func (s *Store) UpdateUser(ctx context.Context, id int64, p UserPatch) (*User, error)

func (*Store) UpsertAccount

func (s *Store) UpsertAccount(ctx context.Context, a *Account) (*Account, error)

UpsertAccount inserts a new account, or refreshes the credentials of an existing one with the same provider and external ID (re-logging into the same subscription shouldn't duplicate it).

func (*Store) UsageBreakdown

func (s *Store) UsageBreakdown(ctx context.Context, f UsageFilter, by string, tzOffsetMinutes int) ([]UsageBucket, error)

UsageBreakdown groups usage by one dimension: "day", "hour", "model", "user", "key", "account" or "provider". For "user", requests made with an admin key are keyed "k<key id>".

func (*Store) UsageTotals

func (s *Store) UsageTotals(ctx context.Context, f UsageFilter) (UsageTotals, error)

type UsageBucket

type UsageBucket struct {
	Key string `json:"key"`
	UsageTotals
}

type UsageEvent

type UsageEvent struct {
	Time             time.Time `json:"time"`
	UserID           int64     `json:"userId"`
	KeyID            int64     `json:"keyId"`
	AccountID        int64     `json:"accountId"`
	Provider         string    `json:"provider"`
	Model            string    `json:"model"`
	RequestedModel   string    `json:"requestedModel"`
	Endpoint         string    `json:"endpoint"`
	Status           int       `json:"status"`
	Stream           bool      `json:"stream"`
	InputTokens      int64     `json:"inputTokens"`
	OutputTokens     int64     `json:"outputTokens"`
	CacheReadTokens  int64     `json:"cacheReadTokens"`
	CacheWriteTokens int64     `json:"cacheWriteTokens"`
	ReasoningTokens  int64     `json:"reasoningTokens"`
	DurationMS       int64     `json:"durationMs"`
	Error            string    `json:"error"`
	// ServiceTier is what the client asked for (e.g. "priority"); ServedTier what the provider reports.
	ServiceTier string `json:"serviceTier"`
	ServedTier  string `json:"servedTier"`
	// TTFTMS is the time until the first output arrived from upstream; 0 when there was none.
	TTFTMS int64 `json:"ttftMs"`
}

type UsageFilter

type UsageFilter struct {
	Since     time.Time
	Until     time.Time
	UserID    int64
	KeyID     int64
	AccountID int64
}

type UsageTotals

type UsageTotals struct {
	Requests         int64 `json:"requests"`
	Errors           int64 `json:"errors"`
	InputTokens      int64 `json:"inputTokens"`
	OutputTokens     int64 `json:"outputTokens"`
	CacheReadTokens  int64 `json:"cacheReadTokens"`
	CacheWriteTokens int64 `json:"cacheWriteTokens"`
	ReasoningTokens  int64 `json:"reasoningTokens"`
	// AvgTTFTMS averages time to first token over requests that produced output.
	AvgTTFTMS int64 `json:"avgTtftMs"`
}

type User

type User struct {
	ID        int64     `json:"id"`
	Name      string    `json:"name"`
	Note      string    `json:"note"`
	Disabled  bool      `json:"disabled"`
	CreatedAt time.Time `json:"createdAt"`
	KeyCount  int       `json:"keyCount"`
}

type UserPatch

type UserPatch struct {
	Name     *string `json:"name"`
	Note     *string `json:"note"`
	Disabled *bool   `json:"disabled"`
}

Jump to

Keyboard shortcuts

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