models

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

internal/models/user_group.go

Index

Constants

View Source
const (
	RoutingScopeGlobal = "global"
	RoutingScopeUser   = "user"
)

Variables

This section is empty.

Functions

func AutoMigrate

func AutoMigrate(db *gorm.DB) error

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 TokenFieldsEqual

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

Types

type Agent

type Agent struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	AgentID   string `gorm:"uniqueIndex;size:64" json:"agent_id"`
	Secret    string `gorm:"size:128" json:"secret,omitempty"`
	Name      string `gorm:"size:64" json:"name"`
	Status    int    `gorm:"default:1" json:"status"`
	LastSeen  int64  `json:"last_seen"`
	CreatedAt int64  `gorm:"autoCreateTime" json:"created_at"`

	// Network & routing
	HTTPAddresses string `gorm:"type:text" json:"http_addresses"` // JSON: [{"url":"...","tag":"..."}]
	Tags          string `gorm:"type:text" json:"tags"`           // comma-separated
	ProxyURL      string `gorm:"size:256" json:"proxy_url"`
}

type AgentRoute

type AgentRoute struct {
	ID         uint   `json:"id" gorm:"primaryKey"`
	SourceType string `json:"source_type" gorm:"size:32;index:idx_agent_route_source;uniqueIndex:uk_agent_route"`
	SourceID   uint   `json:"source_id" gorm:"index:idx_agent_route_source;uniqueIndex:uk_agent_route"`
	Model      string `json:"model" gorm:"size:256;uniqueIndex:uk_agent_route;default:''"`
	AgentID    string `json:"agent_id" gorm:"size:128"`
	AgentTag   string `json:"agent_tag" gorm:"size:128"`
	Priority   int    `json:"priority" gorm:"index"`
	CreatedAt  int64  `json:"created_at" gorm:"autoCreateTime"`
	UpdatedAt  int64  `json:"updated_at" gorm:"autoUpdateTime"`
}

AgentRoute 定义 Agent 路由规则。 管理员可为 Token 或 Channel 配置请求应转发到哪个 Agent 节点/组。

func (*AgentRoute) CalcPriority

func (r *AgentRoute) CalcPriority() int

CalcPriority 根据 SourceType 和 Model 计算优先级。

type Channel

type Channel struct {
	ID           uint   `gorm:"primaryKey" json:"id"`
	Name         string `gorm:"size:64" json:"name"`
	Type         int    `gorm:"index" json:"type"`
	Key          string `gorm:"type:text" json:"key"`
	BaseURL      string `gorm:"size:256" json:"base_url"`
	Models       string `gorm:"type:text" json:"models"`
	ModelMapping string `gorm:"type:text" json:"model_mapping"`
	Weight       uint   `gorm:"default:1" json:"weight"`
	Priority     int    `gorm:"default:0" json:"priority"`
	Status       int    `gorm:"default:1" json:"status"`
	Tag          string `gorm:"size:64;index" json:"tag"`
	Remark       string `gorm:"size:255" json:"remark"`

	// Native protocol layer configuration
	SupportedAPITypes   string `gorm:"type:text" json:"supported_api_types"`
	Endpoints           string `gorm:"type:text" json:"endpoints"`
	PassthroughEnabled  bool   `gorm:"default:false" json:"passthrough_enabled"`
	UseLegacyAdaptor    bool   `gorm:"default:false" json:"use_legacy_adaptor"`
	SystemPrompt        string `gorm:"type:text" json:"system_prompt"`
	RoleMapping         string `gorm:"type:text" json:"role_mapping"`
	SystemPromptInInput bool   `gorm:"default:false" json:"system_prompt_in_input"`
	ProxyURL            string `gorm:"size:256" json:"proxy_url"`
	ParamOverride       string `gorm:"type:text" json:"param_override"`
	HeaderOverride      string `gorm:"type:text" json:"header_override"`

	// Legacy: new-api specific fields (remove together when removing new-api)
	Setting           string `gorm:"type:text" json:"setting"`
	Organization      string `gorm:"size:128" json:"organization"`
	ApiVersion        string `gorm:"size:32" json:"api_version"`
	TestModel         string `gorm:"size:128" json:"test_model"`
	AutoBan           int    `gorm:"default:0" json:"auto_ban"`
	StatusCodeMapping string `gorm:"type:text" json:"status_code_mapping"`
	OtherSettings     string `gorm:"type:text" json:"other_settings"`

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

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 ChannelDailyBilling

type ChannelDailyBilling struct {
	ID               uint   `gorm:"primaryKey" json:"id"`
	Date             string `gorm:"size:10;uniqueIndex:idx_channel_daily_billing_date_channel" json:"date"`
	ChannelID        uint   `gorm:"uniqueIndex:idx_channel_daily_billing_date_channel;index" json:"channel_id"`
	ChannelName      string `gorm:"size:64" json:"channel_name"`
	ChannelType      int    `json:"channel_type"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	LastUsedAt       int64  `gorm:"index" json:"last_used_at"`
	CreatedAt        int64  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt        int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

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 ModelConfig

type ModelConfig struct {
	ID              uint    `gorm:"primaryKey" json:"id"`
	ModelName       string  `gorm:"uniqueIndex;size:128" json:"model_name"`
	InputPrice      float64 `gorm:"default:0" json:"input_price"`
	OutputPrice     float64 `gorm:"default:0" json:"output_price"`
	CacheReadPrice  float64 `gorm:"default:0" json:"cache_read_price"`
	CacheWritePrice float64 `gorm:"default:0" json:"cache_write_price"`
	Status          int     `gorm:"default:1" json:"status"`
	CreatedAt       int64   `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt       int64   `gorm:"autoUpdateTime" json:"updated_at"`
}

type ModelRouting

type ModelRouting struct {
	ID        uint   `gorm:"primaryKey" json:"id"`
	Name      string `gorm:"size:128;index;uniqueIndex:uidx_routing_scope_user_name" json:"name"`
	Scope     string `gorm:"size:8;index;uniqueIndex:uidx_routing_scope_user_name" json:"scope"` // "global" | "user"
	UserID    uint   `gorm:"index;uniqueIndex:uidx_routing_scope_user_name" json:"user_id"`      // scope=global 时为 0
	Members   string `gorm:"type:text" json:"members"`                                           // JSON: []RoutingMember
	Enabled   bool   `gorm:"default:true" json:"enabled"`
	Remark    string `gorm:"size:255" json:"remark"`
	CreatedAt int64  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

func (ModelRouting) TableName

func (ModelRouting) TableName() string

type OAuthIdentity

type OAuthIdentity struct {
	ID          uint   `gorm:"primaryKey" json:"id"`
	UserID      uint   `gorm:"index" json:"user_id"`
	ProviderID  uint   `gorm:"index;uniqueIndex:uk_provider_subject,priority:1" json:"provider_id"`
	Subject     string `gorm:"size:255;uniqueIndex:uk_provider_subject,priority:2" json:"subject"`
	Email       string `gorm:"size:255" json:"email"`
	DisplayName string `gorm:"size:128" json:"display_name"`
	CreatedAt   int64  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt   int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

type OAuthProvider

type OAuthProvider struct {
	ID                    uint   `gorm:"primaryKey" json:"id"`
	Name                  string `gorm:"uniqueIndex;size:32" json:"name"`
	DisplayName           string `gorm:"size:64" json:"display_name"`
	Issuer                string `gorm:"size:255" json:"issuer"`
	AuthorizationEndpoint string `gorm:"size:512" json:"authorization_endpoint"`
	TokenEndpoint         string `gorm:"size:512" json:"token_endpoint"`
	UserinfoEndpoint      string `gorm:"size:512" json:"userinfo_endpoint"`
	JWKSURI               string `gorm:"size:512" json:"jwks_uri"`
	ClientID              string `gorm:"size:255" json:"client_id"`
	ClientSecret          string `gorm:"size:255" json:"client_secret,omitempty"`
	Scopes                string `gorm:"size:255" json:"scopes"`
	IconURL               string `gorm:"size:512" json:"icon_url"`
	Enabled               bool   `gorm:"default:true" json:"enabled"`
	Protocol              string `gorm:"size:16;default:oidc;not null" json:"protocol"`
	CreatedAt             int64  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt             int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

type RoutingMember

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

type Setting

type Setting struct {
	Key   string `gorm:"primaryKey;size:64" json:"key"`
	Value string `gorm:"type:text" json:"value"`
}

Setting stores key-value pairs for persistent server state

type Token

type Token struct {
	ID                uint                      `gorm:"primaryKey" json:"id"`
	UserID            uint                      `gorm:"index" json:"user_id"`
	Key               string                    `gorm:"uniqueIndex;size:64" json:"key"`
	Name              string                    `gorm:"size:64" json:"name"`
	Status            int                       `gorm:"default:1" json:"status"`
	ExpiredAt         int64                     `gorm:"default:-1" json:"expired_at"`
	Models            string                    `gorm:"type:text" json:"models"`
	TemplateID        *uint                     `gorm:"index" json:"template_id"`
	TraceEnabled      bool                      `gorm:"default:false" json:"trace_enabled"`
	AllowedChannelIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_channel_ids"`
	CreatedAt         int64                     `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt         int64                     `gorm:"autoUpdateTime" json:"updated_at"`
}

type TokenDailyBilling

type TokenDailyBilling struct {
	ID               uint   `gorm:"primaryKey" json:"id"`
	Date             string `gorm:"size:10;uniqueIndex:idx_token_daily_billing_date_user_token" json:"date"`
	UserID           uint   `gorm:"uniqueIndex:idx_token_daily_billing_date_user_token;index" json:"user_id"`
	TokenID          uint   `gorm:"uniqueIndex:idx_token_daily_billing_date_user_token;index" json:"token_id"`
	TokenName        string `gorm:"size:64" json:"token_name"`
	RequestCount     int64  `json:"request_count"`
	SuccessCount     int64  `json:"success_count"`
	FailedCount      int64  `json:"failed_count"`
	PromptTokens     int64  `json:"prompt_tokens"`
	CompletionTokens int64  `json:"completion_tokens"`
	CacheReadTokens  int64  `json:"cache_read_tokens"`
	CacheWriteTokens int64  `json:"cache_write_tokens"`
	InputCost        int64  `json:"input_cost"`
	OutputCost       int64  `json:"output_cost"`
	TotalCost        int64  `json:"total_cost"`
	LastUsedAt       int64  `gorm:"index" json:"last_used_at"`
	CreatedAt        int64  `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt        int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

type TokenTemplate

type TokenTemplate struct {
	ID                uint                      `gorm:"primarykey" json:"id"`
	Name              string                    `gorm:"size:64;not null" json:"name"`
	Models            string                    `gorm:"type:text" json:"models"`
	ExpiryDays        int                       `gorm:"not null;default:-1" json:"expiry_days"`
	Status            int                       `gorm:"not null;default:1" json:"status"`
	AllowedChannelIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_channel_ids"`
	CreatedAt         int64                     `gorm:"autoCreateTime" json:"created_at"`
	UpdatedAt         int64                     `gorm:"autoUpdateTime" json:"updated_at"`
}

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"`
	AgentID          string `gorm:"index;size:64" json:"agent_id"`
	ModelName        string `gorm:"size:128" 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"`
	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"`
	TokenSource        string `gorm:"size:32" json:"token_source"`
	RoutingName        string `gorm:"size:128;index" json:"routing_name"`
	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"`
}

type UsageLogTrace

type UsageLogTrace struct {
	ID                 uint   `gorm:"primaryKey" json:"id"`
	RequestID          string `gorm:"size:64;uniqueIndex" json:"request_id"`
	InboundPath        string `gorm:"size:256" json:"inbound_path"`
	OutboundPath       string `gorm:"size:256" json:"outbound_path"`
	InboundHeaders     string `gorm:"type:text" json:"inbound_headers"`
	OutboundHeaders    string `gorm:"type:text" json:"outbound_headers"`
	InboundBody        string `gorm:"type:text" json:"inbound_body"`
	OutboundBody       string `gorm:"type:text" json:"outbound_body"`
	ResponseHeaders    string `gorm:"type:text" json:"response_headers"`
	ResponseBody       string `gorm:"type:text" json:"response_body"`
	ClientResponseBody string `gorm:"type:text" json:"client_response_body"`
	UpstreamStatus     int    `json:"upstream_status"`
	ErrorStage         string `gorm:"size:32;index" json:"error_stage"`
	CreatedAt          int64  `gorm:"autoCreateTime;index" json:"created_at"`
}

type User

type User struct {
	ID          uint   `gorm:"primaryKey" json:"id"`
	Username    string `gorm:"uniqueIndex;size:64" json:"username"`
	Email       string `gorm:"size:191" json:"email"`
	DisplayName string `gorm:"size:64" json:"display_name"`
	AvatarURL   string `gorm:"size:512" json:"avatar_url"`
	Password    string `gorm:"size:128" json:"password,omitempty"`
	Role        int    `gorm:"default:1" json:"role"`
	Status      int    `gorm:"default:1" json:"status"`
	GroupID     uint   `gorm:"index;default:1" json:"group_id"`
	Quota       int64  `gorm:"default:0" json:"quota"`
	UsedQuota   int64  `gorm:"default:0" json:"used_quota"`
	CreatedAt   int64  `gorm:"autoCreateTime" json:"created_at"`
	PasswordSet bool   `gorm:"default:false" json:"password_set"`
	UpdatedAt   int64  `gorm:"autoUpdateTime" json:"updated_at"`
}

type UserGroup

type UserGroup struct {
	ID                uint                      `gorm:"primaryKey" json:"id"`
	Name              string                    `gorm:"uniqueIndex;size:64;not null" json:"name"`
	Description       string                    `gorm:"size:255" json:"description"`
	Status            int                       `gorm:"default:1" json:"status"`
	AllowedChannelIDs datatypes.JSONSlice[uint] `gorm:"type:text" json:"allowed_channel_ids"`
	Models            string                    `gorm:"type:text" json:"models"`
	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