后端(notify 模块) - 新增 notify 模块:DAO/Service/Pusher 接口/Controller/Router/CleanupTask - 数据库 DDL:notify_notifications 表 + 3 索引(user+created/user+is_read/user+category) - 11 种 type 枚举(好友/群聊 9 种 + meeting_* 2 种预留)+ 4 种 category - 跨模块集成:contact 3 处 Pusher(friend_request/accepted/rejected) - 跨模块集成:group 6 处 Pusher(invite/join_request/approved/rejected/kicked/role_changed) - WS handler 断线补偿:连接建立即推送 notify.unread.total - 5 REST API(4 用户 + 1 管理员广播)+ 2 WS 事件(notify.new / notify.unread.total) - 30 天已读通知定时清理(未读永久保留) - Provider/Wire 依赖注入(NotifyPusher、NotifyConnectHook、UserInfoResolver 接口) 前端 - 新增 notify 模块:API/Pinia Store(5 分类分页缓存 + 未读数 + WS 事件)/NotifyItem/通知中心主页 - profile 入口:铃铛 badge + 菜单项 badge + 数字显示 - App.vue/login 初始化 notifyStore WS 监听;logout 调用 notifyStore.reset() 清缓存 - 清理 contact.js/group.js 中散落 toast 与冗余 notify.friend.request/group.join.request 处理 - CustomTabBar 新增 hasDot() 聚合指示器:我的 Tab 显示纯红点(无数字), 当前聚合 notifyStore.unreadTotal,未来可扩展「资料待完善/安全提醒/新版本」等 文档 - 新增 Phase 2e 整体路线图 docs/plans/2026-04-20-phase2e-design.md - 新增 Phase 2e-1 专用设计 docs/plans/2026-04-20-phase2e-1-design.md(§6.4 TabBar 聚合红点) - 新增 Phase 2e-1 实施计划 docs/plans/2026-04-20-phase2e-1-implementation.plan.md - 新增 E2E 验证报告 test-report-phase2e-1-notification.md(含 Playwright MCP 2 个现场 Bug 修复记录) - 更新 docs/progress/CURRENT_STATUS.md、docs/api/README.md、docs/api/frontend/notify.md - 更新 .cursor/rules/project-context.mdc、docs/plans/2026-02-27-echochat-system-design.md 其他 - .gitignore 排除 .playwright-mcp/ MCP 临时快照 架构决策 - 单端 WS 连接:沿用现有 ws.Hub,多端已读同步推迟到 Phase 2f/二期 - 跨模块依赖:contact/group → notify 严格单向(接口注入模式) - 降级策略:Pusher 先入库后推送;WS 失败不回滚入库;入库失败仅 Warn 不影响业务 Playwright MCP 回归(4 类场景全通) - 实时推送(admin 广播 → 1s 内前端自动插入 + 角标 +1) - Deep-link 跳转(好友申请通知 → contact/request 页) - 批量清零(全部已读按钮) - TabBar 聚合红点(有未读亮/全部已读灭)与 notifyStore.unreadTotal 三层同步 Made-with: Cursor
194 lines
6.1 KiB
Go
194 lines
6.1 KiB
Go
// Package ws 提供 WebSocket 连接处理
|
||
// 负责 HTTP → WebSocket 升级、JWT 认证、消息路由分发
|
||
package ws
|
||
|
||
import (
|
||
"context"
|
||
"net/http"
|
||
|
||
"github.com/echochat/backend/config"
|
||
"github.com/echochat/backend/pkg/logs"
|
||
"github.com/echochat/backend/pkg/utils"
|
||
"github.com/echochat/backend/pkg/ws"
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/gorilla/websocket"
|
||
"go.uber.org/zap"
|
||
)
|
||
|
||
// TokenValidator 有状态 JWT 验证接口(检查 Token 是否在 Redis 中有效)
|
||
// 由 auth.AuthService 实现,用于防止已登出用户建立 WebSocket 连接
|
||
type TokenValidator interface {
|
||
ValidateAccessToken(ctx context.Context, userID int64, clientType, token string) bool
|
||
}
|
||
|
||
// OfflineMessagePusher 离线消息推送接口
|
||
// 由 im.handler.OfflinePusher 实现,WebSocket 连接建立后触发推送
|
||
type OfflineMessagePusher interface {
|
||
PushOfflineMessages(ctx context.Context, userID int64)
|
||
}
|
||
|
||
// NotifyConnectHook 通知未读补偿钩子接口
|
||
// 由 notify.service.NotifyService 隐式实现
|
||
// WebSocket 连接建立后触发,向客户端推送 notify.unread.total 事件
|
||
// 用于断线重连场景下的徽标状态同步
|
||
type NotifyConnectHook interface {
|
||
PushUnreadTotalOnConnect(ctx context.Context, userID int64)
|
||
}
|
||
|
||
var upgrader = websocket.Upgrader{
|
||
ReadBufferSize: 1024,
|
||
WriteBufferSize: 1024,
|
||
CheckOrigin: func(r *http.Request) bool {
|
||
return true // TODO: 生产环境通过配置限制 allowed origins
|
||
},
|
||
}
|
||
|
||
// Handler WebSocket 连接处理器
|
||
type Handler struct {
|
||
hub *ws.Hub
|
||
pubsub *ws.PubSub
|
||
jwtCfg *config.JWTConfig
|
||
onlineService *OnlineService
|
||
tokenValidator TokenValidator
|
||
offlinePusher OfflineMessagePusher
|
||
notifyConnectHook NotifyConnectHook
|
||
}
|
||
|
||
// NewHandler 创建 WebSocket Handler 实例
|
||
func NewHandler(hub *ws.Hub, pubsub *ws.PubSub, jwtCfg *config.JWTConfig, onlineService *OnlineService, tokenValidator TokenValidator) *Handler {
|
||
return &Handler{
|
||
hub: hub,
|
||
pubsub: pubsub,
|
||
jwtCfg: jwtCfg,
|
||
onlineService: onlineService,
|
||
tokenValidator: tokenValidator,
|
||
}
|
||
}
|
||
|
||
// SetOfflinePusher 设置离线消息推送器(由 IM 模块在初始化时注入)
|
||
func (h *Handler) SetOfflinePusher(pusher OfflineMessagePusher) {
|
||
h.offlinePusher = pusher
|
||
}
|
||
|
||
// SetNotifyConnectHook 设置通知未读补偿钩子(由 notify 模块在初始化时注入)
|
||
func (h *Handler) SetNotifyConnectHook(hook NotifyConnectHook) {
|
||
h.notifyConnectHook = hook
|
||
}
|
||
|
||
// Upgrade 处理 WebSocket 升级请求
|
||
// GET /ws?token=xxx → JWT 认证 → 升级连接 → 注册 Hub → 订阅 Redis 频道
|
||
func (h *Handler) Upgrade(c *gin.Context) {
|
||
funcName := "ws.handler.Upgrade"
|
||
|
||
token := c.Query("token")
|
||
if token == "" {
|
||
utils.ResponseUnauthorized(c, "缺少认证 Token")
|
||
return
|
||
}
|
||
|
||
claims, err := utils.ParseToken(h.jwtCfg, token)
|
||
if err != nil {
|
||
logs.Warn(nil, funcName, "WebSocket Token 验证失败", zap.Error(err))
|
||
utils.ResponseUnauthorized(c, "Token 无效或已过期")
|
||
return
|
||
}
|
||
|
||
clientType := claims.ClientType
|
||
if clientType == "" {
|
||
clientType = "frontend"
|
||
}
|
||
if h.tokenValidator != nil && !h.tokenValidator.ValidateAccessToken(c.Request.Context(), claims.UserID, clientType, token) {
|
||
logs.Warn(nil, funcName, "WebSocket Token 已失效(Redis 校验)",
|
||
zap.Int64("user_id", claims.UserID))
|
||
utils.ResponseUnauthorized(c, "认证已失效,请重新登录")
|
||
return
|
||
}
|
||
|
||
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
|
||
if err != nil {
|
||
logs.Error(nil, funcName, "WebSocket 升级失败",
|
||
zap.Int64("user_id", claims.UserID), zap.Error(err))
|
||
return
|
||
}
|
||
|
||
client := ws.NewClient(h.hub, conn, claims.UserID)
|
||
client.SetOnDisconnect(func(userID int64) {
|
||
if client.IsClosedByHub() && h.hub.IsOnline(userID) {
|
||
logs.Info(nil, "ws.handler.onDisconnect", "连接被新连接替换,跳过下线清理",
|
||
zap.Int64("user_id", userID))
|
||
return
|
||
}
|
||
h.pubsub.Unsubscribe(userID)
|
||
h.onlineService.UserOffline(context.Background(), userID)
|
||
})
|
||
h.hub.Register(client)
|
||
h.pubsub.Subscribe(claims.UserID)
|
||
h.onlineService.UserOnline(c.Request.Context(), claims.UserID, c.ClientIP())
|
||
|
||
logs.Info(nil, funcName, "WebSocket 连接建立",
|
||
zap.Int64("user_id", claims.UserID),
|
||
zap.String("ip", c.ClientIP()))
|
||
|
||
go client.WritePump()
|
||
go client.ReadPump(h.createReadHandler(claims.UserID))
|
||
|
||
if h.offlinePusher != nil {
|
||
go h.offlinePusher.PushOfflineMessages(context.Background(), claims.UserID)
|
||
}
|
||
|
||
if h.notifyConnectHook != nil {
|
||
go h.notifyConnectHook.PushUnreadTotalOnConnect(context.Background(), claims.UserID)
|
||
}
|
||
}
|
||
|
||
// createReadHandler 创建带生命周期管理的消息处理函数
|
||
// 优先查 Hub 事件路由表(业务模块注册的处理器),未命中再走内置 fallback
|
||
func (h *Handler) createReadHandler(userID int64) ws.MessageHandler {
|
||
return func(client *ws.Client, msg *ws.Message) {
|
||
funcName := "ws.handler.onMessage"
|
||
logs.Debug(nil, funcName, "收到 WebSocket 消息",
|
||
zap.Int64("user_id", client.UserID),
|
||
zap.String("event", msg.Event),
|
||
zap.Int64("seq", msg.Seq))
|
||
|
||
// 优先查事件路由表(IM、Meeting 等模块注册的处理器)
|
||
if h.hub.DispatchEvent(client, msg) {
|
||
return
|
||
}
|
||
|
||
// 内置事件 fallback
|
||
switch msg.Event {
|
||
case "heartbeat":
|
||
h.onlineService.HeartbeatRenew(context.Background(), userID)
|
||
resp := ws.NewResponse(msg.Event, msg.Seq, 0, "pong", nil)
|
||
data, err := ws.MarshalResponse(resp)
|
||
if err != nil {
|
||
logs.Error(nil, funcName, "序列化心跳响应失败", zap.Error(err))
|
||
return
|
||
}
|
||
client.Send(data)
|
||
default:
|
||
logs.Warn(nil, funcName, "未知事件类型",
|
||
zap.String("event", msg.Event),
|
||
zap.Int64("user_id", client.UserID))
|
||
resp := ws.NewResponse(msg.Event, msg.Seq, -1, "未知事件", nil)
|
||
data, err := ws.MarshalResponse(resp)
|
||
if err != nil {
|
||
logs.Error(nil, funcName, "序列化响应失败", zap.Error(err))
|
||
return
|
||
}
|
||
client.Send(data)
|
||
}
|
||
}
|
||
}
|
||
|
||
// GetHub 返回 Hub 实例(供在线状态等模块访问)
|
||
func (h *Handler) GetHub() *ws.Hub {
|
||
return h.hub
|
||
}
|
||
|
||
// GetPubSub 返回 PubSub 实例(供业务模块发送推送)
|
||
func (h *Handler) GetPubSub() *ws.PubSub {
|
||
return h.pubsub
|
||
}
|