httpapi

package
v0.2.0-beta Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: MIT Imports: 32 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 httpapi provides HTTP routing and handlers.

Package httpapi provides HTTP routing and handlers.

Index

Constants

This section is empty.

Variables

View Source
var ErrPoolExhausted = errors.New("httpapi: token pool exhausted")

ErrPoolExhausted indicates all tokens in the pool are exhausted or cooling down.

Functions

func APIKeyAuth

func APIKeyAuth(akStore APIKeyStoreInterface) func(http.Handler) http.Handler

APIKeyAuth returns a middleware that authenticates requests via API key DB lookup. Enforces daily_limit and rate_limit, returning 429 when exceeded.

func APIKeyIDFromContext

func APIKeyIDFromContext(ctx context.Context) (uint, bool)

APIKeyIDFromContext extracts the API key ID from the request context.

func AdminRateLimit

func AdminRateLimit(cfg *config.Config) func(http.Handler) http.Handler

AdminRateLimit returns a middleware that rate-limits admin endpoints by client IP. Only 401 responses count toward the failure limit. When the limit is exceeded, subsequent requests from that IP get 429 until the time window expires. Config values are read per-request for hot-reload support.

func AdminRateLimitRuntime

func AdminRateLimitRuntime(runtime *config.Runtime) func(http.Handler) http.Handler

func AppKeyAuth

func AppKeyAuth(appKey string) func(http.Handler) http.Handler

AppKeyAuth returns a middleware that validates App Key authentication for admin endpoints. AppKeyAuth rejects all requests when appKey is empty (secure by default). Authentication priority: cookie "gf_session" first, then Bearer header (API/script compat). Uses constant-time comparison to prevent timing attacks.

func AppKeyAuthRuntime

func AppKeyAuthRuntime(runtime *config.Runtime) func(http.Handler) http.Handler

func BridgeFlowContext

func BridgeFlowContext(ctx context.Context) context.Context

BridgeFlowContext carries httpapi API key context to the flow layer.

func CheckModelWhitelist

func CheckModelWhitelist(ctx context.Context, model string) bool

CheckModelWhitelist validates the requested model against the API key's whitelist. Returns true if the model is allowed. An empty/nil whitelist allows all models.

func ModelWhitelistFromContext

func ModelWhitelistFromContext(ctx context.Context) []string

ModelWhitelistFromContext extracts the model whitelist from the request context. Returns nil if no whitelist is set (meaning all models are allowed).

func NewSPAHandler

func NewSPAHandler(sub fs.FS) http.Handler

NewSPAHandler serves static files from the given filesystem with SPA fallback for client-side routing.

func SPAHandler

func SPAHandler() http.Handler

SPAHandler serves the embedded frontend with SPA fallback.

func WriteError

func WriteError(w http.ResponseWriter, status int, errType, code, message string)

WriteError writes a JSON error response with the given status code.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON writes a JSON response.

Types

type APIError

type APIError struct {
	Status int         `json:"-"`
	Error  ErrorDetail `json:"error"`
}

APIError represents an OpenAI-compatible error response.

func MapXAIError

func MapXAIError(err error) (int, *APIError)

MapXAIError maps xai package errors to HTTP status and APIError. Error mapping:

  • ErrForbidden, ErrInvalidToken -> 401 authentication_error
  • ErrCFChallenge -> 502 server_error (CF blocking, not auth issue)
  • ErrRateLimited -> 429 rate_limit_error
  • ErrNetwork, ErrStreamClosed, other -> 502 server_error
  • ErrPoolExhausted -> 503 service_unavailable

func NewAPIError

func NewAPIError(status int, errType, code, message string) *APIError

NewAPIError creates a new API error with the given parameters.

type APIKeyCreateRequest

type APIKeyCreateRequest struct {
	Name           string            `json:"name"`
	ModelWhitelist store.StringSlice `json:"model_whitelist,omitempty"`
	RateLimit      *int              `json:"rate_limit,omitempty"`
	DailyLimit     *int              `json:"daily_limit,omitempty"`
	ExpiresAt      *string           `json:"expires_at,omitempty"`
}

APIKeyCreateRequest is the request body for creating an API key.

type APIKeyCreateResponse

type APIKeyCreateResponse struct {
	ID   uint   `json:"id"`
	Key  string `json:"key"`
	Name string `json:"name"`
}

APIKeyCreateResponse is the response when creating or regenerating an API key.

type APIKeyResponse

type APIKeyResponse struct {
	ID             uint              `json:"id"`
	Key            string            `json:"key"`
	Name           string            `json:"name"`
	Status         string            `json:"status"`
	ModelWhitelist store.StringSlice `json:"model_whitelist"`
	RateLimit      int               `json:"rate_limit"`
	DailyLimit     int               `json:"daily_limit"`
	DailyUsed      int               `json:"daily_used"`
	TotalUsed      int               `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"`
}

APIKeyResponse is the masked API key view returned by read endpoints.

type APIKeyStatsResponse

type APIKeyStatsResponse struct {
	Total       int `json:"total"`
	Active      int `json:"active"`
	Inactive    int `json:"inactive"`
	Expired     int `json:"expired"`
	RateLimited int `json:"rate_limited"`
}

APIKeyStatsResponse is the response for API key stats endpoint.

type APIKeyStoreInterface

type APIKeyStoreInterface interface {
	List(ctx context.Context, page, pageSize int, status string) ([]*store.APIKey, int64, error)
	GetByID(ctx context.Context, id uint) (*store.APIKey, error)
	GetByKey(ctx context.Context, key string) (*store.APIKey, error)
	Create(ctx context.Context, ak *store.APIKey) error
	Update(ctx context.Context, ak *store.APIKey) error
	Delete(ctx context.Context, id uint) error
	Regenerate(ctx context.Context, id uint) (string, error)
	CountByStatus(ctx context.Context) (total, active, inactive, expired, rateLimited int, err error)
	IncrementUsage(ctx context.Context, id uint) error
	ResetDailyUsage(ctx context.Context) error
}

APIKeyStoreInterface defines methods for API key operations.

type APIKeyUpdateRequest

type APIKeyUpdateRequest struct {
	Name           *string            `json:"name,omitempty"`
	Status         *string            `json:"status,omitempty"`
	ModelWhitelist *store.StringSlice `json:"model_whitelist,omitempty"`
	RateLimit      *int               `json:"rate_limit,omitempty"`
	DailyLimit     *int               `json:"daily_limit,omitempty"`
	ExpiresAt      *string            `json:"expires_at,omitempty"`
}

APIKeyUpdateRequest is the request body for updating an API key.

type AppConfigResponse

type AppConfigResponse struct {
	AppKey                 string   `json:"app_key"`
	MediaGenerationEnabled bool     `json:"media_generation_enabled"`
	Temporary              bool     `json:"temporary"`
	DisableMemory          bool     `json:"disable_memory"`
	Stream                 bool     `json:"stream"`
	Thinking               bool     `json:"thinking"`
	DynamicStatsig         bool     `json:"dynamic_statsig"`
	CustomInstruction      string   `json:"custom_instruction"`
	FilterTags             []string `json:"filter_tags"`
	Host                   string   `json:"host"`
	Port                   int      `json:"port"`
	LogJSON                bool     `json:"log_json"`
	LogLevel               string   `json:"log_level"`
	DBDriver               string   `json:"db_driver"`
	DBPath                 string   `json:"db_path"`
	DBDSN                  string   `json:"db_dsn"`
	RequestTimeout         int      `json:"request_timeout"`
	ReadHeaderTimeout      int      `json:"read_header_timeout"`
	MaxHeaderBytes         int      `json:"max_header_bytes"`
	BodyLimit              int64    `json:"body_limit"`
	ChatBodyLimit          int64    `json:"chat_body_limit"`
	AdminMaxFails          int      `json:"admin_max_fails"`
	AdminWindowSec         int      `json:"admin_window_sec"`
}

AppConfigResponse is the API response for app config (secrets masked).

type AppConfigUpdate

type AppConfigUpdate struct {
	AppKey                 *string   `json:"app_key,omitempty"`
	MediaGenerationEnabled *bool     `json:"media_generation_enabled,omitempty"`
	RequestTimeout         *int      `json:"request_timeout,omitempty"`
	Temporary              *bool     `json:"temporary,omitempty"`
	Stream                 *bool     `json:"stream,omitempty"`
	Thinking               *bool     `json:"thinking,omitempty"`
	DynamicStatsig         *bool     `json:"dynamic_statsig,omitempty"`
	CustomInstruction      *string   `json:"custom_instruction,omitempty"`
	FilterTags             *[]string `json:"filter_tags,omitempty"`
	DisableMemory          *bool     `json:"disable_memory,omitempty"`
	ReadHeaderTimeout      *int      `json:"read_header_timeout,omitempty"`
	MaxHeaderBytes         *int      `json:"max_header_bytes,omitempty"`
	BodyLimit              *int64    `json:"body_limit,omitempty"`
	ChatBodyLimit          *int64    `json:"chat_body_limit,omitempty"`
	AdminMaxFails          *int      `json:"admin_max_fails,omitempty"`
	AdminWindowSec         *int      `json:"admin_window_sec,omitempty"`
}

AppConfigUpdate contains hot-reloadable app config fields.

type BatchError

type BatchError struct {
	Index   int    `json:"index,omitempty"`
	ID      uint   `json:"id,omitempty"`
	Token   string `json:"token,omitempty"`
	Message string `json:"message"`
}

BatchError represents an error for a single item in a batch operation.

type BatchOperation

type BatchOperation string

BatchOperation represents the type of batch operation.

const (
	BatchOpImport      BatchOperation = "import"
	BatchOpExport      BatchOperation = "export"
	BatchOpDelete      BatchOperation = "delete"
	BatchOpEnable      BatchOperation = "enable"
	BatchOpDisable     BatchOperation = "disable"
	BatchOpEnableNsfw  BatchOperation = "enable_nsfw"
	BatchOpDisableNsfw BatchOperation = "disable_nsfw"
)

type BatchTokenRequest

type BatchTokenRequest struct {
	Operation   BatchOperation `json:"operation"`
	Tokens      []string       `json:"tokens,omitempty"`       // For import: raw token strings
	IDs         []uint         `json:"ids,omitempty"`          // For delete/enable/disable
	Pool        string         `json:"pool,omitempty"`         // For import: default pool
	ChatQuota   *int           `json:"chat_quota,omitempty"`   // For import: chat quota
	ImageQuota  *int           `json:"image_quota,omitempty"`  // For import: image quota
	VideoQuota  *int           `json:"video_quota,omitempty"`  // For import: video quota
	Priority    int            `json:"priority"`               // For import: token priority
	Status      string         `json:"status,omitempty"`       // For import: initial status (active or disabled, default: active)
	Remark      string         `json:"remark,omitempty"`       // For import: default remark
	NsfwEnabled *bool          `json:"nsfw_enabled,omitempty"` // For import: default nsfw
}

BatchTokenRequest is the request body for batch token operations.

type BatchTokenResponse

type BatchTokenResponse struct {
	Operation BatchOperation  `json:"operation"`
	Success   int             `json:"success"`
	Failed    int             `json:"failed"`
	Errors    []BatchError    `json:"errors,omitempty"`
	Tokens    []TokenResponse `json:"tokens,omitempty"`     // For export (masked)
	RawTokens []string        `json:"raw_tokens,omitempty"` // For export with raw=true
}

BatchTokenResponse is the response for batch token operations.

type ChatProvider

type ChatProvider interface {
	SetupRoutes(r chi.Router)
}

ChatProvider abstracts downstream protocol handling for API routes.

type ConfigResponse

type ConfigResponse struct {
	App   AppConfigResponse   `json:"app"`
	Image ImageConfigResponse `json:"image"`
	Proxy ProxyConfigResponse `json:"proxy"`
	Retry RetryConfigResponse `json:"retry"`
	Token TokenConfigResponse `json:"token"`
}

ConfigResponse mirrors config.Config but with masked secrets for API responses.

type ConfigUpdateRequest

type ConfigUpdateRequest struct {
	App   *AppConfigUpdate   `json:"app,omitempty"`
	Image *ImageConfigUpdate `json:"image,omitempty"`
	Proxy *ProxyConfigUpdate `json:"proxy,omitempty"`
	Retry *RetryConfigUpdate `json:"retry,omitempty"`
	Token *TokenConfigUpdate `json:"token,omitempty"`
}

ConfigUpdateRequest represents the fields that can be hot-reloaded.

type ErrorDetail

type ErrorDetail struct {
	Message string  `json:"message"`
	Type    string  `json:"type"`
	Param   *string `json:"param"`
	Code    string  `json:"code"`
}

ErrorDetail contains the error details in OpenAI format.

type HealthResponse

type HealthResponse struct {
	Status    string `json:"status"`
	Uptime    string `json:"uptime"`
	Timestamp string `json:"timestamp"`
}

HealthResponse is the health check response.

type HourlyUsage

type HourlyUsage = store.HourlyUsage

HourlyUsage represents usage count for a specific hour and endpoint.

type ImageConfigResponse

type ImageConfigResponse struct {
	NSFW                    bool `json:"nsfw"`
	BlockedParallelAttempts int  `json:"blocked_parallel_attempts"`
	BlockedParallelEnabled  bool `json:"blocked_parallel_enabled"`
}

ImageConfigResponse is the API response for image config.

type ImageConfigUpdate

type ImageConfigUpdate struct {
	NSFW                    *bool `json:"nsfw,omitempty"`
	BlockedParallelAttempts *int  `json:"blocked_parallel_attempts,omitempty"`
	BlockedParallelEnabled  *bool `json:"blocked_parallel_enabled,omitempty"`
}

ImageConfigUpdate contains hot-reloadable image config fields.

type PaginatedResponse

type PaginatedResponse struct {
	Data       any   `json:"data"`
	Total      int64 `json:"total"`
	Page       int   `json:"page"`
	PageSize   int   `json:"page_size"`
	TotalPages int   `json:"total_pages"`
}

PaginatedResponse is a generic paginated response.

type PaginatedTokenResponse

type PaginatedTokenResponse struct {
	Data       []TokenResponse `json:"data"`
	Total      int             `json:"total"`
	Page       int             `json:"page"`
	PageSize   int             `json:"page_size"`
	TotalPages int             `json:"total_pages"`
}

PaginatedTokenResponse wraps tokens with pagination metadata.

type PoolQuota

type PoolQuota struct {
	Pool                string `json:"pool"`
	TotalChatQuota      int    `json:"total_chat_quota"`
	RemainingChatQuota  int    `json:"remaining_chat_quota"`
	TotalImageQuota     int    `json:"total_image_quota"`
	RemainingImageQuota int    `json:"remaining_image_quota"`
	TotalVideoQuota     int    `json:"total_video_quota"`
	RemainingVideoQuota int    `json:"remaining_video_quota"`
}

PoolQuota represents quota stats for a single pool.

type ProxyConfigResponse

type ProxyConfigResponse struct {
	BaseProxyURL       string `json:"base_proxy_url"`
	AssetProxyURL      string `json:"asset_proxy_url"`
	CFCookies          string `json:"cf_cookies"`
	SkipProxySSLVerify bool   `json:"skip_proxy_ssl_verify"`
	Enabled            bool   `json:"enabled"`
	FlareSolverrURL    string `json:"flaresolverr_url"`
	RefreshInterval    int    `json:"refresh_interval"`
	Timeout            int    `json:"timeout"`
	CFClearance        string `json:"cf_clearance"`
	Browser            string `json:"browser"`
	UserAgent          string `json:"user_agent"`
}

ProxyConfigResponse is the API response for proxy config.

type ProxyConfigUpdate

type ProxyConfigUpdate struct {
	BaseProxyURL       *string `json:"base_proxy_url,omitempty"`
	AssetProxyURL      *string `json:"asset_proxy_url,omitempty"`
	CFCookies          *string `json:"cf_cookies,omitempty"`
	SkipProxySSLVerify *bool   `json:"skip_proxy_ssl_verify,omitempty"`
	Enabled            *bool   `json:"enabled,omitempty"`
	FlareSolverrURL    *string `json:"flaresolverr_url,omitempty"`
	RefreshInterval    *int    `json:"refresh_interval,omitempty"`
	Timeout            *int    `json:"timeout,omitempty"`
	CFClearance        *string `json:"cf_clearance,omitempty"`
	Browser            *string `json:"browser,omitempty"`
	UserAgent          *string `json:"user_agent,omitempty"`
}

ProxyConfigUpdate contains hot-reloadable proxy config fields.

type QuotaStatsResponse

type QuotaStatsResponse struct {
	Pools []PoolQuota `json:"pools"`
}

QuotaStatsResponse is the response for quota stats endpoint.

type RetryConfigResponse

type RetryConfigResponse struct {
	MaxTokens               int     `json:"max_tokens"`
	PerTokenRetries         int     `json:"per_token_retries"`
	ResetSessionStatusCodes []int   `json:"reset_session_status_codes"`
	CoolingStatusCodes      []int   `json:"cooling_status_codes"`
	RetryBackoffBase        float64 `json:"retry_backoff_base"`
	RetryBackoffFactor      float64 `json:"retry_backoff_factor"`
	RetryBackoffMax         float64 `json:"retry_backoff_max"`
	RetryBudget             float64 `json:"retry_budget"`
}

RetryConfigResponse is the API response for retry config.

type RetryConfigUpdate

type RetryConfigUpdate struct {
	MaxTokens               *int     `json:"max_tokens,omitempty"`
	PerTokenRetries         *int     `json:"per_token_retries,omitempty"`
	ResetSessionStatusCodes *[]int   `json:"reset_session_status_codes,omitempty"`
	CoolingStatusCodes      *[]int   `json:"cooling_status_codes,omitempty"`
	RetryBackoffBase        *float64 `json:"retry_backoff_base,omitempty"`
	RetryBackoffFactor      *float64 `json:"retry_backoff_factor,omitempty"`
	RetryBackoffMax         *float64 `json:"retry_backoff_max,omitempty"`
	RetryBudget             *float64 `json:"retry_budget,omitempty"`
}

RetryConfigUpdate contains hot-reloadable retry config fields.

type SSEWriter

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

SSEWriter wraps http.ResponseWriter for Server-Sent Events output.

func NewSSEWriter

func NewSSEWriter(w http.ResponseWriter) *SSEWriter

NewSSEWriter creates a new SSE writer with proper headers. Sets Content-Type: text/event-stream, Cache-Control: no-cache, and X-Accel-Buffering: no for nginx proxy compatibility.

func (*SSEWriter) WriteSSE

func (s *SSEWriter) WriteSSE(data any) error

WriteSSE writes a data event in SSE format: data: {json}\n\n

func (*SSEWriter) WriteSSEDone

func (s *SSEWriter) WriteSSEDone()

WriteSSEDone writes the final [DONE] event.

func (*SSEWriter) WriteSSEError

func (s *SSEWriter) WriteSSEError(apiErr *APIError)

WriteSSEError writes an OpenAI-compatible error payload followed by [DONE].

type Server

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

Server holds HTTP server dependencies.

func NewServer

func NewServer(cfg *ServerConfig) *Server

NewServer creates a new HTTP server with configured routes.

func (*Server) Router

func (s *Server) Router() http.Handler

Router returns the chi router for http.Server.

type ServerConfig

type ServerConfig struct {
	AppKey          string
	Version         string
	Config          *config.Config
	Runtime         *config.Runtime
	ChatProvider    ChatProvider
	TokenStore      TokenStoreInterface
	TokenRefresher  TokenRefresher
	TokenPoolSyncer TokenPoolSyncer
	UsageLogStore   UsageLogStoreInterface
	APIKeyStore     APIKeyStoreInterface
	CacheService    *cache.Service
	ConfigStore     *store.ConfigStore
	ModelRegistry   *registry.ModelRegistry
}

ServerConfig holds server configuration.

type StatusAPIKeyCount

type StatusAPIKeyCount struct {
	Total  int `json:"total"`
	Active int `json:"active"`
}

StatusAPIKeyCount holds API key counts for system status.

type StatusTokenCount

type StatusTokenCount struct {
	Total  int `json:"total"`
	Active int `json:"active"`
}

StatusTokenCount holds token counts for system status.

type SystemStatusResponse

type SystemStatusResponse struct {
	Status  string            `json:"status"`
	Version string            `json:"version"`
	Uptime  float64           `json:"uptime"`
	Tokens  StatusTokenCount  `json:"tokens"`
	APIKeys StatusAPIKeyCount `json:"api_keys"`
}

SystemStatusResponse matches the frontend SystemStatus type.

type SystemUsageResponse

type SystemUsageResponse struct {
	Period       string                      `json:"period"`
	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]store.ModelUsage `json:"by_model"`
	ByAPIKey     []store.APIKeyUsage         `json:"by_api_key"`
}

SystemUsageResponse matches the frontend UsageStats type.

type TokenConfigResponse

type TokenConfigResponse struct {
	FailThreshold         int    `json:"fail_threshold"`
	UsageFlushIntervalSec int    `json:"usage_flush_interval_sec"`
	CoolCheckIntervalSec  int    `json:"cool_check_interval_sec"`
	BasicCoolDurationMin  int    `json:"basic_cool_duration_min"`
	SuperCoolDurationMin  int    `json:"super_cool_duration_min"`
	HeavyCoolDurationMin  int    `json:"heavy_cool_duration_min"`
	DefaultChatQuota      int    `json:"default_chat_quota"`
	DefaultImageQuota     int    `json:"default_image_quota"`
	DefaultVideoQuota     int    `json:"default_video_quota"`
	QuotaRecoveryMode     string `json:"quota_recovery_mode"`
	SelectionAlgorithm    string `json:"selection_algorithm"`
}

TokenConfigResponse is the API response for token config.

type TokenConfigUpdate

type TokenConfigUpdate struct {
	FailThreshold         *int    `json:"fail_threshold,omitempty"`
	CoolCheckIntervalSec  *int    `json:"cool_check_interval_sec,omitempty"`
	UsageFlushIntervalSec *int    `json:"usage_flush_interval_sec,omitempty"`
	BasicCoolDurationMin  *int    `json:"basic_cool_duration_min,omitempty"`
	SuperCoolDurationMin  *int    `json:"super_cool_duration_min,omitempty"`
	HeavyCoolDurationMin  *int    `json:"heavy_cool_duration_min,omitempty"`
	DefaultChatQuota      *int    `json:"default_chat_quota,omitempty"`
	DefaultImageQuota     *int    `json:"default_image_quota,omitempty"`
	DefaultVideoQuota     *int    `json:"default_video_quota,omitempty"`
	QuotaRecoveryMode     *string `json:"quota_recovery_mode,omitempty"`
	SelectionAlgorithm    *string `json:"selection_algorithm,omitempty"`
}

TokenConfigUpdate contains hot-reloadable token config fields.

type TokenPoolSyncer

type TokenPoolSyncer interface {
	AddToPool(token *store.Token) error
	RemoveFromPool(id uint)
	SyncToken(ctx context.Context, id uint) error
}

TokenPoolSyncer syncs admin token changes to in-memory pools.

type TokenRefresher

type TokenRefresher interface {
	RefreshToken(ctx context.Context, id uint) (*store.Token, error)
}

TokenRefresher defines the interface for refreshing token quota.

type TokenResponse

type TokenResponse struct {
	ID              uint       `json:"id"`
	Token           string     `json:"token"`
	Pool            string     `json:"pool"`
	Status          string     `json:"status"`
	StatusReason    string     `json:"status_reason,omitempty"`
	ChatQuota       int        `json:"chat_quota"`
	TotalChatQuota  int        `json:"total_chat_quota"`
	ImageQuota      int        `json:"image_quota"`
	TotalImageQuota int        `json:"total_image_quota"`
	VideoQuota      int        `json:"video_quota"`
	TotalVideoQuota int        `json:"total_video_quota"`
	FailCount       int        `json:"fail_count"`
	CoolUntil       *time.Time `json:"cool_until,omitempty"`
	LastUsed        *time.Time `json:"last_used,omitempty"`
	Remark          string     `json:"remark,omitempty"`
	NsfwEnabled     bool       `json:"nsfw_enabled"`
	Priority        int        `json:"priority"`
	CreatedAt       time.Time  `json:"created_at"`
	UpdatedAt       time.Time  `json:"updated_at"`
}

TokenResponse is the API response for a token (with masked sensitive data).

type TokenStatsResponse

type TokenStatsResponse struct {
	Total    int `json:"total"`
	Active   int `json:"active"`
	Cooling  int `json:"cooling"`
	Expired  int `json:"expired"`
	Disabled int `json:"disabled"`
}

TokenStatsResponse is the response for token stats endpoint.

type TokenStoreInterface

type TokenStoreInterface interface {
	ListTokens(ctx context.Context) ([]*store.Token, error)
	ListTokensFiltered(ctx context.Context, filter store.TokenFilter) ([]*store.Token, error)
	ListTokenIDs(ctx context.Context, filter store.TokenFilter) ([]uint, error)
	GetToken(ctx context.Context, id uint) (*store.Token, error)
	CreateToken(ctx context.Context, token *store.Token) error
	UpdateToken(ctx context.Context, token *store.Token) error
	DeleteToken(ctx context.Context, id uint) error
	BatchUpdateTokens(ctx context.Context, req store.BatchUpdateRequest) (int, error)
}

TokenStoreInterface defines the methods needed for token CRUD operations.

type TokenUpdateRequest

type TokenUpdateRequest struct {
	Status      *string `json:"status,omitempty"`
	Pool        *string `json:"pool,omitempty"`
	ChatQuota   *int    `json:"chat_quota,omitempty"`
	ImageQuota  *int    `json:"image_quota,omitempty"`
	VideoQuota  *int    `json:"video_quota,omitempty"`
	Remark      *string `json:"remark,omitempty"`
	NsfwEnabled *bool   `json:"nsfw_enabled,omitempty"`
}

TokenUpdateRequest is the request body for updating a token.

type UsageLogStoreForUsage

type UsageLogStoreForUsage interface {
	PeriodUsage(ctx context.Context, period string) (*store.UsagePeriodResult, error)
	ListLogs(ctx context.Context, p store.UsageLogListParams) ([]store.UsageLogWithKeyName, int64, error)
}

UsageLogStoreForUsage is a focused interface for the system usage and usage logs endpoints. Separate from UsageLogStoreInterface which serves the Dashboard stats.

type UsageLogStoreInterface

type UsageLogStoreInterface interface {
	Record(ctx context.Context, log *store.UsageLog) error
	TodayCountByEndpoint(ctx context.Context) (map[string]int, error)
	HourlyBreakdown(ctx context.Context, hours int) ([]HourlyUsage, error)
	YesterdayCountByEndpoint(ctx context.Context) (map[string]int, error)
	PeriodUsage(ctx context.Context, period string) (*store.UsagePeriodResult, error)
	ListLogs(ctx context.Context, p store.UsageLogListParams) ([]store.UsageLogWithKeyName, int64, error)
	TodayTokenTotals(ctx context.Context) (*store.TokenTotals, error)
}

UsageLogStoreInterface defines the methods needed for usage stats.

type UsageLogsPaginatedResponse

type UsageLogsPaginatedResponse struct {
	Data       []store.UsageLogWithKeyName `json:"data"`
	Total      int64                       `json:"total"`
	Page       int                         `json:"page"`
	PageSize   int                         `json:"page_size"`
	TotalPages int                         `json:"total_pages"`
}

UsageLogsPaginatedResponse is the paginated response for usage logs.

type UsageStatsResponse

type UsageStatsResponse struct {
	Today       map[string]int      `json:"today"`
	Total       int                 `json:"total"`
	Hourly      []HourlyUsage       `json:"hourly"`
	Delta       map[string]*float64 `json:"delta"`
	TokensToday *store.TokenTotals  `json:"tokens_today,omitempty"`
}

UsageStatsResponse is the response for usage stats endpoint.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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