Documentation
¶
Overview ¶
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 NormalizePoolName(pool string) (string, error)
- func PoolNameForLevel(level PoolLevel) string
- func PoolToShort(pool string) string
- func ValidAlgorithm(algo string) bool
- type ExhaustedModeTarget
- type ModelResolver
- type Persister
- type PoolLevel
- type PoolStats
- type RateLimitsRequest
- type RateLimitsResponse
- type RefreshRequester
- type Scheduler
- type Status
- type TokenManager
- func (m *TokenManager) AddToken(token *store.Token)
- func (m *TokenManager) ClearDirty(ids []uint)
- func (m *TokenManager) ClearModeQuota(id uint, mode string)
- func (m *TokenManager) ClearResumeAt(id uint, mode string)
- func (m *TokenManager) GetActiveTokenInfo(id uint) (authToken string, pool string, ok bool)
- func (m *TokenManager) GetDirtyTokens() []TokenSnapshot
- func (m *TokenManager) GetInflight(id uint) int
- func (m *TokenManager) GetModeQuota(tokenID uint, mode string) int
- func (m *TokenManager) GetPool(name string) *TokenPool
- func (m *TokenManager) GetResumeAt(tokenID uint, mode string) int
- func (m *TokenManager) GetToken(id uint) *store.Token
- func (m *TokenManager) GetTokenPool(id uint) string
- func (m *TokenManager) MarkDirty(id uint)
- 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) MarkFailedKeepInflight(id uint, reason string)
- func (m *TokenManager) MarkSuccess(id uint)
- func (m *TokenManager) Pick(poolName string, mode string) (*store.Token, error)
- func (m *TokenManager) PickAnyExcluding(poolName string, exclude map[uint]struct{}) (*store.Token, error)
- func (m *TokenManager) PickExcluding(poolName string, mode string, exclude map[uint]struct{}) (*store.Token, error)
- func (m *TokenManager) PickForModel(model string, resolver ModelResolver, mode string) (*store.Token, error)
- func (m *TokenManager) RefundQuota(id uint, mode string)
- func (m *TokenManager) ReleaseInflightOnly(id uint)
- func (m *TokenManager) RemoveToken(id uint)
- func (m *TokenManager) ScanExhaustedModes(modes []modelconfig.ModeSpec, now time.Time) []ExhaustedModeTarget
- func (m *TokenManager) SetResumeAt(id uint, mode string, resumeUnix int)
- func (m *TokenManager) SetResumeAtIfDue(id uint, mode string, resumeUnix int, nowUnix int) bool
- func (m *TokenManager) SyncModeQuota(ctx context.Context, tokenID uint, authToken string, baseURL string, ...) (*RateLimitsResponse, error)
- func (m *TokenManager) UpdateConfig(tc *config.TokenConfig)
- func (m *TokenManager) UpdateModeQuota(id uint, mode string, remaining int, limit int)
- type TokenPool
- func (p *TokenPool) Add(token *store.Token)
- func (p *TokenPool) All() []*store.Token
- func (p *TokenPool) Count() (active, 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, mode string) *store.Token
- func (p *TokenPool) SelectAnyExcluding(algorithm string, exclude map[uint]struct{}) *store.Token
- func (p *TokenPool) SelectExcluding(algorithm string, mode string, exclude map[uint]struct{}) *store.Token
- type TokenService
- func (s *TokenService) AddToPool(token *store.Token) error
- func (s *TokenService) BaseURL() string
- 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, mode string) (*store.Token, error)
- func (s *TokenService) PickAnyExcluding(pool string, exclude map[uint]struct{}) (*store.Token, error)
- func (s *TokenService) PickExcluding(pool string, mode string, exclude map[uint]struct{}) (*store.Token, error)
- func (s *TokenService) RefreshToken(ctx context.Context, id uint) (*store.Token, error)
- func (s *TokenService) RefundQuota(id uint, mode string)
- func (s *TokenService) ReleaseToken(id uint)
- func (s *TokenService) RemoveFromPool(id uint)
- func (s *TokenService) ReportError(id uint, mode string, recoverable bool, reason string)
- func (s *TokenService) ReportErrorKeepInflight(id uint, mode string, recoverable bool, reason string)
- func (s *TokenService) ReportRateLimit(id uint, mode string, reason string)
- func (s *TokenService) ReportSuccess(id uint)
- func (s *TokenService) SetRefreshRequester(requester RefreshRequester)
- 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 ( PoolBasic = "ssoBasic" PoolSuper = "ssoSuper" PoolHeavy = "ssoHeavy" )
Pool tier constants.
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 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 PoolToShort ¶
PoolToShort converts canonical pool name to short form for catalog lookup.
func ValidAlgorithm ¶
ValidAlgorithm checks if the given string is a valid selection algorithm.
Types ¶
type ExhaustedModeTarget ¶
type ExhaustedModeTarget struct {
TokenID uint
AuthToken string
Pool string
Mode string
Force bool // true for admin manual refresh: force reset local_quota
}
ExhaustedModeTarget identifies a token+mode that needs upstream refresh.
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 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"`
TotalQueries int `json:"totalQueries"`
WindowSizeSeconds int `json:"windowSizeSeconds"`
WaitTimeSeconds int `json:"waitTimeSeconds,omitempty"`
}
RateLimitsResponse is the response from rate-limits API.
type RefreshRequester ¶
type RefreshRequester interface {
RequestRefresh(tokenID uint, mode string)
RefreshToken(ctx context.Context, id uint) error
ForgetToken(tokenID uint)
}
RefreshRequester refreshes exhausted token mode quotas from upstream.
type Scheduler ¶
type Scheduler struct {
// contains filtered or unexported fields
}
Scheduler periodically refreshes exhausted token mode quotas from upstream.
func NewScheduler ¶
func NewScheduler(manager *TokenManager, modes []modelconfig.ModeSpec, baseURL string) *Scheduler
NewScheduler creates a new mode-based quota refresh scheduler.
func (*Scheduler) ForgetToken ¶
ForgetToken removes scheduler-internal debounce state for a removed token.
func (*Scheduler) RefreshToken ¶
RefreshToken forces an immediate refresh for all supported modes of a token.
func (*Scheduler) RequestRefresh ¶
RequestRefresh schedules an authoritative refresh after a mode-level 429.
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" // 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.
func (*TokenManager) ClearModeQuota ¶
func (m *TokenManager) ClearModeQuota(id uint, mode string)
ClearModeQuota sets the quota for a specific mode to zero and releases inflight.
func (*TokenManager) ClearResumeAt ¶
func (m *TokenManager) ClearResumeAt(id uint, mode string)
ClearResumeAt removes the recovery timestamp for a token mode.
func (*TokenManager) GetActiveTokenInfo ¶
func (m *TokenManager) GetActiveTokenInfo(id uint) (authToken string, pool string, ok bool)
GetActiveTokenInfo returns token credentials for an active token.
func (*TokenManager) GetDirtyTokens ¶
func (m *TokenManager) GetDirtyTokens() []TokenSnapshot
GetDirtyTokens returns snapshots of tokens that have been modified.
func (*TokenManager) GetInflight ¶
func (m *TokenManager) GetInflight(id uint) int
GetInflight returns the current inflight count for a token.
func (*TokenManager) GetModeQuota ¶
func (m *TokenManager) GetModeQuota(tokenID uint, mode string) int
GetModeQuota returns current remaining quota for (tokenID, mode).
func (*TokenManager) GetPool ¶
func (m *TokenManager) GetPool(name string) *TokenPool
GetPool returns a pool by name.
func (*TokenManager) GetResumeAt ¶
func (m *TokenManager) GetResumeAt(tokenID uint, mode string) int
GetResumeAt returns the resume timestamp for a token mode.
func (*TokenManager) GetToken ¶
func (m *TokenManager) GetToken(id uint) *store.Token
GetToken returns a token snapshot by ID.
func (*TokenManager) GetTokenPool ¶
func (m *TokenManager) GetTokenPool(id uint) string
GetTokenPool returns the pool name for a token by ID.
func (*TokenManager) MarkDirty ¶
func (m *TokenManager) MarkDirty(id uint)
MarkDirty marks a token snapshot for persistence.
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) MarkFailedKeepInflight ¶
func (m *TokenManager) MarkFailedKeepInflight(id uint, reason string)
MarkFailedKeepInflight increments fail count without releasing inflight. Used when the same request will retry with the same selected token.
func (*TokenManager) MarkSuccess ¶
func (m *TokenManager) MarkSuccess(id uint)
MarkSuccess transitions a token back to active state.
func (*TokenManager) Pick ¶
Pick selects a token from the specified pool using the configured selection algorithm. Performs optimistic quota deduction on selection.
func (*TokenManager) PickAnyExcluding ¶
func (m *TokenManager) PickAnyExcluding(poolName string, exclude map[uint]struct{}) (*store.Token, error)
PickAnyExcluding selects an active token while ignoring mode quota.
func (*TokenManager) PickExcluding ¶
func (m *TokenManager) PickExcluding(poolName string, mode string, 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, mode string) (*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) RefundQuota ¶
func (m *TokenManager) RefundQuota(id uint, mode string)
RefundQuota restores one unit of quota for the given mode.
func (*TokenManager) ReleaseInflightOnly ¶
func (m *TokenManager) ReleaseInflightOnly(id uint)
ReleaseInflightOnly decrements the inflight counter without any state change.
func (*TokenManager) RemoveToken ¶
func (m *TokenManager) RemoveToken(id uint)
RemoveToken removes a token from its pool.
func (*TokenManager) ScanExhaustedModes ¶
func (m *TokenManager) ScanExhaustedModes( modes []modelconfig.ModeSpec, now time.Time, ) []ExhaustedModeTarget
ScanExhaustedModes returns active token modes whose quota is due for refresh.
func (*TokenManager) SetResumeAt ¶
func (m *TokenManager) SetResumeAt(id uint, mode string, resumeUnix int)
SetResumeAt records when an exhausted mode should be checked again.
func (*TokenManager) SetResumeAtIfDue ¶
SetResumeAtIfDue records a recovery timestamp only while the mode is still exhausted and due.
func (*TokenManager) SyncModeQuota ¶
func (m *TokenManager) SyncModeQuota(ctx context.Context, tokenID uint, authToken string, baseURL string, upstreamName string) (*RateLimitsResponse, error)
SyncModeQuota fetches quota for a specific mode from upstream and updates token state. upstreamName is the mode's upstream_name (e.g., "auto", "fast", "expert").
func (*TokenManager) UpdateConfig ¶
func (m *TokenManager) UpdateConfig(tc *config.TokenConfig)
UpdateConfig replaces the token config with a copy of the provided config.
func (*TokenManager) UpdateModeQuota ¶
func (m *TokenManager) UpdateModeQuota(id uint, mode string, remaining int, limit int)
UpdateModeQuota sets both quota and limit for a specific mode.
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 ¶
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) SelectAnyExcluding ¶
SelectAnyExcluding returns an active token while ignoring mode quota.
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, modes []modelconfig.ModeSpec, 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) BaseURL ¶
func (s *TokenService) BaseURL() string
BaseURL returns the configured upstream base URL.
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) PickAnyExcluding ¶
func (s *TokenService) PickAnyExcluding(pool string, exclude map[uint]struct{}) (*store.Token, error)
PickAnyExcluding selects an active token without checking mode quota.
func (*TokenService) PickExcluding ¶
func (s *TokenService) PickExcluding(pool string, mode string, exclude map[uint]struct{}) (*store.Token, error)
PickExcluding selects a token from the specified pool while skipping excluded IDs.
func (*TokenService) RefreshToken ¶
RefreshToken forces an immediate upstream quota refresh and persists the result.
func (*TokenService) RefundQuota ¶
func (s *TokenService) RefundQuota(id uint, mode string)
RefundQuota restores one unit of quota for the given mode.
func (*TokenService) ReleaseToken ¶
func (s *TokenService) ReleaseToken(id uint)
ReleaseToken decrements the inflight counter without any state change. Used for error paths that don't call a Report/Mark method (e.g. 403, CF challenge).
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, mode string, recoverable bool, reason string)
ReportError handles an error for a token. If recoverable is true, refunds the pre-deducted quota for the mode.
func (*TokenService) ReportErrorKeepInflight ¶
func (s *TokenService) ReportErrorKeepInflight(id uint, mode string, recoverable bool, reason string)
ReportErrorKeepInflight records an intermediate retry error without releasing inflight or refunding quota. The final token exit path decides whether the pre-deducted quota should be refunded.
func (*TokenService) ReportRateLimit ¶
func (s *TokenService) ReportRateLimit(id uint, mode string, reason string)
ReportRateLimit clears local quota and asks the scheduler for authoritative state.
func (*TokenService) ReportSuccess ¶
func (s *TokenService) ReportSuccess(id uint)
ReportSuccess marks a token as successfully used.
func (*TokenService) SetRefreshRequester ¶
func (s *TokenService) SetRefreshRequester(requester RefreshRequester)
SetRefreshRequester wires upstream quota refresh requests into the service.
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
Quotas store.IntMap
LimitQuotas store.IntMap
FailCount int
LastUsed *time.Time
ResumeAts store.IntMap
}
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.