Documentation
¶
Overview ¶
Package token provides token lifecycle management with state machine and pool selection.
Package token provides token lifecycle management with state machine and pool selection.
Index ¶
- Constants
- Variables
- func AllPoolNames() []string
- func GetPoolForModel(model string, resolver ModelResolver) ([]string, bool)
- func GetQuota(t *store.Token, cat QuotaCategory) int
- func NormalizePoolName(pool string) (string, error)
- func PoolNameForLevel(level PoolLevel) string
- func SetQuota(t *store.Token, cat QuotaCategory, val int)
- func ValidAlgorithm(algo string) bool
- type CooldownTicker
- type ModelResolver
- type Persister
- type PoolLevel
- type PoolStats
- type QuotaCategory
- type RateLimitsRequest
- type RateLimitsResponse
- type Scheduler
- type Status
- type TokenManager
- func (m *TokenManager) AddToken(token *store.Token)
- func (m *TokenManager) ClearDirty(ids []uint)
- func (m *TokenManager) Consume(tokenID uint, cat QuotaCategory, cost int) (remaining int, err error)
- func (m *TokenManager) GetCoolingTokens() []TokenSnapshot
- func (m *TokenManager) GetDirtyTokens() []TokenSnapshot
- func (m *TokenManager) GetPool(name string) *TokenPool
- func (m *TokenManager) GetToken(id uint) *store.Token
- func (m *TokenManager) GetTokenPool(id uint) string
- func (m *TokenManager) MarkCooling(id uint, duration time.Duration, reason string)
- func (m *TokenManager) MarkDisabled(id uint, reason string)
- func (m *TokenManager) MarkExpired(id uint, reason string)
- func (m *TokenManager) MarkFailed(id uint, reason string)
- func (m *TokenManager) MarkSuccess(id uint)
- func (m *TokenManager) Pick(poolName string, cat QuotaCategory) (*store.Token, error)
- func (m *TokenManager) PickExcluding(poolName string, cat QuotaCategory, exclude map[uint]struct{}) (*store.Token, error)
- func (m *TokenManager) PickForModel(model string, resolver ModelResolver, cat QuotaCategory) (*store.Token, error)
- func (m *TokenManager) RemoveToken(id uint)
- func (m *TokenManager) RestoreToken(id uint, chatQuota, imageQuota, videoQuota int)
- func (m *TokenManager) SyncQuota(ctx context.Context, tokenID uint, authToken string, baseURL string) error
- type TokenPool
- func (p *TokenPool) Add(token *store.Token)
- func (p *TokenPool) All() []*store.Token
- func (p *TokenPool) Count() (active, cooling, disabled, expired int)
- func (p *TokenPool) Get(id uint) *store.Token
- func (p *TokenPool) Name() string
- func (p *TokenPool) Remove(id uint)
- func (p *TokenPool) Select(algorithm string, cat QuotaCategory) *store.Token
- func (p *TokenPool) SelectExcluding(algorithm string, cat QuotaCategory, exclude map[uint]struct{}) *store.Token
- type TokenService
- func (s *TokenService) AddToPool(token *store.Token) error
- func (s *TokenService) Consume(tokenID uint, cat QuotaCategory, cost int) (int, error)
- func (s *TokenService) FlushDirty(ctx context.Context) error
- func (s *TokenService) LoadTokens(ctx context.Context) error
- func (s *TokenService) Manager() *TokenManager
- func (s *TokenService) MarkDisabled(id uint, reason string)
- func (s *TokenService) MarkExpired(id uint, reason string)
- func (s *TokenService) Pick(pool string, cat QuotaCategory) (*store.Token, error)
- func (s *TokenService) PickExcluding(pool string, cat QuotaCategory, exclude map[uint]struct{}) (*store.Token, error)
- func (s *TokenService) RefreshToken(ctx context.Context, id uint) (*store.Token, error)
- func (s *TokenService) RemoveFromPool(id uint)
- func (s *TokenService) ReportError(id uint, reason string)
- func (s *TokenService) ReportRateLimit(id uint, reason string)
- func (s *TokenService) ReportSuccess(id uint)
- func (s *TokenService) StartTicker(ctx context.Context)
- func (s *TokenService) Stats() map[string]PoolStats
- func (s *TokenService) SyncToken(ctx context.Context, id uint) error
- type TokenSnapshot
- type TokenStore
Constants ¶
const ( AlgoHighQuotaFirst = "high_quota_first" AlgoRandom = "random" AlgoRoundRobin = "round_robin" )
Algorithm constants for token selection.
const ( RecoveryModeAuto = "auto" RecoveryModeUpstream = "upstream" )
RecoveryModeAuto restores configured default quotas when cooldown expires.
const ( PoolBasic = "ssoBasic" PoolSuper = "ssoSuper" PoolHeavy = "ssoHeavy" )
Pool tier constants.
const ( DefaultCoolDuration = 5 * time.Minute DefaultCoolCycleLimit = 3 )
Default cooling configuration.
Variables ¶
var ( // ErrNoQuota is returned when token has no remaining quota. ErrNoQuota = errors.New("no quota remaining") // ErrTokenNotFound is returned when token ID does not exist. ErrTokenNotFound = errors.New("token not found") )
var ErrInvalidPool = errors.New("invalid token pool")
var ErrModelNotFound = errors.New("model not found")
ErrModelNotFound is returned when the model is not in any configured group.
var ( // ErrNoTokenAvailable is returned when no token is available in the pool. ErrNoTokenAvailable = errors.New("no available token") )
Functions ¶
func AllPoolNames ¶
func AllPoolNames() []string
AllPoolNames returns all pool names in ascending level order.
func GetPoolForModel ¶
func GetPoolForModel(model string, resolver ModelResolver) ([]string, bool)
GetPoolForModel returns the eligible pool names for a given model based on its pool_floor. Pools are returned in ascending level order (basic → super → heavy). Uses >= matching: a model with pool_floor=basic can use basic, super, and heavy pools. Returns (nil, false) if the model is not found or the model name is empty.
func GetQuota ¶
func GetQuota(t *store.Token, cat QuotaCategory) int
GetQuota returns the quota value for the given category.
func NormalizePoolName ¶
NormalizePoolName converts accepted pool aliases to canonical pool names.
func PoolNameForLevel ¶
PoolNameForLevel returns the pool name for a given level. Returns empty string for unknown levels.
func SetQuota ¶
func SetQuota(t *store.Token, cat QuotaCategory, val int)
SetQuota sets the quota value for the given category.
func ValidAlgorithm ¶
ValidAlgorithm checks if the given string is a valid selection algorithm.
Types ¶
type CooldownTicker ¶
type CooldownTicker struct {
// contains filtered or unexported fields
}
CooldownTicker periodically checks and restores expired cooling tokens.
func NewCooldownTicker ¶
func NewCooldownTicker(mgr *TokenManager, interval time.Duration) *CooldownTicker
NewCooldownTicker creates a new cooldown ticker.
func (*CooldownTicker) CheckNow ¶
func (t *CooldownTicker) CheckNow() int
CheckNow immediately checks all cooling tokens and restores expired ones. Returns the number of tokens restored.
func (*CooldownTicker) Start ¶
func (t *CooldownTicker) Start(ctx context.Context)
Start begins the ticker loop. Blocks until context is cancelled.
type ModelResolver ¶
ModelResolver resolves a model request name to pool floor info.
type Persister ¶
type Persister struct {
// contains filtered or unexported fields
}
Persister handles batch persistence of dirty tokens.
func NewPersister ¶
func NewPersister(manager *TokenManager, db *gorm.DB) *Persister
NewPersister creates a new token persister.
func (*Persister) FlushDirty ¶
FlushDirty persists all dirty tokens to the database. Returns the number of tokens flushed.
type PoolLevel ¶
type PoolLevel int
PoolLevel represents the numeric tier of a pool for comparison. Higher level pools can serve models with lower pool_floor requirements.
func PoolLevelFor ¶
PoolLevelFor converts a pool name or floor name to its numeric level. Accepts full pool names ("ssoBasic") and short floor names ("basic"). Returns 0 for unknown inputs.
type QuotaCategory ¶
type QuotaCategory string
QuotaCategory represents a quota consumption category.
const ( CategoryChat QuotaCategory = "chat" CategoryImage QuotaCategory = "image" CategoryVideo QuotaCategory = "video" )
type RateLimitsRequest ¶
type RateLimitsRequest struct {
ModelName string `json:"modelName"`
}
RateLimitsRequest is the request body for rate-limits API.
type RateLimitsResponse ¶
type RateLimitsResponse struct {
RemainingQueries int `json:"remainingQueries"`
WindowSizeSeconds int `json:"windowSizeSeconds"`
}
RateLimitsResponse is the response from rate-limits API.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler periodically scans cooling tokens and restores quotas when the cooldown window has expired.
func NewScheduler ¶
func NewScheduler(manager *TokenManager, cfg *config.TokenConfig, baseURL string) *Scheduler
NewScheduler creates a new quota recovery scheduler.
func (*Scheduler) SetConfigProvider ¶
func (s *Scheduler) SetConfigProvider(fn func() *config.TokenConfig)
SetConfigProvider sets a dynamic token config provider.
type Status ¶
type Status string
Status represents the state of a token in the pool.
const ( // StatusActive indicates the token is available for use. StatusActive Status = "active" // StatusCooling indicates the token is temporarily unavailable (rate limited). StatusCooling Status = "cooling" // StatusDisabled indicates the token is manually disabled by the user. StatusDisabled Status = "disabled" // StatusExpired indicates the token was auto-detected as invalid (e.g. 401). StatusExpired Status = "expired" )
type TokenManager ¶
type TokenManager struct {
// contains filtered or unexported fields
}
TokenManager manages token pools and state transitions.
func NewTokenManager ¶
func NewTokenManager(cfg *config.TokenConfig) *TokenManager
NewTokenManager creates a new token manager.
func (*TokenManager) AddToken ¶
func (m *TokenManager) AddToken(token *store.Token)
AddToken adds a token to the appropriate pool.
func (*TokenManager) ClearDirty ¶
func (m *TokenManager) ClearDirty(ids []uint)
ClearDirty removes the given token IDs from the dirty set. Call this only after successful persistence.
func (*TokenManager) Consume ¶
func (m *TokenManager) Consume(tokenID uint, cat QuotaCategory, cost int) (remaining int, err error)
Consume deducts quota from the token for the given category. cost allows variable deduction for different model types. Returns remaining quota after deduction.
func (*TokenManager) GetCoolingTokens ¶
func (m *TokenManager) GetCoolingTokens() []TokenSnapshot
GetCoolingTokens returns all tokens in cooling state.
func (*TokenManager) GetDirtyTokens ¶
func (m *TokenManager) GetDirtyTokens() []TokenSnapshot
GetDirtyTokens returns snapshots of tokens that have been modified. Returns copies to avoid race conditions with concurrent modifications. Call ClearDirty after successful persistence to avoid data loss on DB failure.
func (*TokenManager) GetPool ¶
func (m *TokenManager) GetPool(name string) *TokenPool
GetPool returns a pool by name.
func (*TokenManager) GetToken ¶
func (m *TokenManager) GetToken(id uint) *store.Token
GetToken returns a token by ID.
func (*TokenManager) GetTokenPool ¶
func (m *TokenManager) GetTokenPool(id uint) string
GetTokenPool returns the pool name for a token by ID.
func (*TokenManager) MarkCooling ¶
func (m *TokenManager) MarkCooling(id uint, duration time.Duration, reason string)
MarkCooling transitions a token to cooling state.
func (*TokenManager) MarkDisabled ¶
func (m *TokenManager) MarkDisabled(id uint, reason string)
MarkDisabled transitions a token to disabled state (manual user action).
func (*TokenManager) MarkExpired ¶
func (m *TokenManager) MarkExpired(id uint, reason string)
MarkExpired transitions a token to expired state (auto-detected invalid, e.g. 401).
func (*TokenManager) MarkFailed ¶
func (m *TokenManager) MarkFailed(id uint, reason string)
MarkFailed increments fail count and disables if threshold reached. When FailThreshold <= 0, the token is never auto-disabled (unlimited).
func (*TokenManager) MarkSuccess ¶
func (m *TokenManager) MarkSuccess(id uint)
MarkSuccess transitions a token back to active state.
func (*TokenManager) Pick ¶
func (m *TokenManager) Pick(poolName string, cat QuotaCategory) (*store.Token, error)
Pick selects a token from the specified pool using the configured selection algorithm. Returns ErrNoTokenAvailable when no active tokens are available (no cooling fallback).
func (*TokenManager) PickExcluding ¶
func (m *TokenManager) PickExcluding(poolName string, cat QuotaCategory, exclude map[uint]struct{}) (*store.Token, error)
PickExcluding selects a token while skipping excluded token IDs.
func (*TokenManager) PickForModel ¶
func (m *TokenManager) PickForModel(model string, resolver ModelResolver, cat QuotaCategory) (*store.Token, error)
PickForModel selects a token by trying each eligible pool in order. Returns the first available token, or ErrNoTokenAvailable if all pools are exhausted. Returns ErrModelNotFound if the model is not found in the resolver.
func (*TokenManager) RemoveToken ¶
func (m *TokenManager) RemoveToken(id uint)
RemoveToken removes a token from its pool.
func (*TokenManager) RestoreToken ¶
func (m *TokenManager) RestoreToken(id uint, chatQuota, imageQuota, videoQuota int)
RestoreToken restores a single token to the given quotas and marks it active. Used by the auto-mode recovery scheduler when a token's cooling period expires.
func (*TokenManager) SyncQuota ¶
func (m *TokenManager) SyncQuota(ctx context.Context, tokenID uint, authToken string, baseURL string) error
SyncQuota fetches quota from upstream API and updates token state. Accepts token ID and auth token string to avoid holding a pointer across the network call (which would race with other goroutines).
type TokenPool ¶
type TokenPool struct {
// contains filtered or unexported fields
}
TokenPool manages a collection of tokens with thread-safe access.
func NewTokenPool ¶
NewTokenPool creates a new token pool with the given name.
func (*TokenPool) Select ¶
func (p *TokenPool) Select(algorithm string, cat QuotaCategory) *store.Token
Select returns an active token using the specified algorithm with priority-tier grouping. Tokens are grouped by priority (descending), and the algorithm is applied within each tier. Falls through to lower priority tiers when higher tiers have no active tokens. Returns nil if no active tokens are available.
func (*TokenPool) SelectExcluding ¶
func (p *TokenPool) SelectExcluding(algorithm string, cat QuotaCategory, exclude map[uint]struct{}) *store.Token
SelectExcluding returns an active token while skipping excluded token IDs.
type TokenService ¶
type TokenService struct {
// contains filtered or unexported fields
}
TokenService provides the high-level API for token management.
func NewTokenService ¶
func NewTokenService(cfg *config.TokenConfig, store TokenStore, baseURL string) *TokenService
NewTokenService creates a new token service.
func (*TokenService) AddToPool ¶
func (s *TokenService) AddToPool(token *store.Token) error
AddToPool adds a token to the in-memory pool (called after admin import).
func (*TokenService) Consume ¶
func (s *TokenService) Consume(tokenID uint, cat QuotaCategory, cost int) (int, error)
Consume deducts quota from the token for the given category.
func (*TokenService) FlushDirty ¶
func (s *TokenService) FlushDirty(ctx context.Context) error
FlushDirty persists all dirty tokens to the store.
func (*TokenService) LoadTokens ¶
func (s *TokenService) LoadTokens(ctx context.Context) error
LoadTokens loads all tokens from the store into the manager.
func (*TokenService) Manager ¶
func (s *TokenService) Manager() *TokenManager
Manager returns the underlying token manager.
func (*TokenService) MarkDisabled ¶
func (s *TokenService) MarkDisabled(id uint, reason string)
MarkDisabled immediately disables a token (manual user action).
func (*TokenService) MarkExpired ¶
func (s *TokenService) MarkExpired(id uint, reason string)
MarkExpired marks a token as expired (auto-detected invalid, e.g. 401).
func (*TokenService) Pick ¶
func (s *TokenService) Pick(pool string, cat QuotaCategory) (*store.Token, error)
Pick selects a token from the specified pool.
func (*TokenService) PickExcluding ¶
func (s *TokenService) PickExcluding(pool string, cat QuotaCategory, exclude map[uint]struct{}) (*store.Token, error)
PickExcluding selects a token from the specified pool while skipping excluded IDs.
func (*TokenService) RefreshToken ¶
RefreshToken refreshes a token's quota by syncing with upstream API.
func (*TokenService) RemoveFromPool ¶
func (s *TokenService) RemoveFromPool(id uint)
RemoveFromPool removes a token from the in-memory pool (called after admin delete).
func (*TokenService) ReportError ¶
func (s *TokenService) ReportError(id uint, reason string)
ReportError marks a token as having an error.
func (*TokenService) ReportRateLimit ¶
func (s *TokenService) ReportRateLimit(id uint, reason string)
ReportRateLimit marks a token as rate limited (cooling). Uses per-group cooldown duration based on the token's pool.
func (*TokenService) ReportSuccess ¶
func (s *TokenService) ReportSuccess(id uint)
ReportSuccess marks a token as successfully used.
func (*TokenService) StartTicker ¶
func (s *TokenService) StartTicker(ctx context.Context)
StartTicker starts the cooldown ticker in a goroutine.
func (*TokenService) Stats ¶
func (s *TokenService) Stats() map[string]PoolStats
Stats returns statistics for all pools.
type TokenSnapshot ¶
type TokenSnapshot 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
}
TokenSnapshot holds a copy of token data for safe persistence.
type TokenStore ¶
type TokenStore interface {
ListTokens(ctx context.Context) ([]*store.Token, error)
GetToken(ctx context.Context, id uint) (*store.Token, error)
UpdateTokenSnapshots(ctx context.Context, snapshots []store.TokenSnapshotData) error
}
TokenStore defines the interface for token persistence.