Documentation
¶
Overview ¶
internal/models/user_group.go
Index ¶
- Constants
- func AutoMigrate(db *gorm.DB) error
- func SeedBYOKSettings(db *gorm.DB) error
- func SeedDefaultUserGroup(db *gorm.DB) error
- func TokenFieldsEqual(tplModelsJSON string, tplChannelIDs []uint, tok *Token) bool
- func ValidAction(action string) bool
- func ValidBindingTarget(keyBy, targetType string) bool
- func ValidChannelScope(scope string) bool
- type AdminScript
- type Agent
- type AgentRoute
- type AttemptRecord
- type Channel
- type ChannelCore
- type ChannelDailyBilling
- type ChannelLimit
- type ChannelLimitState
- type ChannelResilience
- type EnrollmentToken
- type InviteCode
- type InviteRedemption
- type LimitRule
- type LimiterBinding
- type ModelConfig
- type ModelRouting
- type OAuthIdentity
- type OAuthProvider
- type PrivateChannel
- type PrivateChannelShare
- type RateLimitHit
- type RequestLimiter
- type RoutingMember
- type ScriptScope
- type Setting
- type Token
- type TokenDailyBilling
- type TokenTemplate
- type UsageHourlyBucket
- type UsageLog
- type UsageLogTrace
- type User
- type UserGroup
Constants ¶
const ( LimitMetricCalls = "calls" LimitMetricCost = "cost" LimitWindowLifetime = "lifetime" LimitWindowDaily = "daily" LimitWindowWeekly = "weekly" LimitWindowMonthly = "monthly" LimitWindowRollingDays = "rolling_days" )
限额指标 / 窗口枚举。
const ( LimiterTargetGlobal = "global" LimiterTargetChannel = "channel" LimiterTargetUserGroup = "user_group" LimiterTargetUser = "user" )
const ( RoutingScopeGlobal = "global" RoutingScopeUser = "user" )
const ( )
const ( LimiterMetricConcurrency = "concurrency" LimiterMetricRate = "rate" LimiterKeyPerUser = "per_user" LimiterKeyPerGroup = "per_group" LimiterKeyPerChannel = "per_channel" LimiterKeyPerChannelUser = "per_channel_user" LimiterScopeAdmin = "admin" LimiterScopePrivate = "private" LimiterScopeAll = "all" LimiterActionReject = "reject" LimiterActionWait = "wait" )
枚举取值(用 const 防手滑拼错)。
扩展契约:新增一个 KeyBy 不只是加常量——必须同步下游 3 处,否则会静默错误:
- (*RequestLimiter).ChannelKeyed() —— 决定该规则落请求级还是尝试级闸门;
- cache.LimiterIndex.Effective{Request,Attempt}Limiters 的入参 —— 新分桶维度 (如 per_model) 需要新数据从热路径透传进来;
- limiter.bucketOf() 的 switch —— 其 default 会把未识别 KeyBy 静默并入 "shared" 桶。
Variables ¶
This section is empty.
Functions ¶
func AutoMigrate ¶
func SeedBYOKSettings ¶ added in v0.0.2
SeedBYOKSettings 把 BYOK 相关默认 settings 写入;仅在 key 不存在时插入, 已有值(如 admin 改过的)保留不覆盖。idempotent,可在每次启动调用。
func SeedDefaultUserGroup ¶
SeedDefaultUserGroup ensures the id=1 default user_group exists, and backfills users whose group_id is 0 / NULL to 1. Idempotent.
func TokenFieldsEqual ¶
func ValidAction ¶ added in v0.0.8
ValidAction 报告超容量处置方式是否合法(reject 拒绝 / wait 排队)。
func ValidBindingTarget ¶ added in v0.0.8
ValidBindingTarget 报告某 KeyBy 的 limiter 能否绑到某 TargetType(§5.1 硬约束)。 这是领域规则:分桶维度(KeyBy)限定了绑定挂载点(TargetType)的合法集合,前后端共用判断。
- shared → 只能 global(无分桶维度,挂全局)
- per_user → global / user_group / user(按用户分桶,可在这三层覆盖)
- per_group → global / user_group(按用户组分桶,挂到具体用户无意义)
- per_channel → global / channel(按渠道分桶)
- per_channel_user → global / channel(按渠道×用户分桶,挂载点仍是渠道)
func ValidChannelScope ¶ added in v0.0.8
ValidChannelScope 报告渠道作用域是否合法。空串视为 admin(向后兼容默认), 仅 channel-keyed 规则真正使用此值,但写入侧统一拦脏枚举防后续静默漂移。
Types ¶
type AdminScript ¶ added in v0.0.6
type AdminScript struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:128;uniqueIndex" json:"name"`
Code string `gorm:"type:text" json:"code"`
Enabled bool `json:"enabled"`
Priority int `gorm:"default:0" json:"priority"`
Scope datatypes.JSONType[ScriptScope] `json:"scope"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
AdminScript 是管理员编写的动态 goja 脚本。仅管理员可管理。
type Agent ¶
type Agent struct {
ID uint `gorm:"primaryKey" json:"id"`
AgentID string `gorm:"uniqueIndex;size:64" json:"agent_id"`
Secret string `gorm:"size:128" json:"secret,omitempty"`
Name string `gorm:"size:64" json:"name"`
Status int `gorm:"default:1" json:"status"`
LastSeen int64 `json:"last_seen"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
// Network & routing
HTTPAddresses string `gorm:"type:text" json:"http_addresses"` // JSON: [{"url":"...","tag":"..."}]
Tags string `gorm:"type:text" json:"tags"` // comma-separated
ProxyURL string `gorm:"size:256" json:"proxy_url"`
}
type AgentRoute ¶
type AgentRoute struct {
ID uint `json:"id" gorm:"primaryKey"`
SourceType string `json:"source_type" gorm:"size:32;index:idx_agent_route_source;uniqueIndex:uk_agent_route"`
SourceID uint `json:"source_id" gorm:"index:idx_agent_route_source;uniqueIndex:uk_agent_route"`
Model string `json:"model" gorm:"size:256;uniqueIndex:uk_agent_route;default:''"`
AgentID string `json:"agent_id" gorm:"size:128"`
AgentTag string `json:"agent_tag" gorm:"size:128"`
Priority int `json:"priority" gorm:"index"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime"`
}
AgentRoute 定义 Agent 路由规则。 管理员可为 Token 或 Channel 配置请求应转发到哪个 Agent 节点/组。
func (*AgentRoute) CalcPriority ¶
func (r *AgentRoute) CalcPriority() int
CalcPriority 根据 SourceType 和 Model 计算优先级。
type AttemptRecord ¶ added in v0.0.6
type AttemptRecord struct {
Seq int `json:"seq"` // 序号,从 1
ChannelID uint `json:"channel_id"` // admin=Channel.ID, private=PrivateChannel.ID
ChannelName string `json:"channel_name"`
Source string `json:"source"` // admin / private
RealModel string `json:"real_model"`
Retries int `json:"retries"` // 同 channel 内层重试次数(0=首发即终)
ByAffinity bool `json:"by_affinity,omitempty"`
BreakerOpen bool `json:"breaker_open,omitempty"` // 该候选因熔断 open 被跳过
HTTPStatus int `json:"http_status,omitempty"`
Status string `json:"status"` // ok / fail
ErrorType string `json:"error_type,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
DurationMs int `json:"duration_ms"`
HasTrace bool `json:"has_trace,omitempty"` // 该候选是否写了 trace 行(= 快照 verbose),供前端按条目决定是否显示调试按钮
}
AttemptRecord 是 fallback 链路里的一条:一次候选 channel 尝试的摘要。 同 channel 的内层重试折叠成 Retries 计数,不单独成条。 定义在 models 包以便 state / protocol / settler 共用而不成环。
type Channel ¶
type Channel struct {
ChannelCore
Key string `gorm:"type:text" json:"key"`
Models string `gorm:"type:text" json:"models"`
ModelMapping string `gorm:"type:text" json:"model_mapping"`
ProxyURL string `gorm:"size:256" json:"proxy_url"`
HeaderOverride string `gorm:"type:text" json:"header_override"`
// Override embedded tag: admin Channel needs an index on Tag.
Tag string `gorm:"size:64;index" json:"tag"`
// DisableKeepalive disables TCP connection reuse for this channel's upstream
// transport. Each request dials a fresh connection and closes it immediately
// after use. Useful for upstreams that exhibit stale-connection bugs at the
// cost of one extra handshake per request.
DisableKeepalive bool `json:"disable_keepalive" gorm:"default:false"`
// Resilience 是每 channel 的重试/熔断/超时覆盖,空 JSON = 全用全局默认。
Resilience datatypes.JSONType[ChannelResilience] `gorm:"type:text" json:"resilience"`
// PriceRatio 是该 channel 的计费倍率。1.0=原价,0.8=8折,>1=加价;0=原价(与 1.0 等价)。
// 取值 0 <= ratio <= 1000,默认 1.0。作用于 settler 算出的全部成本桶。
PriceRatio float64 `gorm:"default:1" json:"price_ratio"`
// Free 为 true 时该 channel 为免费渠道:settler 照常记 token,但四桶成本清零。
// 与 PriceRatio 正交(不复用 ratio=0,因 0 会被归一到原价 1.0)。
Free bool `gorm:"default:false" json:"free"`
// Limit 是该 channel 的用量/时间限额配置,空 = 不启用自动禁用。
Limit datatypes.JSONType[ChannelLimit] `gorm:"type:text" json:"limit"`
// LimitState 是限额评估器写入的运行态(为何被自动禁/能否自动恢复),API 只读不写。
LimitState datatypes.JSONType[ChannelLimitState] `gorm:"type:text" json:"limit_state"`
}
Channel is the admin-managed upstream channel. Scalar fields shared with PrivateChannel / SyncedPrivateChannel live on the embedded ChannelCore; the outer struct keeps fields whose Go type differs (Key/Models/ModelMapping all stored as text in admin) plus admin-only ProxyURL / HeaderOverride.
The Tag field is redeclared to override the ChannelCore tag with an index. BYOK PrivateChannel.Tag mirrors this index — the redeclare is purely for the index tag override, behavior is identical across both channels.
func (*Channel) GetBaseURL ¶
GetBaseURL returns the channel's base URL, falling back to the default from ChannelBaseURLs when not explicitly set. This matches the behavior of new-api's Channel.GetBaseURL().
type ChannelCore ¶ added in v0.0.2
type ChannelCore struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:64" json:"name"`
Type int `gorm:"index" json:"type"`
Status int `gorm:"default:1" json:"status"`
BaseURL string `gorm:"size:256" json:"base_url"`
Weight uint `gorm:"default:1" json:"weight"`
Priority int `gorm:"default:0" json:"priority"`
SupportedAPITypes string `gorm:"type:text" json:"supported_api_types"`
Endpoints string `gorm:"type:text" json:"endpoints"`
PassthroughEnabled bool `gorm:"default:false" json:"passthrough_enabled"`
UseLegacyAdaptor bool `gorm:"default:false" json:"use_legacy_adaptor"`
Organization string `gorm:"size:128" json:"organization"`
ApiVersion string `gorm:"size:32" json:"api_version"`
SystemPrompt string `gorm:"type:text" json:"system_prompt"`
SystemPromptInInput bool `gorm:"default:false" json:"system_prompt_in_input"`
RoleMapping string `gorm:"type:text" json:"role_mapping"`
ParamOverride string `gorm:"type:text" json:"param_override"`
Setting string `gorm:"type:text" json:"setting"`
Tag string `gorm:"size:64" json:"tag"`
Remark string `gorm:"size:255" json:"remark"`
TestModel string `gorm:"size:128" json:"test_model"`
AutoBan int `gorm:"default:0" json:"auto_ban"`
StatusCodeMapping string `gorm:"type:text" json:"status_code_mapping"`
OtherSettings string `gorm:"type:text" json:"other_settings"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
ChannelCore captures the scalar fields that admin Channel, BYOK PrivateChannel, and the master→agent SyncedPrivateChannel projection share verbatim. Fields whose Go type differs between admin (CSV text) and BYOK (strongly typed JSON) — Models / ModelMapping / Key — stay on each outer struct. ProxyURL / HeaderOverride are admin-only and likewise stay on Channel.
Embedding rules:
- GORM expands embedded struct fields into table columns without a prefix.
- Outer structs may redeclare a field (e.g. PrivateChannel.Name with a composite uniqueIndex) to override the embedded GORM tag. The redeclared field shadows the promoted one — both for tags and for composite-literal access.
- JSON tags on ChannelCore fields propagate via Go field promotion so the external JSON shape is unchanged.
type ChannelDailyBilling ¶
type ChannelDailyBilling struct {
ID uint `gorm:"primaryKey" json:"id"`
Date string `gorm:"size:10;uniqueIndex:idx_cdb_date_channel_pchan" json:"date"`
ChannelID uint `gorm:"uniqueIndex:idx_cdb_date_channel_pchan;index" json:"channel_id"`
PrivateChannelID uint `gorm:"uniqueIndex:idx_cdb_date_channel_pchan;index;default:0" json:"private_channel_id"`
OwnerType string `gorm:"size:8;default:'admin'" json:"owner_type"` // "admin" | "private"
ChannelName string `gorm:"size:64" json:"channel_name"`
ChannelType int `json:"channel_type"`
RequestCount int64 `json:"request_count"`
SuccessCount int64 `json:"success_count"`
FailedCount int64 `json:"failed_count"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
InputCost int64 `json:"input_cost"`
OutputCost int64 `json:"output_cost"`
TotalCost int64 `json:"total_cost"`
LastUsedAt int64 `gorm:"index" json:"last_used_at"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
ChannelDailyBilling 按天聚合 channel 维度用量。
同时承担两类来源:
- admin channel: channel_id>0, private_channel_id=0, owner_type="admin"
- BYOK channel: channel_id=0, private_channel_id>0, owner_type="private"
唯一键是 (date, channel_id, private_channel_id) 三列联合,保证两类行 不会因为对方那一列都填 0 而互相冲突——同一天内 admin channel 5 落在 (date, 5, 0),BYOK pchan 7 落在 (date, 0, 7),互不影响。
旧 unique index idx_channel_daily_billing_date_channel 由 migrate.go 的 dropLegacyChannelBillingIndex 在启动时自动 drop(SQLite IF EXISTS 幂等)。
type ChannelLimit ¶ added in v0.0.6
ChannelLimit 是渠道的用量/时间限额配置(管理员设置)。空 = 不启用自动禁用。 多条 Rules 取 OR:任一超限即禁用。DisableAt>0 时到点(绝对截止)永久禁用。
func (ChannelLimit) Validate ¶ added in v0.0.6
func (l ChannelLimit) Validate() error
Validate 校验配置合法性,落库前调用(仿 ChannelResilience.Validate)。
type ChannelLimitState ¶ added in v0.0.6
type ChannelLimitState struct {
Tripped bool `json:"tripped"`
Reason string `json:"reason"`
AutoRecover bool `json:"auto_recover"`
TrippedAt int64 `json:"tripped_at"`
}
ChannelLimitState 是限额评估器写入的运行态(为何被自动禁/能否自动恢复)。API 只读不写。
type ChannelResilience ¶ added in v0.0.6
type ChannelResilience struct {
MaxRetries *int `json:"max_retries,omitempty"`
BackoffBaseMs *int `json:"backoff_base_ms,omitempty"`
BackoffMaxMs *int `json:"backoff_max_ms,omitempty"`
BreakerThreshold *int `json:"breaker_threshold,omitempty"`
BreakerCooldownMs *int `json:"breaker_cooldown_ms,omitempty"`
BreakerEnabled *bool `json:"breaker_enabled,omitempty"`
}
ChannelResilience 是每 channel 的韧性参数覆盖(全局默认之上)。 字段全为指针:nil = 用全局默认;非 nil(含零值)= 显式覆盖。 定义在 models 包以避免 resilience→state→models 的循环 import; resilience 包以类型别名复用它。
func (ChannelResilience) Validate ¶ added in v0.0.6
func (r ChannelResilience) Validate() error
Validate 校验每 channel 覆盖值的边界,与全局 Settings 的 min/max 一致。 非法值(如 max_retries=-1 会变成无限重试、breaker_threshold=0 会首次失败即永久熔断) 必须在落库前拒掉。nil 字段表示不覆盖,跳过。
type EnrollmentToken ¶
type InviteCode ¶ added in v0.0.6
type InviteCode struct {
ID uint `gorm:"primaryKey" json:"id"`
Code string `gorm:"uniqueIndex;size:32;not null" json:"code"`
CreatorID uint `gorm:"index;not null" json:"creator_id"`
MaxUses int `gorm:"not null;default:1" json:"max_uses"`
UsedCount int `gorm:"not null;default:0" json:"used_count"`
ExpiresAt int64 `gorm:"default:0" json:"expires_at"`
Note string `gorm:"size:128" json:"note"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
InviteCode 是一张邀请码。CreatorID 标识归属(用于普通用户限额与审计)。 "有效"= UsedCount < MaxUses 且 (ExpiresAt == 0 或 ExpiresAt > now)。
type InviteRedemption ¶ added in v0.0.6
type InviteRedemption struct {
ID uint `gorm:"primaryKey" json:"id"`
InviteCodeID uint `gorm:"index;not null" json:"invite_code_id"`
Code string `gorm:"size:32;index;not null" json:"code"`
InviterID uint `gorm:"index;not null" json:"inviter_id"`
InviteeID uint `gorm:"uniqueIndex;not null" json:"invitee_id"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
}
InviteRedemption 记录一次成功的邀请注册(一行=一个被邀用户),用于审计。 InviteeID 唯一:一个用户只能被邀请注册一次。
type LimitRule ¶ added in v0.0.6
type LimitRule struct {
Metric string `json:"metric"`
Window string `json:"window"`
Days int `json:"days"`
Threshold int64 `json:"threshold"`
}
LimitRule 是单条用量限额规则。Threshold:calls=请求次数;cost=quota 单位(=美元×100000)。
type LimiterBinding ¶ added in v0.0.8
type LimiterBinding struct {
ID uint `json:"id" gorm:"primaryKey"`
LimiterID uint `json:"limiter_id" gorm:"index;uniqueIndex:uk_limiter_binding"`
TargetType string `json:"target_type" gorm:"size:16;uniqueIndex:uk_limiter_binding;index:idx_lb_target"` // global|channel|user_group|user
TargetID uint `json:"target_id" gorm:"uniqueIndex:uk_limiter_binding;index:idx_lb_target"` // global 时为 0
Enabled bool `json:"enabled" gorm:"default:true"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"`
}
LimiterBinding 只回答"这条 limiter 作用到谁"。 一个 limiter 可多绑定;一个对象可被多 limiter 命中(多对多)。
正交说明:TargetType(global/channel/user_group/user)决定"规则挂在哪个对象上 + 就近覆盖的精细度(specificity)",与 RequestLimiter.KeyBy(分桶维度 shared/per_user/…) 是两套独立的枚举,不需一一对应(如 binding 无 per_channel_user 对应项,KeyBy 无 user_group 对应项)。
type ModelConfig ¶
type ModelConfig struct {
ID uint `gorm:"primaryKey" json:"id"`
ModelName string `gorm:"uniqueIndex;size:128" json:"model_name"`
InputPrice float64 `gorm:"default:0" json:"input_price"`
OutputPrice float64 `gorm:"default:0" json:"output_price"`
CacheReadPrice float64 `gorm:"default:0" json:"cache_read_price"`
CacheWritePrice float64 `gorm:"default:0" json:"cache_write_price"`
Status int `gorm:"default:1" json:"status"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
type ModelRouting ¶
type ModelRouting struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"size:128;index;uniqueIndex:uidx_routing_scope_user_name" json:"name"`
Scope string `gorm:"size:8;index;uniqueIndex:uidx_routing_scope_user_name" json:"scope"` // "global" | "user"
UserID uint `gorm:"index;uniqueIndex:uidx_routing_scope_user_name" json:"user_id"` // scope=global 时为 0
Members string `gorm:"type:text" json:"members"` // JSON: []RoutingMember
Enabled bool `gorm:"default:true" json:"enabled"`
Remark string `gorm:"size:255" json:"remark"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
func (ModelRouting) TableName ¶
func (ModelRouting) TableName() string
type OAuthIdentity ¶
type OAuthIdentity struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index" json:"user_id"`
ProviderID uint `gorm:"index;uniqueIndex:uk_provider_subject,priority:1" json:"provider_id"`
Subject string `gorm:"size:255;uniqueIndex:uk_provider_subject,priority:2" json:"subject"`
Email string `gorm:"size:255" json:"email"`
DisplayName string `gorm:"size:128" json:"display_name"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
type OAuthProvider ¶
type OAuthProvider struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"uniqueIndex;size:32" json:"name"`
DisplayName string `gorm:"size:64" json:"display_name"`
Issuer string `gorm:"size:255" json:"issuer"`
AuthorizationEndpoint string `gorm:"size:512" json:"authorization_endpoint"`
TokenEndpoint string `gorm:"size:512" json:"token_endpoint"`
UserinfoEndpoint string `gorm:"size:512" json:"userinfo_endpoint"`
JWKSURI string `gorm:"size:512" json:"jwks_uri"`
ClientID string `gorm:"size:255" json:"client_id"`
ClientSecret string `gorm:"size:255" json:"client_secret,omitempty"`
Scopes string `gorm:"size:255" json:"scopes"`
IconURL string `gorm:"size:512" json:"icon_url"`
Enabled bool `gorm:"default:true" json:"enabled"`
Protocol string `gorm:"size:16;default:oidc;not null" json:"protocol"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
type PrivateChannel ¶ added in v0.0.2
type PrivateChannel struct {
ChannelCore
OwnerID uint `gorm:"index:idx_pchan_owner_status;not null;uniqueIndex:uidx_pchan_owner_name" json:"owner_id"`
KeyCipher []byte `gorm:"type:blob" json:"-"`
KeyLast4 string `gorm:"size:8" json:"key_last4"`
// Strongly-typed BYOK-only fields (admin Channel stores these as CSV/JSON text).
Models datatypes.JSONSlice[string] `gorm:"type:text" json:"models"`
ModelMapping datatypes.JSONType[map[string]string] `gorm:"type:text" json:"model_mapping"`
// Redeclared to override the ChannelCore gorm tag. Name/Status carry composite
// indexes scoped to (owner_id, ...); Tag carries a single-column index to match
// admin Channel.Tag behavior. Same JSON tags preserve the wire shape.
Name string `gorm:"size:64;uniqueIndex:uidx_pchan_owner_name" json:"name"`
Status int `gorm:"index:idx_pchan_owner_status;default:1" json:"status"`
Tag string `gorm:"size:64;index" json:"tag"`
}
PrivateChannel 是用户自助上传的 BYOK channel。 与 admin Channel 共享的标量字段抽进 ChannelCore(gorm embed 自动展开为列); 仅保留 BYOK 专属字段(Owner/KeyCipher/KeyLast4),以及 Go 类型与 admin 不同的 Models / ModelMapping(强类型 JSON)。Name / Status / Tag 重声明以覆盖 ChannelCore 的 gorm tag——Name/Status 挂 owner 维度复合索引,Tag 加单列 index 与 admin Channel 对齐(admin Channel.Tag 历来带 index,重构不改变现状)。
func (PrivateChannel) TableName ¶ added in v0.0.2
func (PrivateChannel) TableName() string
type PrivateChannelShare ¶ added in v0.0.2
type PrivateChannelShare struct {
}
PrivateChannelShare 是 v1 落地但 API 不暴露的旁路表。 一条记录代表一个分享条目:把某 channel 分享给一个 user 或一个 user_group。
func (PrivateChannelShare) TableName ¶ added in v0.0.2
func (PrivateChannelShare) TableName() string
type RateLimitHit ¶ added in v0.0.8
type RateLimitHit struct {
LimiterID uint `json:"limiter_id"`
Name string `json:"name"`
Dimension string `json:"dimension"` // metric/key_by,如 "concurrency/per_channel"
Bucket string `json:"bucket"` // 命中的分桶键(bucketOf),如 "c:channel:42",排障定位到具体桶
Decision string `json:"decision"` // allow|queued|rejected
WaitMs int `json:"wait_ms"`
}
RateLimitHit 是一条 limiter 在某次请求里的命中明细(落 usage_log 的 JSONSlice 列)。
type RequestLimiter ¶ added in v0.0.8
type RequestLimiter struct {
ID uint `json:"id" gorm:"primaryKey"`
Name string `json:"name" gorm:"size:128;index"`
Enabled bool `json:"enabled" gorm:"default:true"`
// 限什么资源
Metric string `json:"metric" gorm:"size:16"` // "concurrency" | "rate"
Capacity int64 `json:"capacity"` // 并发上限 / 每窗口请求数上限
WindowMs int `json:"window_ms"` // 仅 rate;concurrency 填 0
// 额度怎么分 + 作用于哪类渠道
KeyBy string `json:"key_by" gorm:"size:24"` // shared|per_user|per_group|per_channel|per_channel_user
ChannelScope string `json:"channel_scope" gorm:"size:8"` // admin|private|all(仅对 channel-keyed 生效)
// 超了怎么办
Action string `json:"action" gorm:"size:8"` // "reject" | "wait"
QueueSize int `json:"queue_size"` // wait: 超容量后最多排多少个; 0=不排
QueueTimeMs int `json:"queue_time_ms"` // wait: 最长排队; 0=用全局默认设置
Priority int `json:"priority" gorm:"index"` // 同精细度并列 tie-break + 列表排序
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime"`
UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime"`
}
RequestLimiter 是一条请求级限流策略:限什么资源、限多少、额度怎么分、超了怎么办。 绑定关系另见 LimiterBinding;执行见 internal/agent/relay/limiter。
func (*RequestLimiter) ChannelKeyed ¶ added in v0.0.8
func (l *RequestLimiter) ChannelKeyed() bool
ChannelKeyed 报告该 KeyBy 是否依赖具体渠道(决定落请求级还是尝试级闸门)。
type RoutingMember ¶
type ScriptScope ¶ added in v0.0.6
type ScriptScope struct {
ChannelIDs []uint `json:"channel_ids"`
ModelNames []string `json:"model_names"`
}
ScriptScope 决定一个脚本对哪些请求生效。 ChannelIDs 与 ModelNames 均为空 = 全局;否则命中的 channel 或 model 命中任一列表即生效。
type Setting ¶
type Setting struct {
Key string `gorm:"primaryKey;size:64" json:"key"`
Value string `gorm:"type:text" json:"value"`
}
Setting stores key-value pairs for persistent server state
type Token ¶
type Token struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index" json:"user_id"`
Key string `gorm:"uniqueIndex;size:64" json:"key"`
Name string `gorm:"size:64" json:"name"`
Status int `gorm:"default:1" json:"status"`
ExpiredAt int64 `gorm:"default:-1" json:"expired_at"`
Models string `gorm:"type:text" json:"models"`
TemplateID *uint `gorm:"index" json:"template_id"`
TraceEnabled bool `gorm:"default:false" json:"trace_enabled"`
AllowedChannelIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_channel_ids"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
type TokenDailyBilling ¶
type TokenDailyBilling struct {
ID uint `gorm:"primaryKey" json:"id"`
Date string `gorm:"size:10;uniqueIndex:idx_token_daily_billing_date_user_token" json:"date"`
UserID uint `gorm:"uniqueIndex:idx_token_daily_billing_date_user_token;index" json:"user_id"`
TokenID uint `gorm:"uniqueIndex:idx_token_daily_billing_date_user_token;index" json:"token_id"`
TokenName string `gorm:"size:64" json:"token_name"`
RequestCount int64 `json:"request_count"`
SuccessCount int64 `json:"success_count"`
FailedCount int64 `json:"failed_count"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
InputCost int64 `json:"input_cost"`
OutputCost int64 `json:"output_cost"`
TotalCost int64 `json:"total_cost"`
LastUsedAt int64 `gorm:"index" json:"last_used_at"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
type TokenTemplate ¶
type TokenTemplate struct {
ID uint `gorm:"primarykey" json:"id"`
Name string `gorm:"size:64;not null" json:"name"`
Models string `gorm:"type:text" json:"models"`
ExpiryDays int `gorm:"not null;default:-1" json:"expiry_days"`
Status int `gorm:"not null;default:1" json:"status"`
AllowedChannelIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_channel_ids"`
AllowedGroupIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_group_ids"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
func (*TokenTemplate) AllowsGroup ¶ added in v0.0.8
func (t *TokenTemplate) AllowsGroup(groupID uint) bool
AllowsGroup 报告该模版是否对指定用户组开放。 空白名单语义:未配置任何组 = 对所有组开放(向后兼容)。
type UsageHourlyBucket ¶ added in v0.0.2
type UsageHourlyBucket struct {
ID uint `gorm:"primaryKey" json:"id"`
Date string `gorm:"size:10;uniqueIndex:idx_uhb_bucket" json:"date"` // YYYY-MM-DD UTC
Hour int `gorm:"uniqueIndex:idx_uhb_bucket" json:"hour"` // 0..23 UTC
ChannelID uint `gorm:"uniqueIndex:idx_uhb_bucket;index" json:"channel_id"` // 0 = BYOK
PrivateChannelID uint `gorm:"uniqueIndex:idx_uhb_bucket;index;default:0" json:"private_channel_id"` // 0 = admin
ModelName string `gorm:"size:128;uniqueIndex:idx_uhb_bucket;index" json:"model_name"` // e.g. "gpt-4o"
AgentID string `gorm:"size:64;uniqueIndex:idx_uhb_bucket;index" json:"agent_id"` // e.g. "cn-1"
OwnerType string `gorm:"size:8;default:'admin'" json:"owner_type"`
ChannelName string `gorm:"size:64" json:"channel_name"`
ChannelType int `json:"channel_type"`
RequestCount int64 `json:"request_count"`
SuccessCount int64 `json:"success_count"`
FailedCount int64 `json:"failed_count"`
PromptTokens int64 `json:"prompt_tokens"`
CompletionTokens int64 `json:"completion_tokens"`
CacheReadTokens int64 `json:"cache_read_tokens"`
CacheWriteTokens int64 `json:"cache_write_tokens"`
InputCost int64 `json:"input_cost"`
OutputCost int64 `json:"output_cost"`
TotalCost int64 `json:"total_cost"`
// 速度累计 (仅 stream + success + completion_tokens > 0 才入)
StreamRequestCount int64 `json:"stream_request_count"`
SumFirstResponseMs int64 `json:"sum_first_response_ms"`
SumGenerationMs int64 `json:"sum_generation_ms"` // = Duration − FirstResponseMs
SumStreamCompletionTokens int64 `json:"sum_stream_completion_tokens"`
// 五段延迟累计 (仅成功)
SumInboundDecodeMs int64 `json:"sum_inbound_decode_ms"`
SumUpstreamDispatchMs int64 `json:"sum_upstream_dispatch_ms"`
SumUpstreamDecodeMs int64 `json:"sum_upstream_decode_ms"`
SumOutboundEncodeMs int64 `json:"sum_outbound_encode_ms"`
SumClientEncodeMs int64 `json:"sum_client_encode_ms"`
LastUsedAt int64 `gorm:"index" json:"last_used_at"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
UsageHourlyBucket 是小时级用量聚合表。
维度: (date, hour, channel_id, private_channel_id, model_name, agent_id) 故意不带 user_id —— 用户级 hour 趋势走 UsageLog 原表; 带 user_id 会让 基数膨胀到不可控 (1k user × 20 model × 5 ch × 24h ≈ 240w 行/天)。
维度约定与 ChannelDailyBilling 一致:
admin channel 行: (D, H, 5, 0, "gpt-4o", "cn-1") BYOK pchan 行: (D, H, 0, 7, "gpt-4o", "cn-1")
type UsageLog ¶
type UsageLog struct {
ID uint `gorm:"primaryKey" json:"id"`
UserID uint `gorm:"index" json:"user_id"`
TokenID uint `gorm:"index" json:"token_id"`
ChannelID uint `gorm:"index" json:"channel_id"`
PrivateChannelID uint `gorm:"index;default:0" json:"private_channel_id"` // 0 = 非 BYOK 请求
OwnerType string `gorm:"size:8;default:'admin'" json:"owner_type"` // "admin" | "private"
AgentID string `gorm:"index;size:64" json:"agent_id"`
ModelName string `gorm:"size:128;index" json:"model_name"`
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
InputCost int64 `json:"input_cost"`
OutputCost int64 `json:"output_cost"`
TotalCost int64 `json:"total_cost"`
// CacheReadCost / CacheWriteCost 是 cache 两桶的实付成本(此前只并进 TotalCost,未单列)。
CacheReadCost int64 `json:"cache_read_cost"`
CacheWriteCost int64 `json:"cache_write_cost"`
// Raw* 是乘任何计费因子之前的原价四桶快照;可空(*int64),NULL=上线前老行→前端弹窗降级不出公式。
RawInputCost *int64 `json:"raw_input_cost"`
RawOutputCost *int64 `json:"raw_output_cost"`
RawCacheReadCost *int64 `json:"raw_cache_read_cost"`
RawCacheWriteCost *int64 `json:"raw_cache_write_cost"`
// BillingFactor 是实际生效倍率(普通=price_ratio,免费=0,BYOK免费=0,BYOK服务费=service_fee_ratio);
// 可空,NULL=老行。与 PriceRatio(渠道配置倍率)语义区分。
BillingFactor *float64 `json:"billing_factor"`
// Free 标记这行是否走了免费渠道,供前端展示模式标签;技术上可由 owner_type+factor 推导,显式更稳。
Free bool `json:"free"`
PriceRatio float64 `gorm:"default:1" json:"price_ratio"`
IsStream bool `json:"is_stream"`
Duration int `json:"duration"`
RequestID string `gorm:"size:64;uniqueIndex" json:"request_id"`
ClientIP string `gorm:"size:64" json:"client_ip"`
CreatedAt int64 `gorm:"autoCreateTime;index" json:"created_at"`
// Enhanced logging fields
TokenName string `gorm:"size:64" json:"token_name"`
ChannelName string `gorm:"size:64" json:"channel_name"`
ChannelType int `json:"channel_type"`
UpstreamModel string `gorm:"size:128" json:"upstream_model"`
FirstResponseMs int `json:"first_response_ms"`
CacheReadTokens int `json:"cache_read_tokens"`
CacheWriteTokens int `json:"cache_write_tokens"`
InboundProtocol string `gorm:"size:16" json:"inbound_protocol"`
OutboundProtocol string `gorm:"size:16" json:"outbound_protocol"`
UseLegacy bool `json:"use_legacy"`
Status int `json:"status"` // 1=成功, 0=失败
ErrorMessage string `gorm:"type:text" json:"error_message"`
Other string `gorm:"type:text" json:"other"`
HasTrace bool `json:"has_trace"`
FallbackChain datatypes.JSONSlice[AttemptRecord] `gorm:"type:text" json:"fallback_chain"`
TokenSource string `gorm:"size:32" json:"token_source"`
RoutingName string `gorm:"size:128;index" json:"routing_name"`
AffinityStatus string `gorm:"size:16" json:"affinity_status"`
AffinityRecorded bool `json:"affinity_recorded"`
ErrorStage string `gorm:"size:32;index" json:"error_stage"`
InboundDecodeMs int `json:"inbound_decode_ms"`
OutboundEncodeMs int `json:"outbound_encode_ms"`
UpstreamDispatchMs int `json:"upstream_dispatch_ms"`
UpstreamDecodeMs int `json:"upstream_decode_ms"`
ClientEncodeMs int `json:"client_encode_ms"`
// 请求级限流决策快照:Decision(allow|queued|rejected) / 累计等待 / 人话原因 / 命中明细。
RateLimitDecision string `gorm:"size:16;index" json:"rate_limit_decision"`
RateLimitWaitMs int `json:"rate_limit_wait_ms"`
RateLimitReason string `gorm:"size:256" json:"rate_limit_reason"`
RateLimitHits datatypes.JSONSlice[RateLimitHit] `gorm:"type:text" json:"rate_limit_hits"`
}
type UsageLogTrace ¶
type UsageLogTrace struct {
ID uint `gorm:"primaryKey" json:"id"`
RequestID string `gorm:"size:64;index:idx_trace_req_attempt,unique;index" json:"request_id"`
AttemptIndex int `gorm:"index:idx_trace_req_attempt,unique" json:"attempt_index"`
InboundPath string `gorm:"size:256" json:"inbound_path"`
OutboundPath string `gorm:"size:256" json:"outbound_path"`
InboundHeaders string `gorm:"type:text" json:"inbound_headers"`
OutboundHeaders string `gorm:"type:text" json:"outbound_headers"`
InboundBody string `gorm:"type:text" json:"inbound_body"`
OutboundBody string `gorm:"type:text" json:"outbound_body"`
ResponseHeaders string `gorm:"type:text" json:"response_headers"`
ResponseBody string `gorm:"type:text" json:"response_body"`
ClientResponseBody string `gorm:"type:text" json:"client_response_body"`
UpstreamStatus int `json:"upstream_status"`
ErrorStage string `gorm:"size:32;index" json:"error_stage"`
CreatedAt int64 `gorm:"autoCreateTime;index" json:"created_at"`
}
type User ¶
type User struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"uniqueIndex;size:64" json:"username"`
Email string `gorm:"size:191" json:"email"`
DisplayName string `gorm:"size:64" json:"display_name"`
AvatarURL string `gorm:"size:512" json:"avatar_url"`
Password string `gorm:"size:128" json:"password,omitempty"`
Role int `gorm:"default:1" json:"role"`
Status int `gorm:"default:1" json:"status"`
GroupID uint `gorm:"index;default:1" json:"group_id"`
Quota int64 `gorm:"default:0" json:"quota"`
UsedQuota int64 `gorm:"default:0" json:"used_quota"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
PasswordSet bool `gorm:"default:false" json:"password_set"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
type UserGroup ¶
type UserGroup struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"uniqueIndex;size:64;not null" json:"name"`
Description string `gorm:"size:255" json:"description"`
Status int `gorm:"default:1" json:"status"`
AllowedChannelIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_channel_ids"`
Models string `gorm:"type:text" json:"models"`
BYOKEnabled *bool `gorm:"default:null" json:"byok_enabled"`
BYOKMaxChannels *int `gorm:"default:null" json:"byok_max_channels"`
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}
Source Files
¶
- agent.go
- agent_route.go
- attempt_record.go
- billing_daily.go
- channel.go
- channel_core.go
- channel_limit.go
- enrollment_token.go
- invite_code.go
- invite_redemption.go
- limiter_binding.go
- migrate.go
- model_config.go
- model_routing.go
- oauth_identity.go
- oauth_provider.go
- private_channel.go
- private_channel_share.go
- request_limiter.go
- script.go
- seed.go
- setting.go
- token.go
- token_template.go
- usage_hourly_bucket.go
- usage_log.go
- usage_log_trace.go
- user.go
- user_group.go