Files
memoryweave/go/internal/api/routes/ws.go
T
小唯 886c0c20e2 style(gofmt): 全仓 66 文件对齐 gofmt 1.25
gofmt -l 实测 66 文件不合规(历史遗留+gofmt 1.25 规范化:
单行 if/for/case 展开成块、Go1.19+ doc 注释 // 与段落 // 空行)。
本 commit 只含格式化,零逻辑改动:
- 66/66 文件「去注释+去空白+分号归一」后 token 流与 HEAD 完全一致
- go build ./... exit 0;go vet ./... exit 0(改前后一致)
- go test ./... 17 包全 ok(改前后一致)
验收: gofmt -l . 为空;git diff -w 非空系 gofmt 1.25 非纯空白特性,
非逻辑改动(等价性以 token 流 + test 兜底)。
2026-10-10 15:51:25 +08:00

157 lines
3.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — WebSocket 实时事件推送(gorilla/websocket)
package routes
import (
"log"
"net/http"
"sync"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
// WSManager 管理所有 WebSocket 连接,支持按 AgentID 定向推送
type WSManager struct {
mu sync.RWMutex
clients map[string]map[*websocket.Conn]bool // agentID → 连接集合
connMu sync.Map // per-conn mutex: *websocket.Conn → *sync.Mutex
}
// 全局 WebSocket 管理器
var WSBus = &WSManager{
clients: make(map[string]map[*websocket.Conn]bool),
}
// Register 注册一个新 WebSocket 连接
func (wm *WSManager) Register(agentID string, conn *websocket.Conn) {
wm.mu.Lock()
defer wm.mu.Unlock()
if wm.clients[agentID] == nil {
wm.clients[agentID] = make(map[*websocket.Conn]bool)
}
wm.clients[agentID][conn] = true
wm.connMu.Store(conn, &sync.Mutex{})
log.Printf("[ws] agent %s connected (%d total)", agentID, len(wm.clients[agentID]))
}
// Unregister 移除连接
func (wm *WSManager) Unregister(agentID string, conn *websocket.Conn) {
wm.mu.Lock()
defer wm.mu.Unlock()
if clients, ok := wm.clients[agentID]; ok {
delete(clients, conn)
if len(clients) == 0 {
delete(wm.clients, agentID)
}
}
// 先获取该 conn 的锁,确保没有正在进行的 write,然后关闭
if muVal, ok := wm.connMu.Load(conn); ok {
mu := muVal.(*sync.Mutex)
mu.Lock()
conn.Close()
mu.Unlock()
} else {
conn.Close()
}
wm.connMu.Delete(conn)
log.Printf("[ws] agent %s disconnected", agentID)
}
// writeWithLock 安全地写入 WebSocket JSON(每个连接保证单 writer)
func (wm *WSManager) writeWithLock(conn *websocket.Conn, msg interface{}) error {
muVal, _ := wm.connMu.Load(conn)
mu := muVal.(*sync.Mutex)
mu.Lock()
defer mu.Unlock()
return conn.WriteJSON(msg)
}
// Push 推送到指定 Agent 所有连接
func (wm *WSManager) Push(agentID string, msgType string, payload interface{}) {
wm.mu.RLock()
defer wm.mu.RUnlock()
clients, ok := wm.clients[agentID]
if !ok || len(clients) == 0 {
return
}
msg := map[string]interface{}{
"type": msgType,
"payload": payload,
}
for conn := range clients {
go func(c *websocket.Conn) {
if err := wm.writeWithLock(c, msg); err != nil {
log.Printf("[ws] write error: %v", err)
wm.Unregister(agentID, c)
}
}(conn)
}
}
// Broadcast 广播到所有 Agent 的所有连接
func (wm *WSManager) Broadcast(msgType string, payload interface{}) {
wm.mu.RLock()
defer wm.mu.RUnlock()
msg := map[string]interface{}{
"type": msgType,
"payload": payload,
}
for agentID, clients := range wm.clients {
for conn := range clients {
go func(c *websocket.Conn, aid string) {
if err := wm.writeWithLock(c, msg); err != nil {
log.Printf("[ws] broadcast error: %v", err)
wm.Unregister(aid, c)
}
}(conn, agentID)
}
}
}
// Stats 返回连接统计
func (wm *WSManager) Stats() map[string]int {
wm.mu.RLock()
defer wm.mu.RUnlock()
stats := make(map[string]int)
for aid, clients := range wm.clients {
stats[aid] = len(clients)
}
return stats
}
// ─── HTTP Handler ─────────────────────────────────────
// WSHandler 处理 /api/v1/ws/{agent_id} 连接
func WSHandler(w http.ResponseWriter, r *http.Request) {
// 从路径提取 agentID: /api/v1/ws/{agent_id}
agentID := r.PathValue("id")
if agentID == "" {
agentID = "anonymous"
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("[ws] upgrade error: %v", err)
return
}
WSBus.Register(agentID, conn)
// 保持连接,等待断开
for {
_, _, err := conn.ReadMessage()
if err != nil {
WSBus.Unregister(agentID, conn)
return
}
}
}