cache

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LimiterIndex added in v0.0.8

type LimiterIndex struct {
	// contains filtered or unexported fields
}

LimiterIndex 持有同步下发的 limiters + bindings,重建候选索引, 并按 spec §6.1 就近覆盖解析出每个 (Metric,KeyBy) 维度的生效 limiter。 放在 cache 包(同 RouteIndex),由 Store 持有;relay 侧通过接口读取,避免循环依赖。

func NewLimiterIndex added in v0.0.8

func NewLimiterIndex() *LimiterIndex

func (*LimiterIndex) CacheName added in v0.0.8

func (li *LimiterIndex) CacheName() string

CacheName / CacheStat 实现 NamedCacheStat:报限流器/绑定条数(持锁读)。

func (*LimiterIndex) CacheStat added in v0.0.8

func (li *LimiterIndex) CacheStat() protocol.CacheEntityStats

func (*LimiterIndex) DeleteBinding added in v0.0.8

func (li *LimiterIndex) DeleteBinding(id uint)

func (*LimiterIndex) DeleteLimiter added in v0.0.8

func (li *LimiterIndex) DeleteLimiter(id uint)

func (*LimiterIndex) EffectiveAttemptLimiters added in v0.0.8

func (li *LimiterIndex) EffectiveAttemptLimiters(userID, groupID uint, src string, channelID uint) []*models.RequestLimiter

EffectiveAttemptLimiters 返回尝试级(KeyBy 依赖渠道)的生效 limiter,含 ChannelScope 过滤。 src 是渠道来源字符串:"admin" | "private"(等于 string(state.SourceAdmin/SourcePrivate))。

func (*LimiterIndex) EffectiveRequestLimiters added in v0.0.8

func (li *LimiterIndex) EffectiveRequestLimiters(userID, groupID uint) []*models.RequestLimiter

EffectiveRequestLimiters 返回请求级(KeyBy 不依赖渠道)的生效 limiter。

func (*LimiterIndex) Limiter added in v0.0.8

func (li *LimiterIndex) Limiter(id uint) *models.RequestLimiter

Limiter 按 ID 返回限流器副本(快照/展示用)。不存在返回 nil。持锁读。

func (*LimiterIndex) LoadBindings added in v0.0.8

func (li *LimiterIndex) LoadBindings(bs []models.LimiterBinding)

func (*LimiterIndex) LoadLimiters added in v0.0.8

func (li *LimiterIndex) LoadLimiters(ls []models.RequestLimiter)

func (*LimiterIndex) PutBinding added in v0.0.8

func (li *LimiterIndex) PutBinding(b *models.LimiterBinding)

func (*LimiterIndex) PutLimiter added in v0.0.8

func (li *LimiterIndex) PutLimiter(l *models.RequestLimiter)

type NamedCacheStat added in v0.0.8

type NamedCacheStat interface {
	CacheName() string // 监控页唯一键,如 "route_index" / "limiter_index"
	CacheStat() protocol.CacheEntityStats
}

NamedCacheStat 是任意"带名字、能自报统计"的缓存/索引。 实现它即可被 Store.CacheSnapshot() 自动纳入心跳上报——无需再在多处手抄清单。 新增缓存务必实现此接口(或由 Store 的反射完整性测试 TestCacheSnapshot_Complete 拦截遗漏)。

type RouteIndex

type RouteIndex struct {
	// contains filtered or unexported fields
}

RouteIndex 封装 Agent 路由规则的存储和索引。

func NewRouteIndex

func NewRouteIndex() *RouteIndex

NewRouteIndex 创建空的 RouteIndex。

func (*RouteIndex) CacheName added in v0.0.8

func (ri *RouteIndex) CacheName() string

CacheName / CacheStat 实现 NamedCacheStat:索引类只报条目数(无 LRU 命中语义)。

func (*RouteIndex) CacheStat added in v0.0.8

func (ri *RouteIndex) CacheStat() protocol.CacheEntityStats

func (*RouteIndex) Delete

func (ri *RouteIndex) Delete(routeID uint)

Delete 单条删除。

func (*RouteIndex) Load

func (ri *RouteIndex) Load(routes []*models.AgentRoute)

Load 全量加载:清空旧数据后重建索引。

func (*RouteIndex) Match

func (ri *RouteIndex) Match(tokenID uint, model string, channelIDs []uint) *models.AgentRoute

Match 按优先级匹配路由规则: 1. token + model 精确匹配 (priority 100) 2. token 默认 (priority 90) 3. channel + model 精确匹配 (priority 80) 4. channel 默认 (priority 70)

func (*RouteIndex) Put

func (ri *RouteIndex) Put(route *models.AgentRoute)

Put 单条增改。

type Store

type Store struct {
	RouteIndex *RouteIndex

	LimiterIndex *LimiterIndex
	// contains filtered or unexported fields
}

func NewStore

func NewStore(client app.WSClient, cfg config.AgentCacheConfig) *Store

NewStore 装配 agent 端缓存 Store。 client 用于 LRU 实体的 miss 拉取(可为 nil;nil 时 LRU 实体只读缓存)。 cfg 决定 LRU 容量与负缓存 TTL;零值/非法值由 normalize 兜底为默认。

选择性 LRU:tokens / users 走 LRU;channels / modelConfigs / agents / userGroups 仍是 admin 维护的小规模实体,走 FullCache。

func (*Store) AgentCount

func (s *Store) AgentCount() int

func (*Store) CacheSnapshot

func (s *Store) CacheSnapshot() map[string]protocol.CacheEntityStats

CacheSnapshot 收集每实体/索引的 Stats 用于 heartbeat 上报。 单一 provider 列表:实体缓存(LRU/Full)+ 实现 NamedCacheStat 的索引。 新增缓存请加进 namedStats() 或让其实现 NamedCacheStat; TestCacheSnapshot_Complete 反射兜底拦截遗漏。

func (*Store) ChannelCount

func (s *Store) ChannelCount() int

func (*Store) DeleteAgent

func (s *Store) DeleteAgent(agentID string)

func (*Store) DeleteChannel

func (s *Store) DeleteChannel(id uint)

func (*Store) DeleteGlobalRouting

func (s *Store) DeleteGlobalRouting(name string)

DeleteGlobalRouting 删除全局 routing。

func (*Store) DeleteModelConfig

func (s *Store) DeleteModelConfig(modelName string)

func (*Store) DeleteToken

func (s *Store) DeleteToken(key string)

func (*Store) DeleteTokenByID

func (s *Store) DeleteTokenByID(id uint)

func (*Store) DeleteUser

func (s *Store) DeleteUser(id uint)

func (*Store) DeleteUserGroup

func (s *Store) DeleteUserGroup(id uint)

func (*Store) EffectiveAttemptLimiters added in v0.0.8

func (s *Store) EffectiveAttemptLimiters(userID, groupID uint, src string, channelID uint) []*models.RequestLimiter

func (*Store) EffectiveRequestLimiters added in v0.0.8

func (s *Store) EffectiveRequestLimiters(userID, groupID uint) []*models.RequestLimiter

EffectiveRequestLimiters / EffectiveAttemptLimiters 委托给 LimiterIndex, 供 relay 侧 Gate 通过 app.AgentCache 接口读取(src: "admin"|"private")。

func (*Store) FallbackSleepMs added in v0.0.2

func (s *Store) FallbackSleepMs() int

FallbackSleepMs 实现 exec.SleepReader 接口。 单独抽出方法是为了避免 exec 包 import cache 包(叶子原则)。

func (*Store) GetAgent

func (s *Store) GetAgent(agentID string) *models.Agent

func (*Store) GetAgentsByTag

func (s *Store) GetAgentsByTag(tag string) []*models.Agent

GetAgentsByTag returns all active agents that have the given tag.

func (*Store) GetAllAgents

func (s *Store) GetAllAgents() []*models.Agent

GetAllAgents returns all cached agents.

func (*Store) GetAllModelNames

func (s *Store) GetAllModelNames() []string

GetAllModelNames 返回所有暴露给 /v1/models 的 model 名: - 真实 model(来自 channel.Models 派生的 modelChannels 索引) - 全局 enabled routing 的 name 用户级 routing 不进全局列表(避免命名冲突;用户调 /v1/models 时由 handler 叠加该用户的 user routing)。

func (*Store) GetChannel

func (s *Store) GetChannel(id uint) *models.Channel

func (*Store) GetChannelsForModel

func (s *Store) GetChannelsForModel(model string) []*models.Channel

func (*Store) GetGlobalRouting

func (s *Store) GetGlobalRouting(name string) *protocol.SyncedRouting

GetGlobalRouting 返回 enabled 的全局 routing;disabled 或 not found 都返回 nil。 disabled 等同于运行时"临时移除"——校验层另有一份不过滤 enabled 的查询。

func (*Store) GetModelConfig

func (s *Store) GetModelConfig(modelName string) *models.ModelConfig

func (*Store) GetSystemTestToken

func (s *Store) GetSystemTestToken() *models.Token

GetSystemTestToken finds the system test token by name. 走 Range 遍历主存储——LRU 模式下只看缓存中的 token,未缓存的不会被找到。

func (*Store) GetToken

func (s *Store) GetToken(ctx context.Context, key string) *models.Token

func (*Store) GetTokenByID

func (s *Store) GetTokenByID(ctx context.Context, id uint) *models.Token

func (*Store) GetUser

func (s *Store) GetUser(ctx context.Context, id uint) *protocol.SyncedUser

func (*Store) GetUserGroup

func (s *Store) GetUserGroup(id uint) *models.UserGroup

func (*Store) GetVisiblePrivateChannelsForUser added in v0.0.2

func (s *Store) GetVisiblePrivateChannelsForUser(userID uint, model string) []*protocol.SyncedPrivateChannel

func (*Store) GlobalRoutingCount

func (s *Store) GlobalRoutingCount() int

GlobalRoutingCount 返回当前缓存的全局 routing 数(用于 stats / 日志)。

func (*Store) HandleSyncEvent

func (s *Store) HandleSyncEvent(entity, action string, data []byte)

func (*Store) HasRealModel added in v0.0.6

func (s *Store) HasRealModel(name string) bool

HasRealModel 判断 name 是否有 channel 支撑的真实模型(不含 routing)。

func (*Store) InvalidateUserRoutings

func (s *Store) InvalidateUserRoutings(userID uint)

InvalidateUserRoutings 清掉某 user 的整块 cache,下次 ResolveRouting LRU miss 时由 Loader 重新拉取(B3.4 接入)。

func (*Store) InvalidateVisiblePrivateChannels added in v0.0.2

func (s *Store) InvalidateVisiblePrivateChannels(userID uint)

InvalidateVisiblePrivateChannels 删该 user 的整块 cache,下次 LRU miss 由 loader 重新拉取(与 user_routings 同模式:不增量合并,整块失效)。 share 表变更 / channel CRUD / user 离开 group 都触发。

func (*Store) ListGlobalRoutingNames

func (s *Store) ListGlobalRoutingNames() []string

ListGlobalRoutingNames 返回所有 enabled 全局 routing 名,按字典序排序。 用于 /v1/models 暴露 routing 作为可调用 model 名。

func (*Store) ListUserRoutingNames

func (s *Store) ListUserRoutingNames(userID uint) []string

ListUserRoutingNames 返回当前用户 enabled user-scope routing 名,按字典序排序。 userID==0 或无 entry 时返回 nil。LRU miss 触发 loader 失败时同样返回 nil。

func (*Store) ListVisibleBYOKModelNamesForUser added in v0.0.2

func (s *Store) ListVisibleBYOKModelNamesForUser(userID uint) []string

ListVisibleBYOKModelNamesForUser 返回某 user 全部 enabled BYOK channel 的 Models 字段并集(去重,保序:channel 内部 Models 原序,跨 channel 先到先得)。 userID == 0 / 缓存 miss / 无 enabled channel 时返回 nil。 复用 visiblePrivateChannels LRU 缓存层,不引入新缓存。

func (*Store) LoadAgents

func (s *Store) LoadAgents(agents []models.Agent)

func (*Store) LoadChannels

func (s *Store) LoadChannels(channels []models.Channel)

func (*Store) LoadGlobalRoutings

func (s *Store) LoadGlobalRoutings(items []models.ModelRouting)

LoadGlobalRoutings 全量替换 globalRoutings 缓存(用于 FullSync)。 把 models.ModelRouting 投影成 protocol.SyncedRouting;只加载 enabled=true 的条目。

func (*Store) LoadModelConfigs

func (s *Store) LoadModelConfigs(configs []models.ModelConfig)

func (*Store) LoadScripts added in v0.0.6

func (s *Store) LoadScripts(list []models.AdminScript)

LoadScripts 增量入列(full sync,分页友好——逐条 set,不整体替换, 避免分页第 2 页清掉第 1 页)。坏脚本不入列、disabled 入列但 match 时被过滤。

func (*Store) LoadSettings

func (s *Store) LoadSettings(settings []models.Setting)

func (*Store) LoadTokens

func (s *Store) LoadTokens(tokens []models.Token)

func (*Store) LoadUserGroups

func (s *Store) LoadUserGroups(groups []models.UserGroup)

func (*Store) LoadUsers

func (s *Store) LoadUsers(users []protocol.SyncedUser)

func (*Store) MatchScripts added in v0.0.6

func (s *Store) MatchScripts(channelID uint, model string) []*script.Compiled

MatchScripts 实现 script.ScriptProvider,转发给内部 scriptStore。

func (*Store) ModelConfigCount

func (s *Store) ModelConfigCount() int

func (*Store) OnChannelChange

func (s *Store) OnChannelChange(fn func(old, new *models.Channel))

OnChannelChange 注册一个 channel upsert 时的回调。 old 可能是 nil(首次出现);new 可能是 nil(删除)。 同步调用,回调函数应保持轻量。

func (*Store) OverrideVisiblePrivateChannels added in v0.0.2

func (s *Store) OverrideVisiblePrivateChannels(userID uint, channels []protocol.SyncedPrivateChannel)

OverrideVisiblePrivateChannels 直接写入 visiblePrivateChannels LRU, 绕过 loader——仅供跨包测试用,调用方必须在测试上下文中(testing.Testing())。 非测试上下文调用会 panic,避免生产代码意外污染用户 BYOK 缓存。

func (*Store) RebuildModelIndex

func (s *Store) RebuildModelIndex()

RebuildModelIndex 从 channels 重建 model→channels 派生索引。

func (*Store) ResolveRouting

func (s *Store) ResolveRouting(name string, userID uint) *protocol.SyncedRouting

ResolveRouting 按 spec §1.4 优先级解析:用户 routing > 全局 routing > nil(让上层当真实 model 处理)。

func (*Store) ScriptCount added in v0.0.6

func (s *Store) ScriptCount() int

ScriptCount 返回成功编译入列的脚本数。

func (*Store) ScriptEngine added in v0.0.6

func (s *Store) ScriptEngine() *script.Engine

ScriptEngine 返回共享的脚本执行引擎。

func (*Store) SetAgent

func (s *Store) SetAgent(agent *models.Agent)

func (*Store) SetChannel

func (s *Store) SetChannel(ch *models.Channel)

func (*Store) SetGlobalRouting

func (s *Store) SetGlobalRouting(name string, r *protocol.SyncedRouting)

SetGlobalRouting 写入全局 routing。WS push / FullSync 调用。

func (*Store) SetLogger

func (s *Store) SetLogger(l *zap.Logger)

SetLogger 注入 zap.Logger,用于 routing apply / resolve 等可观测性日志。 默认 NewStore 使用 zap.NewNop();server 装配时调用以接入实际 logger。

func (*Store) SetModelConfig

func (s *Store) SetModelConfig(mc *models.ModelConfig)

func (*Store) SetToken

func (s *Store) SetToken(token *models.Token)

func (*Store) SetUser

func (s *Store) SetUser(u *protocol.SyncedUser)

func (*Store) SetUserGroup

func (s *Store) SetUserGroup(g *models.UserGroup)

func (*Store) SetUserQuota added in v0.0.8

func (s *Store) SetUserQuota(id uint, quota int64)

SetUserQuota 更新已缓存 user 的 Quota 字段;用于配额扣减后的原地刷新。 若 user 不在缓存中则静默忽略(不触发 loader 拉取)。

func (*Store) SetUserRoutings

func (s *Store) SetUserRoutings(userID uint, routings map[string]*protocol.SyncedRouting)

SetUserRoutings 用整块替换某 user 的全部 user-scope routings。 WS push 按 user 粒度推送时调用。

func (*Store) SetVersion

func (s *Store) SetVersion(v int64)

func (*Store) Settings added in v0.0.2

func (s *Store) Settings() settings.AgentSettings

Settings 返回当前同步配置快照(value copy,不可变,无锁读)。

func (*Store) TokenCount

func (s *Store) TokenCount() int

func (*Store) TraceMaxBodySize

func (s *Store) TraceMaxBodySize() int

TraceMaxBodySize 兼容老调用方(internal/agent/relay/handler.go:125-126 等)。 新代码请走 Settings().TraceMaxBodySize 直读。

func (*Store) UpdateAgentAutoAddresses

func (s *Store) UpdateAgentAutoAddresses(agentID string, addrs []agentproxy.Address)

UpdateAgentAutoAddresses updates in-memory auto-detected addresses for an agent without overriding manually configured addresses.

func (*Store) UserCount

func (s *Store) UserCount() int

func (*Store) UserGroupCount

func (s *Store) UserGroupCount() int

func (*Store) UserRoutingsCount

func (s *Store) UserRoutingsCount() int

UserRoutingsCount 返回当前 LRU 中缓存的 user-scope routing 块数(每个 user 一块)。

func (*Store) Version

func (s *Store) Version() int64

func (*Store) VisiblePrivateChannelsCount added in v0.0.2

func (s *Store) VisiblePrivateChannelsCount() int

VisiblePrivateChannelsCount 返回当前 LRU 中缓存的 user-scope private channel 块数。

type Syncer

type Syncer struct {
	Store            *Store
	Client           app.WSClient
	Bus              app.EventBus
	Logger           *zap.Logger
	FullSyncInterval time.Duration
	// contains filtered or unexported fields
}

func NewSyncer

func NewSyncer(store *Store, client app.WSClient, bus app.EventBus, logger *zap.Logger, interval time.Duration) *Syncer

func (*Syncer) FullSync

func (s *Syncer) FullSync(ctx context.Context) error

FullSync pulls all data from master.

LRU 模式实体(token / user / private_channel)不参与 FullSync——它们靠 push invalidate + miss 时 RPC 拉取保持最新。全量重拉违背 LRU 容量目标,会让 agent 内存重新涨回基线。

func (*Syncer) SetClient

func (s *Syncer) SetClient(client app.WSClient)

SetClient replaces the WS client (e.g., after reconnection)

func (*Syncer) StartPeriodicCheck

func (s *Syncer) StartPeriodicCheck(ctx context.Context)

StartPeriodicCheck starts periodic version comparison

func (*Syncer) SubscribeEvents

func (s *Syncer) SubscribeEvents()

SubscribeEvents subscribes to local EventBus for sync events from WSBridge

type TokenIDFetcher

type TokenIDFetcher interface {
	LoadByID(ctx context.Context, id uint) (*models.Token, error)
}

TokenIDFetcher 负责按 id 从 master 拉 token—— 当 byID 命中但 primary 已被 LRU 淘汰时使用。 接入将在 Task 16 / Task 18 完成;当前可传 nil。

type WSBridge

type WSBridge struct {
	Client app.WSClient
	Store  *Store
	Bus    app.EventBus
	Logger *zap.Logger
	Syncer *Syncer
}

func NewWSBridge

func NewWSBridge(client app.WSClient, store *Store, bus app.EventBus, logger *zap.Logger) *WSBridge

func (*WSBridge) Start

func (b *WSBridge) Start()

Start registers WS notification handlers that bridge to local EventBus

Directories

Path Synopsis
Package entitycache 提供通用实体缓存抽象。
Package entitycache 提供通用实体缓存抽象。
Package loaders 提供 entitycache.Loader 的具体实现(每实体一个文件)。
Package loaders 提供 entitycache.Loader 的具体实现(每实体一个文件)。

Jump to

Keyboard shortcuts

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