app

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AgentApplication

type AgentApplication interface {
	GetCache() AgentCache
	GetRouteForwarder() RouteForwarder
	GetLogger() *zap.Logger
	GetConfig() *config.AgentRuntimeConfig
	GetTransportPool() TransportPool
	RelayTimeout() time.Duration // 非流式请求的总超时;0 表示不限
}

AgentApplication 是 agent 端专用服务容器,跟 Application 并列存在于 RelayContext。 Relay pipeline 通过此接口拿到 cache / forwarder / logger / config / transport pool, 避免把整个 *Handler 当参数到处传,方便测试时 stub 单个依赖。

type AgentCache

type AgentCache interface {
	Store
	MatchRoute(tokenID uint, model string, channelIDs []uint) *models.AgentRoute
	EffectiveRequestLimiters(userID, groupID uint) []*models.RequestLimiter
	EffectiveAttemptLimiters(userID, groupID uint, src string, channelID uint) []*models.RequestLimiter
}

AgentCache 在 Store 基础上加 relay 需要的 route 查询能力。 嵌入 Store 是为了让 relay 路径既能查 Token / Channel / ModelConfig, 也能查 AgentRoute,不必持有两个对象。

type AgentRuntime

type AgentRuntime struct {
	Uptime            int64 `json:"uptime"`
	CachedTokens      int   `json:"cached_tokens"`
	CachedChannels    int   `json:"cached_channels"`
	CachedModels      int   `json:"cached_models"`
	ActiveConnections int   `json:"active_connections"`
	Version           int64 `json:"version"`
	MasterVersion     int64 `json:"master_version"`
}

AgentRuntime Agent 运行时信息 包含 Agent 的缓存状态、连接数、版本等运行时数据

type AgentServer

type AgentServer interface {
	Run() error
	RunBackground(ctx context.Context)
	Shutdown(ctx context.Context) error
	MountRoutes(router *gin.Engine)
}

AgentServer Agent 数据面服务器 负责请求中继、配置缓存同步、指标上报等数据面功能

type Application

type Application interface {
	GetDB() *gorm.DB
	SetDB(*gorm.DB)
	GetMasterServer() MasterServer
	SetMasterServer(MasterServer)
	GetHub() Hub
	SetHub(Hub)
	GetPublisher() Publisher
	SetPublisher(Publisher)
	GetSettler() Settler
	SetSettler(Settler)
	GetQuotaChecker() QuotaChecker
	SetQuotaChecker(QuotaChecker)
	GetAgentServer() AgentServer
	SetAgentServer(AgentServer)
	GetStore() Store
	SetStore(Store)
	GetSyncer() Syncer
	SetSyncer(Syncer)
	GetWSBridge() WSBridge
	SetWSBridge(WSBridge)
	GetRelayHandler() RelayHandler
	SetRelayHandler(RelayHandler)
	GetReporter() Reporter
	SetReporter(Reporter)
	GetEventBus() EventBus
	SetEventBus(EventBus)
	GetWSClient() WSClient
	SetWSClient(WSClient)
}

Application 是整个应用的顶层容器接口 统一管理 Master 和 Agent 侧的所有组件,通过 Get/Set 方法实现依赖注入 并发安全策略:仅在初始化阶段 Set,运行时只 Get,无需加锁

func NewApplication

func NewApplication() Application

type Context

type Context struct {
	*gin.Context

	App      Application
	UserInfo *UserInfo
	Logger   *zap.Logger
	Settings *config.MasterRuntimeConfig
}

Context 承载请求级别的数据和全局共享服务。

func NewContext

func NewContext(c *gin.Context, settings *config.MasterRuntimeConfig, logger *zap.Logger, application Application) *Context

func (*Context) GetBus

func (c *Context) GetBus() EventBus

GetBus 从应用容器获取事件总线,App 为 nil 时返回 nil。

type EventBus

type EventBus interface {
	Publish(ctx context.Context, event eventbus.Event) error
	Subscribe(topic string, handler eventbus.EventHandler) (eventbus.Subscription, error)
	SubscribePattern(pattern string, handler eventbus.EventHandler) (eventbus.Subscription, error)
	Close() error
}

EventBus 事件总线接口 — 所有核心接口的规范定义位于 app 包。

type Hub

type Hub interface {
	// HandleWS 处理 Agent 的 WebSocket 连接请求
	HandleWS(c *gin.Context)
	// Call 向指定 Agent 发起 RPC 调用并等待响应
	Call(agentID string, method string, params any, timeout time.Duration) (json.RawMessage, error)
	// Broadcast 向所有在线 Agent 广播通知
	Broadcast(method string, params any)
	// GetOnlineAgentIDs 获取所有在线 Agent 的 ID 列表
	GetOnlineAgentIDs() []string
	// GetRuntime 获取指定 Agent 的运行时信息(心跳、延迟等)
	GetRuntime(agentID string) *AgentRuntime
	// IsOnline 检查指定 Agent 是否在线
	IsOnline(agentID string) bool
	// GetAgentAddresses 获取 Agent 的合并地址列表(配置地址 + 自动探测地址)
	GetAgentAddresses(agentID string, dbHTTPAddrs string) []agentproxy.Address
	// ConnectedAgents 返回当前在线的 Agent 数量
	ConnectedAgents() int
}

Hub WebSocket 连接管理中心 Master 端用于管理所有 Agent 的 WebSocket 连接,支持 RPC 调用、广播和在线状态查询

type MasterServer

type MasterServer interface {
	Run() error
	Shutdown(ctx context.Context) error
	InitAdminUser(username, password string) error
}

MasterServer Master 控制面服务器 负责管理 API、WebSocket Hub、计费结算等控制面功能

type NotificationHandler

type NotificationHandler func(ctx context.Context, params json.RawMessage) (any, error)

NotificationHandler 处理 JSON-RPC 通知的回调函数。

type Publisher

type Publisher interface {
	// Start 启动推送监听
	Start()
}

Publisher 配置变更推送器 监听事件总线上的配置变更事件,通过 Hub 将增量更新推送给所有在线 Agent

type QuotaChecker

type QuotaChecker interface {
	Start()
}

QuotaChecker 额度检查器 定期检查用户额度使用情况,对超额用户进行处理

type RelayHandler

type RelayHandler interface {
	Relay(c *gin.Context)
}

RelayHandler 请求中继处理器 Agent 端的核心组件,负责接收客户端 API 请求,通过 Codec 转换协议后转发到上游服务商

type Reporter

type Reporter interface {
	Start(ctx context.Context)
	Stop()
	SetClient(client WSClient)
	PendingCount() int
}

Reporter 使用量指标上报器 Agent 端组件,收集 API 请求的使用量数据(token 消耗、模型、耗时等), 批量聚合后通过 WebSocket 上报给 Master

type RouteForwarder

type RouteForwarder interface {
	ForwardByRoute(c *gin.Context, route *models.AgentRoute) (forwarded bool, err error)
}

RouteForwarder 抽象 agent → agent 转发能力。 Relay 在解析到 AgentRoute 时调用 ForwardByRoute,把请求转给目标 agent。

type Settler

type Settler interface {
	Start()
	Settle(ctx context.Context, agentID string, logs []protocol.UsageLogEntry)
}

Settler 计费结算器 监听 Agent 上报的使用量数据,计算费用并更新用户额度

type Store

type Store interface {
	// --- Token 操作 ---
	GetToken(ctx context.Context, key string) *models.Token
	SetToken(token *models.Token)
	DeleteToken(key string)
	GetTokenByID(ctx context.Context, id uint) *models.Token
	DeleteTokenByID(id uint)
	LoadTokens(tokens []models.Token)
	TokenCount() int

	// --- Channel 操作 ---
	GetChannel(id uint) *models.Channel
	SetChannel(ch *models.Channel)
	DeleteChannel(id uint)
	LoadChannels(channels []models.Channel)
	ChannelCount() int

	// --- ModelConfig 操作 ---
	GetModelConfig(modelName string) *models.ModelConfig
	SetModelConfig(mc *models.ModelConfig)
	DeleteModelConfig(modelName string)
	LoadModelConfigs(configs []models.ModelConfig)
	ModelConfigCount() int

	// --- 模型路由 ---
	GetChannelsForModel(model string) []*models.Channel
	RebuildModelIndex()
	GetAllModelNames() []string

	// --- User 操作 ---
	GetUser(ctx context.Context, id uint) *protocol.SyncedUser
	SetUserQuota(id uint, quota int64) // 更新已缓存 user 的 Quota;不在缓存则忽略

	// --- BYOK 私有 channel ---
	GetVisiblePrivateChannelsForUser(userID uint, model string) []*protocol.SyncedPrivateChannel
	ListVisibleBYOKModelNamesForUser(userID uint) []string // 列举 user 全部 enabled BYOK channel 的 Models 并集(去重)

	// --- Agent 操作 ---
	GetAgent(agentID string) *models.Agent
	SetAgent(agent *models.Agent)
	UpdateAgentAutoAddresses(agentID string, addrs []agentproxy.Address)
	DeleteAgent(agentID string)
	GetAgentsByTag(tag string) []*models.Agent
	GetAllAgents() []*models.Agent
	LoadAgents(agents []models.Agent)
	AgentCount() int

	// --- 版本与设置 ---
	Version() int64
	SetVersion(v int64)
	LoadSettings(s []models.Setting)
	Settings() settings.AgentSettings
	TraceMaxBodySize() int
	FallbackSleepMs() int

	// --- 系统 Token ---
	GetSystemTestToken() *models.Token

	// --- 事件处理 ---
	HandleSyncEvent(entity, action string, data []byte)
}

Store 本地配置缓存 Agent 端用于缓存从 Master 同步的 Token、Channel、Model 等配置数据, 支持增量更新和全量加载

type Syncer

type Syncer interface {
	SetClient(client WSClient)
	FullSync(ctx context.Context) error
	SubscribeEvents()
	StartPeriodicCheck(ctx context.Context)
}

Syncer 缓存同步器 负责与 Master 建立连接,拉取全量配置并订阅增量事件,保持本地缓存与 Master 一致

type TransportPool

type TransportPool interface {
	Get(ch *models.Channel) *http.Transport
	Invalidate(channelID uint, oldProxyURL string)
}

TransportPool 抽象 channel → *http.Transport 缓存能力。 让 relay 在多次 upstream 请求间共享连接池,避免每次 new(http.Transport)。

Invalidate 用于 channel.ProxyURL 变更时让旧 transport 失效; server.go 在装配阶段通过 Store.OnChannelChange 回调调用。

type UserInfo

type UserInfo struct {
	UserID            uint
	Username          string
	DisplayName       string // JWT claim ClaimDisplayName,SSO 注册时由 IdP 同步,可空
	AvatarURL         string // JWT claim ClaimAvatarURL,SSO 注册时由 IdP 同步,可空
	Role              int
	TokenID           uint // API Token 认证时填充,JWT 登录时为 0
	TokenName         string
	TraceEnabled      bool     // Agent 侧:Token 是否开启 trace
	TokenModels       []string // Agent 侧:Token 允许的模型列表(空表示不限)
	AllowedChannelIDs []uint   // Agent 侧:Token 允许的频道列表(空表示不限)

	// 新增:来自该用户所在 Group
	GroupID                uint
	GroupModels            []string
	GroupAllowedChannelIDs []uint
}

UserInfo 承载认证用户身份信息,在应用内流转。

type WSBridge

type WSBridge interface {
	Start()
}

WSBridge WebSocket 同步桥 监听 WebSocket 连接上的消息,将 Master 推送的增量更新转发给 Store 处理

type WSClient

type WSClient interface {
	// OnNotification 注册指定方法的通知回调处理器
	OnNotification(method string, handler NotificationHandler)
	// Call 发起 RPC 调用并等待响应
	Call(ctx context.Context, method string, params any) (json.RawMessage, error)
	// Notify 发送单向通知(不等待响应)
	Notify(method string, params any) error
	// Close 关闭 WebSocket 连接
	Close() error
	// ReadLoop 启动消息读取循环(通常在 goroutine 中运行)
	ReadLoop()
}

WSClient WebSocket 客户端 封装 WebSocket 连接,提供 JSON-RPC 风格的 Call(请求-响应)和 Notify(单向通知)能力

type WSConn

type WSConn interface {
	// SendNotification 向客户端发送 JSON-RPC 通知
	SendNotification(method string, params any) error
	// SendResponse 向客户端发送 JSON-RPC 响应
	SendResponse(resp *jsonrpc.Response) error
	// ReadMessage 读取一条消息,区分请求和响应
	ReadMessage() (*jsonrpc.Request, *jsonrpc.Response, error)
	// WriteJSON 发送任意 JSON 数据
	WriteJSON(v any) error
	// Close 关闭连接
	Close() error
	// Done 返回连接关闭的通知 channel
	Done() <-chan struct{}
}

WSConn WebSocket 服务端连接 封装单个 WebSocket 连接的服务端视角,提供消息读写和生命周期管理

Jump to

Keyboard shortcuts

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