Documentation
¶
Index ¶
- func EnrichLastSeen[T any](tracker *HeartbeatTracker, items []T, getID func(T) string, ...)
- func ExpandPrivateChannelAudience(q dao.AdminQuery, channelID uint, ownerID uint) ([]uint, error)
- func PublishPrivateChannelMutation(ctx context.Context, q dao.AdminQuery, bus app.EventBus, ...) error
- type AgentRuntime
- type AutoAddrUpdate
- type FetchHandler
- type FetchRegistry
- type HeartbeatTracker
- func (t *HeartbeatTracker) ConfigChanged(agentID string, params protocol.HeartbeatParams) bool
- func (t *HeartbeatTracker) Flush() error
- func (t *HeartbeatTracker) Get(agentID string) (int64, bool)
- func (t *HeartbeatTracker) GetMany(ids []string) map[string]int64
- func (t *HeartbeatTracker) SetLastSeenPersistFn(fn LastSeenPersistFn)
- func (t *HeartbeatTracker) Start(ctx context.Context)
- func (t *HeartbeatTracker) Stop()
- func (t *HeartbeatTracker) Touch(agentID string, ts int64)
- type Hub
- func (h *Hub) Broadcast(method string, params any)
- func (h *Hub) Call(agentID string, method string, params any, timeout time.Duration) (json.RawMessage, error)
- func (h *Hub) ConnectedAgents() int
- func (h *Hub) GetAgentAddresses(agentID string, dbHTTPAddrs string) []agentproxy.Address
- func (h *Hub) GetOnlineAgentIDs() []string
- func (h *Hub) GetRuntime(agentID string) *AgentRuntime
- func (h *Hub) HandleWS(c *gin.Context)
- func (h *Hub) IsOnline(agentID string) bool
- type LastSeenPersistFn
- type Publisher
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func EnrichLastSeen ¶ added in v0.0.2
func EnrichLastSeen[T any]( tracker *HeartbeatTracker, items []T, getID func(T) string, getLastSeen func(T) int64, setLastSeen func(*T, int64), )
EnrichLastSeen overrides each item's last_seen with the value from tracker when the in-memory value is fresher (greater) than the DB value.
Used by API handlers that read agent rows from DB but want the latest last_seen visible in the UI without waiting for the periodic batch flush.
Generic over item type T. Callers supply:
- getID: extract agent_id from the item
- getLastSeen: extract the current (DB-side) last_seen from the item
- setLastSeen: write the new last_seen back into the item
Nil tracker or empty slice is a no-op.
func ExpandPrivateChannelAudience ¶ added in v0.0.2
ExpandPrivateChannelAudience returns the deduplicated set of user IDs whose visiblePrivateChannels cache must be invalidated when a private channel is created/updated/deleted/shared:
- the owner
- users directly targeted by share rows (target_type='user')
- members of groups targeted by share rows (target_type='group')
Called by master CRUD handlers before publishing the invalidate event. channelID may not exist (e.g., for pre-delete computation); in that case only the owner is returned.
func PublishPrivateChannelMutation ¶ added in v0.0.2
func PublishPrivateChannelMutation(ctx context.Context, q dao.AdminQuery, bus app.EventBus, channelID, ownerID uint) error
PublishPrivateChannelMutation 在 Create/Update/Delete PrivateChannel 后调用, 展开受影响 user 集合(owner ∪ share→user ∪ share→group 内的 members)并发布 invalidate 事件。agent 收到事件后失效这些 user 的 visiblePrivateChannels cache。
用法:portal/admin 在写入 DB 后调用一次此函数;publish 失败仅记日志,不阻塞主流程 (调用方自行决定 log 策略)。
Types ¶
type AgentRuntime ¶
type AgentRuntime struct {
Uptime int64 `json:"uptime"`
CachedTokens int `json:"cached_tokens"`
CachedChannels int `json:"cached_channels"`
CachedModels int `json:"cached_models"`
CachedGlobalRoutings int `json:"cached_global_routings"`
CachedUserRoutings int `json:"cached_user_routings"`
ActiveConnections int `json:"active_connections"`
Version int64 `json:"version"`
MasterVersion int64 `json:"master_version"`
CacheStats map[string]protocol.CacheEntityStats `json:"cache_stats,omitempty"`
}
type AutoAddrUpdate ¶
type AutoAddrUpdate struct {
AgentID string `json:"agent_id"`
HTTPAddresses []agentproxy.Address `json:"http_addresses"`
}
AutoAddrUpdate is the push event payload for auto-detected address updates.
type FetchHandler ¶
type FetchHandler interface {
Fetch(ctx context.Context, q dao.AdminQuery, key string) (
data, side json.RawMessage, found bool, err error,
)
}
FetchHandler 是单实体的按需拉取处理器。 返回 (data, side, found, err):
- data 是实体本身的 JSON
- side 是可选旁路负载(如 token 响应里的 SyncedUser)
- found=false 表示 master 也未查到(调用方应让 agent 进入负缓存)
- err 仅用于真正的内部错误(DB 故障等),not-found 用 found=false 表示
type FetchRegistry ¶
type FetchRegistry struct {
// contains filtered or unexported fields
}
FetchRegistry 是实体名 → handler 的注册表。 主流程通过 Resolve 路由请求;新增实体仅需注册一次。
func NewFetchRegistry ¶
func NewFetchRegistry(cipher *byokcrypto.Cipher) *FetchRegistry
NewFetchRegistry 返回带默认实体(token / user / user_routings / private_channel)注册的 registry。 cipher 用于 private_channel 拉取时解密 key;可为 nil(仅在 BYOK 未配置的早期/测试场景), 此时 private channel handler 在被调用时返回 error。
func (*FetchRegistry) Register ¶
func (r *FetchRegistry) Register(entity string, h FetchHandler)
Register 注册或替换某实体的 handler。
func (*FetchRegistry) Resolve ¶
func (r *FetchRegistry) Resolve(entity string) (FetchHandler, bool)
Resolve 返回实体对应的 handler。
type HeartbeatTracker ¶ added in v0.0.2
type HeartbeatTracker struct {
// contains filtered or unexported fields
}
HeartbeatTracker holds the in-memory authoritative source for agent last_seen and config fingerprints. last_seen is batch-flushed to DB periodically; the config fingerprint is only used to skip mergeAgentConfig SELECTs on unchanged heartbeats.
func NewHeartbeatTracker ¶ added in v0.0.2
func NewHeartbeatTracker(app dao.AppProvider, logger *zap.Logger, flushEvery time.Duration) *HeartbeatTracker
NewHeartbeatTracker constructs a tracker. app may be nil for pure-memory tests. flushEvery <= 0 disables the background ticker.
func (*HeartbeatTracker) ConfigChanged ¶ added in v0.0.2
func (t *HeartbeatTracker) ConfigChanged(agentID string, params protocol.HeartbeatParams) bool
ConfigChanged 返回 params 是否与上次记录的指纹不同,并在变化时更新指纹。 冷启动(首次见到该 agent)永远返回 true。 用于跳过无变化心跳的 mergeAgentConfig SELECT。
func (*HeartbeatTracker) Flush ¶ added in v0.0.2
func (t *HeartbeatTracker) Flush() error
Flush snapshots dirty entries to DB and clears the dirty set. On persistence failure: dirty is cleared but updates are dropped. Live agents recover on their next Touch (re-marks dirty). For agents that never heartbeat again, last_seen may stay stale in DB — acceptable, since such agents are stale anyway and the UI reads memory first.
func (*HeartbeatTracker) Get ¶ added in v0.0.2
func (t *HeartbeatTracker) Get(agentID string) (int64, bool)
Get returns the in-memory last_seen; (0, false) when not present.
func (*HeartbeatTracker) GetMany ¶ added in v0.0.2
func (t *HeartbeatTracker) GetMany(ids []string) map[string]int64
GetMany returns only the in-memory hits among ids.
func (*HeartbeatTracker) SetLastSeenPersistFn ¶ added in v0.0.2
func (t *HeartbeatTracker) SetLastSeenPersistFn(fn LastSeenPersistFn)
SetLastSeenPersistFn installs the persistence function used by Flush.
func (*HeartbeatTracker) Start ¶ added in v0.0.2
func (t *HeartbeatTracker) Start(ctx context.Context)
Start spawns a background goroutine that calls Flush every flushEvery. When ctx is canceled (or Stop is called), the goroutine exits. flushEvery <= 0 disables the ticker entirely; callers must Flush manually or rely on Stop's force-flush.
func (*HeartbeatTracker) Stop ¶ added in v0.0.2
func (t *HeartbeatTracker) Stop()
Stop signals the ticker goroutine to exit and runs one final Flush to persist anything still in dirty. Safe to call concurrently and idempotent: stopCh 关闭走 sync.Once,Flush 自身由 mu 保护可重复调用。
func (*HeartbeatTracker) Touch ¶ added in v0.0.2
func (t *HeartbeatTracker) Touch(agentID string, ts int64)
Touch records a heartbeat/connect event purely in memory.
type Hub ¶
type Hub struct {
App dao.AppProvider
Logger *zap.Logger
Bus app.EventBus
GetVersion func() int64
// Heartbeat captures agent last_seen in memory + skips redundant
// mergeAgentConfig SELECTs via the ConfigChanged fingerprint. May be nil
// in tests / pre-wiring; callers must nil-check before use.
Heartbeat *HeartbeatTracker
// contains filtered or unexported fields
}
func NewHub ¶
func NewHub(application dao.AppProvider, logger *zap.Logger, bus app.EventBus, getVersion func() int64, cipher *byokcrypto.Cipher) *Hub
func (*Hub) Broadcast ¶
Broadcast sends a notification to all connected agents. 复制 conns snapshot 后释放 RLock,再 fan-out。 每条 conn 的 SendNotification 是非阻塞 enqueue(见 ws.Conn.WriteJSON), 病 conn 队列满会自己 Close,不会拖累其他 conn 或新接入。
func (*Hub) Call ¶
func (h *Hub) Call(agentID string, method string, params any, timeout time.Duration) (json.RawMessage, error)
Call sends an RPC request to a connected agent and waits for response.
func (*Hub) ConnectedAgents ¶
ConnectedAgents returns the number of connected agents
func (*Hub) GetAgentAddresses ¶
func (h *Hub) GetAgentAddresses(agentID string, dbHTTPAddrs string) []agentproxy.Address
GetAgentAddresses returns merged addresses for an agent. Priority: manual config (DB) > auto-detected (memory).
func (*Hub) GetOnlineAgentIDs ¶
GetOnlineAgentIDs returns IDs of currently connected agents.
func (*Hub) GetRuntime ¶
func (h *Hub) GetRuntime(agentID string) *AgentRuntime
GetRuntime returns cached runtime info for an agent, or nil if not available.
type LastSeenPersistFn ¶ added in v0.0.2
LastSeenPersistFn is the function Flush calls to persist updates. Inject the real dao.BatchUpdateLastSeen for production; nil makes Flush a no-op.