Documentation
¶
Index ¶
- Constants
- Variables
- func AllAPITypes() []string
- func AllCLITools() []string
- func CleanupKeyModelCooldown(cooldownSec int)
- func ClearKeyModelCooldown(keyID int, modelName string)
- func CompactSiteModelRouteTypeName(routeType SiteModelRouteType) string
- func ComposeSiteChannelBindingKey(groupKey string, routeType SiteModelRouteType, split bool) string
- func IsConversationEndpointType(endpointType string) bool
- func IsKeyModelOnCooldown(keyID int, modelName string, cooldownSec int) bool
- func IsMaskedSiteTokenValue(value string) bool
- func IsOpenAIOnlyPlatform(platform SitePlatform) bool
- func IsProjectedSiteModelRouteType(routeType SiteModelRouteType) bool
- func IsReadySiteToken(token SiteToken) bool
- func IsSupportedEndpointType(endpointType string) bool
- func NormalizeComparableSiteTokenValue(value string) string
- func NormalizeEndpointType(endpointType string) string
- func NormalizeProxyURL(value string) (string, error)
- func NormalizeSiteGroupKey(value string) string
- func NormalizeSiteGroupName(groupKey string, name string) string
- func NormalizeSiteModelRouteMetadataGroupKeys(values []string) []string
- func NormalizeSiteSyncTokenValue(value string) string
- func RecordKeyModelCooldown(keyID int, modelName string)
- func ShouldSplitSiteChannelRoutes(platform SitePlatform) bool
- func SiteMaskedTokenMatches(fullToken string, maskedToken string) bool
- func SiteModelRouteTypeName(routeType SiteModelRouteType) string
- func SiteModelRouteTypeSuffix(routeType SiteModelRouteType) string
- func ValidateAIRouteServiceConfigs(raw string) error
- type AIRouteBatchStatus
- type AIRouteChannelStatus
- type AIRouteEntry
- type AIRouteItemSpec
- type AIRouteModelInput
- type AIRouteResponse
- type AIRouteScope
- type AIRouteServiceConfig
- type AIRouteTask
- type AIRouteTaskStatus
- type AIRouteTaskStep
- type APICredentialCreateRequest
- type APICredentialProfile
- type APICredentialUpdateRequest
- type APIKey
- type AlertHistory
- type AlertNotifChannel
- type AlertNotifChannelType
- type AlertRule
- type AlertRuleConditionType
- type AlertState
- type AlertStateRecord
- type AllAPIHubImportResult
- type AnalyticsAPIKeyBreakdownItem
- type AnalyticsChannelModelItem
- type AnalyticsEvaluationSummary
- type AnalyticsGroupHealthItem
- type AnalyticsMetrics
- type AnalyticsModelBreakdownItem
- type AnalyticsOverview
- type AnalyticsProviderBreakdownItem
- type AnalyticsRange
- type AnalyticsUtilization
- type AnthropicModel
- type AnthropicModelList
- type AttemptStatus
- type AuditLog
- type AutoGroupCreatedItem
- type AutoGroupDeletedItem
- type AutoGroupResult
- type AutoGroupSkippedItem
- type AutoGroupType
- type AutoStrategyRecord
- type AutoStrategySnapshotItem
- type AutoStrategyState
- type BaseUrl
- type CLIExportRequest
- type CLIExportResult
- type CandidateGroup
- type Channel
- func (c *Channel) EnabledKeyCount() int
- func (c *Channel) GetBaseUrl() string
- func (c *Channel) GetChannelKeyExcludingWithCooldown(excludeKeyIDs []int, ratelimitCooldownSec int) ChannelKey
- func (c *Channel) GetChannelKeyExcludingWithCooldownForModel(excludeKeyIDs []int, ratelimitCooldownSec int, modelName string) ChannelKey
- func (c *Channel) GetChannelKeyWithCooldown(ratelimitCooldownSec int) ChannelKey
- func (c *Channel) GetNormalizedBaseUrl() string
- func (c *Channel) GetNormalizedBaseUrlFor(rawURL string) string
- type ChannelAttempt
- type ChannelFetchModelRequest
- type ChannelGroup
- type ChannelKey
- type ChannelKeyAddRequest
- type ChannelKeyUpdateRequest
- type ChannelModelRef
- type ChannelUpdateRequest
- type ChatSession
- type CircuitBreakerState
- type CustomHeader
- type DBDump
- type DBImportResult
- type DBImportStep
- type DatabaseMigrationRequest
- type DatabaseMigrationResult
- type DingTalkConfig
- type EmailConfig
- type ErrorLog
- type FailingChannelItem
- type Feedback
- type FeishuConfig
- type GeminiModel
- type GeminiModelList
- type GenerateAIRouteChannelProgress
- type GenerateAIRouteCurrentBatch
- type GenerateAIRouteProgress
- type GenerateAIRouteProgressSummary
- type GenerateAIRouteRequest
- type GenerateAIRouteResult
- type GenerateAIRouteRunningBatch
- type GotifyConfig
- type Group
- type GroupIDAndLLMName
- type GroupItem
- type GroupItemAddRequest
- type GroupItemUpdateRequest
- type GroupMode
- type GroupModelTestResult
- type GroupTestResult
- type GroupTestResultStatus
- type GroupUpdateRequest
- type HistogramBucket
- type ImageRecord
- type InviteCode
- type LLMChannel
- type LLMInfo
- type LLMPrice
- type LatencyDistribution
- type ManagedChannelSource
- type MatchType
- type MetAPIImportResult
- type ModelCapability
- type ModelIdentity
- type ModelLatencyItem
- type ModelMapping
- type ModelMappingCreateRequest
- type ModelMappingUpdateRequest
- type ModelMarketChannel
- type ModelMarketItem
- type ModelMarketResponse
- type ModelMarketSummary
- type ModelPriceCategory
- type ModelProbeState
- type NtfyConfig
- type OAuthBinding
- type OpenAIModel
- type OpenAIModelList
- type OpsAIRouteServiceSummary
- type OpsCacheStatus
- type OpsHealthGroupItem
- type OpsHealthStatus
- type OpsProviderPromptCacheProviderItem
- type OpsProviderPromptCacheSummary
- type OpsProviderPromptCacheTrendPoint
- type OpsQuotaKeyItem
- type OpsQuotaSummary
- type OpsSystemSummary
- type OpsTelemetryDatabaseHealth
- type OpsTelemetryDrilldownShortcut
- type OpsTelemetryHeroMetrics
- type OpsTelemetryPromptCache
- type OpsTelemetryProviderHealth
- type OpsTelemetryProviderItem
- type OpsTelemetryRuntimeSignals
- type OpsTelemetrySessionQuotaActivity
- type OpsTelemetrySummary
- type OpsTelemetryTrendPoint
- type PaymentOrder
- type PriceCategoryRule
- type ProxyConfiguration
- type ProxyConfigurationReference
- type ProxyConfigurationReferenceType
- type ProxyConfigurationUpdateRequest
- type ProxyTestRequest
- type ProxyTestResult
- type ProxyUsageMode
- type QuotaLedger
- type RedemptionBatchResult
- type RedemptionRecord
- type RedemptionRequest
- type RelayLog
- type RelayLogAttempt
- type RelayLogListItem
- type RequestRewriteConfig
- type RequestRewriteProfile
- type SemanticCacheEvaluationSummary
- type Setting
- type SettingKey
- type Site
- type SiteAccount
- type SiteAccountUpdateRequest
- type SiteBatchFailure
- type SiteBatchRequest
- type SiteBatchResult
- type SiteChannelAccount
- type SiteChannelBinding
- type SiteChannelCard
- type SiteChannelGroup
- type SiteChannelKeyCreateRequest
- type SiteChannelModel
- type SiteCheckinResult
- type SiteCredentialType
- type SiteExecutionStatus
- type SiteGroupProjectionUpdateRequest
- type SiteManualModelAddEntry
- type SiteManualModelAddRequest
- type SiteManualModelDeleteRequest
- type SiteModel
- type SiteModelDisableUpdateRequest
- type SiteModelHistoryBucket
- type SiteModelHistorySummary
- type SiteModelRouteMetadata
- type SiteModelRouteSource
- type SiteModelRouteType
- func InferSiteModelRouteType(modelName string) SiteModelRouteType
- func NormalizeSiteModelRouteType(routeType SiteModelRouteType) SiteModelRouteType
- func ParseSiteChannelBindingKey(groupKey string) (string, SiteModelRouteType)
- func SiteModelRouteTypeFromOutboundType(t outbound.OutboundType) SiteModelRouteType
- type SiteModelRouteUpdateRequest
- type SitePlatform
- type SiteProjectedChannelSettings
- type SiteProjectedChannelSettingsUpdateRequest
- type SiteProjectedKey
- type SiteProjectedKeyAddRequest
- type SiteProjectedKeyUpdateItem
- type SiteProjectedKeyUpdateRequest
- type SiteRouteSummary
- type SiteSourceKey
- type SiteSourceKeyAddRequest
- type SiteSourceKeyUpdateItem
- type SiteSourceKeyUpdateRequest
- type SiteSyncGroupResult
- type SiteSyncResult
- type SiteToken
- type SiteTokenValueStatus
- type SiteUpdateRequest
- type SiteUserGroup
- type StatsAPIKey
- type StatsChannel
- type StatsDaily
- type StatsHourly
- type StatsMetrics
- type StatsModel
- type StatsSiteModelHourly
- type StatsTotal
- type SubscriptionOrder
- type SubscriptionPlan
- type SystemMessageStrategy
- type TelegramConfig
- type ToolRoleStrategy
- type TopupCode
- type TwoFA
- type TwoFABackupCode
- type User
- type UserAlertState
- type UserBootstrapCreate
- type UserChangePassword
- type UserChangeUsername
- type UserCreateRequest
- type UserLogin
- type UserLoginResponse
- type UserSubscription
- type VerificationRequest
- type VerificationResult
- type WSResponseAffinity
- type WeComConfig
- type WebAuthnCredential
Constants ¶
const ( APITypeOpenAI = "openai" APITypeAnthropic = "anthropic" APITypeGemini = "gemini" )
API type constants for credential profiles.
const ( HealthStatusUnknown = "unknown" HealthStatusHealthy = "healthy" HealthStatusWarning = "warning" HealthStatusError = "error" )
Health status constants for credential profiles (used by APICredentialProfile.HealthStatus).
const ( ImportModeIncremental = "incremental" // insert new, skip existing ImportModeFull = "full" // delete all then insert )
const ( EndpointTypeAll = "*" EndpointTypeChat = "chat" EndpointTypeDeepSeek = "deepseek" EndpointTypeMimo = "mimo" EndpointTypeResponses = "responses" EndpointTypeMessages = "messages" EndpointTypeEmbeddings = "embeddings" EndpointTypeRerank = "rerank" EndpointTypeModerations = "moderations" EndpointTypeImageGeneration = "image_generation" EndpointTypeAudioSpeech = "audio_speech" EndpointTypeAudioTranscription = "audio_transcription" EndpointTypeVideoGeneration = "video_generation" EndpointTypeMusicGeneration = "music_generation" EndpointTypeSearch = "search" )
const ( // LedgerKindOpeningBalance 是流水表上线时给存量用户补的开账行。 // delta = quota + used_quota(不是 quota)—— 已消耗的部分也属于历史入账, // 否则存量用户第一天就对不上账。 LedgerKindOpeningBalance = "opening_balance" LedgerKindTopupEpay = "topup_epay" LedgerKindTopupStripe = "topup_stripe" LedgerKindRedeem = "redeem" // LedgerKindAdminAdjust 覆盖管理员的加款与扣款(delta 有符号)。 // 这是唯一的人工纠错手段:退款到支付网关走网关后台,余额侧用一条负 delta 平账。 LedgerKindAdminAdjust = "admin_adjust" LedgerKindSubscriptionPurchase = "subscription_purchase" )
流水事件类型。新增类型必须在这里定义常量 —— 不要在调用点散落字符串字面量, 否则 kind 拼错不会有任何信号(DB 照样收下),对账时才发现分类是错的。
const ( LedgerRefPaymentOrder = "payment_order" LedgerRefTopupCode = "topup_code" LedgerRefSubscriptionPlan = "subscription_plan" )
关联单据类型。
const ( RedemptionStatusSuccess = "success" RedemptionStatusAlreadyUsed = "already_used" RedemptionStatusInvalid = "invalid" RedemptionStatusFailed = "failed" )
Redemption status constants.
const ( SiteDefaultGroupKey = "default" SiteDefaultGroupName = "default" )
const ( SiteModelRouteMetadataKind = "site_route_metadata" SiteModelRouteMetadataVersion = 1 )
const ( // Subscription duration types SubDurationMonth = "month" SubDurationDay = "day" SubDurationHour = "hour" SubDurationCustom = "custom" // Subscription order statuses SubOrderStatusPending = "pending" SubOrderStatusSuccess = "success" SubOrderStatusExpired = "expired" SubOrderStatusCancelled = "cancelled" // Subscription statuses SubStatusActive = "active" SubStatusExpired = "expired" SubStatusCancelled = "cancelled" )
const ( MaxFailAttempts = 5 LockoutDuration = 15 * time.Minute BackupCodeCount = 8 BackupCodeLength = 8 TOTPPeriod = 30 TOTPSkew = 1 )
const ( UserRoleAdmin = "admin" UserRoleEditor = "editor" UserRoleViewer = "viewer" // Lodestar commercial: minimal-privilege end-customer role (manage own API keys // + read public settings/stats only). Registered users get this, NOT viewer // (which is read-only STAFF and can see channels/logs/sites). UserRoleUser = "user" )
const DefaultChannelGroupName = "Default"
Variables ¶
var ErrTwoFANotEnabled = errors.New("2FA is not enabled")
Functions ¶
func AllCLITools ¶
func AllCLITools() []string
AllCLITools returns the list of supported CLI export tools.
func CleanupKeyModelCooldown ¶
func CleanupKeyModelCooldown(cooldownSec int)
CleanupKeyModelCooldown removes expired cooldown entries.
func ClearKeyModelCooldown ¶
ClearKeyModelCooldown removes the 429 cooldown for a (keyID, model) pair so the key can be re-selected immediately. Used by the rate-limit hold path, which retries the same channel after a delay instead of switching keys.
func CompactSiteModelRouteTypeName ¶
func CompactSiteModelRouteTypeName(routeType SiteModelRouteType) string
func ComposeSiteChannelBindingKey ¶
func ComposeSiteChannelBindingKey(groupKey string, routeType SiteModelRouteType, split bool) string
func IsKeyModelOnCooldown ¶
IsKeyModelOnCooldown checks if a specific (keyID, model) pair is still in cooldown.
func IsMaskedSiteTokenValue ¶
func IsOpenAIOnlyPlatform ¶
func IsOpenAIOnlyPlatform(platform SitePlatform) bool
IsOpenAIOnlyPlatform reports whether the given aggregation platform only supports OpenAI-compatible API formats. For these platforms, models like gemini-* or claude-* must still use the OpenAI Chat adapter because the upstream aggregation site does not expose native Gemini/Anthropic endpoints.
func IsProjectedSiteModelRouteType ¶
func IsProjectedSiteModelRouteType(routeType SiteModelRouteType) bool
func IsReadySiteToken ¶
func IsSupportedEndpointType ¶
IsSupportedEndpointType reports whether the given endpoint type string (after normalization) is a known, user-facing endpoint type that callers can filter by via ?endpoint=.
func NormalizeEndpointType ¶
func NormalizeProxyURL ¶
func NormalizeSiteGroupKey ¶
func NormalizeSiteGroupName ¶
func RecordKeyModelCooldown ¶
RecordKeyModelCooldown records a 429 cooldown for a specific (keyID, model) pair.
func ShouldSplitSiteChannelRoutes ¶
func ShouldSplitSiteChannelRoutes(platform SitePlatform) bool
func SiteMaskedTokenMatches ¶
SiteMaskedTokenMatches reports whether fullToken can plausibly produce maskedToken under the upstream masking scheme. Both sides are normalised so that an optional "sk-" prefix on either value does not break the comparison.
func SiteModelRouteTypeName ¶
func SiteModelRouteTypeName(routeType SiteModelRouteType) string
func SiteModelRouteTypeSuffix ¶
func SiteModelRouteTypeSuffix(routeType SiteModelRouteType) string
Types ¶
type AIRouteBatchStatus ¶
type AIRouteBatchStatus string
const ( AIRouteBatchStatusRunning AIRouteBatchStatus = "running" AIRouteBatchStatusParsing AIRouteBatchStatus = "parsing" AIRouteBatchStatusRetrying AIRouteBatchStatus = "retrying" AIRouteBatchStatusFailed AIRouteBatchStatus = "failed" )
type AIRouteChannelStatus ¶
type AIRouteChannelStatus string
const ( AIRouteChannelStatusPending AIRouteChannelStatus = "pending" AIRouteChannelStatusRunning AIRouteChannelStatus = "running" AIRouteChannelStatusCompleted AIRouteChannelStatus = "completed" AIRouteChannelStatusFailed AIRouteChannelStatus = "failed" )
type AIRouteEntry ¶
type AIRouteEntry struct {
EndpointType string `json:"endpoint_type,omitempty"`
RequestedModel string `json:"requested_model"`
MatchRegex string `json:"match_regex,omitempty"`
Items []AIRouteItemSpec `json:"items"`
}
func (AIRouteEntry) TableName ¶
func (AIRouteEntry) TableName() string
type AIRouteItemSpec ¶
type AIRouteItemSpec struct {
ChannelID int `json:"channel_id"`
UpstreamModel string `json:"upstream_model"`
Priority int `json:"priority"`
Weight int `json:"weight"`
}
func (AIRouteItemSpec) TableName ¶
func (AIRouteItemSpec) TableName() string
type AIRouteModelInput ¶
type AIRouteModelInput struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
Provider string `json:"provider"`
Model string `json:"model"`
}
func (AIRouteModelInput) TableName ¶
func (AIRouteModelInput) TableName() string
type AIRouteResponse ¶
type AIRouteResponse struct {
Routes []AIRouteEntry `json:"routes"`
}
func (AIRouteResponse) TableName ¶
func (AIRouteResponse) TableName() string
type AIRouteScope ¶
type AIRouteScope string
const ( AIRouteScopeGroup AIRouteScope = "group" AIRouteScopeTable AIRouteScope = "table" )
func (AIRouteScope) Valid ¶
func (s AIRouteScope) Valid() bool
type AIRouteServiceConfig ¶
type AIRouteServiceConfig struct {
Name string `json:"name,omitempty"`
BaseURL string `json:"base_url"`
APIKey string `json:"api_key"`
Model string `json:"model"`
Enabled *bool `json:"enabled,omitempty"`
}
func (AIRouteServiceConfig) IsEnabled ¶
func (c AIRouteServiceConfig) IsEnabled() bool
func (AIRouteServiceConfig) TableName ¶
func (AIRouteServiceConfig) TableName() string
type AIRouteTask ¶
type AIRouteTask struct {
ID string `json:"id" gorm:"primaryKey;size:64"`
Scope AIRouteScope `json:"scope" gorm:"size:16;not null;index:idx_ai_route_task_scope_group_done,priority:1"`
GroupID int `json:"group_id" gorm:"not null;default:0;index:idx_ai_route_task_scope_group_done,priority:2"`
Status AIRouteTaskStatus `json:"status" gorm:"size:32;not null;index"`
CurrentStep AIRouteTaskStep `json:"current_step" gorm:"size:32;not null"`
ProgressPercent int `json:"progress_percent" gorm:"not null;default:0"`
TotalBatches int `json:"total_batches" gorm:"not null;default:0"`
CompletedBatches int `json:"completed_batches" gorm:"not null;default:0"`
Done bool `json:"done" gorm:"not null;default:false;index:idx_ai_route_task_scope_group_done,priority:3"`
ResultReady bool `json:"result_ready" gorm:"not null;default:false"`
Message string `json:"message" gorm:"type:text"`
MessageKey string `json:"message_key" gorm:"type:text"`
MessageArgs map[string]any `json:"message_args,omitempty" gorm:"serializer:json"`
ErrorReason string `json:"error_reason" gorm:"type:text"`
ErrorReasonKey string `json:"error_reason_key" gorm:"type:text"`
ErrorReasonArgs map[string]any `json:"error_reason_args,omitempty" gorm:"serializer:json"`
StartedAt *time.Time `json:"started_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
HeartbeatAt *time.Time `json:"heartbeat_at,omitempty;index"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
EventSequence int64 `json:"event_sequence" gorm:"not null;default:0"`
Summary *GenerateAIRouteProgressSummary `json:"summary,omitempty" gorm:"serializer:json"`
CurrentBatch *GenerateAIRouteCurrentBatch `json:"current_batch,omitempty" gorm:"serializer:json"`
RunningBatches []GenerateAIRouteRunningBatch `json:"running_batches,omitempty" gorm:"serializer:json"`
Channels []GenerateAIRouteChannelProgress `json:"channels,omitempty" gorm:"serializer:json"`
Result *GenerateAIRouteResult `json:"result,omitempty" gorm:"serializer:json"`
}
func NewAIRouteTask ¶
func NewAIRouteTask(progress GenerateAIRouteProgress) AIRouteTask
func (AIRouteTask) TableName ¶
func (AIRouteTask) TableName() string
func (*AIRouteTask) ToProgress ¶
func (task *AIRouteTask) ToProgress() GenerateAIRouteProgress
type AIRouteTaskStatus ¶
type AIRouteTaskStatus string
const ( AIRouteTaskStatusQueued AIRouteTaskStatus = "queued" AIRouteTaskStatusRunning AIRouteTaskStatus = "running" AIRouteTaskStatusCompleted AIRouteTaskStatus = "completed" AIRouteTaskStatusFailed AIRouteTaskStatus = "failed" AIRouteTaskStatusTimeout AIRouteTaskStatus = "timeout" )
type AIRouteTaskStep ¶
type AIRouteTaskStep string
const ( AIRouteTaskStepQueued AIRouteTaskStep = "queued" AIRouteTaskStepCollectingModels AIRouteTaskStep = "collecting_models" AIRouteTaskStepBuildingBatches AIRouteTaskStep = "building_batches" AIRouteTaskStepAnalyzingBatches AIRouteTaskStep = "analyzing_batches" AIRouteTaskStepParsingResponse AIRouteTaskStep = "parsing_response" AIRouteTaskStepValidatingRoutes AIRouteTaskStep = "validating_routes" AIRouteTaskStepWritingGroups AIRouteTaskStep = "writing_groups" AIRouteTaskStepFinalizing AIRouteTaskStep = "finalizing" AIRouteTaskStepCompleted AIRouteTaskStep = "completed" AIRouteTaskStepFailed AIRouteTaskStep = "failed" AIRouteTaskStepTimeout AIRouteTaskStep = "timeout" )
type APICredentialCreateRequest ¶
type APICredentialCreateRequest struct {
Name string `json:"name" binding:"required"`
APIType string `json:"api_type"`
BaseURL string `json:"base_url" binding:"required"`
APIKey string `json:"api_key" binding:"required"`
Tags string `json:"tags"`
Notes string `json:"notes"`
}
APICredentialCreateRequest is the payload for creating a credential profile.
func (APICredentialCreateRequest) TableName ¶
func (APICredentialCreateRequest) TableName() string
type APICredentialProfile ¶
type APICredentialProfile struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"not null"`
APIType string `json:"api_type" gorm:"not null;default:'openai'"`
BaseURL string `json:"base_url" gorm:"not null"`
APIKey string `json:"api_key,omitempty"`
Tags string `json:"tags"`
Notes string `json:"notes"`
LastVerifiedAt *time.Time `json:"last_verified_at"`
HealthStatus string `json:"health_status" gorm:"default:'unknown'"`
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
}
APICredentialProfile stores a reusable Base URL + API Key pair.
type APICredentialUpdateRequest ¶
type APICredentialUpdateRequest struct {
ID int `json:"id" binding:"required"`
Name *string `json:"name,omitempty"`
APIType *string `json:"api_type,omitempty"`
BaseURL *string `json:"base_url,omitempty"`
APIKey *string `json:"api_key,omitempty"`
Tags *string `json:"tags,omitempty"`
Notes *string `json:"notes,omitempty"`
}
APICredentialUpdateRequest is the payload for updating a credential profile.
func (APICredentialUpdateRequest) TableName ¶
func (APICredentialUpdateRequest) TableName() string
type APIKey ¶
type APIKey struct {
ID int `json:"id" gorm:"primaryKey"`
UserID uint `json:"user_id" gorm:"index;default:0;constraint:OnDelete:CASCADE"` // Lodestar: owning user (commercial multi-tenant); 0 = admin/legacy unowned
Name string `json:"name" gorm:"not null"`
APIKey string `json:"api_key" gorm:"not null;uniqueIndex"`
Enabled bool `json:"enabled" gorm:"default:true"`
ExpireAt int64 `json:"expire_at,omitempty"`
MaxCost float64 `json:"max_cost,omitempty"`
MaxTokens int64 `json:"max_tokens,omitempty" gorm:"default:0"` // Token 用量上限(0=不限制)
SupportedModels string `json:"supported_models,omitempty"`
RateLimitRPM int `json:"rate_limit_rpm,omitempty" gorm:"default:0"`
RateLimitTPM int `json:"rate_limit_tpm,omitempty" gorm:"default:0"`
PerModelQuotaJSON string `json:"per_model_quota_json,omitempty" gorm:"column:per_model_quota_json"`
AllowedIPs string `json:"allowed_ips,omitempty" gorm:"column:allowed_ips"` // 逗号分隔的允许 IP/CIDR 列表
Tags string `json:"tags,omitempty" gorm:"column:tags"` // 逗号分隔的标签,用于分类与快速检索
ExcludedChannels string `json:"excluded_channels,omitempty" gorm:"column:excluded_channels"` // 逗号分隔的被排除渠道 ID,该 Key 不会命中这些渠道(issue #55)
}
type AlertHistory ¶
type AlertHistory struct {
ID int64 `json:"id" gorm:"primaryKey"`
RuleID int `json:"rule_id"`
RuleName string `json:"rule_name"`
State AlertState `json:"state"`
Message string `json:"message"`
DetailJSON string `json:"detail_json,omitempty"`
Time int64 `json:"time" gorm:"autoCreateTime:milli"`
}
AlertHistory records a single alert event.
type AlertNotifChannel ¶
type AlertNotifChannel struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"not null"`
Type string `json:"type" gorm:"not null;default:'webhook'"`
URL string `json:"url"`
Secret string `json:"secret,omitempty"`
Headers string `json:"headers,omitempty"`
Config string `json:"config,omitempty"` // JSON blob for type-specific config (gotify token, email SMTP, etc.)
}
AlertNotifChannel defines a notification channel (webhook, gotify, email, etc.).
type AlertNotifChannelType ¶
type AlertNotifChannelType string
AlertNotifChannelType defines the type of a notification channel.
const ( AlertNotifWebhook AlertNotifChannelType = "webhook" AlertNotifGotify AlertNotifChannelType = "gotify" AlertNotifEmail AlertNotifChannelType = "email" AlertNotifTelegram AlertNotifChannelType = "telegram" AlertNotifFeishu AlertNotifChannelType = "feishu" AlertNotifDingTalk AlertNotifChannelType = "dingtalk" AlertNotifWeCom AlertNotifChannelType = "wecom" AlertNotifNtfy AlertNotifChannelType = "ntfy" )
type AlertRule ¶
type AlertRule struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"not null"`
Enabled bool `json:"enabled" gorm:"default:true"`
ConditionType AlertRuleConditionType `json:"condition_type" gorm:"not null"`
Threshold float64 `json:"threshold"`
ConditionJSON string `json:"condition_json,omitempty"`
NotifChannelID int `json:"notif_channel_id"`
CooldownSec int `json:"cooldown_sec" gorm:"default:300"`
ScopeChannelID int `json:"scope_channel_id,omitempty"`
ScopeAPIKeyID int `json:"scope_api_key_id,omitempty"`
}
AlertRule defines an alert rule with condition, threshold, and notification channel.
type AlertRuleConditionType ¶
type AlertRuleConditionType string
AlertRuleConditionType defines the trigger condition for an alert rule.
const ( AlertConditionCostThreshold AlertRuleConditionType = "cost_threshold" AlertConditionErrorRate AlertRuleConditionType = "error_rate" AlertConditionQuotaExceeded AlertRuleConditionType = "quota_exceeded" AlertConditionChannelDown AlertRuleConditionType = "channel_down" )
type AlertState ¶
type AlertState int
AlertState represents the current firing state of an alert rule.
const ( AlertStateOK AlertState = 0 AlertStateFiring AlertState = 1 AlertStateResolved AlertState = 2 )
type AlertStateRecord ¶
type AlertStateRecord struct {
RuleID int `json:"rule_id" gorm:"primaryKey"`
State AlertState `json:"state"`
LastFiredAt int64 `json:"last_fired_at"`
LastResolvedAt int64 `json:"last_resolved_at"`
LastCheckedAt int64 `json:"last_checked_at"`
FiredCount int64 `json:"fired_count"`
}
AlertStateRecord tracks the current state of an alert rule.
type AllAPIHubImportResult ¶
type AllAPIHubImportResult struct {
CreatedSites int `json:"created_sites"`
ReusedSites int `json:"reused_sites"`
CreatedAccounts int `json:"created_accounts"`
UpdatedAccounts int `json:"updated_accounts"`
SkippedAccounts int `json:"skipped_accounts"`
ScheduledSyncAccounts int `json:"scheduled_sync_accounts"`
Warnings []string `json:"warnings,omitempty"`
}
type AnalyticsAPIKeyBreakdownItem ¶
type AnalyticsAPIKeyBreakdownItem struct {
APIKeyID *int `json:"api_key_id,omitempty"`
Name string `json:"name"`
AnalyticsMetrics
}
type AnalyticsChannelModelItem ¶
type AnalyticsChannelModelItem struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
ModelName string `json:"model_name"`
Enabled bool `json:"enabled"`
AnalyticsMetrics
}
AnalyticsChannelModelItem 描述某个 (渠道,模型) 维度的统计,用于"渠道×模型"分析视图。 与 AnalyticsProviderBreakdownItem 的区别:这里是渠道与模型的交叉维度,且失败数 基于单次尝试(relay_log_attempts)聚合,使"渠道A 失败→重试到B 成功"的请求中 渠道A 的失败也能反映到 A 的成功率上(issue #67)。
type AnalyticsEvaluationSummary ¶
type AnalyticsEvaluationSummary struct {
SemanticCache SemanticCacheEvaluationSummary `json:"semantic_cache"`
}
type AnalyticsGroupHealthItem ¶
type AnalyticsGroupHealthItem struct {
GroupID int `json:"group_id"`
GroupName string `json:"group_name"`
EndpointType string `json:"endpoint_type"`
ItemCount int `json:"item_count"`
EnabledItemCount int `json:"enabled_item_count"`
DisabledItemCount int `json:"disabled_item_count"`
FailureCount int64 `json:"failure_count"`
LastFailureAt int64 `json:"last_failure_at"`
HealthScore int `json:"health_score"`
Status string `json:"status"`
FailingChannels []FailingChannelItem `json:"failing_channels"`
Mode int `json:"mode"`
ChannelIDs []int `json:"channel_ids"`
}
type AnalyticsMetrics ¶
type AnalyticsModelBreakdownItem ¶
type AnalyticsModelBreakdownItem struct {
ModelName string `json:"model_name"`
AnalyticsMetrics
}
type AnalyticsOverview ¶
type AnalyticsOverview struct {
AnalyticsMetrics
ProviderCount int `json:"provider_count"`
APIKeyCount int `json:"api_key_count"`
ModelCount int `json:"model_count"`
FallbackRate float64 `json:"fallback_rate"`
}
type AnalyticsProviderBreakdownItem ¶
type AnalyticsProviderBreakdownItem struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
Enabled bool `json:"enabled"`
AnalyticsMetrics
}
type AnalyticsRange ¶
type AnalyticsRange string
const ( AnalyticsRange1D AnalyticsRange = "1d" AnalyticsRange7D AnalyticsRange = "7d" AnalyticsRange30D AnalyticsRange = "30d" AnalyticsRange90D AnalyticsRange = "90d" AnalyticsRangeYTD AnalyticsRange = "ytd" AnalyticsRangeAll AnalyticsRange = "all" )
func ParseAnalyticsRange ¶
func ParseAnalyticsRange(raw string) (AnalyticsRange, error)
type AnalyticsUtilization ¶
type AnalyticsUtilization struct {
ProviderBreakdown []AnalyticsProviderBreakdownItem `json:"provider_breakdown"`
ModelBreakdown []AnalyticsModelBreakdownItem `json:"model_breakdown"`
APIKeyBreakdown []AnalyticsAPIKeyBreakdownItem `json:"apikey_breakdown"`
}
type AnthropicModel ¶
type AnthropicModel struct {
ID string `json:"id"`
CreatedAt string `json:"created_at"`
DisplayName string `json:"display_name"`
Type string `json:"type"`
}
func (AnthropicModel) TableName ¶
func (AnthropicModel) TableName() string
type AnthropicModelList ¶
type AnthropicModelList struct {
Data []AnthropicModel `json:"data"`
FirstID string `json:"first_id"`
HasMore bool `json:"has_more"`
LastID string `json:"last_id"`
}
func (AnthropicModelList) TableName ¶
func (AnthropicModelList) TableName() string
type AttemptStatus ¶
type AttemptStatus string
AttemptStatus 尝试状态
const ( AttemptSuccess AttemptStatus = "success" // 转发成功 AttemptFailed AttemptStatus = "failed" // 转发失败 AttemptCircuitBreak AttemptStatus = "circuit_break" // 熔断跳过 AttemptSkipped AttemptStatus = "skipped" // 其他原因跳过(禁用、无Key、类型不兼容等) )
type AuditLog ¶
type AuditLog struct {
ID int64 `json:"id" gorm:"primaryKey"`
UserID int `json:"user_id" gorm:"index"`
Username string `json:"username" gorm:"index"`
Action string `json:"action" gorm:"index"`
Method string `json:"method"`
Path string `json:"path"`
StatusCode int `json:"status_code"`
Target string `json:"target"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"`
}
type AutoGroupCreatedItem ¶
type AutoGroupDeletedItem ¶
type AutoGroupResult ¶
type AutoGroupResult struct {
TotalChannels int `json:"total_channels"`
TotalModelsSeen int `json:"total_models_seen"`
TotalDistinctRawModels int `json:"total_distinct_raw_models"`
TotalCandidates int `json:"total_candidates"`
CreatedGroups int `json:"created_groups"`
SkippedExistingGroups int `json:"skipped_existing_groups"`
SkippedCoveredModels int `json:"skipped_covered_models"`
FailedGroups int `json:"failed_groups"`
DeletedGroups int `json:"deleted_groups"`
Created []AutoGroupCreatedItem `json:"created"`
Skipped []AutoGroupSkippedItem `json:"skipped"`
Deleted []AutoGroupDeletedItem `json:"deleted"`
}
type AutoGroupSkippedItem ¶
type AutoGroupType ¶
type AutoGroupType int
const ( AutoGroupTypeNone AutoGroupType = 0 //不自动分组 AutoGroupTypeFuzzy AutoGroupType = 1 //模糊匹配 AutoGroupTypeExact AutoGroupType = 2 //准确匹配 AutoGroupTypeRegex AutoGroupType = 3 //正则匹配 )
func ParseAutoGroupSettingValue ¶
func ParseAutoGroupSettingValue(value string) (AutoGroupType, bool)
func (AutoGroupType) Valid ¶
func (t AutoGroupType) Valid() bool
type AutoStrategyRecord ¶
type AutoStrategySnapshotItem ¶
type AutoStrategySnapshotItem struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
Enabled bool `json:"enabled"`
ModelName string `json:"model_name"`
SuccessRate float64 `json:"success_rate"` // 0-100
SampleCount int `json:"sample_count"`
AvgLatencyMs float64 `json:"avg_latency_ms"`
LastActiveAt int64 `json:"last_active_at"` // unix 秒,0 表示无活动
MinSamplesMet bool `json:"min_samples_met"` // 样本数是否达到最小阈值
}
AutoStrategySnapshotItem 是 Auto 策略运行态某个 (渠道,模型) 维度的实时快照, 反映滑动窗口内的成功率/样本数/延迟。供分组健康中的"Auto 实时表现"展示(issue #67)。
type AutoStrategyState ¶
type AutoStrategyState struct {
Key string `json:"key" gorm:"primaryKey"`
ChannelID int `json:"channel_id" gorm:"index"`
ModelName string `json:"model_name"`
Records []AutoStrategyRecord `json:"records" gorm:"serializer:json"`
UpdatedAt int64 `json:"updated_at"`
}
type CLIExportRequest ¶
type CLIExportRequest struct {
BaseURL string `json:"base_url" binding:"required"`
APIKey string `json:"api_key" binding:"required"`
APIType string `json:"api_type"`
Tool string `json:"tool" binding:"required"` // claude_code, codex, gemini_cli, cherry_studio, kilo_code
}
CLIExportRequest is the payload for generating CLI config snippets.
func (CLIExportRequest) TableName ¶
func (CLIExportRequest) TableName() string
type CLIExportResult ¶
type CLIExportResult struct {
Tool string `json:"tool"`
Format string `json:"format"` // json, env, toml, yaml
Content string `json:"content"`
Filename string `json:"filename"`
Description string `json:"description"`
}
CLIExportResult holds the generated config snippet.
type CandidateGroup ¶
type Channel ¶
type Channel struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"unique;not null"`
GroupID int `json:"group_id" gorm:"not null;default:0;index"`
Type outbound.OutboundType `json:"type"`
Enabled bool `json:"enabled" gorm:"default:true"`
BaseUrls []BaseUrl `json:"base_urls" gorm:"serializer:json"`
Keys []ChannelKey `json:"keys" gorm:"foreignKey:ChannelID"`
Model string `json:"model"`
CustomModel string `json:"custom_model"`
ProxyMode ProxyUsageMode `json:"proxy_mode" gorm:"type:varchar(16);not null;default:'direct'"`
ProxyConfigID *int `json:"proxy_config_id"`
Proxy bool `json:"-" gorm:"default:false"`
AutoSync bool `json:"auto_sync" gorm:"default:false"`
AutoGroup AutoGroupType `json:"auto_group" gorm:"default:0"`
CustomHeader []CustomHeader `json:"custom_header" gorm:"serializer:json"`
ParamOverride *string `json:"param_override"`
ChannelProxy *string `json:"-" gorm:"column:channel_proxy"`
RequestRewrite *RequestRewriteConfig `json:"request_rewrite" gorm:"serializer:json"`
Stats *StatsChannel `json:"stats,omitempty" gorm:"foreignKey:ChannelID"`
MatchRegex *string `json:"match_regex"`
Managed bool `json:"managed" gorm:"-"`
ManagedSource *ManagedChannelSource `json:"managed_source,omitempty" gorm:"-"`
}
func (*Channel) EnabledKeyCount ¶
EnabledKeyCount returns the number of enabled keys with non-empty ChannelKey.
func (*Channel) GetBaseUrl ¶
func (*Channel) GetChannelKeyExcludingWithCooldown ¶
func (c *Channel) GetChannelKeyExcludingWithCooldown(excludeKeyIDs []int, ratelimitCooldownSec int) ChannelKey
func (*Channel) GetChannelKeyExcludingWithCooldownForModel ¶
func (c *Channel) GetChannelKeyExcludingWithCooldownForModel(excludeKeyIDs []int, ratelimitCooldownSec int, modelName string) ChannelKey
GetChannelKeyExcludingWithCooldownForModel selects the least-cost key, excluding keys in excludeKeyIDs and keys in per-model cooldown. When modelName is non-empty, per (key, model) cooldown is checked so that a 429 on one model doesn't block the same key for other models.
func (*Channel) GetChannelKeyWithCooldown ¶
func (c *Channel) GetChannelKeyWithCooldown(ratelimitCooldownSec int) ChannelKey
GetChannelKeyWithCooldown 及其下游只接受显式传入的冷却秒数,不自己读设置 —— internal/op/setting 依赖本包,反向读会成环。所以调用方必须自己读 SettingKeyRatelimitCooldown 再传进来(relay/type.go:getRatelimitCooldown、 helper/ratelimit_cooldown.go:ratelimitCooldownSeconds)。
这里刻意不提供写死默认值的无参包装。曾经有 GetChannelKey() 与 GetChannelKeyExcluding() 两个包装写死 300,helper 的四个调用点全用了它们, 结果 ratelimit_cooldown=0(关闭)对模型拉取和分组探测完全无效。少一个便捷 包装,就少一处能悄悄绕过这个旋钮的入口。
func (*Channel) GetNormalizedBaseUrl ¶
func (*Channel) GetNormalizedBaseUrlFor ¶
type ChannelAttempt ¶
type ChannelAttempt struct {
ChannelID int `json:"channel_id"`
ChannelKeyID int `json:"channel_key_id,omitempty"`
ChannelName string `json:"channel_name"`
ModelName string `json:"model_name"`
AdapterType string `json:"adapter_type,omitempty"` // 适配器类型: response, chat, anthropic, gemini 等
AttemptNum int `json:"attempt_num"`
Status AttemptStatus `json:"status"`
Duration int `json:"duration"`
Sticky bool `json:"sticky,omitempty"`
Msg string `json:"msg,omitempty"`
}
ChannelAttempt 记录单次渠道尝试的决策和结果
func (ChannelAttempt) TableName ¶
func (ChannelAttempt) TableName() string
TableName explicitly returns "-" for DTO structs to prevent GORM auto-mapping.
type ChannelFetchModelRequest ¶
type ChannelFetchModelRequest struct {
Type outbound.OutboundType `json:"type" binding:"required"`
BaseURL string `json:"base_url" binding:"required"`
Key string `json:"key" binding:"required"`
Proxy bool `json:"proxy"`
}
ChannelFetchModelRequest is used by /channel/fetch-model (not persisted).
func (ChannelFetchModelRequest) TableName ¶
func (ChannelFetchModelRequest) TableName() string
type ChannelGroup ¶
type ChannelGroup struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"unique;not null"`
IsDefault bool `json:"is_default" gorm:"not null;default:false"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime:milli"`
UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime:milli"`
}
type ChannelKey ¶
type ChannelKey struct {
ID int `json:"id" gorm:"primaryKey"`
ChannelID int `json:"channel_id" gorm:"constraint:OnDelete:CASCADE"`
Enabled bool `json:"enabled" gorm:"default:true"`
ChannelKey string `json:"channel_key"`
StatusCode int `json:"status_code"`
LastUseTimeStamp int64 `json:"last_use_time_stamp"`
TotalCost float64 `json:"total_cost"`
Remark string `json:"remark"`
// EnabledSet 标记请求里是否显式给出了 enabled(仿 SiteAccount 的 *Set 模式)。
// 只在内存里传递,不落库:Enabled 的 default:true 标签会让 struct Create
// 把显式的 false 吞成 true,create 级联靠这个标记事后补偿。
EnabledSet bool `json:"-" gorm:"-"`
}
type ChannelKeyAddRequest ¶
type ChannelKeyAddRequest struct {
Enabled bool `json:"enabled"`
EnabledSet bool `json:"-"` // 由 UnmarshalJSON 填充:区分"字段缺失"与"显式 false"
ChannelKey string `json:"channel_key" binding:"required"`
Remark string `json:"remark"`
}
func (ChannelKeyAddRequest) TableName ¶
func (ChannelKeyAddRequest) TableName() string
func (*ChannelKeyAddRequest) UnmarshalJSON ¶
func (r *ChannelKeyAddRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON 记录 "enabled" 键是否出现,用于区分「字段缺失(默认启用)」 和「显式 false(操作者要求停用)」——裸 bool 下两者到达 Go 时都是 false。
type ChannelKeyUpdateRequest ¶
type ChannelKeyUpdateRequest struct {
ID int `json:"id" binding:"required"`
Enabled *bool `json:"enabled,omitempty"`
ChannelKey *string `json:"channel_key,omitempty"`
Remark *string `json:"remark,omitempty"`
}
func (ChannelKeyUpdateRequest) TableName ¶
func (ChannelKeyUpdateRequest) TableName() string
type ChannelModelRef ¶
type ChannelUpdateRequest ¶
type ChannelUpdateRequest struct {
ID int `json:"id" binding:"required"`
Name *string `json:"name,omitempty"`
GroupID *int `json:"group_id,omitempty"`
Type *outbound.OutboundType `json:"type,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
BaseUrls *[]BaseUrl `json:"base_urls,omitempty"`
Model *string `json:"model,omitempty"`
CustomModel *string `json:"custom_model,omitempty"`
ProxyMode *ProxyUsageMode `json:"proxy_mode,omitempty"`
ProxyConfigID *int `json:"proxy_config_id,omitempty"`
// ProxyConfigIDSet 区分"字段缺省"与"显式传 null",与 SiteUpdateRequest 同构。
// 由 UnmarshalJSON 填充,客户端不可直接设置。
ProxyConfigIDSet bool `json:"-"`
Proxy *bool `json:"proxy,omitempty"`
AutoSync *bool `json:"auto_sync,omitempty"`
AutoGroup *AutoGroupType `json:"auto_group,omitempty"`
CustomHeader *[]CustomHeader `json:"custom_header,omitempty"`
ChannelProxy *string `json:"channel_proxy,omitempty"`
ParamOverride *string `json:"param_override,omitempty"`
RequestRewrite *RequestRewriteConfig `json:"request_rewrite,omitempty"`
MatchRegex *string `json:"match_regex,omitempty"`
KeysToAdd []ChannelKeyAddRequest `json:"keys_to_add,omitempty"`
KeysToUpdate []ChannelKeyUpdateRequest `json:"keys_to_update,omitempty"`
KeysToDelete []int `json:"keys_to_delete,omitempty"`
BypassManagedCheck bool `json:"-"` // 内部使用:允许投影逻辑更新 managed channel
}
ChannelUpdateRequest 渠道更新请求 - 仅包含变更的数据
func (ChannelUpdateRequest) TableName ¶
func (ChannelUpdateRequest) TableName() string
TableName explicitly returns "-" for DTO structs to prevent GORM auto-mapping.
func (*ChannelUpdateRequest) UnmarshalJSON ¶
func (r *ChannelUpdateRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON 记录 proxy_config_id 是否出现在请求体里,使"显式清空(null)" 能与"本次不改该字段"区分开。与 SiteUpdateRequest.UnmarshalJSON 同构。
type ChatSession ¶
type ChatSession struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index;not null"`
Title string `json:"title" gorm:"type:varchar(128);not null;default:''"`
Model string `json:"model" gorm:"type:varchar(128);not null;default:''"`
APIKeyID int `json:"api_key_id" gorm:"not null;default:0"`
Messages string `json:"messages" gorm:"type:text;not null;default:'[]'"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
}
ChatSession stores a user's portal chat thread (messages as JSON array).
func (ChatSession) TableName ¶
func (ChatSession) TableName() string
type CircuitBreakerState ¶
type CircuitBreakerState struct {
Key string `json:"key" gorm:"primaryKey"`
ChannelID int `json:"channel_id" gorm:"index"`
ChannelKeyID int `json:"channel_key_id" gorm:"index"`
ModelName string `json:"model_name"`
State int `json:"state"`
ConsecutiveFailures int64 `json:"consecutive_failures"`
LastFailureTime int64 `json:"last_failure_time"`
TripCount int `json:"trip_count"`
UpdatedAt int64 `json:"updated_at"`
}
type CustomHeader ¶
type DBDump ¶
type DBDump struct {
Version int `json:"version"`
ExportedAt time.Time `json:"exported_at"`
IncludeLogs bool `json:"include_logs"`
IncludeStats bool `json:"include_stats"`
Channels []Channel `json:"channels,omitempty"`
ChannelKeys []ChannelKey `json:"channel_keys,omitempty"`
ChannelGroups []ChannelGroup `json:"channel_groups,omitempty"`
Groups []Group `json:"groups,omitempty"`
GroupItems []GroupItem `json:"group_items,omitempty"`
LLMInfos []LLMInfo `json:"llm_infos,omitempty"`
APIKeys []APIKey `json:"api_keys,omitempty"`
Users []User `json:"users,omitempty"`
Settings []Setting `json:"settings,omitempty"`
AlertRules []AlertRule `json:"alert_rules,omitempty"`
AlertNotifChannels []AlertNotifChannel `json:"alert_notif_channels,omitempty"`
AlertStateRecords []AlertStateRecord `json:"alert_state_records,omitempty"`
AlertHistory []AlertHistory `json:"alert_history,omitempty"`
AuditLogs []AuditLog `json:"audit_logs,omitempty"`
RuntimeStates []AutoStrategyState `json:"runtime_states,omitempty"`
CircuitBreakerStates []CircuitBreakerState `json:"circuit_breaker_states,omitempty"`
StatsTotal []StatsTotal `json:"stats_total,omitempty"`
StatsDaily []StatsDaily `json:"stats_daily,omitempty"`
StatsHourly []StatsHourly `json:"stats_hourly,omitempty"`
StatsModel []StatsModel `json:"stats_model,omitempty"`
StatsChannel []StatsChannel `json:"stats_channel,omitempty"`
StatsAPIKey []StatsAPIKey `json:"stats_api_key,omitempty"`
RelayLogs []RelayLog `json:"relay_logs,omitempty"`
// Hub tables
APICredentialProfiles []APICredentialProfile `json:"api_credential_profiles,omitempty"`
}
DBDump is a full-database JSON export format for Octopus.
type DBImportResult ¶
type DBImportResult struct {
// RowsAffected contains the rows affected for each table.
RowsAffected map[string]int64 `json:"rows_affected"`
Progress []DBImportStep `json:"progress,omitempty"`
}
type DBImportStep ¶
type DatabaseMigrationResult ¶
type DingTalkConfig ¶
type DingTalkConfig struct {
WebhookKey string `json:"webhook_key"` // robot access_token
Secret string `json:"secret,omitempty"` // optional HMAC-SHA256 signing secret
}
DingTalkConfig holds the configuration for a DingTalk notification channel.
type EmailConfig ¶
type EmailConfig struct {
SMTPHost string `json:"smtp_host"`
SMTPPort int `json:"smtp_port"` // default 587
Username string `json:"username"`
Password string `json:"password"`
From string `json:"from"` // sender address
To string `json:"to"` // comma-separated recipient addresses
UseTLS bool `json:"use_tls"` // default true
}
EmailConfig holds the configuration for an Email notification channel.
type ErrorLog ¶
type ErrorLog struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement:false"` // Snowflake ID
Time int64 `json:"time" gorm:"column:time;index"` // 时间戳(秒)
Source string `json:"source" gorm:"column:source;size:16"` // backend | frontend
Level string `json:"level" gorm:"column:level;size:32"` // panic | error | unhandledrejection | uncaught
// Message 错误信息(panic 值 / JS 错误信息)
Message string `json:"message" gorm:"column:message;type:text"`
// Stack 完整堆栈(后端 debug.Stack() / 前端 error.stack)
Stack string `json:"stack" gorm:"column:stack;type:text"`
// 后端请求信息(panic 发生时)
RequestMethod string `json:"request_method" gorm:"column:request_method;size:16"`
RequestPath string `json:"request_path" gorm:"column:request_path;size:512"`
ClientIP string `json:"client_ip" gorm:"column:client_ip;size:64"`
UserAgent string `json:"user_agent" gorm:"column:user_agent;size:512"`
// 前端页面信息(错误发生时)
PageURL string `json:"page_url" gorm:"column:page_url;size:1024"`
RouteID string `json:"route_id" gorm:"column:route_id;size:128"`
// 上报方版本(后端 conf.Version / 前端 APP_VERSION)
Version string `json:"version" gorm:"column:version;size:64"`
}
ErrorLog 记录前后端崩溃/错误日志(排障用),落主库(随主库备份)。 与 relay log 体系完全不同:relay log 是中继请求日志,可能存独立日志库且 视为可丢弃;ErrorLog 是崩溃日志,重启不丢。
来源(Source):
- backend:后端 Go panic(gin CustomRecovery 捕获)
- frontend:管理 UI 捕获的 JS 错误(window.onerror / unhandledrejection / React ErrorBoundary)
Level 区分严重程度:panic(崩溃)、error、unhandledrejection、uncaught。 Message 为错误简述,Stack 为完整堆栈;请求/页面信息辅助定位触发场景。
type FailingChannelItem ¶
type FailingChannelItem struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
ModelName string `json:"model_name"`
FailureCount int64 `json:"failure_count"`
LastFailureAt int64 `json:"last_failure_at"`
}
FailingChannelItem 描述组内某个 (渠道,模型) 维度的失败情况,供分组健康下钻展示。
type Feedback ¶
type Feedback struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index"`
Content string `json:"content" gorm:"type:text;not null"`
Contact string `json:"contact" gorm:"type:varchar(128)"`
Status string `json:"status" gorm:"type:varchar(16);default:'new'"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
}
Lodestar — 用户意见反馈(消费级平台的互动闭环)。
type FeishuConfig ¶
type FeishuConfig struct {
WebhookKey string `json:"webhook_key"` // bot webhook key
}
FeishuConfig holds the configuration for a Feishu (Lark) notification channel.
type GeminiModel ¶
type GeminiModel struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
}
func (GeminiModel) TableName ¶
func (GeminiModel) TableName() string
type GeminiModelList ¶
type GeminiModelList struct {
Models []GeminiModel `json:"models"`
NextPageToken string `json:"nextPageToken"`
}
func (GeminiModelList) TableName ¶
func (GeminiModelList) TableName() string
type GenerateAIRouteChannelProgress ¶
type GenerateAIRouteChannelProgress struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name,omitempty"`
Provider string `json:"provider,omitempty"`
Status AIRouteChannelStatus `json:"status,omitempty"`
TotalModels int `json:"total_models"`
ProcessedModels int `json:"processed_models"`
Message string `json:"message,omitempty"`
MessageKey string `json:"message_key,omitempty"`
MessageArgs map[string]any `json:"message_args,omitempty"`
}
func (GenerateAIRouteChannelProgress) TableName ¶
func (GenerateAIRouteChannelProgress) TableName() string
type GenerateAIRouteCurrentBatch ¶
type GenerateAIRouteCurrentBatch struct {
Index int `json:"index"`
Total int `json:"total"`
EndpointType string `json:"endpoint_type,omitempty"`
ModelCount int `json:"model_count"`
ChannelIDs []int `json:"channel_ids,omitempty"`
ChannelNames []string `json:"channel_names,omitempty"`
ServiceName string `json:"service_name,omitempty"`
Attempt int `json:"attempt,omitempty"`
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
MessageKey string `json:"message_key,omitempty"`
MessageArgs map[string]any `json:"message_args,omitempty"`
}
func (GenerateAIRouteCurrentBatch) TableName ¶
func (GenerateAIRouteCurrentBatch) TableName() string
type GenerateAIRouteProgress ¶
type GenerateAIRouteProgress struct {
ID string `json:"id"`
Scope AIRouteScope `json:"scope,omitempty"`
GroupID int `json:"group_id,omitempty"`
Status AIRouteTaskStatus `json:"status,omitempty"`
CurrentStep AIRouteTaskStep `json:"current_step,omitempty"`
ProgressPercent int `json:"progress_percent"`
TotalBatches int `json:"total_batches"`
CompletedBatches int `json:"completed_batches"`
Done bool `json:"done"`
ResultReady bool `json:"result_ready"`
Message string `json:"message,omitempty"`
MessageKey string `json:"message_key,omitempty"`
MessageArgs map[string]any `json:"message_args,omitempty"`
ErrorReason string `json:"error_reason,omitempty"`
ErrorReasonKey string `json:"error_reason_key,omitempty"`
ErrorReasonArgs map[string]any `json:"error_reason_args,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
HeartbeatAt *time.Time `json:"heartbeat_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
EventSequence int64 `json:"event_sequence"`
Summary *GenerateAIRouteProgressSummary `json:"summary,omitempty"`
CurrentBatch *GenerateAIRouteCurrentBatch `json:"current_batch,omitempty"`
RunningBatches []GenerateAIRouteRunningBatch `json:"running_batches,omitempty"`
Channels []GenerateAIRouteChannelProgress `json:"channels,omitempty"`
Result *GenerateAIRouteResult `json:"result,omitempty"`
}
func (GenerateAIRouteProgress) TableName ¶
func (GenerateAIRouteProgress) TableName() string
type GenerateAIRouteProgressSummary ¶
type GenerateAIRouteProgressSummary struct {
TotalChannels int `json:"total_channels"`
CompletedChannels int `json:"completed_channels"`
RunningChannels int `json:"running_channels"`
PendingChannels int `json:"pending_channels"`
FailedChannels int `json:"failed_channels"`
TotalModels int `json:"total_models"`
CompletedModels int `json:"completed_models"`
}
func (GenerateAIRouteProgressSummary) TableName ¶
func (GenerateAIRouteProgressSummary) TableName() string
type GenerateAIRouteRequest ¶
type GenerateAIRouteRequest struct {
Scope AIRouteScope `json:"scope,omitempty"`
GroupID int `json:"group_id,omitempty"`
}
func (GenerateAIRouteRequest) TableName ¶
func (GenerateAIRouteRequest) TableName() string
func (GenerateAIRouteRequest) Validate ¶
func (req GenerateAIRouteRequest) Validate() error
type GenerateAIRouteResult ¶
type GenerateAIRouteResult struct {
Scope AIRouteScope `json:"scope,omitempty"`
GroupID int `json:"group_id,omitempty"`
GroupCount int `json:"group_count"`
RouteCount int `json:"route_count"`
ItemCount int `json:"item_count"`
}
func (GenerateAIRouteResult) TableName ¶
func (GenerateAIRouteResult) TableName() string
type GenerateAIRouteRunningBatch ¶
type GenerateAIRouteRunningBatch struct {
Index int `json:"index"`
Total int `json:"total"`
EndpointType string `json:"endpoint_type,omitempty"`
ModelCount int `json:"model_count"`
ChannelIDs []int `json:"channel_ids,omitempty"`
ChannelNames []string `json:"channel_names,omitempty"`
ServiceName string `json:"service_name,omitempty"`
Attempt int `json:"attempt,omitempty"`
Status AIRouteBatchStatus `json:"status,omitempty"`
Message string `json:"message,omitempty"`
MessageKey string `json:"message_key,omitempty"`
MessageArgs map[string]any `json:"message_args,omitempty"`
}
func (GenerateAIRouteRunningBatch) TableName ¶
func (GenerateAIRouteRunningBatch) TableName() string
type GotifyConfig ¶
type GotifyConfig struct {
ServerURL string `json:"server_url"` // e.g. https://gotify.example.com
Token string `json:"token"` // application token
Priority int `json:"priority,omitempty"` // message priority (1-10, default 5)
}
GotifyConfig holds the configuration for a Gotify notification channel.
type Group ¶
type Group struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"unique;not null"`
EndpointType string `json:"endpoint_type" gorm:"not null;default:*;index"`
EndpointProvider string `json:"endpoint_provider,omitempty" gorm:"not null;default:''"`
OutboundFormat string `json:"outbound_format,omitempty" gorm:"not null;default:''"` // 出站格式: "" (auto), "chat", "responses", "passthrough"
Mode GroupMode `json:"mode" gorm:"not null"`
MatchRegex string `json:"match_regex"`
FirstTokenTimeOut int `json:"first_token_time_out"` // 单个渠道首个Token响应超时时间(秒)
SessionKeepTime int `json:"session_keep_time"` // 会话保持时间(秒) 0 为禁用
Condition string `json:"condition,omitempty"` // 条件路由 JSON:[{"key":"model","op":"contains","value":"gpt-4"}]
Items []GroupItem `json:"items,omitempty" gorm:"foreignKey:GroupID"`
}
type GroupIDAndLLMName ¶
GroupIDAndLLMName is a DTO for batch operations.
func (GroupIDAndLLMName) TableName ¶
func (GroupIDAndLLMName) TableName() string
TableName explicitly returns "-" for DTO structs to prevent GORM auto-mapping.
type GroupItem ¶
type GroupItem struct {
ID int `json:"id" gorm:"primaryKey"`
GroupID int `json:"group_id" gorm:"not null;index:idx_group_channel_model,unique;constraint:OnDelete:CASCADE"` // 创建时不携带此字段,更新时需要
ChannelID int `json:"channel_id" gorm:"not null;index:idx_group_channel_model,unique"`
ModelName string `json:"model_name" gorm:"not null;index:idx_group_channel_model,unique"`
Priority int `json:"priority"`
Weight int `json:"weight"`
}
type GroupItemAddRequest ¶
type GroupItemAddRequest struct {
ChannelID int `json:"channel_id" binding:"required"`
ModelName string `json:"model_name" binding:"required"`
Priority int `json:"priority,omitempty"`
Weight int `json:"weight,omitempty"`
}
GroupItemAddRequest 新增 item 请求
func (GroupItemAddRequest) TableName ¶
func (GroupItemAddRequest) TableName() string
type GroupItemUpdateRequest ¶
type GroupItemUpdateRequest struct {
ID int `json:"id" binding:"required"`
Priority int `json:"priority,omitempty"`
Weight int `json:"weight,omitempty"`
}
GroupItemUpdateRequest 更新 item 请求
func (GroupItemUpdateRequest) TableName ¶
func (GroupItemUpdateRequest) TableName() string
type GroupModelTestResult ¶
type GroupModelTestResult struct {
ClientID string `json:"client_id,omitempty"`
ItemID int `json:"item_id"`
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
ModelName string `json:"model_name"`
Passed bool `json:"passed"`
Attempts int `json:"attempts"`
StatusCode int `json:"status_code"`
ResponseText string `json:"response_text,omitempty"`
Message string `json:"message,omitempty"`
}
GroupModelTestResult mirrors helper.GroupModelTestResult for JSON persistence.
type GroupTestResult ¶
type GroupTestResult struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement:false"`
GroupName string `json:"group_name" gorm:"size:255;not null;index"`
TotalModels int `json:"total_models" gorm:"not null;default:0"`
PassedModels int `json:"passed_models" gorm:"not null;default:0"`
FailedModels int `json:"failed_models" gorm:"not null;default:0"`
Status GroupTestResultStatus `json:"status" gorm:"size:16;not null;default:'passed';index"`
Results []GroupModelTestResult `json:"results" gorm:"serializer:json"`
Error string `json:"error" gorm:"type:text"`
StartedAt time.Time `json:"started_at" gorm:"not null;index"`
FinishedAt time.Time `json:"finished_at" gorm:"not null"`
}
GroupTestResult stores a completed group model test run for persistence and analytics.
func (GroupTestResult) TableName ¶
func (GroupTestResult) TableName() string
type GroupTestResultStatus ¶
type GroupTestResultStatus string
const ( GroupTestResultPassed GroupTestResultStatus = "passed" GroupTestResultFailed GroupTestResultStatus = "failed" GroupTestResultRunning GroupTestResultStatus = "running" )
type GroupUpdateRequest ¶
type GroupUpdateRequest struct {
ID int `json:"id" binding:"required"`
Name *string `json:"name,omitempty"` // 仅在名称变更时发送
EndpointType *string `json:"endpoint_type,omitempty"` // 仅在 API 分类变更时发送
EndpointProvider *string `json:"endpoint_provider,omitempty"` // 仅在端点提供方变更时发送
OutboundFormat *string `json:"outbound_format,omitempty"` // 仅在出站格式变更时发送
Mode *GroupMode `json:"mode,omitempty"` // 仅在模式变更时发送
MatchRegex *string `json:"match_regex,omitempty"` // 仅在匹配正则变更时发送
Condition *string `json:"condition,omitempty"` // 仅在条件变更时发送
FirstTokenTimeOut *int `json:"first_token_time_out,omitempty"` // 仅在超时变更时发送(秒)
SessionKeepTime *int `json:"session_keep_time,omitempty"` // 仅在会话保持时间变更时发送(秒)
ItemsToAdd []GroupItemAddRequest `json:"items_to_add,omitempty"` // 新增的 items
ItemsToUpdate []GroupItemUpdateRequest `json:"items_to_update,omitempty"` // 更新的 items (priority 变更)
ItemsToDelete []int `json:"items_to_delete,omitempty"` // 删除的 item IDs
}
GroupUpdateRequest 分组更新请求 - 仅包含变更的数据
func (GroupUpdateRequest) TableName ¶
func (GroupUpdateRequest) TableName() string
type HistogramBucket ¶
HistogramBucket is a single bucket in a latency histogram.
type ImageRecord ¶
type ImageRecord struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index;not null"`
Prompt string `json:"prompt" gorm:"type:text;not null;default:''"`
Model string `json:"model" gorm:"type:varchar(128);not null;default:''"`
Size string `json:"size" gorm:"type:varchar(32);not null;default:''"`
APIKeyID int `json:"api_key_id" gorm:"not null;default:0"`
URL string `json:"url" gorm:"type:text;not null;default:''"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
}
ImageRecord stores one generated image for a user (portal image playground history).
URL holds either a remote URL or a "data:image/...;base64,..." data URI. We store whichever the upstream returned so playback works without re-fetching; the trade-off (large base64 payloads inflating the DB) is acceptable for a self-hosted single-user deployment and is bounded by maxRecordsPerUser.
func (ImageRecord) TableName ¶
func (ImageRecord) TableName() string
type InviteCode ¶
type InviteCode struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
Code string `json:"code" gorm:"type:varchar(64);uniqueIndex;not null"`
Used bool `json:"used" gorm:"default:false"`
UsedBy uint `json:"used_by" gorm:"default:0"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UsedAt int64 `json:"used_at" gorm:"bigint;default:0"`
}
func (InviteCode) TableName ¶
func (InviteCode) TableName() string
type LLMChannel ¶
type LLMChannel struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
}
func (LLMChannel) TableName ¶
func (LLMChannel) TableName() string
TableName explicitly returns "-" for DTO structs to prevent GORM auto-mapping.
type LatencyDistribution ¶
type LatencyDistribution struct {
TotalRequests int64 `json:"total_requests"`
AvgMs int64 `json:"avg_ms"`
P50Ms int64 `json:"p50_ms"`
P95Ms int64 `json:"p95_ms"`
P99Ms int64 `json:"p99_ms"`
FtutAvgMs int64 `json:"ftut_avg_ms"`
FtutP50Ms int64 `json:"ftut_p50_ms"`
FtutP95Ms int64 `json:"ftut_p95_ms"`
FtutP99Ms int64 `json:"ftut_p99_ms"`
Buckets []HistogramBucket `json:"buckets"`
}
LatencyDistribution holds latency and FTUT distribution data for a time range.
type ManagedChannelSource ¶
type ManagedChannelSource struct {
SiteID int `json:"site_id"`
SiteAccountID int `json:"site_account_id"`
SiteUserGroupID *int `json:"site_user_group_id,omitempty"`
GroupKey string `json:"group_key"`
}
ManagedChannelSource identifies the origin of a managed channel.
type MatchType ¶
type MatchType string
MatchType defines how the Pattern field is matched against request model names.
type MetAPIImportResult ¶
type MetAPIImportResult struct {
CreatedSites int `json:"created_sites"`
ReusedSites int `json:"reused_sites"`
CreatedAccounts int `json:"created_accounts"`
UpdatedAccounts int `json:"updated_accounts"`
SkippedAccounts int `json:"skipped_accounts"`
ImportedTokens int `json:"imported_tokens"`
ImportedGroups int `json:"imported_groups"`
ImportedModels int `json:"imported_models"`
DisabledModels int `json:"disabled_models"`
Warnings []string `json:"warnings,omitempty"`
}
type ModelCapability ¶
type ModelCapability struct {
Name string `json:"name"`
Endpoints []string `json:"endpoints"`
Conversation bool `json:"conversation"`
Available bool `json:"available"`
}
ModelCapability describes which endpoints a model supports, whether it belongs to the conversation family, and whether it is currently available.
Available 是 WO-028 的实测标记:定时探测连续失败达阈值 → false; 探测关闭或该模型从未探测 → true(回退到探测引入前的行为)。 它从不反映渠道配置(那是路由层的事),也从不影响路由,仅供呈现。
type ModelIdentity ¶
type ModelLatencyItem ¶
type ModelLatencyItem struct {
ModelName string `json:"model_name"`
TotalRequests int64 `json:"total_requests"`
AvgMs int64 `json:"avg_ms"`
P50Ms int64 `json:"p50_ms"`
P95Ms int64 `json:"p95_ms"`
P99Ms int64 `json:"p99_ms"`
}
ModelLatencyItem holds per-model latency statistics.
type ModelMapping ¶
type ModelMapping struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
Name string `json:"name" gorm:"size:255;not null"` // Human-readable name
Pattern string `json:"pattern" gorm:"size:512;not null"` // Match pattern
MatchType MatchType `json:"match_type" gorm:"size:20;not null"` // exact/wildcard/regex
TargetModel string `json:"target_model" gorm:"size:255;not null"` // Model name to rewrite to
Priority int `json:"priority" gorm:"default:0"` // Higher priority matches first
Enabled bool `json:"enabled" gorm:"default:true"` // Whether this mapping is active
ScopeGroupID *int `json:"scope_group_id" gorm:"index"` // Optional: only apply to specific group
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
ModelMapping defines a global rule to rewrite request model names before they are resolved to upstream channels.
type ModelMappingCreateRequest ¶
type ModelMappingCreateRequest struct {
Name string `json:"name" binding:"required"`
Pattern string `json:"pattern" binding:"required"`
MatchType MatchType `json:"match_type" binding:"required"`
TargetModel string `json:"target_model" binding:"required"`
Priority int `json:"priority"`
Enabled *bool `json:"enabled"`
ScopeGroupID *int `json:"scope_group_id"`
}
ModelMappingCreateRequest is the payload for creating a new model mapping.
func (ModelMappingCreateRequest) TableName ¶
func (ModelMappingCreateRequest) TableName() string
type ModelMappingUpdateRequest ¶
type ModelMappingUpdateRequest struct {
Name *string `json:"name"`
Pattern *string `json:"pattern"`
MatchType *MatchType `json:"match_type"`
TargetModel *string `json:"target_model"`
Priority *int `json:"priority"`
Enabled *bool `json:"enabled"`
ScopeGroupID *int `json:"scope_group_id"`
}
ModelMappingUpdateRequest is the payload for updating an existing model mapping.
func (ModelMappingUpdateRequest) TableName ¶
func (ModelMappingUpdateRequest) TableName() string
type ModelMarketChannel ¶
type ModelMarketChannel struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
Enabled bool `json:"enabled"`
EnabledKeyCount int `json:"enabled_key_count"`
}
func (ModelMarketChannel) TableName ¶
func (ModelMarketChannel) TableName() string
type ModelMarketItem ¶
type ModelMarketItem struct {
Name string `json:"name"`
// DisplayName carries the upstream spelling of the model (e.g.
// "Qwen/Qwen3-8B") while Name stays the lowercased registry key that
// update/delete mutations are addressed by. Empty when no channel
// advertises the model, in which case the UI falls back to Name.
DisplayName string `json:"display_name"`
Input float64 `json:"input"`
Output float64 `json:"output"`
CacheRead float64 `json:"cache_read"`
CacheWrite float64 `json:"cache_write"`
ChannelCount int `json:"channel_count"`
EnabledKeyCount int `json:"enabled_key_count"`
AverageLatencyMS int64 `json:"average_latency_ms"`
SuccessRate float64 `json:"success_rate"`
RequestSuccess int64 `json:"request_success"`
RequestFailed int64 `json:"request_failed"`
Channels []ModelMarketChannel `json:"channels"`
// ProbeFailedAt 由定时探测任务回灌(WO-028):连续失败达到阈值时为最近一次
// 探测失败的时刻,nil = 从未探测或当前健康。呈现层专用,不影响路由。
//
// ★ 必须是指针。`omitempty` 对非指针 time.Time 无效(结构体永远不算 empty),
// 早先的 `time.Time` 版本让每个健康模型都序列化出
// `"probe_failed_at":"0001-01-01T00:00:00Z"`,而前端判的是 truthiness
// (index.tsx / Item.tsx / MobileModelItem.tsx),非空字符串为真 → 广场默认
// 视图把**全部**模型判为探测失败并隐藏,横幅还报出"N 个模型连续探测失败"。
// 生产实测:探测开关为 false、model_probe_states 零行(从未探测),
// 却有 94 个模型被隐藏,含真实出活过的 Qwen3-Max。
// 本 struct 的 TableName() 返回 "-"(纯响应体,不落库),故改指针无需迁移。
ProbeFailedAt *time.Time `json:"probe_failed_at,omitempty"`
}
func (ModelMarketItem) TableName ¶
func (ModelMarketItem) TableName() string
type ModelMarketResponse ¶
type ModelMarketResponse struct {
Summary ModelMarketSummary `json:"summary"`
Items []ModelMarketItem `json:"items"`
}
func (ModelMarketResponse) TableName ¶
func (ModelMarketResponse) TableName() string
type ModelMarketSummary ¶
type ModelMarketSummary struct {
ModelCount int `json:"model_count"`
CoverageCount int `json:"coverage_count"`
UniqueChannelCount int `json:"unique_channel_count"`
AverageLatencyMS int64 `json:"average_latency_ms"`
LastUpdateTime time.Time `json:"last_update_time"`
}
func (ModelMarketSummary) TableName ¶
func (ModelMarketSummary) TableName() string
type ModelPriceCategory ¶
type ModelPriceCategory struct {
ID uint `json:"id" gorm:"primaryKey;autoIncrement"`
Name string `json:"name" gorm:"size:191;not null;uniqueIndex"`
RuleType string `json:"rule_type" gorm:"size:32;not null;default:'contains'"`
RuleValue string `json:"rule_value" gorm:"size:191;not null"`
LLMPrice
// SortOrder 越小越优先匹配。
SortOrder int `json:"sort_order" gorm:"not null;default:0;index"`
Enabled bool `json:"enabled" gorm:"not null"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
ModelPriceCategory 模型价格分类:为未匹配到精确价格的模型提供按规则的兜底定价。 当模型名在 DB(LLMInfo) 和内置 presets 都未命中时,price.GetLLMPrice 会按 sort_order 升序遍历启用的分类,命中第一条规则的分类用其 LLMPrice 作为兜底价 (优先于原有的整词子串启发式兜底)。
type ModelProbeState ¶
type ModelProbeState struct {
GroupName string `json:"group_name" gorm:"primaryKey;size:255"`
ConsecutiveFailures int `json:"consecutive_failures" gorm:"not null;default:0"`
LastProbedAt time.Time `json:"last_probed_at"`
LastNotifiedFails int `json:"last_notified_fails" gorm:"not null;default:0"`
UpdatedAt time.Time `json:"updated_at"`
}
ModelProbeState 记录每个分组(= 模型广场里的一个模型)跨轮次的探测结果。
分组名是主键:本系统里"模型广场的一个模型"就是一个分组(GroupListModelCapabilities 按分组名聚合),探测按分组跑,隐藏/通知也按分组判定。
为什么不直接查 group_test_results 历史:连续失败计数是状态不是日志,重启后必须 保留(否则重启就永远凑不满阈值),跨轮递增/重置也要单行原子更新,独立一行最省心。 计数在探测成功时归零(对称性),通知去重靠 LastNotifiedFails(同一失败episode 只通知一次,发送失败下一轮自动重试)。
func (ModelProbeState) TableName ¶
func (ModelProbeState) TableName() string
type NtfyConfig ¶
type NtfyConfig struct {
TopicURL string `json:"topic_url"` // e.g. "https://ntfy.sh/mytopic" or just "mytopic"
AccessToken string `json:"access_token,omitempty"` // optional Bearer token
}
NtfyConfig holds the configuration for an ntfy push notification channel.
type OAuthBinding ¶
type OAuthBinding struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index;not null" json:"user_id"`
Provider string `gorm:"type:varchar(32);index;not null" json:"provider"` // e.g. "github"
ProviderUserID string `gorm:"type:varchar(128);not null" json:"provider_user_id"` // stable numeric ID from provider
ProviderUsername string `gorm:"type:varchar(128)" json:"provider_username"` // display-only login name
CreatedAt time.Time `json:"created_at"`
}
OAuthBinding stores the link between a local user and an external OAuth provider (e.g. GitHub). Using a separate table keeps the User model clean and is easily extensible to other providers later.
func (OAuthBinding) TableName ¶
func (OAuthBinding) TableName() string
type OpenAIModel ¶
type OpenAIModel struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
OwnedBy string `json:"owned_by"`
}
func (OpenAIModel) TableName ¶
func (OpenAIModel) TableName() string
type OpenAIModelList ¶
type OpenAIModelList struct {
Object string `json:"object"`
Data []OpenAIModel `json:"data"`
}
func (OpenAIModelList) TableName ¶
func (OpenAIModelList) TableName() string
type OpsCacheStatus ¶
type OpsCacheStatus struct {
Enabled bool `json:"enabled"`
RuntimeEnabled bool `json:"runtime_enabled"`
TTLSeconds int `json:"ttl_seconds"`
Threshold int `json:"threshold"`
MaxEntries int `json:"max_entries"`
CurrentEntries int `json:"current_entries"`
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
HitRate float64 `json:"hit_rate"`
UsageRate float64 `json:"usage_rate"`
ProviderPromptCache OpsProviderPromptCacheSummary `json:"provider_prompt_cache"`
}
type OpsHealthGroupItem ¶
type OpsHealthStatus ¶
type OpsHealthStatus struct {
DatabaseOK bool `json:"database_ok"`
CacheOK bool `json:"cache_ok"`
TaskRuntimeOK bool `json:"task_runtime_ok"`
RecentErrorCount int64 `json:"recent_error_count"`
HealthyGroupCount int `json:"healthy_group_count"`
WarningGroupCount int `json:"warning_group_count"`
DegradedGroupCount int `json:"degraded_group_count"`
DownGroupCount int `json:"down_group_count"`
EmptyGroupCount int `json:"empty_group_count"`
FailingGroups []OpsHealthGroupItem `json:"failing_groups"`
CheckedAt int64 `json:"checked_at"`
}
type OpsProviderPromptCacheProviderItem ¶
type OpsProviderPromptCacheProviderItem struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
RequestCount int64 `json:"request_count"`
CachedRequestCount int64 `json:"cached_request_count"`
CacheRate float64 `json:"cache_rate"`
CacheReuseRatio float64 `json:"cache_reuse_ratio"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
EstimatedCostSaved float64 `json:"estimated_cost_saved"`
}
type OpsProviderPromptCacheSummary ¶
type OpsProviderPromptCacheSummary struct {
RequestCount int64 `json:"request_count"`
CachedRequestCount int64 `json:"cached_request_count"`
CacheRate float64 `json:"cache_rate"`
CacheReuseRatio float64 `json:"cache_reuse_ratio"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
EstimatedCostSaved float64 `json:"estimated_cost_saved"`
UsageSignalAvailable bool `json:"usage_signal_available"`
SampledLogCount int64 `json:"sampled_log_count"`
ParsedLogCount int64 `json:"parsed_log_count"`
Providers []OpsProviderPromptCacheProviderItem `json:"providers"`
Trend []OpsProviderPromptCacheTrendPoint `json:"trend"`
}
type OpsProviderPromptCacheTrendPoint ¶
type OpsProviderPromptCacheTrendPoint struct {
Timestamp int64 `json:"timestamp"`
RequestCount int64 `json:"request_count"`
CachedRequestCount int64 `json:"cached_request_count"`
CacheRate float64 `json:"cache_rate"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
EstimatedCostSaved float64 `json:"estimated_cost_saved"`
}
type OpsQuotaKeyItem ¶
type OpsQuotaKeyItem struct {
APIKeyID int `json:"api_key_id"`
Name string `json:"name"`
Enabled bool `json:"enabled"`
Expired bool `json:"expired"`
Status string `json:"status"`
SupportedModelCount int `json:"supported_model_count"`
HasPerModelQuota bool `json:"has_per_model_quota"`
RateLimitRPM int `json:"rate_limit_rpm"`
RateLimitTPM int `json:"rate_limit_tpm"`
MaxCost float64 `json:"max_cost"`
RequestCount int64 `json:"request_count"`
TotalCost float64 `json:"total_cost"`
}
type OpsQuotaSummary ¶
type OpsQuotaSummary struct {
TotalKeyCount int `json:"total_key_count"`
EnabledKeyCount int `json:"enabled_key_count"`
AvailableKeyCount int `json:"available_key_count"`
ExpiredKeyCount int `json:"expired_key_count"`
LimitedKeyCount int `json:"limited_key_count"`
UnlimitedKeyCount int `json:"unlimited_key_count"`
ExhaustedKeyCount int `json:"exhausted_key_count"`
PerModelQuotaKeyCount int `json:"per_model_quota_key_count"`
ActiveUsageKeyCount int `json:"active_usage_key_count"`
TotalRPM int `json:"total_rpm"`
TotalTPM int `json:"total_tpm"`
TotalMaxCost float64 `json:"total_max_cost"`
Keys []OpsQuotaKeyItem `json:"keys"`
}
type OpsSystemSummary ¶
type OpsSystemSummary struct {
Version string `json:"version"`
Commit string `json:"commit"`
BuildTime string `json:"build_time"`
Repo string `json:"repo"`
DatabaseType string `json:"database_type"`
RedisStatus string `json:"redis_status"`
PublicAPIBaseURL string `json:"public_api_base_url"`
ProxyURL string `json:"proxy_url"`
RelayLogKeepEnabled bool `json:"relay_log_keep_enabled"`
RelayLogKeepDays int `json:"relay_log_keep_days"`
RelayLogKeepCount int `json:"relay_log_keep_count"`
StatsSaveIntervalMinutes int `json:"stats_save_interval_minutes"`
SyncLLMIntervalHours int `json:"sync_llm_interval_hours"`
ModelInfoUpdateIntervalHours int `json:"model_info_update_interval_hours"`
ImportEnabled bool `json:"import_enabled"`
ExportEnabled bool `json:"export_enabled"`
AIRouteGroupID int `json:"ai_route_group_id"`
AIRouteTimeoutSeconds int `json:"ai_route_timeout_seconds"`
AIRouteParallelism int `json:"ai_route_parallelism"`
AIRouteLegacyMode bool `json:"ai_route_legacy_mode"`
AIRouteServiceCount int `json:"ai_route_service_count"`
AIRouteEnabledServiceCount int `json:"ai_route_enabled_service_count"`
AIRouteServices []OpsAIRouteServiceSummary `json:"ai_route_services"`
ChannelCount int `json:"channel_count"`
GroupCount int `json:"group_count"`
APIKeyCount int `json:"api_key_count"`
}
type OpsTelemetryHeroMetrics ¶
type OpsTelemetryHeroMetrics struct {
UptimeSeconds int64 `json:"uptime_seconds"`
TotalRequests int64 `json:"total_requests"`
AvgLatencyMs float64 `json:"avg_latency_ms"`
ErrorRate float64 `json:"error_rate"`
ActiveConnections int64 `json:"active_connections"`
MemoryUsageMB int64 `json:"memory_usage_mb"`
}
type OpsTelemetryPromptCache ¶
type OpsTelemetryProviderHealth ¶
type OpsTelemetryProviderHealth struct {
Providers []OpsTelemetryProviderItem `json:"providers"`
Active int `json:"active"`
Monitored int `json:"monitored"`
}
type OpsTelemetryProviderItem ¶
type OpsTelemetryProviderItem struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
Enabled bool `json:"enabled"`
BaseURL string `json:"base_url"`
RequestCount int64 `json:"request_count"`
SuccessRate float64 `json:"success_rate"`
AverageLatencyMs float64 `json:"average_latency_ms"`
HealthStatus string `json:"health_status"`
HealthHint string `json:"health_hint"`
Sparkline7d []float64 `json:"sparkline_7d,omitempty"`
Sparkline30d []float64 `json:"sparkline_30d,omitempty"`
}
type OpsTelemetryRuntimeSignals ¶
type OpsTelemetryRuntimeSignals struct {
P95LatencyMs float64 `json:"p95_latency_ms"`
ThroughputRPS float64 `json:"throughput_rps"`
MemoryMB int64 `json:"memory_mb"`
TrendSnapshots []OpsTelemetryTrendPoint `json:"trend_snapshots"`
}
type OpsTelemetrySummary ¶
type OpsTelemetrySummary struct {
Hero OpsTelemetryHeroMetrics `json:"hero"`
RuntimeSignals OpsTelemetryRuntimeSignals `json:"runtime_signals"`
DatabaseHealth OpsTelemetryDatabaseHealth `json:"database_health"`
SessionQuotaActivity OpsTelemetrySessionQuotaActivity `json:"session_quota_activity"`
PromptCache OpsTelemetryPromptCache `json:"prompt_cache"`
ProviderHealth OpsTelemetryProviderHealth `json:"provider_health"`
DrilldownShortcuts []OpsTelemetryDrilldownShortcut `json:"drilldown_shortcuts"`
}
type OpsTelemetryTrendPoint ¶
type PaymentOrder ¶
type PaymentOrder struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index;not null"`
AmountUSD float64 `json:"amount_usd" gorm:"type:double precision;not null"` // credit added to balance on success
Money float64 `json:"money" gorm:"type:double precision"` // amount actually paid (gateway currency)
TradeNo string `json:"trade_no" gorm:"type:varchar(128);uniqueIndex;not null"`
Method string `json:"method" gorm:"type:varchar(32)"` // alipay / wxpay
Provider string `json:"provider" gorm:"type:varchar(32);default:'epay'"`
Status string `json:"status" gorm:"type:varchar(16);default:'pending'"` // pending / success
CreateTime int64 `json:"create_time" gorm:"bigint"`
CompleteTime int64 `json:"complete_time" gorm:"bigint;default:0"`
}
func (PaymentOrder) TableName ¶
func (PaymentOrder) TableName() string
type PriceCategoryRule ¶
type PriceCategoryRule string
PriceCategoryRule 分类规则类型。 命中语义(modelName 由 price.GetLLMPrice 统一小写后传入):
- exact: 模型名与 rule_value 完全相等(忽略大小写)
- prefix: 模型名以 rule_value 为前缀
- contains: 模型名包含 rule_value 子串
const ( PriceCategoryRuleExact PriceCategoryRule = "exact" PriceCategoryRulePrefix PriceCategoryRule = "prefix" PriceCategoryRuleContains PriceCategoryRule = "contains" )
type ProxyConfiguration ¶
type ProxyConfiguration struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"unique;not null"`
URL string `json:"url" gorm:"unique;not null"`
Enabled bool `json:"enabled" gorm:"default:true"`
Remark string `json:"remark"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ReferenceCount int `json:"reference_count" gorm:"-"`
}
func (*ProxyConfiguration) Normalize ¶
func (p *ProxyConfiguration) Normalize() error
func (*ProxyConfiguration) Validate ¶
func (p *ProxyConfiguration) Validate() error
type ProxyConfigurationReference ¶
type ProxyConfigurationReference struct {
Type ProxyConfigurationReferenceType `json:"type"`
SiteID int `json:"site_id,omitempty"`
SiteName string `json:"site_name,omitempty"`
SiteArchived bool `json:"site_archived,omitempty"`
SiteAccountID int `json:"site_account_id,omitempty"`
SiteAccountName string `json:"site_account_name,omitempty"`
ChannelID int `json:"channel_id,omitempty"`
ChannelName string `json:"channel_name,omitempty"`
Managed bool `json:"managed,omitempty"`
ManagedSource *ManagedChannelSource `json:"managed_source,omitempty"`
}
type ProxyConfigurationReferenceType ¶
type ProxyConfigurationReferenceType string
const ( ProxyConfigurationReferenceTypeSite ProxyConfigurationReferenceType = "site" ProxyConfigurationReferenceTypeSiteAccount ProxyConfigurationReferenceType = "site_account" ProxyConfigurationReferenceTypeChannel ProxyConfigurationReferenceType = "channel" ProxyConfigurationReferenceTypeManagedChannel ProxyConfigurationReferenceType = "managed_channel" )
type ProxyTestRequest ¶
type ProxyTestResult ¶
type ProxyUsageMode ¶
type ProxyUsageMode string
const ( ProxyUsageModeDirect ProxyUsageMode = "direct" ProxyUsageModeSystem ProxyUsageMode = "system" ProxyUsageModePool ProxyUsageMode = "pool" ProxyUsageModeInherit ProxyUsageMode = "inherit" )
func (ProxyUsageMode) Validate ¶
func (m ProxyUsageMode) Validate(allowInherit bool) error
type QuotaLedger ¶
type QuotaLedger struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index;not null"`
Delta float64 `json:"delta" gorm:"type:double precision;not null"` // 有符号:+ 入账,− 出账
Kind string `json:"kind" gorm:"type:varchar(32);index;not null"`
RefType string `json:"ref_type" gorm:"type:varchar(32)"` // 关联单据类型,可空
RefID string `json:"ref_id" gorm:"type:varchar(64);index"`
// ActorID 是**操作者**,不是受益人。管理员调整时填管理员的 user_id;
// 网关回调 / 系统开账填 0。把它填成受益人等于审计失效。
ActorID uint `json:"actor_id" gorm:"index"`
Reason string `json:"reason" gorm:"type:varchar(255)"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index;autoCreateTime"`
}
QuotaLedger 是一条不可变的余额变动记录。写入后不应被 UPDATE。
func (QuotaLedger) TableName ¶
func (QuotaLedger) TableName() string
type RedemptionBatchResult ¶
type RedemptionBatchResult struct {
TotalCodes int `json:"total_codes"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
Results []RedemptionRecord `json:"results"`
}
RedemptionBatchResult aggregates the outcome of redeeming multiple codes.
type RedemptionRecord ¶
type RedemptionRecord struct {
ID int64 `json:"id" gorm:"primaryKey"`
RemoteSiteID int `json:"remote_site_id" gorm:"not null;index"`
Code string `json:"code" gorm:"not null;size:255"`
Status string `json:"status"` // success, already_used, invalid, failed
QuotaAwarded float64 `json:"quota_awarded"`
Message string `json:"message"`
ExecutedAt time.Time `json:"executed_at"`
}
RedemptionRecord stores the result of a redemption code attempt for a remote site.
type RedemptionRequest ¶
type RedemptionRequest struct {
SiteID int `json:"site_id" binding:"required"`
Codes []string `json:"codes" binding:"required"`
}
RedemptionRequest is the payload for redeeming codes on a remote site.
type RelayLog ¶
type RelayLog struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement:false"` // Snowflake ID
Time int64 `json:"time" gorm:"column:time;index:idx_relay_logs_time"` // 时间戳(秒)
RequestModelName string `json:"request_model_name" gorm:"column:request_model_name"` // 请求模型名称
RequestAPIKeyID int `json:"request_api_key_id" gorm:"column:request_api_key_id"` // 请求使用的 API Key ID
RequestAPIKeyName string `json:"request_api_key_name" gorm:"column:request_api_key_name"` // 请求使用的 API Key 名称
ClientIP string `json:"client_ip" gorm:"column:client_ip"` // 客户端 IP
EndpointType string `json:"endpoint_type" gorm:"column:endpoint_type"` // 命中的端点分类
ChannelId int `json:"channel" gorm:"column:channel_id"` // 实际使用的渠道ID
ChannelName string `json:"channel_name" gorm:"column:channel_name"` // 渠道名称
ActualModelName string `json:"actual_model_name" gorm:"column:actual_model_name"` // 实际使用模型名称
InputTokens int `json:"input_tokens" gorm:"column:input_tokens"` // 输入Token
OutputTokens int `json:"output_tokens" gorm:"column:output_tokens"` // 输出 Token
SemanticCacheHit bool `json:"semantic_cache_hit" gorm:"column:semantic_cache_hit"` // 语义缓存命中(写入时落库,避免列表查询重解析大字段)
CacheReadTokens int `json:"cache_read_tokens" gorm:"column:cache_read_tokens"` // 提供方提示缓存命中 Token(写入时落库)
Ftut int `json:"ftut" gorm:"column:ftut"` // 首字时间(毫秒)
UseTime int `json:"use_time" gorm:"column:use_time"` // 总用时(毫秒)
Cost float64 `json:"cost" gorm:"column:cost"` // 消耗费用
RequestContent string `json:"request_content" gorm:"column:request_content"` // 请求内容
ResponseContent string `json:"response_content" gorm:"column:response_content"` // 响应内容
Error string `json:"error" gorm:"column:error"` // 错误信息
Attempts []ChannelAttempt `json:"attempts" gorm:"column:attempts;serializer:json"` // 所有尝试记录
TotalAttempts int `json:"total_attempts" gorm:"column:total_attempts"` // 总尝试次数
IsTest bool `json:"is_test" gorm:"column:is_test;default:false"` // 是否为测试请求日志(issue #82)
}
func (*RelayLog) ToListItem ¶
func (r *RelayLog) ToListItem() RelayLogListItem
ToListItem 将完整的 RelayLog 转换为轻量的列表条目
type RelayLogAttempt ¶
type RelayLogAttempt struct {
ID int64 `json:"id" gorm:"primaryKey;autoIncrement"`
RelayLogID int64 `` /* 134-byte string literal not displayed */
ChannelID int `` /* 139-byte string literal not displayed */
ChannelName string `json:"channel_name" gorm:"column:channel_name"`
ModelName string `json:"model_name" gorm:"column:model_name;index:idx_rla_chan_model_time,priority:2"`
Status string `json:"status" gorm:"column:status;index:idx_rla_log_status,priority:2"` // success | failed | circuit_break | skipped
Duration int `json:"duration" gorm:"column:duration"`
Time int64 `json:"time" gorm:"column:time;index:idx_rla_time;index:idx_rla_chan_model_time,priority:3"`
}
RelayLogAttempt 是 relay_log_attempts 关联表的一行,把单次渠道尝试从 RelayLog.Attempts JSON 数组中抽出为可索引行。这样"渠道A 失败 → 重试到渠道B 成功"的请求中,渠道A 的失败 才能被按 channel_id 过滤/聚合(issue #67)。Time 取自所属 RelayLog 的完成时间, 用于窗口聚合。仅对修复部署后的新请求生效,不回填历史日志。
func (RelayLogAttempt) TableName ¶
func (RelayLogAttempt) TableName() string
type RelayLogListItem ¶
type RelayLogListItem struct {
ID int64 `json:"id" gorm:"column:id"`
Time int64 `json:"time" gorm:"column:time;index:idx_relay_logs_time"`
RequestModelName string `json:"request_model_name" gorm:"column:request_model_name"`
RequestAPIKeyID int `json:"request_api_key_id" gorm:"column:request_api_key_id"`
RequestAPIKeyName string `json:"request_api_key_name" gorm:"column:request_api_key_name"`
ClientIP string `json:"client_ip" gorm:"column:client_ip"`
EndpointType string `json:"endpoint_type" gorm:"column:endpoint_type"`
ChannelId int `json:"channel" gorm:"column:channel_id"`
ChannelName string `json:"channel_name" gorm:"column:channel_name"`
ActualModelName string `json:"actual_model_name" gorm:"column:actual_model_name"`
InputTokens int `json:"input_tokens" gorm:"column:input_tokens"`
OutputTokens int `json:"output_tokens" gorm:"column:output_tokens"`
SemanticCacheHit bool `json:"semantic_cache_hit" gorm:"column:semantic_cache_hit"`
CacheReadTokens int `json:"cache_read_tokens" gorm:"column:cache_read_tokens"`
Ftut int `json:"ftut" gorm:"column:ftut"`
UseTime int `json:"use_time" gorm:"column:use_time"`
Cost float64 `json:"cost" gorm:"column:cost"`
Error string `json:"error" gorm:"column:error"`
Attempts []ChannelAttempt `json:"attempts" gorm:"column:attempts;serializer:json"`
TotalAttempts int `json:"total_attempts" gorm:"column:total_attempts"`
IsTest bool `json:"is_test" gorm:"column:is_test;default:false"` // 是否为测试请求日志(issue #82)
}
RelayLogListItem 日志列表轻量条目,排除了 RequestContent 和 ResponseContent 大字段
func (RelayLogListItem) TableName ¶
func (RelayLogListItem) TableName() string
TableName 指定 RelayLogListItem 使用与 RelayLog 相同的数据库表
type RequestRewriteConfig ¶
type RequestRewriteConfig struct {
Enabled bool `json:"enabled"`
Profile RequestRewriteProfile `json:"profile,omitempty"`
ToolRoleStrategy ToolRoleStrategy `json:"tool_role_strategy,omitempty"`
SystemMessageStrategy SystemMessageStrategy `json:"system_message_strategy,omitempty"`
HeaderProfile string `json:"header_profile,omitempty"`
}
func (*RequestRewriteConfig) Validate ¶
func (c *RequestRewriteConfig) Validate(channelType outbound.OutboundType) error
type RequestRewriteProfile ¶
type RequestRewriteProfile string
const ( RequestRewriteProfilePreserve RequestRewriteProfile = "preserve" RequestRewriteProfileOpenAIChatCompat RequestRewriteProfile = "openai_chat_compat" RequestRewriteProfileCodexHeaders RequestRewriteProfile = "codex" )
type SemanticCacheEvaluationSummary ¶
type SemanticCacheEvaluationSummary struct {
Enabled bool `json:"enabled"`
RuntimeEnabled bool `json:"runtime_enabled"`
TTLSeconds int `json:"ttl_seconds"`
Threshold int `json:"threshold"`
MaxEntries int `json:"max_entries"`
CurrentEntries int `json:"current_entries"`
Hits int64 `json:"hits"`
Misses int64 `json:"misses"`
HitRate float64 `json:"hit_rate"`
UsageRate float64 `json:"usage_rate"`
EvaluatedRequests int64 `json:"evaluated_requests"`
CacheHitResponses int64 `json:"cache_hit_responses"`
CacheMissRequests int64 `json:"cache_miss_requests"`
BypassedRequests int64 `json:"bypassed_requests"`
StoredResponses int64 `json:"stored_responses"`
}
type Setting ¶
type Setting struct {
Key SettingKey `json:"key" gorm:"primaryKey"`
Value string `json:"value" gorm:"not null"`
}
func DefaultSettings ¶
func DefaultSettings() []Setting
type SettingKey ¶
type SettingKey string
const ( SettingKeyProxyURL SettingKey = "proxy_url" SettingKeyStatsSaveInterval SettingKey = "stats_save_interval" // 将统计信息写入数据库的周期(分钟) SettingKeyModelInfoUpdateInterval SettingKey = "model_info_update_interval" // 模型信息更新间隔(小时) SettingKeySyncLLMInterval SettingKey = "sync_llm_interval" // LLM 同步间隔(小时) SettingKeyRelayLogKeepPeriod SettingKey = "relay_log_keep_period" // 日志保存时间范围(天) SettingKeyRelayLogKeepCount SettingKey = "relay_log_keep_count" // 日志保留条数(0=不按条数) SettingKeyRelayLogKeepEnabled SettingKey = "relay_log_keep_enabled" // 是否保留历史日志 SettingKeyCORSAllowOrigins SettingKey = "cors_allow_origins" // 跨域白名单(逗号分隔, 如 "example.com,example2.com"). 为空不允许跨域, "*"允许所有 SettingKeyRelayRetryCount SettingKey = "relay_retry_count" // 单个候选渠道内 Key 级最大重试次数 SettingKeyRelayRouteRetries SettingKey = "relay_route_retries" // 路由级最大重试次数(全部渠道遍历一轮算一次) SettingKeyCircuitBreakerThreshold SettingKey = "circuit_breaker_threshold" // 熔断触发阈值(连续失败次数) SettingKeyCircuitBreakerCooldown SettingKey = "circuit_breaker_cooldown" // 熔断基础冷却时间(秒) SettingKeyCircuitBreakerMaxCooldown SettingKey = "circuit_breaker_max_cooldown" // 熔断最大冷却时间(秒),指数退避上限 SettingKeyPublicAPIBaseURL SettingKey = "public_api_base_url" // 对外可访问的 API 基础地址,用于生成示例 SettingKeyAlertNotifyLanguage SettingKey = "alert_notify_language" // 告警通知发送语言 SettingKeyRatelimitCooldown SettingKey = "ratelimit_cooldown" // Key 错误冷却时间(秒),0=关闭 SettingKeyRelayMaxTotalAttempts SettingKey = "relay_max_total_attempts" // 所有候选渠道的最大总尝试次数,0 表示不限制 SettingKeyRateLimitHoldEnabled SettingKey = "rate_limit_hold_enabled" // 429 限流时是否在当前渠道内延时重试(默认关闭,保持立即换 Key/渠道) SettingKeyRateLimitHoldInterval SettingKey = "rate_limit_hold_interval" // 429 渠道内延时重试间隔(秒) SettingKeyRateLimitHoldMaxWait SettingKey = "rate_limit_hold_max_wait" // 429 渠道内延时重试总等待上限(秒),超过后换下一渠道 SettingKeyAutoStrategyMinSamples SettingKey = "auto_strategy_min_samples" // Auto策略最小样本数阈值 SettingKeyAutoStrategyTimeWindow SettingKey = "auto_strategy_time_window" // Auto策略时间窗口(秒) SettingKeyAutoStrategySampleThreshold SettingKey = "auto_strategy_sample_threshold" // Auto策略滑动窗口大小 SettingKeyAutoStrategyLatencyWeight SettingKey = "auto_strategy_latency_weight" // Auto策略延迟权重(0-100) SettingKeySemanticCacheEnabled SettingKey = "semantic_cache_enabled" // 语义缓存开关 SettingKeySemanticCacheTTL SettingKey = "semantic_cache_ttl" // 语义缓存 TTL(秒) SettingKeySemanticCacheThreshold SettingKey = "semantic_cache_threshold" // 语义缓存相似度阈值(0-1) SettingKeySemanticCacheMaxEntries SettingKey = "semantic_cache_max_entries" // 语义缓存最大条目数 SettingKeySemanticCacheEmbeddingBaseURL SettingKey = "semantic_cache_embedding_base_url" // 语义缓存 embedding 服务 Base URL SettingKeySemanticCacheEmbeddingAPIKey SettingKey = "semantic_cache_embedding_api_key" // 语义缓存 embedding 服务 API Key SettingKeySemanticCacheEmbeddingModel SettingKey = "semantic_cache_embedding_model" // 语义缓存 embedding 模型名称 SettingKeySemanticCacheEmbeddingTimeoutSeconds SettingKey = "semantic_cache_embedding_timeout_seconds" // 语义缓存 embedding 请求超时(秒) SettingKeyAIRouteGroupID SettingKey = "ai_route_group_id" // AI路由目标分组 ID SettingKeyAIRouteBaseURL SettingKey = "ai_route_base_url" // AI路由分析服务 Base URL SettingKeyAIRouteAPIKey SettingKey = "ai_route_api_key" // AI路由分析服务 API Key SettingKeyAIRouteModel SettingKey = "ai_route_model" // AI路由分析模型名称 SettingKeyAIRouteTimeoutSeconds SettingKey = "ai_route_timeout_seconds" // AI路由分析单次请求超时(秒) SettingKeyAIRouteParallelism SettingKey = "ai_route_parallelism" // AI路由分析批次最大并发数 SettingKeyAIRouteServices SettingKey = "ai_route_services" // AI路由分析服务池(JSON) SettingKeyStatsTimezoneOffset SettingKey = "stats_timezone_offset" // 统计时区偏移(小时),当前为整型偏移;未来计划新增 stats_timezone (IANA) 配置项,此处为定义与校验入口 SettingKeyJWTDefaultExpiryMinutes SettingKey = "jwt_default_expiry_minutes" // 默认JWT过期时间(分钟) SettingKeyJWTRememberMeExpiryDays SettingKey = "jwt_remember_me_expiry_days" // 记住我JWT过期时间(天) SettingKeyLoginRateLimitWindow SettingKey = "login_rate_limit_window" // 登录限流时间窗口(分钟) SettingKeyLoginRateLimitMaxFailed SettingKey = "login_rate_limit_max_failed" // 登录限流最大失败次数 SettingKeyStreamSessionTTLMinutes SettingKey = "stream_session_ttl_minutes" // 流会话TTL(分钟) SettingKeyStreamSessionMaxEvents SettingKey = "stream_session_max_events" // 流会话最大事件数 SettingKeyStreamSessionMaxBytesMB SettingKey = "stream_session_max_bytes_mb" // 流会话最大字节数(MB) SettingKeyNotifyHTTPTimeoutSeconds SettingKey = "notify_http_timeout_seconds" // 通知HTTP请求超时(秒) SettingKeyFailureHintTTLRateLimit SettingKey = "failure_hint_ttl_rate_limit" // 限流失败提示缓存TTL(秒) SettingKeyFailureHintTTLNetwork SettingKey = "failure_hint_ttl_network" // 网络失败提示缓存TTL(秒) SettingKeyWebDAVConfig SettingKey = "webdav_config" // WebDAV 云备份配置(JSON) SettingKeySiteSyncInterval SettingKey = "site_sync_interval" // 站点账号同步间隔(小时) SettingKeySiteCheckinInterval SettingKey = "site_checkin_interval" // 站点自动签到间隔(小时) SettingKeyStatsSiteModelBackfilled SettingKey = "stats_site_model_backfilled" // 站点模型统计回填标记 SettingKeyProjectedChannelAutoGroupEnabled SettingKey = "projected_channel_auto_group_enabled" // 站点投影渠道自动分组全局开关 SettingKeyResponseFilterEnabled SettingKey = "response_filter_enabled" // 输出结果关键词拦截开关 SettingKeyResponseFilterKeywords SettingKey = "response_filter_keywords" // 拦截关键词列表(JSON 数组) SettingKeyResponseFilterAction SettingKey = "response_filter_action" // 拦截动作: block(阻断) / replace(替换为*) SettingKeyResponseFilterErrorMessage SettingKey = "response_filter_error_message" // 阻断时返回的错误信息 SettingKeyLogLevel SettingKey = "log_level" // 应用日志级别: debug, info, warn, error SettingKeyLogExcludedGroups SettingKey = "log_excluded_groups" // 在日志列表/实时流中屏蔽的分组名称列表(JSON 数组) SettingKeyWebAuthnRPID SettingKey = "webauthn_rp_id" // WebAuthn RP ID(域名,不含协议/端口) SettingKeyWebAuthnRPName SettingKey = "webauthn_rp_name" // WebAuthn RP 展示名 SettingKeyWebAuthnOrigins SettingKey = "webauthn_origins" // WebAuthn 允许的 Origin 列表(逗号分隔,完整 scheme://host[:port]) SettingKeyCustomThemes SettingKey = "custom_themes" // Lodestar 自定义主题预设(JSON 数组), 可经设置 API 上传, 全站可选 SettingKeyCommercialMode SettingKey = "commercial_mode" // Lodestar 商业模式开关: false=自用(关闭公开注册), true=商业(开放公开注册) SettingKeyMaxExpectedRequestCost SettingKey = "max_expected_request_cost" // Lodestar 单次请求假定最坏成本(USD): 并发闸门用它限制在途请求数, 0=关闭该限制 SettingKeySiteName SettingKey = "site_name" // Lodestar 站点名称(对外展示/封面刊头) SettingKeySiteDescription SettingKey = "site_description" // Lodestar 站点简介(关于本站) SettingKeySiteAnnouncement SettingKey = "site_announcement" // Lodestar 站点公告(对外公开展示) SettingKeyLandingAmbientMode SettingKey = "landing_ambient_mode" // Lodestar 封面氛围: photo | classic | color4bg | pretext (失败回退 photo) SettingKeyEpayEnabled SettingKey = "epay_enabled" // Lodestar 易支付开关 SettingKeyPayAddress SettingKey = "pay_address" // 易支付网关地址 (https://xxx) SettingKeyEpayPID SettingKey = "epay_pid" // 易支付商户 PID SettingKeyEpayKey SettingKey = "epay_key" // 易支付商户密钥 SettingKeyTopupRate SettingKey = "topup_rate" // 充值汇率: 每 1 USD 额度对应的支付金额(网关货币) SettingKeyPaymentCallbackBase SettingKey = "payment_callback_base" // 支付回调站点基址 (https://your-site),用于 notify/return SettingKeyMaintenanceMode SettingKey = "maintenance_mode" // Lodestar 维护模式: true=对非管理员显示维护页 SettingKeyRegisterInviteRequired SettingKey = "register_invite_required" // Lodestar 注册需邀请码(仅商业模式下生效) SettingKeySMTPEnabled SettingKey = "smtp_enabled" // Lodestar SMTP 邮件开关 SettingKeySMTPHost SettingKey = "smtp_host" // SMTP 服务器 SettingKeySMTPPort SettingKey = "smtp_port" // SMTP 端口(587 STARTTLS) SettingKeySMTPUser SettingKey = "smtp_user" // SMTP 用户名 SettingKeySMTPPass SettingKey = "smtp_pass" // SMTP 密码/授权码 SettingKeySMTPFrom SettingKey = "smtp_from" // 发件人地址 SettingKeyRegisterEmailRequired SettingKey = "register_email_required" // Lodestar 注册需邮箱验证(仅商业模式下生效) SettingKeySiteBannerEnabled SettingKey = "site_banner_enabled" SettingKeySiteBannerText SettingKey = "site_banner_text" SettingKeySiteBannerTone SettingKey = "site_banner_tone" SettingKeyBillingExpr SettingKey = "billing_expr" // Lodestar 表达式计费(JSON: {"model":"expr",...}) SettingKeyStripeEnabled SettingKey = "stripe_enabled" // Stripe 支付开关 SettingKeyStripeAPIKey SettingKey = "stripe_api_key" // Stripe API 密钥 (sk_...) SettingKeyStripeWebhookSecret SettingKey = "stripe_webhook_secret" // Stripe Webhook 签名密钥 (whsec_...) SettingKeyStripeCurrency SettingKey = "stripe_currency" // Stripe 货币代码 (默认 usd) SettingKeyStripeMinTopUp SettingKey = "stripe_min_topup" // Stripe 最低充值金额(USD) SettingKeyGitHubOAuthEnabled SettingKey = "github_oauth_enabled" // GitHub OAuth 登录开关 SettingKeyGitHubOAuthClientID SettingKey = "github_oauth_client_id" // GitHub OAuth Client ID SettingKeyGitHubOAuthClientSecret SettingKey = "github_oauth_client_secret" // GitHub OAuth Client Secret SettingKeyTOTPIssuer SettingKey = "totp_issuer" // TOTP 两步验证发行者名称(认证器App显示) SettingKeyPIIRedactionEnabled SettingKey = "pii_redaction_enabled" // Relay 日志 PII 脱敏开关 SettingKeyTurnstileEnabled SettingKey = "turnstile_enabled" // Cloudflare Turnstile 注册验证开关 SettingKeyTurnstileSiteKey SettingKey = "turnstile_site_key" // Cloudflare Turnstile Site Key SettingKeyTurnstileSecretKey SettingKey = "turnstile_secret_key" // Cloudflare Turnstile Secret Key SettingKeyGuardrailEnabled SettingKey = "guardrail_enabled" // Guardrail 输入/输出过滤开关 SettingKeyGuardrailRules SettingKey = "guardrail_rules" // Guardrail 规则配置(JSON: GuardrailConfig) SettingKeyImageBedEnabled SettingKey = "image_bed_enabled" // 图床上传开关 SettingKeyImageBedEndpoint SettingKey = "image_bed_endpoint" // 图床上传 API 地址 SettingKeyImageBedToken SettingKey = "image_bed_token" // 图床 API Token SettingKeyRetryEmptyOutput SettingKey = "retry_empty_output" // 空输出自动重试: 上游返回 200 但内容为空时自动换 Key 重试 SettingKeyModelProbeEnabled SettingKey = "model_probe_enabled" // 定时模型可用度探测开关(默认关闭:探测会真花上游的钱) SettingKeyModelProbeIntervalHours SettingKey = "model_probe_interval_hours" // 探测周期(小时) SettingKeyModelProbeFailThreshold SettingKey = "model_probe_fail_threshold" // 连续失败多少轮后隐藏 + 通知 SettingKeyModelProbeSkipGroups SettingKey = "model_probe_skip_groups" // 人工跳过探测的分组名列表(JSON 数组),跳过=不探测/不计数/不通知 SettingKeyCustomerAlertEnabled SettingKey = "customer_alert_enabled" // 面向客户的低余额/到期预警邮件开关(默认关闭:给客户发邮件的决定不替运营者做) SettingKeyCustomerAlertBalanceThreshold SettingKey = "customer_alert_balance_threshold" // 低余额预警阈值(USD),0=关闭该维度 SettingKeyCustomerAlertExpiryDays SettingKey = "customer_alert_expiry_days" // 订阅到期提前预警天数,0=关闭该维度 )
type Site ¶
type Site struct {
ID int `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"unique;not null"`
Platform SitePlatform `json:"platform" gorm:"type:varchar(32);not null"`
BaseURL string `json:"base_url" gorm:"not null"`
Enabled bool `json:"enabled" gorm:"default:true"`
EnabledSet bool `json:"-" gorm:"-"`
ProxyMode ProxyUsageMode `json:"proxy_mode" gorm:"type:varchar(16);not null;default:'direct'"`
ProxyConfigID *int `json:"proxy_config_id"`
Proxy bool `json:"-" gorm:"default:false"`
SiteProxy *string `json:"-" gorm:"column:site_proxy"`
UseSystemProxy bool `json:"-" gorm:"default:false"`
ExternalCheckinURL *string `json:"external_checkin_url"`
IsPinned bool `json:"is_pinned" gorm:"default:false"`
SortOrder int `json:"sort_order" gorm:"default:0"`
GlobalWeight float64 `json:"global_weight" gorm:"default:1"`
CustomHeader []CustomHeader `json:"custom_header" gorm:"serializer:json"`
Archived bool `json:"archived" gorm:"default:false;index"`
ArchivedAt *time.Time `json:"archived_at"`
Accounts []SiteAccount `json:"accounts,omitempty" gorm:"foreignKey:SiteID"`
}
func (*Site) UnmarshalJSON ¶
type SiteAccount ¶
type SiteAccount struct {
ID int `json:"id" gorm:"primaryKey"`
SiteID int `json:"site_id" gorm:"index;not null"`
Name string `json:"name" gorm:"not null"`
CredentialType SiteCredentialType `json:"credential_type" gorm:"type:varchar(32);not null"`
Username string `json:"username"`
Password string `json:"password"`
AccessToken string `json:"access_token"`
APIKey string `json:"api_key"`
RefreshToken string `json:"refresh_token"`
TokenExpiresAt int64 `json:"token_expires_at" gorm:"default:0"`
PlatformUserID *int `json:"platform_user_id"`
ProxyMode ProxyUsageMode `json:"proxy_mode" gorm:"type:varchar(16);not null;default:'inherit'"`
ProxyConfigID *int `json:"proxy_config_id"`
AccountProxy *string `json:"-" gorm:"column:account_proxy"`
Enabled bool `json:"enabled" gorm:"default:true"`
EnabledSet bool `json:"-" gorm:"-"`
AutoSync bool `json:"auto_sync" gorm:"default:true"`
AutoSyncSet bool `json:"-" gorm:"-"`
AutoCheckin bool `json:"auto_checkin" gorm:"default:true"`
AutoCheckinSet bool `json:"-" gorm:"-"`
RandomCheckin bool `json:"random_checkin" gorm:"default:false"`
CheckinIntervalHours int `json:"checkin_interval_hours" gorm:"default:24"`
CheckinRandomWindowMinutes int `json:"checkin_random_window_minutes" gorm:"default:120"`
Balance float64 `json:"balance" gorm:"default:0"`
BalanceUsed float64 `json:"balance_used" gorm:"default:0"`
TodayIncome float64 `json:"today_income" gorm:"default:0"`
NextAutoCheckinAt *time.Time `json:"next_auto_checkin_at"`
LastSyncAt *time.Time `json:"last_sync_at"`
LastCheckinAt *time.Time `json:"last_checkin_at"`
LastSyncStatus SiteExecutionStatus `json:"last_sync_status" gorm:"type:varchar(16);default:'idle'"`
LastCheckinStatus SiteExecutionStatus `json:"last_checkin_status" gorm:"type:varchar(16);default:'idle'"`
LastSyncMessage string `json:"last_sync_message"`
LastCheckinMessage string `json:"last_checkin_message"`
Tokens []SiteToken `json:"tokens,omitempty" gorm:"foreignKey:SiteAccountID"`
UserGroups []SiteUserGroup `json:"user_groups,omitempty" gorm:"foreignKey:SiteAccountID"`
Models []SiteModel `json:"models,omitempty" gorm:"foreignKey:SiteAccountID"`
ChannelBindings []SiteChannelBinding `json:"channel_bindings,omitempty" gorm:"foreignKey:SiteAccountID"`
}
func (*SiteAccount) Normalize ¶
func (a *SiteAccount) Normalize()
func (*SiteAccount) UnmarshalJSON ¶
func (a *SiteAccount) UnmarshalJSON(data []byte) error
func (*SiteAccount) Validate ¶
func (a *SiteAccount) Validate() error
type SiteAccountUpdateRequest ¶
type SiteAccountUpdateRequest struct {
ID int `json:"id" binding:"required"`
Name *string `json:"name,omitempty"`
CredentialType *SiteCredentialType `json:"credential_type,omitempty"`
Username *string `json:"username,omitempty"`
Password *string `json:"password,omitempty"`
AccessToken *string `json:"access_token,omitempty"`
APIKey *string `json:"api_key,omitempty"`
RefreshToken *string `json:"refresh_token,omitempty"`
TokenExpiresAt *int64 `json:"token_expires_at,omitempty"`
PlatformUserID *int `json:"platform_user_id,omitempty"`
PlatformUserIDSet bool `json:"-"`
ProxyMode *ProxyUsageMode `json:"proxy_mode,omitempty"`
ProxyConfigID *int `json:"proxy_config_id,omitempty"`
ProxyConfigIDSet bool `json:"-"`
AccountProxy *string `json:"-"`
Enabled *bool `json:"enabled,omitempty"`
AutoSync *bool `json:"auto_sync,omitempty"`
AutoCheckin *bool `json:"auto_checkin,omitempty"`
RandomCheckin *bool `json:"random_checkin,omitempty"`
CheckinIntervalHours *int `json:"checkin_interval_hours,omitempty"`
CheckinRandomWindowMinutes *int `json:"checkin_random_window_minutes,omitempty"`
}
func (*SiteAccountUpdateRequest) UnmarshalJSON ¶
func (r *SiteAccountUpdateRequest) UnmarshalJSON(data []byte) error
type SiteBatchFailure ¶
type SiteBatchRequest ¶
type SiteBatchResult ¶
type SiteBatchResult struct {
SuccessIDs []int `json:"success_ids"`
FailedItems []SiteBatchFailure `json:"failed_items"`
}
type SiteChannelAccount ¶
type SiteChannelAccount struct {
SiteID int `json:"site_id"`
AccountID int `json:"account_id"`
AccountName string `json:"account_name"`
Enabled bool `json:"enabled"`
AutoSync bool `json:"auto_sync"`
GroupCount int `json:"group_count"`
ModelCount int `json:"model_count"`
Groups []SiteChannelGroup `json:"groups"`
RouteSummaries []SiteRouteSummary `json:"route_summaries"`
}
type SiteChannelBinding ¶
type SiteChannelBinding struct {
ID int `json:"id" gorm:"primaryKey"`
SiteID int `json:"site_id" gorm:"index;not null"`
SiteAccountID int `json:"site_account_id" gorm:"uniqueIndex:idx_site_account_channel_group;not null"`
SiteUserGroupID *int `json:"site_user_group_id"`
GroupKey string `json:"group_key" gorm:"size:128;uniqueIndex:idx_site_account_channel_group;not null"`
ChannelID int `json:"channel_id" gorm:"uniqueIndex;not null"`
}
type SiteChannelCard ¶
type SiteChannelCard struct {
SiteID int `json:"site_id"`
SiteName string `json:"site_name"`
BaseURL string `json:"base_url"`
Platform SitePlatform `json:"platform"`
Enabled bool `json:"enabled"`
AccountCount int `json:"account_count"`
Accounts []SiteChannelAccount `json:"accounts"`
}
type SiteChannelGroup ¶
type SiteChannelGroup struct {
GroupKey string `json:"group_key"`
GroupName string `json:"group_name"`
ProjectionDisabled bool `json:"projection_disabled"`
KeyCount int `json:"key_count"`
EnabledKeyCount int `json:"enabled_key_count"`
MaskedPendingKeyCount int `json:"masked_pending_key_count"`
HasKeys bool `json:"has_keys"`
HasProjectedChannel bool `json:"has_projected_channel"`
ProjectedChannelIDs []int `json:"projected_channel_ids"`
ProjectedChannels []SiteProjectedChannelSettings `json:"projected_channels,omitempty"`
SourceKeys []SiteSourceKey `json:"source_keys,omitempty"`
ProjectedKeys []SiteProjectedKey `json:"projected_keys,omitempty"`
Models []SiteChannelModel `json:"models"`
}
type SiteChannelModel ¶
type SiteChannelModel struct {
ModelName string `json:"model_name"`
Source string `json:"source"`
RouteType SiteModelRouteType `json:"route_type"`
RouteSource SiteModelRouteSource `json:"route_source"`
ManualOverride bool `json:"manual_override"`
Disabled bool `json:"disabled"`
ProjectedChannelID *int `json:"projected_channel_id,omitempty"`
RouteMetadata *SiteModelRouteMetadata `json:"route_metadata,omitempty"`
History *SiteModelHistorySummary `json:"history,omitempty"`
}
type SiteCheckinResult ¶
type SiteCheckinResult struct {
AccountID int `json:"account_id"`
SiteID int `json:"site_id"`
Status SiteExecutionStatus `json:"status"`
Message string `json:"message"`
Reward string `json:"reward,omitempty"`
}
type SiteCredentialType ¶
type SiteCredentialType string
const ( SiteCredentialTypeUsernamePassword SiteCredentialType = "username_password" SiteCredentialTypeAccessToken SiteCredentialType = "access_token" SiteCredentialTypeAPIKey SiteCredentialType = "api_key" )
func (SiteCredentialType) Validate ¶
func (t SiteCredentialType) Validate() error
type SiteExecutionStatus ¶
type SiteExecutionStatus string
const ( SiteExecutionStatusIdle SiteExecutionStatus = "idle" SiteExecutionStatusSuccess SiteExecutionStatus = "success" SiteExecutionStatusPartial SiteExecutionStatus = "partial" SiteExecutionStatusFailed SiteExecutionStatus = "failed" SiteExecutionStatusSkipped SiteExecutionStatus = "skipped" )
type SiteManualModelAddEntry ¶
type SiteManualModelAddEntry struct {
ModelName string `json:"model_name" binding:"required"`
RouteType SiteModelRouteType `json:"route_type" binding:"required"`
}
type SiteManualModelAddRequest ¶
type SiteManualModelAddRequest struct {
GroupKey string `json:"group_key" binding:"required"`
Models []SiteManualModelAddEntry `json:"models" binding:"required"`
}
type SiteModel ¶
type SiteModel struct {
ID int `json:"id" gorm:"primaryKey"`
SiteAccountID int `json:"site_account_id" gorm:"uniqueIndex:idx_site_account_group_model;not null"`
GroupKey string `json:"group_key" gorm:"size:128;uniqueIndex:idx_site_account_group_model;not null;default:'default'"`
ModelName string `json:"model_name" gorm:"size:191;uniqueIndex:idx_site_account_group_model;not null"`
Source string `json:"source"`
RouteType SiteModelRouteType `json:"route_type" gorm:"type:varchar(32);not null;default:'openai_chat';index"`
RouteSource SiteModelRouteSource `json:"route_source" gorm:"type:varchar(32);not null;default:'sync_inferred'"`
ManualOverride bool `json:"manual_override" gorm:"default:false"`
RouteRawPayload string `json:"route_raw_payload"`
RouteUpdatedAt *time.Time `json:"route_updated_at"`
Disabled bool `json:"disabled" gorm:"default:false;index"`
}
type SiteModelHistoryBucket ¶
type SiteModelHistorySummary ¶
type SiteModelHistorySummary struct {
SuccessCount int `json:"success_count"`
FailureCount int `json:"failure_count"`
LastRequestAt *int64 `json:"last_request_at,omitempty"`
BucketSpan int `json:"bucket_span,omitempty"`
Buckets []SiteModelHistoryBucket `json:"buckets,omitempty"`
}
type SiteModelRouteMetadata ¶
type SiteModelRouteMetadata struct {
Kind string `json:"kind"`
Version int `json:"version"`
Source string `json:"source,omitempty"`
RouteSupported bool `json:"route_supported"`
RouteType SiteModelRouteType `json:"route_type,omitempty"`
EnableGroups []string `json:"enable_groups,omitempty"`
SupportedEndpointTypes []string `json:"supported_endpoint_types,omitempty"`
HeuristicEndpointTypes []string `json:"heuristic_endpoint_types,omitempty"`
NormalizedEndpointTypes []string `json:"normalized_endpoint_types,omitempty"`
UnsupportedReason string `json:"unsupported_reason,omitempty"`
}
func ParseSiteModelRouteMetadata ¶
func ParseSiteModelRouteMetadata(raw string) (*SiteModelRouteMetadata, bool)
func (SiteModelRouteMetadata) Marshal ¶
func (m SiteModelRouteMetadata) Marshal() string
type SiteModelRouteSource ¶
type SiteModelRouteSource string
const ( SiteModelRouteSourceSyncInferred SiteModelRouteSource = "sync_inferred" SiteModelRouteSourceManualOverride SiteModelRouteSource = "manual_override" SiteModelRouteSourceRuntimeLearned SiteModelRouteSource = "runtime_learned" SiteModelRouteSourceDefaultAssigned SiteModelRouteSource = "default_assigned" )
func NormalizeSiteModelRouteSource ¶
func NormalizeSiteModelRouteSource(routeSource SiteModelRouteSource, manualOverride bool) SiteModelRouteSource
type SiteModelRouteType ¶
type SiteModelRouteType string
const ( SiteModelRouteTypeOpenAIChat SiteModelRouteType = "openai_chat" SiteModelRouteTypeOpenAIResponse SiteModelRouteType = "openai_response" SiteModelRouteTypeAnthropic SiteModelRouteType = "anthropic" SiteModelRouteTypeGemini SiteModelRouteType = "gemini" SiteModelRouteTypeVolcengine SiteModelRouteType = "volcengine" SiteModelRouteTypeOpenAIEmbedding SiteModelRouteType = "openai_embedding" SiteModelRouteTypeUnknown SiteModelRouteType = "unknown" )
func InferSiteModelRouteType ¶
func InferSiteModelRouteType(modelName string) SiteModelRouteType
func NormalizeSiteModelRouteType ¶
func NormalizeSiteModelRouteType(routeType SiteModelRouteType) SiteModelRouteType
func ParseSiteChannelBindingKey ¶
func ParseSiteChannelBindingKey(groupKey string) (string, SiteModelRouteType)
func SiteModelRouteTypeFromOutboundType ¶
func SiteModelRouteTypeFromOutboundType(t outbound.OutboundType) SiteModelRouteType
func (SiteModelRouteType) ToOutboundType ¶
func (t SiteModelRouteType) ToOutboundType() outbound.OutboundType
type SiteModelRouteUpdateRequest ¶
type SiteModelRouteUpdateRequest struct {
GroupKey string `json:"group_key" binding:"required"`
ModelName string `json:"model_name" binding:"required"`
RouteType SiteModelRouteType `json:"route_type" binding:"required"`
RouteRawPayload string `json:"route_raw_payload,omitempty"`
}
type SitePlatform ¶
type SitePlatform string
const ( SitePlatformNewAPI SitePlatform = "new-api" SitePlatformAnyRouter SitePlatform = "anyrouter" SitePlatformOneAPI SitePlatform = "one-api" SitePlatformOneHub SitePlatform = "one-hub" SitePlatformDoneHub SitePlatform = "done-hub" SitePlatformSub2API SitePlatform = "sub2api" SitePlatformOpenAI SitePlatform = "openai" SitePlatformClaude SitePlatform = "claude" SitePlatformGemini SitePlatform = "gemini" )
func (SitePlatform) Validate ¶
func (p SitePlatform) Validate() error
type SiteProjectedChannelSettings ¶
type SiteProjectedChannelSettings struct {
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
RouteType SiteModelRouteType `json:"route_type"`
AutoGroup AutoGroupType `json:"auto_group"`
EffectiveGroup AutoGroupType `json:"effective_auto_group"`
ParamOverride string `json:"param_override"`
GlobalOverride bool `json:"global_override"`
}
type SiteProjectedChannelSettingsUpdateRequest ¶
type SiteProjectedChannelSettingsUpdateRequest struct {
ChannelID int `json:"channel_id" binding:"required"`
AutoGroup AutoGroupType `json:"auto_group"`
ParamOverride string `json:"param_override"`
}
type SiteProjectedKey ¶
type SiteProjectedKey struct {
ID int `json:"id"`
ChannelID int `json:"channel_id"`
ChannelName string `json:"channel_name"`
Enabled bool `json:"enabled"`
ChannelKey string `json:"channel_key"`
ChannelKeyMasked string `json:"channel_key_masked"`
Remark string `json:"remark"`
StatusCode int `json:"status_code"`
LastUseTimeStamp int64 `json:"last_use_time_stamp"`
TotalCost float64 `json:"total_cost"`
}
type SiteProjectedKeyUpdateRequest ¶
type SiteProjectedKeyUpdateRequest struct {
GroupKey string `json:"group_key" binding:"required"`
KeysToAdd []SiteProjectedKeyAddRequest `json:"keys_to_add,omitempty"`
KeysToUpdate []SiteProjectedKeyUpdateItem `json:"keys_to_update,omitempty"`
KeysToDelete []int `json:"keys_to_delete,omitempty"`
}
type SiteRouteSummary ¶
type SiteRouteSummary struct {
RouteType SiteModelRouteType `json:"route_type"`
Count int `json:"count"`
}
type SiteSourceKey ¶
type SiteSourceKey struct {
ID int `json:"id"`
Enabled bool `json:"enabled"`
Token string `json:"token"`
TokenMasked string `json:"token_masked"`
Name string `json:"name"`
GroupKey string `json:"group_key"`
GroupName string `json:"group_name"`
ValueStatus SiteTokenValueStatus `json:"value_status"`
LastSyncAt *int64 `json:"last_sync_at,omitempty"`
}
type SiteSourceKeyAddRequest ¶
type SiteSourceKeyUpdateItem ¶
type SiteSourceKeyUpdateRequest ¶
type SiteSourceKeyUpdateRequest struct {
GroupKey string `json:"group_key" binding:"required"`
KeysToAdd []SiteSourceKeyAddRequest `json:"keys_to_add,omitempty"`
KeysToUpdate []SiteSourceKeyUpdateItem `json:"keys_to_update,omitempty"`
KeysToDelete []int `json:"keys_to_delete,omitempty"`
}
type SiteSyncGroupResult ¶
type SiteSyncResult ¶
type SiteSyncResult struct {
AccountID int `json:"account_id"`
SiteID int `json:"site_id"`
Status SiteExecutionStatus `json:"status"`
ChannelCount int `json:"channel_count"`
GroupCount int `json:"group_count"`
TokenCount int `json:"token_count"`
ModelCount int `json:"model_count"`
ManagedChannels []int `json:"managed_channels,omitempty"`
Models []string `json:"models,omitempty"`
GroupResults []SiteSyncGroupResult `json:"group_results,omitempty"`
Message string `json:"message"`
}
type SiteToken ¶
type SiteToken struct {
ID int `json:"id" gorm:"primaryKey"`
SiteAccountID int `json:"site_account_id" gorm:"index;not null"`
// UpstreamID is the token's id on the remote site, needed to ask that site
// for the plaintext key: management platforms mask keys in their token list,
// and the only way back to the real value is a per-id lookup.
UpstreamID int `json:"upstream_id" gorm:"default:0"`
Name string `json:"name"`
Token string `json:"token" gorm:"not null"`
ValueStatus SiteTokenValueStatus `json:"value_status" gorm:"type:varchar(32);not null;default:'ready'"`
GroupKey string `json:"group_key" gorm:"size:128;index"`
GroupName string `json:"group_name"`
Enabled bool `json:"enabled" gorm:"default:true"`
Source string `json:"source"`
IsDefault bool `json:"is_default" gorm:"default:false"`
LastSyncAt *time.Time `json:"last_sync_at"`
}
type SiteTokenValueStatus ¶
type SiteTokenValueStatus string
const ( SiteTokenValueStatusReady SiteTokenValueStatus = "ready" SiteTokenValueStatusMaskedPending SiteTokenValueStatus = "masked_pending" )
func NormalizeSiteTokenValueStatus ¶
func NormalizeSiteTokenValueStatus(value SiteTokenValueStatus, token string) SiteTokenValueStatus
type SiteUpdateRequest ¶
type SiteUpdateRequest struct {
ID int `json:"id" binding:"required"`
Name *string `json:"name,omitempty"`
Platform *SitePlatform `json:"platform,omitempty"`
BaseURL *string `json:"base_url,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
ProxyMode *ProxyUsageMode `json:"proxy_mode,omitempty"`
ProxyConfigID *int `json:"proxy_config_id,omitempty"`
ProxyConfigIDSet bool `json:"-"`
Proxy *bool `json:"-"`
SiteProxy *string `json:"-"`
UseSystemProxy *bool `json:"-"`
ExternalCheckinURL *string `json:"external_checkin_url,omitempty"`
ExternalCheckinSet bool `json:"-"`
IsPinned *bool `json:"is_pinned,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
GlobalWeight *float64 `json:"global_weight,omitempty"`
CustomHeader *[]CustomHeader `json:"custom_header,omitempty"`
}
func (*SiteUpdateRequest) UnmarshalJSON ¶
func (r *SiteUpdateRequest) UnmarshalJSON(data []byte) error
type SiteUserGroup ¶
type SiteUserGroup struct {
ID int `json:"id" gorm:"primaryKey"`
SiteAccountID int `json:"site_account_id" gorm:"uniqueIndex:idx_site_account_group;not null"`
GroupKey string `json:"group_key" gorm:"size:128;uniqueIndex:idx_site_account_group;not null"`
Name string `json:"name"`
RawPayload string `json:"raw_payload"`
ProjectionDisabled bool `json:"projection_disabled" gorm:"default:false"`
}
type StatsAPIKey ¶
type StatsAPIKey struct {
APIKeyID int `json:"api_key_id" gorm:"primaryKey"`
StatsMetrics
}
type StatsChannel ¶
type StatsChannel struct {
ChannelID int `json:"channel_id" gorm:"primaryKey;constraint:OnDelete:CASCADE"`
StatsMetrics
}
type StatsDaily ¶
type StatsDaily struct {
Date string `json:"date" gorm:"primaryKey"`
StatsMetrics
}
type StatsHourly ¶
type StatsHourly struct {
Hour int `json:"hour" gorm:"primaryKey"`
Date string `json:"date" gorm:"primaryKey;not null"` // 记录最后更新日期,格式:20060102
StatsMetrics
}
type StatsMetrics ¶
type StatsMetrics struct {
InputToken int64 `json:"input_token" gorm:"bigint"`
OutputToken int64 `json:"output_token" gorm:"bigint"`
InputCost float64 `json:"input_cost" gorm:"type:double precision"`
OutputCost float64 `json:"output_cost" gorm:"type:double precision"`
WaitTime int64 `json:"wait_time" gorm:"bigint"`
RequestSuccess int64 `json:"request_success" gorm:"bigint"`
RequestFailed int64 `json:"request_failed" gorm:"bigint"`
// 延迟分布统计(毫秒)
LatencyP50 int64 `json:"latency_p50" gorm:"bigint"`
LatencyP95 int64 `json:"latency_p95" gorm:"bigint"`
LatencyP99 int64 `json:"latency_p99" gorm:"bigint"`
// 首 Token 时间统计(毫秒)
FtutAvg int64 `json:"ftut_avg" gorm:"bigint"`
FtutP50 int64 `json:"ftut_p50" gorm:"bigint"`
FtutP95 int64 `json:"ftut_p95" gorm:"bigint"`
FtutP99 int64 `json:"ftut_p99" gorm:"bigint"`
// 延迟直方图(请求计数)
HistogramLt100 int64 `json:"histogram_lt_100" gorm:"bigint"`
Histogram100to500 int64 `json:"histogram_100_500" gorm:"bigint"`
Histogram500to1k int64 `json:"histogram_500_1k" gorm:"bigint"`
Histogram1kto5k int64 `json:"histogram_1k_5k" gorm:"bigint"`
HistogramGt5k int64 `json:"histogram_gt_5k" gorm:"bigint"`
}
func (*StatsMetrics) Add ¶
func (s *StatsMetrics) Add(delta StatsMetrics)
Add aggregates another StatsMetrics into the current one.
type StatsModel ¶
type StatsModel struct {
ID int64 `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"not null"`
ChannelID int `json:"channel_id" gorm:"not null"`
StatsMetrics
}
type StatsSiteModelHourly ¶
type StatsSiteModelHourly struct {
Hour int `json:"hour" gorm:"primaryKey;autoIncrement:false"`
SiteAccountID int `json:"site_account_id" gorm:"primaryKey;index:idx_stats_site_model_lookup"`
GroupKey string `json:"group_key" gorm:"primaryKey;type:varchar(128);index:idx_stats_site_model_lookup"`
ModelName string `json:"model_name" gorm:"primaryKey;type:varchar(128);index:idx_stats_site_model_lookup"`
Date string `json:"date" gorm:"not null;type:varchar(8)"`
LastRequestAt int64 `json:"last_request_at" gorm:"not null;default:0"`
StatsMetrics
}
StatsSiteModelHourly stores hourly request stats for site-channel models, used for availability trend charts on the site-channel page.
type StatsTotal ¶
type StatsTotal struct {
ID int `gorm:"primaryKey"`
StatsMetrics
}
type SubscriptionOrder ¶
type SubscriptionOrder struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index;not null"`
PlanID int `json:"plan_id" gorm:"index;not null"`
TradeNo string `json:"trade_no" gorm:"type:varchar(128);uniqueIndex;not null"`
Money float64 `json:"money" gorm:"type:double precision;not null"`
PaymentMethod string `json:"payment_method" gorm:"type:varchar(32);default:'balance'"`
Status string `json:"status" gorm:"type:varchar(16);default:'pending'"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
CompletedAt int64 `json:"completed_at" gorm:"bigint;default:0"`
}
SubscriptionOrder represents a purchase attempt for a plan.
func (SubscriptionOrder) TableName ¶
func (SubscriptionOrder) TableName() string
type SubscriptionPlan ¶
type SubscriptionPlan struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
Name string `json:"name" gorm:"type:varchar(128);not null"`
Description string `json:"description" gorm:"type:varchar(512);default:''"`
Price float64 `json:"price" gorm:"type:double precision;not null;default:0"` // USD
Currency string `json:"currency" gorm:"type:varchar(8);not null;default:'USD'"`
DurationType string `json:"duration_type" gorm:"type:varchar(16);not null;default:'month'"` // month/day/hour/custom
DurationDays int `json:"duration_days" gorm:"type:int;not null;default:30"`
CustomDurationS int64 `json:"custom_duration_s" gorm:"type:bigint;not null;default:0"` // seconds, for custom
QuotaAmount float64 `json:"quota_amount" gorm:"type:double precision;not null;default:0"` // USD quota pool granted; must be > 0 to be sellable
Enabled bool `json:"enabled" gorm:"default:true"`
SortOrder int `json:"sort_order" gorm:"type:int;default:0"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
// EnabledSet 标记请求里是否显式给出了 enabled(仿 SiteAccount 的 *Set 模式)。
// 只在内存里传递,不落库:Enabled 的 default:true 标签会让 struct Create
// 把显式的 false 吞成 true(停用套餐创建即上架),CreatePlan 靠它事后补偿。
EnabledSet bool `json:"-" gorm:"-"`
}
SubscriptionPlan defines a purchasable subscription plan.
func (SubscriptionPlan) TableName ¶
func (SubscriptionPlan) TableName() string
func (*SubscriptionPlan) UnmarshalJSON ¶
func (p *SubscriptionPlan) UnmarshalJSON(data []byte) error
UnmarshalJSON 记录 "enabled" 键是否出现:裸 bool 下"字段缺失"(默认启用) 与"显式 false(管理员要求下架)"到达 Go 时都是 false,必须可区分。
type SystemMessageStrategy ¶
type SystemMessageStrategy string
const ( SystemMessageStrategyKeep SystemMessageStrategy = "keep" SystemMessageStrategyMerge SystemMessageStrategy = "merge" )
type TelegramConfig ¶
type TelegramConfig struct {
BotToken string `json:"bot_token"` // Telegram Bot API token
ChatID string `json:"chat_id"` // target chat ID
}
TelegramConfig holds the configuration for a Telegram notification channel.
type ToolRoleStrategy ¶
type ToolRoleStrategy string
const ( ToolRoleStrategyKeep ToolRoleStrategy = "keep" ToolRoleStrategyStringifyToUser ToolRoleStrategy = "stringify_to_user" )
type TopupCode ¶
type TopupCode struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
Code string `json:"code" gorm:"type:varchar(64);uniqueIndex;not null"`
Quota float64 `json:"quota" gorm:"type:double precision;not null"` // USD credited on redeem
// Note carries the reconciliation trail for money collected outside the app:
// who paid, how much, through which channel, when. Codes are the only inbound
// money path when no payment provider is configured, and unlike PaymentOrder
// they otherwise record nothing about the payment they represent — leaving the
// operator to match a code against a bank transfer from memory months later.
// Free-form on purpose: the shape of an offline receipt is not ours to dictate.
Note string `json:"note" gorm:"type:varchar(256)"`
Used bool `json:"used" gorm:"default:false"`
UsedBy uint `json:"used_by" gorm:"default:0"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UsedAt int64 `json:"used_at" gorm:"bigint;default:0"`
}
type TwoFA ¶
type TwoFA struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"uniqueIndex;not null" json:"user_id"`
Secret string `gorm:"type:varchar(255);not null" json:"-"` // TOTP secret, never sent to frontend
IsEnabled bool `gorm:"default:false" json:"is_enabled"`
FailedAttempts int `gorm:"default:0" json:"failed_attempts"`
LockedUntil *time.Time `json:"locked_until,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
TwoFA stores a user's TOTP-based two-factor authentication settings.
type TwoFABackupCode ¶
type TwoFABackupCode struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index;not null" json:"user_id"`
CodeHash string `gorm:"type:varchar(255);not null" json:"-"` // SHA-256 hash of the backup code
IsUsed bool `gorm:"default:false" json:"is_used"`
UsedAt *time.Time `json:"used_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
TwoFABackupCode stores hashed backup codes for TOTP 2FA recovery.
func (TwoFABackupCode) TableName ¶
func (TwoFABackupCode) TableName() string
type User ¶
type User struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"unique" json:"username"`
Password string `gorm:"not null" json:"-"`
Role string `gorm:"default:'admin'" json:"role"`
// Lodestar: per-user UI preferences (JSON), e.g. {"themePreset":"winter"}.
// Lets a user's chosen theme follow their account across devices.
Preferences string `gorm:"type:text" json:"preferences,omitempty"`
// Lodestar commercial layer (ported from new-api's prepaid-quota model, adapted
// to Lodestar's float-dollar cost): Quota = remaining balance (USD), UsedQuota
// = cumulative spent. Only enforced when commercial_mode is on.
Quota float64 `gorm:"type:double precision;default:0" json:"quota"`
UsedQuota float64 `gorm:"type:double precision;default:0;column:used_quota" json:"used_quota"`
// Lodestar commercial: optional email (verified at registration when required).
Email string `gorm:"type:varchar(256)" json:"email,omitempty"`
}
func (*User) ComparePassword ¶
func (*User) HashPassword ¶
type UserAlertState ¶
type UserAlertState struct {
UserID uint `gorm:"primaryKey"`
// 低余额维度:上次发送时的余额档位(threshold 起按半阈值递减);0 = 从未发过。
LastBalanceTier float64 `gorm:"default:0"`
LastBalanceSentAt int64 `gorm:"default:0;bigint"`
// 到期维度:LastExpirySentAt 非 0 = 已发送过(WO-030 缺陷 A:daysLeft 在最后
// 24 小时为 0,不能当"从未发送"哨兵用);LastExpiryDaysSent 记发送时点的剩余
// 天数。旧版本行可能只有 days 非零、sentAt 为零——同样视为已发(见
// customeralert.expiryAlertNeeded 的兼容逻辑),双零才是真正的未发送。
LastExpiryDaysSent int64 `gorm:"default:0"`
LastExpirySentAt int64 `gorm:"default:0;bigint"`
UpdatedAt int64 `gorm:"bigint"`
}
UserAlertState 每用户一行的预警防重状态。
func (UserAlertState) TableName ¶
func (UserAlertState) TableName() string
type UserBootstrapCreate ¶
type UserBootstrapCreate struct {
Username string `json:"username"`
Password string `json:"password"`
}
func (UserBootstrapCreate) TableName ¶
func (UserBootstrapCreate) TableName() string
type UserChangePassword ¶
type UserChangePassword struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
func (UserChangePassword) TableName ¶
func (UserChangePassword) TableName() string
type UserChangeUsername ¶
type UserChangeUsername struct {
NewUsername string `json:"new_username"`
}
func (UserChangeUsername) TableName ¶
func (UserChangeUsername) TableName() string
type UserCreateRequest ¶
type UserCreateRequest struct {
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
}
func (UserCreateRequest) TableName ¶
func (UserCreateRequest) TableName() string
type UserLogin ¶
type UserLoginResponse ¶
type UserLoginResponse struct {
Token string `json:"token"`
ExpireAt string `json:"expire_at"`
RequiresTwoFactor bool `json:"requires_two_factor,omitempty"` // true when 2FA is on and totp_code was not supplied
}
func (UserLoginResponse) TableName ¶
func (UserLoginResponse) TableName() string
type UserSubscription ¶
type UserSubscription struct {
ID int `json:"id" gorm:"primaryKey;autoIncrement"`
UserID uint `json:"user_id" gorm:"index;not null"`
PlanID int `json:"plan_id" gorm:"index;not null"`
OrderID int `json:"order_id" gorm:"index;default:0"`
AmountTotal float64 `json:"amount_total" gorm:"type:double precision;not null;default:0"` // USD quota total
AmountUsed float64 `json:"amount_used" gorm:"type:double precision;not null;default:0"` // USD quota used
StartsAt int64 `json:"starts_at" gorm:"bigint"`
ExpiresAt int64 `json:"expires_at" gorm:"bigint;index"`
Status string `json:"status" gorm:"type:varchar(16);index;default:'active'"` // active/expired/cancelled
Source string `json:"source" gorm:"type:varchar(16);default:'order'"` // order/admin
CreatedAt int64 `json:"created_at" gorm:"bigint"`
}
UserSubscription represents an active or historical subscription for a user.
func (UserSubscription) TableName ¶
func (UserSubscription) TableName() string
type VerificationRequest ¶
type VerificationRequest struct {
BaseURL string `json:"base_url" binding:"required"`
APIKey string `json:"api_key" binding:"required"`
APIType string `json:"api_type"`
Model string `json:"model"`
Probes []string `json:"probes"` // text_gen, tool_calling, structured_output, web_search
}
VerificationRequest is the payload for running API verification probes.
func (VerificationRequest) TableName ¶
func (VerificationRequest) TableName() string
type VerificationResult ¶
type VerificationResult struct {
Probe string `json:"probe"`
Success bool `json:"success"`
Latency int64 `json:"latency_ms"`
Error string `json:"error,omitempty"`
Output string `json:"output,omitempty"`
}
VerificationResult holds the outcome of running verification probes.
type WSResponseAffinity ¶
type WSResponseAffinity struct {
ID uint `json:"id" gorm:"primaryKey"`
APIKeyID int `json:"api_key_id" gorm:"not null;index:idx_ws_response_affinity_scope,unique"`
GroupID int `json:"group_id" gorm:"not null;index:idx_ws_response_affinity_scope,unique"`
RequestModel string `json:"request_model" gorm:"size:191;not null;index:idx_ws_response_affinity_scope,unique"`
ResponseIDHash string `json:"response_id_hash" gorm:"size:64;not null;index:idx_ws_response_affinity_scope,unique"`
ChannelID int `json:"channel_id" gorm:"not null"`
ChannelKeyID int `json:"channel_key_id" gorm:"not null"`
UpstreamModel string `json:"upstream_model" gorm:"size:191"`
ExpiresAt time.Time `json:"expires_at" gorm:"not null;index"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
WSResponseAffinity stores the preferred upstream route for an OpenAI Responses response id. The response id itself is hashed before storage.
type WeComConfig ¶
type WeComConfig struct {
WebhookKey string `json:"webhook_key"` // group robot key
}
WeComConfig holds the configuration for a WeCom (Enterprise WeChat) notification channel.
type WebAuthnCredential ¶
type WebAuthnCredential struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index;not null" json:"user_id"`
CredentialIDHex string `gorm:"uniqueIndex;size:64;not null" json:"-"` // 原始 credential id 的 SHA-256 十六进制摘要,用于唯一约束
Credential string `gorm:"type:text;not null" json:"-"` // webauthn.Credential 的 JSON
Name string `json:"name"` // 用户自定义标签(如「MacBook」)
CreatedAt time.Time `json:"created_at"`
LastUsedAt *time.Time `json:"last_used_at"`
}
WebAuthnCredential 存储用户绑定的 Passkey(WebAuthn)凭证。
一个用户可绑定多个凭证;凭证的核心数据(公钥、计数器、transports 等)以 github.com/go-webauthn/webauthn/webauthn.Credential 的 JSON 序列化形式整体存入 Credential 字段,登录校验时由 go-webauthn 在内存中按原始 credential id 匹配, 因此 DB 层无需对原始 id 建唯一索引——改用其 SHA-256 摘要做唯一约束,规避各方言 对长字符串唯一索引的长度限制(尤其 MySQL utf8mb4)。
func (WebAuthnCredential) TableName ¶
func (WebAuthnCredential) TableName() string
Source Files
¶
- ai_route.go
- ai_route_service.go
- ai_route_task.go
- alert.go
- analytics.go
- api_credential.go
- apikey.go
- audit_log.go
- auto_group.go
- backup.go
- channel.go
- channel_group.go
- chat_session.go
- customer_alert.go
- endpoint_type.go
- error_log.go
- feedback.go
- group.go
- group_test_result.go
- image_record.go
- invite_code.go
- key_cooldown.go
- llm.go
- log.go
- model_capability.go
- model_mapping.go
- model_probe.go
- oauth.go
- ops.go
- payment_order.go
- price_category.go
- proxy.go
- quota_ledger.go
- redemption.go
- runtime_state.go
- setting.go
- site.go
- site_channel.go
- site_import.go
- site_route_metadata.go
- stats.go
- subscription.go
- topup_code.go
- twofa.go
- user.go
- webauthn.go
- ws_affinity.go