feat(messages): 接入用户聊天 SSE 实时刷新

This commit is contained in:
yml2213
2026-10-30 14:15:16 +08:00
parent 395f056d64
commit ca2c8fee26
4 changed files with 154 additions and 1 deletions
+33
View File
@@ -0,0 +1,33 @@
# Phase 2 聊天实时推送验收
> 日期:2026-10-30
> 范围:用户端聊天 SSE 实时刷新、轮询降频兜底。
## 1. 交付内容
- 新增 `frontend/src/features/messages/ChatEventsBridge.tsx`
- 使用 `fetch` 流读取 `GET /api/chats/events`,解决浏览器 `EventSource` 无法附加 `Authorization` 的问题。
- 自动携带 Bearer token、Cookie 与分销站点头 `X-Distribution-Site-Code`。
- 解析 `event:` / `data:` 块,兼容 CRLF 与多行 data。
- 收到事件后刷新:
- `chat-conversations`
- `chat-unread-count`
- `notifications`
- 对应会话的 `chat-messages` 与 `chat-conversation`
- 断线后 3 秒自动重连,组件卸载时中止连接并清理定时器。
- `frontend/src/App.tsx` 在 `QueryClientProvider` 与 `BrowserRouter` 内挂载桥接组件。
- `useChatMessages` 轮询从 6 秒调整为 30 秒,仅作为 SSE 不可用时的兜底,减少无效请求。
## 2. 验证记录
| 检查 | 结果 |
|---|---|
| `curl --max-time 3 -H 'Accept: text/event-stream' /api/chats/events` | 返回 `event: connected` 与 `data: {"ok":true}` |
| SSE 鉴权 | 复用用户 Bearer token,后端返回 200 |
| 前端类型检查 / 构建 | 见本次提交时的 `npx tsc --noEmit`、`npm run build` 结果 |
## 3. 说明
- 当前仍是「SSE 实时 + 30 秒轮询兜底」;后续可在连接状态稳定后进一步关闭轮询。
- 事件中的消息体暂不直接写入 React Query 缓存,而是触发对应会话刷新,避免分页合并与去重逻辑分叉。
- 多实例部署时,SSE 只推送当前进程内连接;若后端横向扩容,需要 Redis Pub/Sub 或粘性会话。