models

package
v0.0.27 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

internal/models/user_group.go

Index

Constants

View Source
const (
	AgentRouteSourceToken      = "token"
	AgentRouteSourceChannel    = "channel"
	AgentRouteSourceAPIService = "api_service"
	AgentRouteSourceAPIRoute   = "api_route"
)
View Source
const (
	AgentPathLocal  AgentPathKind = "local"
	AgentPathDirect AgentPathKind = "direct"
	AgentPathRelay  AgentPathKind = "relay"

	AgentPathSelected    AgentPathResult = "selected"
	AgentPathDisabled    AgentPathResult = "disabled"
	AgentPathUnavailable AgentPathResult = "unavailable"
	AgentPathRejected    AgentPathResult = "rejected"
	AgentPathUncertain   AgentPathResult = "uncertain"

	AgentPathConnect      AgentPathStage = "connect"
	AgentPathPolicy       AgentPathStage = "policy"
	AgentPathAuthenticate AgentPathStage = "authenticate"
	AgentPathDispatch     AgentPathStage = "dispatch"
	AgentPathResponse     AgentPathStage = "response"

	AgentPathNotCommitted    AgentPathCommitState = "not_committed"
	AgentPathCommitted       AgentPathCommitState = "committed"
	AgentPathCommitUncertain AgentPathCommitState = "uncertain"
)
View Source
const (
	LimitMetricCalls = "calls"
	LimitMetricCost  = "cost"

	LimitWindowLifetime    = "lifetime"
	LimitWindowDaily       = "daily"
	LimitWindowWeekly      = "weekly"
	LimitWindowMonthly     = "monthly"
	LimitWindowRollingDays = "rolling_days"

	// cost 指标的成本口径:raw=折扣前原价(真实成本),billed=折扣后实付额度。空 = raw。
	CostBasisRaw    = "raw"
	CostBasisBilled = "billed"
)

限额指标 / 窗口枚举。

View Source
const (
	DailyBillingBackfillPending   DailyBillingBackfillState = "pending"
	DailyBillingBackfillRunning   DailyBillingBackfillState = "running"
	DailyBillingBackfillFailed    DailyBillingBackfillState = "failed"
	DailyBillingBackfillCompleted DailyBillingBackfillState = "completed"

	DailyBillingBackfillVersion uint = 1
)
View Source
const (
	DatabaseLayoutVersion = 1
	DatabaseLayoutID      = 1
	DatabaseRoleCore      = "core"
	DatabaseRoleLog       = "log"
)
View Source
const (
	LimiterTargetGlobal      = "global"
	LimiterTargetChannel     = "channel"
	LimiterTargetUserGroup   = "user_group"
	LimiterTargetUser        = "user"
	LimiterTargetAPIService  = "api_service"
	LimiterTargetAPIRoute    = "api_route"
	LimiterTargetAPIUpstream = "api_upstream"
)
View Source
const (
	RoutingScopeGlobal = "global"
	RoutingScopeUser   = "user"
	RoutingScopeToken  = "token"
)
View Source
const (
	PrivateShareTargetUser  = "user"
	PrivateShareTargetGroup = "group"
)
View Source
const (
	MaxRateLimitHitNameBytes = 128

	LimiterMetricConcurrency = "concurrency"
	LimiterMetricRate        = "rate"

	LimiterKeyShared         = "shared"
	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 处,否则会静默错误:

  1. (*RequestLimiter).ChannelKeyed() —— 决定该规则落请求级还是尝试级闸门;
  2. cache.LimiterIndex.Effective{Request,Attempt}Limiters 的入参 —— 新分桶维度 (如 per_model) 需要新数据从热路径透传进来;
  3. limiter.bucketOf() 的 switch —— 其 default 会把未识别 KeyBy 静默并入 "shared" 桶。
View Source
const BillingProjectionBaselineID uint = 1
View Source
const DefaultUserGroupID uint = 1
View Source
const HistoryMigrationSingletonID uint = 1
View Source
const MaxAPIRequestExampleBytes = 64 * 1024

Variables

View Source
var (
	ErrUpstreamAuthHeader   = errors.New("upstream auth header is invalid")
	ErrUpstreamAuthValue    = errors.New("upstream auth value is invalid")
	ErrUpstreamAuthProtocol = errors.New("upstream auth protocol is unsupported")
)

Functions

func APIRequestExampleErrorCode added in v0.0.16

func APIRequestExampleErrorCode(err error) (string, bool)

func AutoMigrate

func AutoMigrate(db *gorm.DB) error

func IsAPILimiterTarget added in v0.0.16

func IsAPILimiterTarget(targetType string) bool

func ManagedAPIRoleKey added in v0.0.16

func ManagedAPIRoleKey(principalType APIPrincipalType, principalID uint) string

func MigrateCoreDB added in v0.0.14

func MigrateCoreDB(db *gorm.DB) error

func MigrateLogDB added in v0.0.14

func MigrateLogDB(db *gorm.DB) error

func NormalizeStandardHTTPMethod added in v0.0.18

func NormalizeStandardHTTPMethod(method string) (string, bool)

NormalizeStandardHTTPMethod returns the canonical uppercase form of a standard HTTP method supported by API routes. CONNECT is intentionally not supported because routes do not expose tunnel semantics.

func SeedBYOKSettings added in v0.0.2

func SeedBYOKSettings(db *gorm.DB) error

SeedBYOKSettings 把 BYOK 相关默认 settings 写入;仅在 key 不存在时插入, 已有值(如 admin 改过的)保留不覆盖。idempotent,可在每次启动调用。

func SeedDefaultUserGroup

func SeedDefaultUserGroup(db *gorm.DB) error

SeedDefaultUserGroup ensures the id=1 default user_group exists, and backfills users whose group_id is 0 / NULL to 1. Idempotent.

func SeedGatewayAdminRole added in v0.0.16

func SeedGatewayAdminRole(db *gorm.DB) error

SeedGatewayAdminRole keeps the built-in generic API administrator role and its global invoke grant present. It intentionally never creates a binding: Master derives this role into every administrator's effective API RoleSet.

func TokenFieldsEqual

func TokenFieldsEqual(tplModelsJSON string, tplChannelIDs []uint, tok *Token) bool

func TokenFieldsEqualForFields added in v0.0.10

func TokenFieldsEqualForFields(tpl *TokenTemplate, tok *Token, f SyncFields) bool

TokenFieldsEqualForFields 只比较 f 选中的字段;未选字段视为相等(不参与差异判定)。

func UserGroupAccessDisabled added in v0.0.15

func UserGroupAccessDisabled(group *UserGroup) bool

UserGroupAccessDisabled follows the relay authorization contract: the default group remains usable even if its persisted disabled flag is set.

func ValidAPILimiterBinding added in v0.0.16

func ValidAPILimiterBinding(limiter RequestLimiter, targetType string) bool

ValidAPILimiterBinding is the write-side contract for API resource bindings. ChannelScope belongs only to the LLM channel hot path and must be empty here.

func ValidAction added in v0.0.8

func ValidAction(action string) bool

ValidAction 报告超容量处置方式是否合法(reject 拒绝 / wait 排队)。

func ValidBindingTarget added in v0.0.8

func ValidBindingTarget(keyBy, targetType string) bool

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

func ValidChannelScope(scope string) bool

ValidChannelScope 报告渠道作用域是否合法。空串视为 admin(向后兼容默认), 仅 channel-keyed 规则真正使用此值,但写入侧统一拦脏枚举防后续静默漂移。

func ValidRateLimitText added in v0.0.16

func ValidRateLimitText(value string, maxBytes int, allowEmpty bool) bool

ValidRateLimitText reports whether a limiter-owned text fact is safe to persist and carry on the wire without normalization or replacement.

func ValidRequestLimiterName added in v0.0.16

func ValidRequestLimiterName(value string) bool

func ValidateChannelAuth added in v0.0.27

func ValidateChannelAuth(auth ChannelAuth) error

ValidateChannelAuth 校验整体和协议认证的头名、值与协议键。

func ValidateToolCompatibility added in v0.0.26

func ValidateToolCompatibility(otherSettings string) error

ValidateToolCompatibility 校验渠道工具兼容规则的模型正则和兼容方式。

func WireSafeRequestLimiterName added in v0.0.16

func WireSafeRequestLimiterName(limiterID uint, persistedName string) string

WireSafeRequestLimiterName preserves a valid persisted name and gives legacy invalid rows a stable, traceable fallback without changing the limiter ID.

Types

type APIBackend added in v0.0.16

type APIBackend struct {
	ID           uint   `gorm:"primaryKey" json:"id"`
	APIServiceID uint   `gorm:"not null;uniqueIndex:idx_api_backend_service_name" json:"api_service_id"`
	Name         string `gorm:"size:64;not null;uniqueIndex:idx_api_backend_service_name" json:"name"`
	CreatedAt    int64  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt    int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

APIBackend groups the upstream pool selected by routes in one API service.

func (*APIBackend) BeforeCreate added in v0.0.16

func (b *APIBackend) BeforeCreate(*gorm.DB) error

func (*APIBackend) BeforeUpdate added in v0.0.16

func (b *APIBackend) BeforeUpdate(tx *gorm.DB) error

func (*APIBackend) Validate added in v0.0.16

func (b *APIBackend) Validate() error

type APIBodyCapture added in v0.0.16

type APIBodyCapture struct {
	Captured      bool   `json:"captured"`
	Status        string `json:"status,omitempty"`
	SkipReason    string `json:"skip_reason,omitempty"`
	Data          string `json:"data,omitempty"`
	CapturedBytes int64  `json:"captured_bytes,omitempty"`
	TotalBytes    int64  `json:"total_bytes,omitempty"`
	Truncated     bool   `json:"truncated,omitempty"`
}

type APIPermissionAction added in v0.0.16

type APIPermissionAction string
const (
	APIPermissionInvoke APIPermissionAction = "invoke"
)

type APIPrincipalType added in v0.0.16

type APIPrincipalType string
const (
	APIPrincipalUser      APIPrincipalType = "user"
	APIPrincipalUserGroup APIPrincipalType = "user_group"
	APIPrincipalToken     APIPrincipalType = "token"
)

type APIProtocol added in v0.0.16

type APIProtocol string
const (
	APIProtocolHTTP      APIProtocol = "http"
	APIProtocolWebSocket APIProtocol = "websocket"
)

type APIRequestExample added in v0.0.16

type APIRequestExample struct {
	Method  string            `json:"method"`
	Subpath string            `json:"subpath"`
	Query   string            `json:"query"`
	Headers map[string]string `json:"headers"`
	Body    string            `json:"body"`
}

APIRequestExample is a route-local request template for operators and API consumers. It intentionally excludes credentials and gateway execution state.

func NormalizeAPIRequestExample added in v0.0.16

func NormalizeAPIRequestExample(example APIRequestExample, allowedMethods datatypes.JSONSlice[string]) (APIRequestExample, error)

NormalizeAPIRequestExample produces the only request-example representation that may be persisted on an API route. It is deliberately independent from runtime forwarding: this protects operator documentation without changing data-plane request behavior.

func (APIRequestExample) MarshalJSON added in v0.0.16

func (e APIRequestExample) MarshalJSON() ([]byte, error)

type APIRequestExampleError added in v0.0.16

type APIRequestExampleError struct {
	Code string
}

func (*APIRequestExampleError) Error added in v0.0.16

func (e *APIRequestExampleError) Error() string

type APIRequestLog added in v0.0.16

type APIRequestLog struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	RequestID string `gorm:"size:64;not null;uniqueIndex" json:"request_id"`
	UserID    uint   `gorm:"index" json:"user_id"`
	TokenID   uint   `gorm:"index" json:"token_id"`
	TokenName string `gorm:"size:64" json:"token_name"`
	ClientIP  string `gorm:"size:64" json:"client_ip"`

	APIServiceID    uint   `gorm:"index" json:"api_service_id"`
	APIServiceName  string `gorm:"size:128" json:"api_service_name"`
	APIRouteID      uint   `gorm:"index" json:"api_route_id"`
	APIRouteName    string `gorm:"size:128" json:"api_route_name"`
	APIUpstreamID   uint   `gorm:"index" json:"api_upstream_id"`
	APIUpstreamName string `gorm:"size:128" json:"api_upstream_name"`

	Protocol APIProtocol `gorm:"size:16" json:"protocol"`
	Method   string      `gorm:"size:16" json:"method"`
	Subpath  string      `gorm:"type:text" json:"subpath"`

	SourceAgentID    string `gorm:"size:128;index" json:"source_agent_id"`
	ExecutionAgentID string `gorm:"size:128;index" json:"execution_agent_id"`
	AgentRouteID     uint   `gorm:"index" json:"agent_route_id"`
	AgentRoutePath   string `gorm:"size:256" json:"agent_route_path"`

	StatusCode         int   `gorm:"index" json:"status_code"`
	DurationMs         int   `json:"duration_ms"`
	FirstByteMs        int   `json:"first_byte_ms"`
	RequestBytes       int64 `json:"request_bytes"`
	ResponseBytes      int64 `json:"response_bytes"`
	WebSocketCloseCode *int  `json:"websocket_close_code"`

	ProviderDispatchKnown      bool                              `json:"provider_dispatch_known"`
	ProviderDispatched         bool                              `json:"provider_dispatched"`
	QuotaGateDecision          string                            `gorm:"size:16;index" json:"quota_gate_decision"`
	ErrorStage                 string                            `gorm:"size:32;index" json:"error_stage"`
	ErrorCode                  string                            `gorm:"size:64;index" json:"error_code"`
	ErrorMessage               string                            `gorm:"type:text" json:"error_message"`
	ServiceMissingAtSettlement bool                              `gorm:"index" json:"service_missing_at_settlement"`
	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"`
	UnitPrice                  int64                             `json:"unit_price"`
	TotalCost                  int64                             `json:"total_cost"`
	CreatedAt                  int64                             `gorm:"autoCreateTime;index" json:"created_at"`
}

APIRequestLog is the log-database record of a generic API request. Its fields are dispatch facts captured by the gateway; generic API requests do not have the LLM fallback-chain semantics.

type APIRequestTrace added in v0.0.16

type APIRequestTrace struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	RequestID string `gorm:"size:64;uniqueIndex" json:"request_id"`

	SourceRequestHeaders           datatypes.JSONType[map[string][]string] `gorm:"type:text" json:"source_request_headers"`
	SourceRequestTrailers          datatypes.JSONType[map[string][]string] `gorm:"type:text" json:"source_request_trailers"`
	SourceRequestHeadersTruncated  bool                                    `json:"source_request_headers_truncated"`
	SourceRequestTrailersTruncated bool                                    `json:"source_request_trailers_truncated"`
	SourceRequestBody              datatypes.JSONType[APIBodyCapture]      `gorm:"type:text" json:"source_request_body"`

	RequestHeaders           datatypes.JSONType[map[string][]string] `gorm:"type:text" json:"request_headers"`
	RequestTrailers          datatypes.JSONType[map[string][]string] `gorm:"type:text" json:"request_trailers"`
	RequestHeadersTruncated  bool                                    `json:"request_headers_truncated"`
	RequestTrailersTruncated bool                                    `json:"request_trailers_truncated"`
	RequestBody              datatypes.JSONType[APIBodyCapture]      `gorm:"type:text" json:"request_body"`

	ResponseHeaders           datatypes.JSONType[map[string][]string] `gorm:"type:text" json:"response_headers"`
	ResponseTrailers          datatypes.JSONType[map[string][]string] `gorm:"type:text" json:"response_trailers"`
	ResponseHeadersTruncated  bool                                    `json:"response_headers_truncated"`
	ResponseTrailersTruncated bool                                    `json:"response_trailers_truncated"`
	ResponseBody              datatypes.JSONType[APIBodyCapture]      `gorm:"type:text" json:"response_body"`
	CreatedAt                 int64                                   `gorm:"autoCreateTime;index" json:"created_at"`
}

APIRequestTrace is intentionally independent from the LLM RequestTrace. Task 12 adds the generic API capture payload; this entity establishes the separate log-database persistence boundary now without reusing LLM fields.

type APIResource added in v0.0.16

type APIResource string
const (
	APIResourceService APIResource = "api_service"
	APIResourceRoute   APIResource = "api_route"
)

type APIRoleKind added in v0.0.16

type APIRoleKind string
const (
	APIRoleKindCustom  APIRoleKind = "custom"
	APIRoleKindManaged APIRoleKind = "managed"
)

type APIRoleMode added in v0.0.16

type APIRoleMode string
const (
	APIRoleModeInherit  APIRoleMode = "inherit"
	APIRoleModeExplicit APIRoleMode = "explicit"
	GatewayAdminRoleKey             = "gateway_admin"
)

type APIRoute added in v0.0.16

type APIRoute struct {
	ID                    uint                                           `gorm:"primaryKey" json:"id"`
	APIServiceID          uint                                           `gorm:"not null;uniqueIndex:idx_api_route_service_slug" json:"api_service_id"`
	BackendID             uint                                           `gorm:"not null;index" json:"backend_id"`
	Slug                  string                                         `gorm:"size:64;not null;uniqueIndex:idx_api_route_service_slug" json:"slug"`
	Protocols             datatypes.JSONSlice[APIProtocol]               `gorm:"type:text;not null;default:'[\"http\"]'" json:"protocols"`
	AllowedMethods        datatypes.JSONSlice[string]                    `gorm:"type:text;not null;default:'[]'" json:"allowed_methods"`
	WebSocketSubprotocols datatypes.JSONSlice[string]                    `gorm:"type:text;not null;default:'[]'" json:"websocket_subprotocols"`
	UpstreamPath          string                                         `gorm:"type:text;not null;default:''" json:"upstream_path"`
	ForwardSubpath        bool                                           `gorm:"not null;default:false" json:"forward_subpath"`
	ExampleRequest        datatypes.JSONType[APIRequestExample]          `gorm:"type:text;not null;default:'{}'" json:"example_request"`
	Status                int                                            `gorm:"not null;default:1" json:"status"`
	OpenAPIPaths          datatypes.JSONType[map[string]OpenAPIPathItem] `gorm:"column:openapi_paths;type:text;not null;default:'{}'" json:"-"`
	CreatedAt             int64                                          `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt             int64                                          `gorm:"autoUpdateTime" json:"updated_at"`
}

APIRoute selects an APIService endpoint. An empty AllowedMethods set means every standard HTTP method except CONNECT is accepted.

func (*APIRoute) BeforeCreate added in v0.0.16

func (r *APIRoute) BeforeCreate(*gorm.DB) error

BeforeCreate normalizes and validates the complete initial route. It must not run on partial GORM updates, whose receiver omits unrelated fields.

func (*APIRoute) BeforeUpdate added in v0.0.16

func (r *APIRoute) BeforeUpdate(tx *gorm.DB) error

func (*APIRoute) NormalizeForWrite added in v0.0.16

func (r *APIRoute) NormalizeForWrite() error

func (*APIRoute) Validate added in v0.0.16

func (r *APIRoute) Validate() error

type APIService added in v0.0.16

type APIService struct {
	ID              uint                                       `gorm:"primaryKey" json:"id"`
	Slug            string                                     `gorm:"uniqueIndex;size:64;not null" json:"slug"`
	Name            string                                     `gorm:"size:128;not null" json:"name"`
	Description     string                                     `gorm:"type:text" json:"description"`
	PricePerCall    int64                                      `gorm:"not null;default:0;check:chk_api_service_price_per_call,price_per_call >= 0" json:"price_per_call"`
	Status          int                                        `gorm:"not null;default:1" json:"status"`
	OpenAPIDocument datatypes.JSONType[OpenAPIServiceDocument] `gorm:"column:openapi_document;type:text;not null;default:'{}'" json:"-"`
	CreatedAt       int64                                      `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt       int64                                      `gorm:"autoUpdateTime" json:"updated_at"`
}

APIService is an externally invokable generic API product. PricePerCall is measured in quota units: 100000 is one USD and zero means free.

func (*APIService) BeforeCreate added in v0.0.16

func (s *APIService) BeforeCreate(*gorm.DB) error

BeforeCreate protects the initial persisted contract. Partial updates use zero-value GORM receivers, so later DAO code must load, patch, and call Validate explicitly instead of relying on a full-object update hook.

func (*APIService) BeforeUpdate added in v0.0.16

func (s *APIService) BeforeUpdate(tx *gorm.DB) error

func (*APIService) NormalizeForWrite added in v0.0.18

func (s *APIService) NormalizeForWrite() error

func (*APIService) Validate added in v0.0.16

func (s *APIService) Validate() error

type APIUpstream added in v0.0.16

type APIUpstream struct {
	ID        uint                `gorm:"primaryKey" json:"id"`
	BackendID uint                `gorm:"not null;uniqueIndex:idx_api_upstream_backend_name" json:"backend_id"`
	Name      string              `gorm:"size:64;not null;uniqueIndex:idx_api_upstream_backend_name" json:"name"`
	BaseURL   string              `gorm:"size:2048;not null" json:"base_url"`
	Weight    int                 `gorm:"not null;default:1;check:chk_api_upstream_weight,weight > 0" json:"weight"`
	Priority  int                 `gorm:"not null;default:0;index" json:"priority"`
	AuthType  APIUpstreamAuthType `` /* 142-byte string literal not displayed */

	// CredentialCiphertext and ProxyURLCiphertext are opaque encrypted bytes
	// represented as text. They must never be JSON encoded because encryption
	// framing and key rotation consume their exact stored representation.
	CredentialCiphertext string                                `gorm:"type:text" json:"credential_ciphertext"`
	ProxyURLCiphertext   string                                `gorm:"type:text" json:"proxy_url_ciphertext"`
	HeaderOverride       datatypes.JSONType[map[string]string] `gorm:"type:text;not null;default:'{}'" json:"header_override"`

	Status    int   `gorm:"not null;default:1" json:"status"`
	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

APIUpstream belongs to one APIBackend and can be shared by every route that selects that backend.

func (*APIUpstream) BeforeCreate added in v0.0.16

func (u *APIUpstream) BeforeCreate(*gorm.DB) error

BeforeCreate validates the complete upstream. DAO update paths must validate a loaded, patched object because a partial GORM update has no full receiver.

func (*APIUpstream) BeforeUpdate added in v0.0.16

func (u *APIUpstream) BeforeUpdate(tx *gorm.DB) error

func (*APIUpstream) Validate added in v0.0.16

func (u *APIUpstream) Validate() error

type APIUpstreamAuthType added in v0.0.16

type APIUpstreamAuthType string
const (
	APIUpstreamAuthNone   APIUpstreamAuthType = "none"
	APIUpstreamAuthBearer APIUpstreamAuthType = "bearer"
	APIUpstreamAuthHeader APIUpstreamAuthType = "header"
	APIUpstreamAuthQuery  APIUpstreamAuthType = "query"
	APIUpstreamAuthBasic  APIUpstreamAuthType = "basic"
)

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"`
	RelayMode     string `gorm:"size:16;not null;default:inherit" json:"relay_mode"`
	RelayURI      string `gorm:"size:2048" json:"relay_uri"`

	DirectInboundEnabled  bool `gorm:"not null;default:true" json:"direct_inbound_enabled"`
	DirectOutboundEnabled bool `gorm:"not null;default:true" json:"direct_outbound_enabled"`
	RelayInboundEnabled   bool `gorm:"not null;default:true" json:"relay_inbound_enabled"`
	RelayOutboundEnabled  bool `gorm:"not null;default:true" json:"relay_outbound_enabled"`
}

type AgentPathCommitState added in v0.0.13

type AgentPathCommitState string

type AgentPathKind added in v0.0.13

type AgentPathKind string

type AgentPathRecord added in v0.0.13

type AgentPathRecord struct {
	AgentID     string               `json:"agent_id"`
	Path        AgentPathKind        `json:"path"`
	Result      AgentPathResult      `json:"result"`
	Stage       AgentPathStage       `json:"stage"`
	CommitState AgentPathCommitState `json:"commit_state"`
	ReasonCode  string               `json:"reason_code,omitempty"`
	DurationMs  int                  `json:"duration_ms"`
}

type AgentPathResult added in v0.0.13

type AgentPathResult string

type AgentPathStage added in v0.0.13

type AgentPathStage string

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 Announcement added in v0.0.25

type Announcement struct {
	ID            uint   `gorm:"primaryKey" json:"id"`
	Title         string `gorm:"size:200;not null" json:"title"`
	Content       string `gorm:"type:text;not null" json:"content"`
	ShowForGuests bool   `gorm:"not null" json:"show_for_guests"`
	Pinned        bool   `gorm:"not null;default:false" json:"pinned"`
	Revision      uint   `gorm:"not null;default:1" json:"revision"`
	GroupIDs      []uint `gorm:"-" json:"group_ids"`
	CreatedAt     int64  `gorm:"autoCreateTime;index" json:"created_at"`
	UpdatedAt     int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

Announcement targets all authenticated users when it has no group rows. Guest visibility is independent of authenticated recipient groups.

type AnnouncementGroup added in v0.0.25

type AnnouncementGroup struct {
	AnnouncementID uint `gorm:"primaryKey;autoIncrement:false"`
	GroupID        uint `gorm:"primaryKey;autoIncrement:false;index"`
}

Keep target rows when a group is deleted: dropping the final target would accidentally turn a private announcement into a global one.

type AnnouncementPage added in v0.0.25

type AnnouncementPage[T any] struct {
	Items    []T   `json:"items"`
	Total    int64 `json:"total"`
	Page     int   `json:"page"`
	PageSize int   `json:"page_size"`
}

type AnnouncementSeen added in v0.0.25

type AnnouncementSeen struct {
	UserID         uint  `gorm:"primaryKey;autoIncrement:false"`
	AnnouncementID uint  `gorm:"primaryKey;autoIncrement:false;index"`
	Revision       uint  `gorm:"not null;default:1"`
	CreatedAt      int64 `gorm:"autoCreateTime"`
}

type AnnouncementSummary added in v0.0.25

type AnnouncementSummary struct {
	ID            uint   `json:"id"`
	Title         string `json:"title"`
	ShowForGuests bool   `json:"show_for_guests"`
	Pinned        bool   `json:"pinned"`
	Revision      uint   `json:"revision"`
	GroupIDs      []uint `gorm:"-" json:"group_ids"`
	CreatedAt     int64  `json:"created_at"`
	UpdatedAt     int64  `json:"updated_at"`
}

AnnouncementSummary deliberately excludes the body from history pages.

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),供前端按条目决定是否显示调试按钮
	AgentRouteID   uint              `json:"agent_route_id,omitempty"`
	AgentRouteKind string            `json:"agent_route_kind,omitempty"`
	AgentPaths     []AgentPathRecord `json:"agent_paths,omitempty"`
}

AttemptRecord 是 fallback 链路里的一条:一次候选 channel 尝试的摘要。 同 channel 的内层重试折叠成 Retries 计数,不单独成条。 定义在 models 包以便 state / protocol / settler 共用而不成环。

type AuthType added in v0.0.27

type AuthType struct {
	Header string `json:"header"`
	Value  string `json:"value"`
}

AuthType 指定上游认证头及其原始值模板。

type BillingHourlyBucket added in v0.0.14

type BillingHourlyBucket struct {
	ID uint `gorm:"primaryKey" json:"id"`

	Date             string `` /* 210-byte string literal not displayed */
	Hour             int    `` /* 202-byte string literal not displayed */
	UserID           uint   `` /* 205-byte string literal not displayed */
	TokenID          uint   `gorm:"uniqueIndex:idx_bhb_bucket,priority:4;index:idx_bhb_user_token,priority:2" json:"token_id"`
	ChannelID        uint   `gorm:"uniqueIndex:idx_bhb_bucket,priority:5" json:"channel_id"`
	PrivateChannelID uint   `gorm:"uniqueIndex:idx_bhb_bucket,priority:6;default:0" json:"private_channel_id"`
	OwnerType        string `gorm:"size:8;uniqueIndex:idx_bhb_bucket,priority:7;default:'admin'" json:"owner_type"`
	ModelName        string `` /* 180-byte string literal not displayed */

	TokenName   string `gorm:"size:64" json:"token_name"`
	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"`
	CacheReadCost    int64 `json:"cache_read_cost"`
	CacheWriteCost   int64 `json:"cache_write_cost"`
	TotalCost        int64 `json:"total_cost"`
	RawCost          int64 `json:"raw_cost"`

	LastUsedAt int64 `gorm:"index" json:"last_used_at"`
	CreatedAt  int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt  int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

type BillingLog added in v0.0.14

type BillingLog struct {
	ID                uint     `gorm:"primaryKey;index:idx_billing_logs_created_id,priority:2" json:"id"`
	RequestID         string   `gorm:"size:64;uniqueIndex" json:"request_id"`
	UserID            uint     `gorm:"index" json:"user_id"`
	TokenID           uint     `gorm:"index" json:"token_id"`
	TokenName         string   `gorm:"size:64" json:"token_name"`
	ChannelID         uint     `gorm:"index" json:"channel_id"`
	PrivateChannelID  uint     `gorm:"index;default:0" json:"private_channel_id"`
	OwnerType         string   `gorm:"size:8;default:'admin'" json:"owner_type"`
	ChannelName       string   `gorm:"size:64" json:"channel_name"`
	ChannelType       int      `json:"channel_type"`
	ModelName         string   `gorm:"size:128;index" json:"model_name"`
	PromptTokens      int      `json:"prompt_tokens"`
	CompletionTokens  int      `json:"completion_tokens"`
	CacheReadTokens   int      `json:"cache_read_tokens"`
	CacheWriteTokens  int      `json:"cache_write_tokens"`
	InputCost         int64    `json:"input_cost"`
	OutputCost        int64    `json:"output_cost"`
	CacheReadCost     int64    `json:"cache_read_cost"`
	CacheWriteCost    int64    `json:"cache_write_cost"`
	TotalCost         int64    `json:"total_cost"`
	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     *float64 `json:"billing_factor"`
	PriceRatio        float64  `gorm:"default:1" json:"price_ratio"`
	Free              bool     `json:"free"`
	Status            int      `json:"status"`
	CreatedAt         int64    `gorm:"autoCreateTime;index;index:idx_billing_logs_created_id,priority:1" json:"created_at"`
}

func (*BillingLog) RawTotal added in v0.0.14

func (l *BillingLog) RawTotal() int64

type BillingProjectionBaseline added in v0.0.14

type BillingProjectionBaseline struct {
	ID                      uint `gorm:"primaryKey;autoIncrement:false;not null;check:chk_billing_projection_baseline_singleton,id = 1" json:"id"`
	BillingLogHighWatermark uint `gorm:"not null" json:"billing_log_high_watermark"`
}

BillingProjectionBaseline records the billing-log high watermark that predates durable receipts. Facts at or below it were projected by the legacy live path and must not be replayed after upgrade.

type BillingProjectionReceipt added in v0.0.14

type BillingProjectionReceipt struct {
	RequestID       string                 `gorm:"primaryKey;size:64" json:"request_id"`
	BillingLogID    uint                   `gorm:"not null;default:0;index:idx_billing_projection_pending,priority:2" json:"billing_log_id"`
	State           BillingProjectionState `` /* 166-byte string literal not displayed */
	ProjectedAtUnix int64                  `gorm:"not null" json:"projected_at_unix"`
}

BillingProjectionReceipt is the durable projection outbox for one billing fact. Pending is inserted in the same transaction as BillingLog; applied is published in the same transaction as all core projections.

type BillingProjectionState added in v0.0.14

type BillingProjectionState string
const (
	BillingProjectionPending BillingProjectionState = "pending"
	BillingProjectionApplied BillingProjectionState = "applied"
)

type Channel

type Channel struct {
	ChannelCore

	PublicDisplayName string `gorm:"size:64;not null;default:''" json:"public_display_name"`
	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[ChannelDisableState] `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

func (ch *Channel) GetBaseURL() string

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 ChannelAffinity added in v0.0.10

type ChannelAffinity struct {
	Enabled *bool `json:"enabled,omitempty"` // 覆盖 affinity_enabled
	TTLSec  *int  `json:"ttl_sec,omitempty"` // 覆盖 affinity_ttl_sec(秒)
}

ChannelAffinity 是每 channel 对全局粘性设置(affinity_enabled / affinity_ttl_sec)的覆盖。 字段全为指针:nil = 继承全局;非 nil = 显式覆盖。挂在共享的 ChannelCore 上, 让 admin Channel 与 BYOK PrivateChannel 用同一处声明、同一份语义。

func (ChannelAffinity) Validate added in v0.0.10

func (a ChannelAffinity) Validate() error

Validate 校验覆盖值边界,与全局 Settings 的 affinity_ttl_sec(0..86400) 一致。 nil 字段表示不覆盖,跳过。Enabled 为布尔无需范围校验。

type ChannelAuth added in v0.0.27

type ChannelAuth struct {
	Default   *AuthType           `json:"default,omitempty"`
	Protocols map[string]AuthType `json:"protocols,omitempty"`
}

ChannelAuth 保存整体默认认证和出站协议覆盖。

func (ChannelAuth) Clone added in v0.0.27

func (a ChannelAuth) Clone() ChannelAuth

Clone 复制认证指针和协议 map。

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"`
	Auth                datatypes.JSONType[ChannelAuth]         `gorm:"type:text;not null;default:'{}'" json:"auth"`
	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"`
	AutoBanState        datatypes.JSONType[ChannelDisableState] `gorm:"type:text;not null;default:'{}'" json:"auto_ban_state"`
	AutoBanRevision     uint64                                  `gorm:"default:0;not null" json:"auto_ban_revision"`
	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"`
	// Affinity 是粘性参与/ TTL 的每渠道覆盖。挂在 ChannelCore(而非 admin-only 的
	// Channel)上,因为这是唯一 admin 与 BYOK 都需要的覆盖;Resilience/Limit 仍是 admin 专属。
	Affinity datatypes.JSONType[ChannelAffinity] `gorm:"type:text" json:"affinity"`
}

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"`
	RawCost          int64  `json:"raw_cost"` // 折扣前原价日聚合(免费/折扣渠道亦 >0)
	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 ChannelDisableState added in v0.0.15

type ChannelDisableState struct {
	Tripped     bool   `json:"tripped"`
	Reason      string `json:"reason"`
	AutoRecover bool   `json:"auto_recover"`
	TrippedAt   int64  `json:"tripped_at"`
}

ChannelDisableState 是限额/连续错误自动禁用写入的运行态。API 只读不写。

type ChannelLimit added in v0.0.6

type ChannelLimit struct {
	DisableAt int64       `json:"disable_at"`
	Rules     []LimitRule `json:"rules"`
}

ChannelLimit 是渠道的用量/时间限额配置(管理员设置)。空 = 不启用自动禁用。 多条 Rules 取 OR:任一超限即禁用。DisableAt>0 时到点(绝对截止)永久禁用。

func (ChannelLimit) Validate added in v0.0.6

func (l ChannelLimit) Validate() error

Validate 校验配置合法性,落库前调用(仿 ChannelResilience.Validate)。

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 DailyBillingBackfill added in v0.0.15

type DailyBillingBackfill struct {
	Version           uint                      `gorm:"primaryKey;autoIncrement:false;not null" json:"version"`
	State             DailyBillingBackfillState `` /* 127-byte string literal not displayed */
	StartDate         string                    `gorm:"size:10" json:"start_date"`
	EndDate           string                    `gorm:"size:10" json:"end_date"`
	LastCompletedDate string                    `gorm:"size:10" json:"last_completed_date"`
	LastError         string                    `gorm:"type:text" json:"last_error"`
	StartedAtUnix     int64                     `gorm:"not null" json:"started_at_unix"`
	CompletedAtUnix   int64                     `gorm:"not null" json:"completed_at_unix"`
	UpdatedAtUnix     int64                     `gorm:"not null" json:"updated_at_unix"`
}

func (DailyBillingBackfill) TableName added in v0.0.15

func (DailyBillingBackfill) TableName() string

type DailyBillingBackfillState added in v0.0.15

type DailyBillingBackfillState string

type DatabaseLayout added in v0.0.14

type DatabaseLayout struct {
	ID      uint   `gorm:"primaryKey;autoIncrement:false;not null;check:chk_database_layout_singleton,id = 1" json:"id"`
	Role    string `gorm:"size:8;not null;uniqueIndex;check:chk_database_layout_role,role IN ('core','log')" json:"role"`
	Version int    `gorm:"not null" json:"version"`
}

type EnrollmentToken

type EnrollmentToken struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	Token     string `gorm:"uniqueIndex;size:128" json:"token"`
	ExpiresAt int64  `json:"expires_at"`
	CreatedAt int64  `gorm:"autoCreateTime" json:"created_at"`
}

type HistoryCursor added in v0.0.14

type HistoryCursor struct {
	Key           string `gorm:"primaryKey;size:64"`
	LastSourceID  uint   `gorm:"not null"`
	ProcessedRows int64  `gorm:"not null"`
	Skipped       bool   `gorm:"not null;default:false"`
	UpdatedAtUnix int64  `gorm:"not null"`
}

func (HistoryCursor) TableName added in v0.0.14

func (HistoryCursor) TableName() string

type HistoryMigration added in v0.0.14

type HistoryMigration struct {
	ID                   uint   `gorm:"primaryKey;autoIncrement:false"`
	SourceKind           string `gorm:"not null"`
	SourcePath           string `gorm:"not null"`
	State                string `gorm:"not null;index"`
	SkipLogHistory       bool   `gorm:"not null;default:false"`
	LastError            string
	StartedAtUnix        int64
	LastSuccessfulAtUnix int64
	CompletedAtUnix      int64
	SourceDeletedAtUnix  int64
}

func (HistoryMigration) TableName added in v0.0.14

func (HistoryMigration) TableName() string

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"`
	CostBasis string `json:"cost_basis"` // 仅 metric=="cost" 有意义;空 = raw(折前)
}

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 LogHistoryAggregateMerge added in v0.0.14

type LogHistoryAggregateMerge struct {
	ID          uint   `gorm:"primaryKey"`
	SourceTable string `gorm:"size:64;uniqueIndex:idx_log_history_aggregate_merge,priority:1"`
	SourceKey   string `gorm:"size:255;uniqueIndex:idx_log_history_aggregate_merge,priority:2"`
	CreatedAt   int64  `gorm:"autoCreateTime"`
}

LogHistoryAggregateMerge makes cutover-hour delta merges idempotent across restarts.

func (LogHistoryAggregateMerge) TableName added in v0.0.14

func (LogHistoryAggregateMerge) TableName() string

type MasterSigningKey added in v0.0.13

type MasterSigningKey struct {
	KeyID      string `gorm:"primaryKey;size:64"`
	PublicKey  []byte `gorm:"type:blob;not null"`
	PrivateKey []byte `gorm:"type:blob;not null" json:"-"`
	ActiveSlot *uint8 `gorm:"uniqueIndex" json:"-"`
	CreatedAt  int64  `gorm:"autoCreateTime"`
}

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"`
	SyncedMetadata   datatypes.JSONType[ModelMetadata]         `gorm:"type:text;not null;default:'{}'" json:"synced_metadata"`
	MetadataOverride datatypes.JSONType[ModelMetadataOverride] `gorm:"type:text;not null;default:'{}'" json:"metadata_override"`
	CreatedAt        int64                                     `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt        int64                                     `gorm:"autoUpdateTime" json:"updated_at"`
}

func (ModelConfig) EffectiveMetadata added in v0.0.15

func (m ModelConfig) EffectiveMetadata() ModelMetadata

type ModelMetadata added in v0.0.15

type ModelMetadata struct {
	DisplayName         string   `json:"display_name"`
	Description         string   `json:"description"`
	Provider            string   `json:"provider"`
	InputModalities     []string `json:"input_modalities"`
	OutputModalities    []string `json:"output_modalities"`
	ContextLength       int64    `json:"context_length"`
	MaxOutputTokens     int64    `json:"max_output_tokens"`
	SupportedParameters []string `json:"supported_parameters"`
	ToolCalling         bool     `json:"tool_calling"`
	StructuredOutput    bool     `json:"structured_output"`
	Reasoning           bool     `json:"reasoning"`
	PromptCache         bool     `json:"prompt_cache"`
}

ModelMetadata is the normalized model information synced from models.dev. It deliberately contains only the first marketplace version's approved fields.

func EffectiveModelMetadata added in v0.0.15

func EffectiveModelMetadata(synced ModelMetadata, override ModelMetadataOverride) ModelMetadata

EffectiveModelMetadata returns synced metadata with every explicitly present admin override applied. The returned slices never alias persisted values.

type ModelMetadataOverride added in v0.0.15

type ModelMetadataOverride struct {
	DisplayName         *string                      `json:"display_name,omitempty"`
	Description         *string                      `json:"description,omitempty"`
	Provider            *string                      `json:"provider,omitempty"`
	InputModalities     *datatypes.JSONSlice[string] `json:"input_modalities,omitempty"`
	OutputModalities    *datatypes.JSONSlice[string] `json:"output_modalities,omitempty"`
	ContextLength       *int64                       `json:"context_length,omitempty"`
	MaxOutputTokens     *int64                       `json:"max_output_tokens,omitempty"`
	SupportedParameters *datatypes.JSONSlice[string] `json:"supported_parameters,omitempty"`
	ToolCalling         *bool                        `json:"tool_calling,omitempty"`
	StructuredOutput    *bool                        `json:"structured_output,omitempty"`
	Reasoning           *bool                        `json:"reasoning,omitempty"`
	PromptCache         *bool                        `json:"prompt_cache,omitempty"`
}

ModelMetadataOverride distinguishes an absent field (inherit the synced value) from an explicitly supplied zero value. List pointers preserve the same distinction for an explicitly empty array.

type ModelRouting

type ModelRouting struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	Name      string `gorm:"size:128;index;uniqueIndex:uidx_routing_owner_name" json:"name"`
	Scope     string `gorm:"size:8;index;uniqueIndex:uidx_routing_owner_name" json:"scope"` // "global" | "user" | "token"
	UserID    uint   `gorm:"index;uniqueIndex:uidx_routing_owner_name" json:"user_id"`
	TokenID   uint   `gorm:"index;uniqueIndex:uidx_routing_owner_name" json:"token_id"`
	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 OpenAPIComponents added in v0.0.18

type OpenAPIComponents struct {
	Schemas         map[string]json.RawMessage    `json:"schemas,omitempty"`
	Responses       map[string]OpenAPIResponse    `json:"responses,omitempty"`
	Parameters      map[string]OpenAPIParameter   `json:"parameters,omitempty"`
	Examples        map[string]json.RawMessage    `json:"examples,omitempty"`
	RequestBodies   map[string]OpenAPIRequestBody `json:"requestBodies,omitempty"`
	Headers         map[string]OpenAPIHeader      `json:"headers,omitempty"`
	SecuritySchemes map[string]json.RawMessage    `json:"securitySchemes,omitempty"`
	Links           map[string]json.RawMessage    `json:"links,omitempty"`
	Callbacks       map[string]json.RawMessage    `json:"callbacks,omitempty"`
	PathItems       map[string]OpenAPIPathItem    `json:"pathItems,omitempty"`
	Extensions      map[string]json.RawMessage    `json:"extensions,omitempty"`
}

OpenAPIComponents keeps reusable objects in named fields. JSON Schema and component kinds whose complete semantics belong to OpenAPI are preserved as raw JSON values rather than flattened into string-encoded JSON.

type OpenAPIContact added in v0.0.18

type OpenAPIContact struct {
	Name       string                     `json:"name,omitempty"`
	URL        string                     `json:"url,omitempty"`
	Email      string                     `json:"email,omitempty"`
	Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}

type OpenAPIExternalDocs added in v0.0.18

type OpenAPIExternalDocs struct {
	Description string                     `json:"description,omitempty"`
	URL         string                     `json:"url"`
	Extensions  map[string]json.RawMessage `json:"extensions,omitempty"`
}

type OpenAPIHeader added in v0.0.18

type OpenAPIHeader struct {
	Ref             string                      `json:"$ref,omitempty"`
	Description     string                      `json:"description,omitempty"`
	Required        bool                        `json:"required,omitempty"`
	Deprecated      bool                        `json:"deprecated,omitempty"`
	AllowEmptyValue bool                        `json:"allowEmptyValue,omitempty"`
	Style           string                      `json:"style,omitempty"`
	Explode         *bool                       `json:"explode,omitempty"`
	AllowReserved   bool                        `json:"allowReserved,omitempty"`
	Schema          json.RawMessage             `json:"schema,omitempty"`
	Example         json.RawMessage             `json:"example,omitempty"`
	Examples        map[string]json.RawMessage  `json:"examples,omitempty"`
	Content         map[string]OpenAPIMediaType `json:"content,omitempty"`
	Extensions      map[string]json.RawMessage  `json:"extensions,omitempty"`
}

type OpenAPIInfo added in v0.0.18

type OpenAPIInfo struct {
	Summary        string                     `json:"summary,omitempty"`
	Version        string                     `json:"version,omitempty"`
	TermsOfService string                     `json:"termsOfService,omitempty"`
	Contact        *OpenAPIContact            `json:"contact,omitempty"`
	License        *OpenAPILicense            `json:"license,omitempty"`
	Extensions     map[string]json.RawMessage `json:"extensions,omitempty"`
}

type OpenAPILicense added in v0.0.18

type OpenAPILicense struct {
	Name       string                     `json:"name,omitempty"`
	Identifier string                     `json:"identifier,omitempty"`
	URL        string                     `json:"url,omitempty"`
	Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}

type OpenAPIMediaType added in v0.0.18

type OpenAPIMediaType struct {
	Schema     json.RawMessage            `json:"schema,omitempty"`
	Example    json.RawMessage            `json:"example,omitempty"`
	Examples   map[string]json.RawMessage `json:"examples,omitempty"`
	Encoding   map[string]json.RawMessage `json:"encoding,omitempty"`
	Extensions map[string]json.RawMessage `json:"extensions,omitempty"`
}

type OpenAPIOperation added in v0.0.18

type OpenAPIOperation struct {
	Tags         []string                      `json:"tags,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	ExternalDocs *OpenAPIExternalDocs          `json:"externalDocs,omitempty"`
	OperationID  string                        `json:"operationId,omitempty"`
	Parameters   []OpenAPIParameter            `json:"parameters,omitempty"`
	RequestBody  *OpenAPIRequestBody           `json:"requestBody,omitempty"`
	Responses    map[string]OpenAPIResponse    `json:"responses,omitempty"`
	Callbacks    map[string]json.RawMessage    `json:"callbacks,omitempty"`
	Deprecated   bool                          `json:"deprecated,omitempty"`
	Security     *[]OpenAPISecurityRequirement `json:"security,omitempty"`
	Servers      []OpenAPIServer               `json:"servers,omitempty"`
	Extensions   map[string]json.RawMessage    `json:"extensions,omitempty"`
}

type OpenAPIParameter added in v0.0.18

type OpenAPIParameter struct {
	Ref             string                      `json:"$ref,omitempty"`
	Name            string                      `json:"name,omitempty"`
	In              string                      `json:"in,omitempty"`
	Description     string                      `json:"description,omitempty"`
	Required        bool                        `json:"required,omitempty"`
	Deprecated      bool                        `json:"deprecated,omitempty"`
	AllowEmptyValue bool                        `json:"allowEmptyValue,omitempty"`
	Style           string                      `json:"style,omitempty"`
	Explode         *bool                       `json:"explode,omitempty"`
	AllowReserved   bool                        `json:"allowReserved,omitempty"`
	Schema          json.RawMessage             `json:"schema,omitempty"`
	Example         json.RawMessage             `json:"example,omitempty"`
	Examples        map[string]json.RawMessage  `json:"examples,omitempty"`
	Content         map[string]OpenAPIMediaType `json:"content,omitempty"`
	Extensions      map[string]json.RawMessage  `json:"extensions,omitempty"`
}

type OpenAPIPathItem added in v0.0.18

type OpenAPIPathItem struct {
	Ref         string                      `json:"$ref,omitempty"`
	Summary     string                      `json:"summary,omitempty"`
	Description string                      `json:"description,omitempty"`
	Parameters  []OpenAPIParameter          `json:"parameters,omitempty"`
	Servers     []OpenAPIServer             `json:"servers,omitempty"`
	Operations  map[string]OpenAPIOperation `json:"operations,omitempty"`
	Extensions  map[string]json.RawMessage  `json:"extensions,omitempty"`
}

type OpenAPIRequestBody added in v0.0.18

type OpenAPIRequestBody struct {
	Ref         string                      `json:"$ref,omitempty"`
	Description string                      `json:"description,omitempty"`
	Required    bool                        `json:"required,omitempty"`
	Content     map[string]OpenAPIMediaType `json:"content,omitempty"`
	Extensions  map[string]json.RawMessage  `json:"extensions,omitempty"`
}

type OpenAPIResponse added in v0.0.18

type OpenAPIResponse struct {
	Ref         string                      `json:"$ref,omitempty"`
	Description string                      `json:"description,omitempty"`
	Headers     map[string]OpenAPIHeader    `json:"headers,omitempty"`
	Content     map[string]OpenAPIMediaType `json:"content,omitempty"`
	Links       map[string]json.RawMessage  `json:"links,omitempty"`
	Extensions  map[string]json.RawMessage  `json:"extensions,omitempty"`
}

type OpenAPISecurityRequirement added in v0.0.18

type OpenAPISecurityRequirement map[string][]string

type OpenAPIServer added in v0.0.18

type OpenAPIServer struct {
	URL         string                           `json:"url"`
	Description string                           `json:"description,omitempty"`
	Variables   map[string]OpenAPIServerVariable `json:"variables,omitempty"`
	Extensions  map[string]json.RawMessage       `json:"extensions,omitempty"`
}

type OpenAPIServerVariable added in v0.0.18

type OpenAPIServerVariable struct {
	Default     string                     `json:"default"`
	Enum        []string                   `json:"enum,omitempty"`
	Description string                     `json:"description,omitempty"`
	Extensions  map[string]json.RawMessage `json:"extensions,omitempty"`
}

type OpenAPIServiceDocument added in v0.0.18

type OpenAPIServiceDocument struct {
	Version           string                       `json:"openapi,omitempty"`
	JSONSchemaDialect string                       `json:"jsonSchemaDialect,omitempty"`
	Info              OpenAPIInfo                  `json:"info,omitempty"`
	Tags              []OpenAPITag                 `json:"tags,omitempty"`
	Servers           []OpenAPIServer              `json:"servers,omitempty"`
	ExternalDocs      *OpenAPIExternalDocs         `json:"externalDocs,omitempty"`
	Security          []OpenAPISecurityRequirement `json:"security,omitempty"`
	Components        OpenAPIComponents            `json:"components,omitempty"`
	Extensions        map[string]json.RawMessage   `json:"extensions,omitempty"`
}

OpenAPIServiceDocument contains service-level OpenAPI facts. APIService owns the exported info title and description, so they are deliberately absent from OpenAPIInfo.

type OpenAPITag added in v0.0.18

type OpenAPITag struct {
	Name         string                     `json:"name"`
	Description  string                     `json:"description,omitempty"`
	ExternalDocs *OpenAPIExternalDocs       `json:"externalDocs,omitempty"`
	Extensions   map[string]json.RawMessage `json:"extensions,omitempty"`
}

type Permission added in v0.0.16

type Permission struct {
	ID         uint                `gorm:"primaryKey" json:"id"`
	Resource   APIResource         `` /* 167-byte string literal not displayed */
	ResourceID uint                `` /* 168-byte string literal not displayed */
	Action     APIPermissionAction `` /* 150-byte string literal not displayed */
	CreatedAt  int64               `gorm:"autoCreateTime" json:"created_at"`
}

func (*Permission) BeforeCreate added in v0.0.16

func (p *Permission) BeforeCreate(*gorm.DB) error

func (*Permission) BeforeUpdate added in v0.0.16

func (p *Permission) BeforeUpdate(tx *gorm.DB) error

func (*Permission) Validate added in v0.0.16

func (p *Permission) Validate() error

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 {
	ID         uint   `gorm:"primaryKey" json:"id"`
	ChannelID  uint   `gorm:"index:idx_share_lookup;not null;uniqueIndex:uidx_share_triple" json:"channel_id"`
	TargetType string `gorm:"size:8;index:idx_share_lookup;uniqueIndex:uidx_share_triple" json:"target_type"`
	TargetID   uint   `gorm:"index:idx_share_lookup;uniqueIndex:uidx_share_triple" json:"target_id"`
	CreatedAt  int64  `gorm:"autoCreateTime" json:"created_at"`
}

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 ReceivedAnnouncement added in v0.0.25

type ReceivedAnnouncement struct {
	Announcement
	Seen bool `json:"seen"`
}

type ReceivedAnnouncementSummary added in v0.0.25

type ReceivedAnnouncementSummary struct {
	AnnouncementSummary
	Seen bool `json:"seen"`
}

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 RequestLog added in v0.0.14

type RequestLog UsageLog

RequestLog is the current persistent LLM request-log schema. It deliberately shares UsageLog's complete field and tag contract so the split log database does not fork the LLM shape while UsageLog remains legacy compatibility data.

func (RequestLog) TableName added in v0.0.14

func (RequestLog) TableName() string

type RequestTrace added in v0.0.14

type RequestTrace UsageLogTrace

RequestTrace deliberately shares UsageLogTrace's complete field and tag contract.

func (RequestTrace) TableName added in v0.0.14

func (RequestTrace) TableName() string

type Role added in v0.0.16

type Role struct {
	ID          uint        `gorm:"primaryKey" json:"id"`
	Key         string      `gorm:"uniqueIndex;size:64;not null" json:"key"`
	Name        string      `gorm:"size:128;not null" json:"name"`
	Description string      `gorm:"type:text" json:"description"`
	Kind        APIRoleKind `gorm:"size:16;not null;default:custom;index;check:chk_api_role_kind,kind IN ('custom','managed')" json:"kind"`
	BuiltIn     bool        `gorm:"not null;default:false" json:"built_in"`
	Status      int         `gorm:"not null;default:1" json:"status"`
	CreatedAt   int64       `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt   int64       `gorm:"autoUpdateTime" json:"updated_at"`
}

func (*Role) BeforeCreate added in v0.0.16

func (r *Role) BeforeCreate(*gorm.DB) error

Creation receives complete objects. Partial update receivers do not, so DAO code validates an explicitly loaded and patched model before updating it.

func (*Role) BeforeUpdate added in v0.0.16

func (r *Role) BeforeUpdate(tx *gorm.DB) error

func (*Role) Validate added in v0.0.16

func (r *Role) Validate() error

type RoleBinding added in v0.0.16

type RoleBinding struct {
	ID            uint             `gorm:"primaryKey" json:"id"`
	PrincipalType APIPrincipalType `` /* 183-byte string literal not displayed */
	PrincipalID   uint             `gorm:"not null;uniqueIndex:idx_api_role_binding_principal_role" json:"principal_id"`
	RoleID        uint             `gorm:"not null;uniqueIndex:idx_api_role_binding_principal_role" json:"role_id"`
	CreatedAt     int64            `gorm:"autoCreateTime" json:"created_at"`
}

func (*RoleBinding) BeforeCreate added in v0.0.16

func (b *RoleBinding) BeforeCreate(*gorm.DB) error

func (*RoleBinding) BeforeUpdate added in v0.0.16

func (b *RoleBinding) BeforeUpdate(tx *gorm.DB) error

func (*RoleBinding) Validate added in v0.0.16

func (b *RoleBinding) Validate() error

type RolePermission added in v0.0.16

type RolePermission struct {
	ID           uint  `gorm:"primaryKey" json:"id"`
	RoleID       uint  `gorm:"not null;uniqueIndex:idx_api_role_permission" json:"role_id"`
	PermissionID uint  `gorm:"not null;uniqueIndex:idx_api_role_permission" json:"permission_id"`
	CreatedAt    int64 `gorm:"autoCreateTime" json:"created_at"`
}

type RoutingMember

type RoutingMember struct {
	Ref      string `json:"ref"`
	Priority int    `json:"priority"`
	Weight   int    `json:"weight"`
}

type ScriptScope added in v0.0.6

type ScriptScope struct {
	ChannelIDs        []uint   `json:"channel_ids"`
	PrivateChannelIDs []uint   `json:"private_channel_ids"`
	ModelNames        []string `json:"model_names"`
	GroupIDs          []uint   `json:"group_ids"`
	UserIDs           []uint   `json:"user_ids"`
}

ScriptScope 决定一个脚本对哪些请求生效。 五类条件均为空 = 全局;否则命中任一条件即生效。

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 SyncFields added in v0.0.10

type SyncFields struct {
	Models   bool
	Channels bool
	BYOKOnly bool
}

SyncFields 标记一次模版→令牌同步要覆盖哪些字段。

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"`
	TraceMode         TokenTraceMode            `gorm:"size:16;default:full" json:"trace_mode"`
	APIRoleMode       APIRoleMode               `` /* 131-byte string literal not displayed */
	BYOKOnly          bool                      `gorm:"default:false" json:"byok_only"`
	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"`
	BYOKOnly          bool                      `gorm:"not null;default:false" json:"byok_only"`
	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 TokenTraceMode added in v0.0.14

type TokenTraceMode string
const (
	TokenTraceModeFull    TokenTraceMode = "full"
	TokenTraceModeHeaders TokenTraceMode = "headers"
)

func NormalizeTokenTraceModeForWrite added in v0.0.14

func NormalizeTokenTraceModeForWrite(raw string) (TokenTraceMode, error)

func (TokenTraceMode) ForRuntime added in v0.0.14

func (m TokenTraceMode) ForRuntime() (TokenTraceMode, bool)

type TraceRetentionStatus added in v0.0.16

type TraceRetentionStatus string

TraceRetentionStatus describes how much LLM trace data survived capture and asynchronous upload. It lives on the request log so a stripped trace can still explain its own absence.

const (
	TraceRetentionFull          TraceRetentionStatus = "full"
	TraceRetentionHeadersOnly   TraceRetentionStatus = "headers_only"
	TraceRetentionBodyTruncated TraceRetentionStatus = "body_truncated"
	TraceRetentionBodyTrimmed   TraceRetentionStatus = "body_trimmed"
	TraceRetentionStripped      TraceRetentionStatus = "trace_stripped"
	TraceRetentionBillingOnly   TraceRetentionStatus = "billing_only"
	TraceRetentionDisabled      TraceRetentionStatus = "disabled"
)

type UsageDurationHistogram added in v0.0.13

type UsageDurationHistogram struct {
	ID uint `gorm:"primaryKey" json:"id"`

	Date             string `gorm:"size:10;uniqueIndex:idx_udh_bucket" json:"date"`
	Hour             int    `gorm:"uniqueIndex:idx_udh_bucket" json:"hour"`
	ChannelID        uint   `gorm:"uniqueIndex:idx_udh_bucket;index" json:"channel_id"`
	PrivateChannelID uint   `gorm:"uniqueIndex:idx_udh_bucket;index;default:0" json:"private_channel_id"`
	ModelName        string `gorm:"size:128;uniqueIndex:idx_udh_bucket;index" json:"model_name"`
	AgentID          string `gorm:"size:64;uniqueIndex:idx_udh_bucket;index" json:"agent_id"`

	MaxDurationMs int64 `json:"max_duration_ms"`

	// H0..H16:各槽成功请求计数,定长列便于 SQL 直接 SUM(spec §8.3 用户决策)。
	// 例外说明:不用 datatypes.JSONSlice——概览热路径要 SUM(h0)..SUM(h16) 在
	// SQL 内一行完成,JSON 列做不到,这正是本表存在的目的。
	H0  int64 `json:"h0"`
	H1  int64 `json:"h1"`
	H2  int64 `json:"h2"`
	H3  int64 `json:"h3"`
	H4  int64 `json:"h4"`
	H5  int64 `json:"h5"`
	H6  int64 `json:"h6"`
	H7  int64 `json:"h7"`
	H8  int64 `json:"h8"`
	H9  int64 `json:"h9"`
	H10 int64 `json:"h10"`
	H11 int64 `json:"h11"`
	H12 int64 `json:"h12"`
	H13 int64 `json:"h13"`
	H14 int64 `json:"h14"`
	H15 int64 `json:"h15"`
	H16 int64 `json:"h16"`

	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

UsageDurationHistogram 是成功请求耗时直方图的小时级聚合(spec §8.3)。

独立于 UsageHourlyBucket 的专用侧表:概览 p95/slowest 只 SUM/MAX 本表, 不污染原表 schema。维度约定与 UsageHourlyBucket 完全一致(含 BYOK 行写法), 同样不带 user_id(用户级走 usage_logs 原表 + 覆盖索引)。

只统计 status=1(成功)——与概览 p95/slowest 现有口径一致。 槽定义见 internal/pkg/durhist(17 槽,编译期常量;改档必须 rebuild)。

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"`
	RawCost          int64 `json:"raw_cost"` // 折前原价日聚合(与 ChannelDailyBilling.RawCost 同口径)

	// 速度累计 (仅 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"`
	RouteSourceAgentID string `gorm:"size:64;index" json:"route_source_agent_id"`
	AgentRouteID       uint   `gorm:"index" json:"agent_route_id"`
	AgentRoutePath     string `gorm:"size:16;index" json:"agent_route_path"`
	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"`

	TraceRetentionStatus TraceRetentionStatus `gorm:"size:24" json:"trace_retention_status"`

	// 请求级限流决策快照: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"`
}

UsageLog is the legacy mixed-database LLM log shape retained for transitional compatibility. New split-layout LLM persistence uses RequestLog instead.

func (*UsageLog) RawTotal added in v0.0.10

func (l *UsageLog) RawTotal() int64

RawTotal 返回这行 usage_log 的折前原价(四个 Raw* 桶之和)。 四者全 nil 的老行(原价快照特性之前;当时还没有免费/折扣,total==raw)回退 TotalCost。 部分 nil 的桶按 0 计。

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 UsageTPSHistogram added in v0.0.14

type UsageTPSHistogram struct {
	ID uint `gorm:"primaryKey" json:"id"`

	Date             string `gorm:"size:10;uniqueIndex:idx_utps_bucket" json:"date"`
	Hour             int    `gorm:"uniqueIndex:idx_utps_bucket" json:"hour"`
	ChannelID        uint   `gorm:"uniqueIndex:idx_utps_bucket;index" json:"channel_id"`
	PrivateChannelID uint   `gorm:"uniqueIndex:idx_utps_bucket;index;default:0" json:"private_channel_id"`
	ModelName        string `gorm:"size:128;uniqueIndex:idx_utps_bucket;index" json:"model_name"`
	AgentID          string `gorm:"size:64;uniqueIndex:idx_utps_bucket;index" json:"agent_id"`

	MaxTps int64 `json:"max_tps"`

	H0  int64 `json:"h0"`
	H1  int64 `json:"h1"`
	H2  int64 `json:"h2"`
	H3  int64 `json:"h3"`
	H4  int64 `json:"h4"`
	H5  int64 `json:"h5"`
	H6  int64 `json:"h6"`
	H7  int64 `json:"h7"`
	H8  int64 `json:"h8"`
	H9  int64 `json:"h9"`
	H10 int64 `json:"h10"`
	H11 int64 `json:"h11"`
	H12 int64 `json:"h12"`
	H13 int64 `json:"h13"`
	H14 int64 `json:"h14"`
	H15 int64 `json:"h15"`
	H16 int64 `json:"h16"`

	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

UsageTPSHistogram 是成功流式请求 TPS(生成速率)直方图的小时级聚合。 维度约定与 UsageHourlyBucket / UsageDurationHistogram 完全一致(含 BYOK 行写法), 同样不带 user_id。只统计 IsStream && status=1 && completion_tokens>0 && 生成耗时>0。 槽定义见 internal/pkg/tpshist(17 槽,编译期常量;改档必须 rebuild)。

type UsageTTFTHistogram added in v0.0.14

type UsageTTFTHistogram struct {
	ID uint `gorm:"primaryKey" json:"id"`

	Date             string `gorm:"size:10;uniqueIndex:idx_utth_bucket" json:"date"`
	Hour             int    `gorm:"uniqueIndex:idx_utth_bucket" json:"hour"`
	ChannelID        uint   `gorm:"uniqueIndex:idx_utth_bucket;index" json:"channel_id"`
	PrivateChannelID uint   `gorm:"uniqueIndex:idx_utth_bucket;index;default:0" json:"private_channel_id"`
	ModelName        string `gorm:"size:128;uniqueIndex:idx_utth_bucket;index" json:"model_name"`
	AgentID          string `gorm:"size:64;uniqueIndex:idx_utth_bucket;index" json:"agent_id"`

	MaxFirstResponseMs int64 `json:"max_first_response_ms"`

	H0  int64 `json:"h0"`
	H1  int64 `json:"h1"`
	H2  int64 `json:"h2"`
	H3  int64 `json:"h3"`
	H4  int64 `json:"h4"`
	H5  int64 `json:"h5"`
	H6  int64 `json:"h6"`
	H7  int64 `json:"h7"`
	H8  int64 `json:"h8"`
	H9  int64 `json:"h9"`
	H10 int64 `json:"h10"`
	H11 int64 `json:"h11"`
	H12 int64 `json:"h12"`
	H13 int64 `json:"h13"`
	H14 int64 `json:"h14"`
	H15 int64 `json:"h15"`
	H16 int64 `json:"h16"`

	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

UsageTTFTHistogram 是成功流式请求 TTFT(首 token 时延)直方图的小时级聚合。 维度约定与 UsageHourlyBucket / UsageDurationHistogram 完全一致(含 BYOK 行写法), 同样不带 user_id。只统计 IsStream && status=1 && first_response_ms>0。 槽定义见 internal/pkg/ttfthist(17 槽,编译期常量;改档必须 rebuild)。

type UsageUserTPSHistogram added in v0.0.14

type UsageUserTPSHistogram struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	Date      string `gorm:"size:10;uniqueIndex:idx_uutps_bucket,priority:1" json:"date"`
	Hour      int    `gorm:"uniqueIndex:idx_uutps_bucket,priority:2" json:"hour"`
	UserID    uint   `gorm:"uniqueIndex:idx_uutps_bucket,priority:3;index" json:"user_id"`
	ModelName string `gorm:"size:128;uniqueIndex:idx_uutps_bucket,priority:4" json:"model_name"`

	MaxTps int64 `json:"max_tps"`
	// Fixed columns allow aggregation with direct SQL SUMs; JSON cannot serve that hot path.
	H0        int64 `json:"h0"`
	H1        int64 `json:"h1"`
	H2        int64 `json:"h2"`
	H3        int64 `json:"h3"`
	H4        int64 `json:"h4"`
	H5        int64 `json:"h5"`
	H6        int64 `json:"h6"`
	H7        int64 `json:"h7"`
	H8        int64 `json:"h8"`
	H9        int64 `json:"h9"`
	H10       int64 `json:"h10"`
	H11       int64 `json:"h11"`
	H12       int64 `json:"h12"`
	H13       int64 `json:"h13"`
	H14       int64 `json:"h14"`
	H15       int64 `json:"h15"`
	H16       int64 `json:"h16"`
	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

func (UsageUserTPSHistogram) TableName added in v0.0.14

func (UsageUserTPSHistogram) TableName() string

type UsageUserTTFTHistogram added in v0.0.14

type UsageUserTTFTHistogram struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	Date      string `gorm:"size:10;uniqueIndex:idx_uutth_bucket,priority:1" json:"date"`
	Hour      int    `gorm:"uniqueIndex:idx_uutth_bucket,priority:2" json:"hour"`
	UserID    uint   `gorm:"uniqueIndex:idx_uutth_bucket,priority:3;index" json:"user_id"`
	ModelName string `gorm:"size:128;uniqueIndex:idx_uutth_bucket,priority:4" json:"model_name"`

	MaxFirstResponseMs int64 `json:"max_first_response_ms"`
	// Fixed columns allow aggregation with direct SQL SUMs; JSON cannot serve that hot path.
	H0        int64 `json:"h0"`
	H1        int64 `json:"h1"`
	H2        int64 `json:"h2"`
	H3        int64 `json:"h3"`
	H4        int64 `json:"h4"`
	H5        int64 `json:"h5"`
	H6        int64 `json:"h6"`
	H7        int64 `json:"h7"`
	H8        int64 `json:"h8"`
	H9        int64 `json:"h9"`
	H10       int64 `json:"h10"`
	H11       int64 `json:"h11"`
	H12       int64 `json:"h12"`
	H13       int64 `json:"h13"`
	H14       int64 `json:"h14"`
	H15       int64 `json:"h15"`
	H16       int64 `json:"h16"`
	CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
}

func (UsageUserTTFTHistogram) TableName added in v0.0.14

func (UsageUserTTFTHistogram) TableName() string

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"`
}

Jump to

Keyboard shortcuts

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