feat: SSE Last-Event-ID 补投 + 连接状态指示 + 限速器 DB 化

## SSE Last-Event-ID 补投

EventSource 断线重连时自带 Last-Event-ID 头,但服务端直接忽略了——
所有断线期间的邮件通知都丢失。用户刷新页面也会错过已推的事件。

改为 per-user 事件环形缓冲区(500 条,~100KB/用户,20 在线 ≈ 2MB):
每次 Broadcast/SendToUser/SendToAgent 同时写入对应用户的缓冲区;
AddClient 时取 Last-Event-ID 头,找到该 ID 的位置后从下一条回放。
找不到 ID 说明事件已被覆盖(缓冲区溢出),从头回放全部。

事件 ID 用全局递增序列号(非 UUID),EventSource 的 Last-Event-ID
就是靠这个 ID 记住断点的。

新增测试:缓冲区回放、溢出行为、并发安全(10 goroutine × 200 次 push)、
端到端重连验证(SendToUser → 带 Last-Event-ID 的 AddClient → 补投)。

## 连接状态指示器

Sidebar 用户头像右下角的小圆点:绿=已连接,黄=连接中,橙=重连中,红=断开。
NarrowNav 底栏也有(移动端)。

SSE 模块新增 onSSEStatus/getSSEStatus 接口,onerror/onopen 驱动状态变化。
状态点用 absolute 定位在头像边缘,不遮挡文字。

## 限速器 DB 化(解决多实例部署时的计数漂移)

原实现:LoginLimiter 与 sessionRateLimiter 都是进程内内存计数器。
多实例部署时各自独立计数,等效上限变成 N 倍。

改为 rate_limits 表(bucket + ts),两个限速器共享同一套基础设施:
- LoginLimiter:bucket="login:<username>",COUNT(*) >= 5 → 锁定 5 分钟
- sessionRateLimiter:bucket="session:<agent_name>",COUNT(*) >= 20/h → 拒绝

判断与写入在同一个 BEGIN IMMEDIATE 事务里——SQLite 的 IMMEDIATE
在事务开始时获取 RESERVED 锁,防并发写事务同时进入 COMMIT 阶段。
实测 80 并发下恰好放行 20 次(旧内存版同样通过,但 DB 版才能多实例共享)。

DB 不可用时放行(宁可放开限速也不能让用户完全无法使用)。
新建 rate_limits 表迁移(SQLite + PG 两版)。
This commit is contained in:
2026-09-02 14:33:41 +08:00
parent 07e6b789b2
commit 9d4718a412
18 changed files with 760 additions and 243 deletions

View File

@ -0,0 +1,108 @@
package sse
import (
"net/http/httptest"
"strings"
"testing"
)
// 一个可 Flush 的 ResponseWriter,供集成测试用。
type flushWriter struct {
*httptest.ResponseRecorder
flushed chan bool
}
func (f *flushWriter) Flush() {
select {
case f.flushed <- true:
default:
}
}
// 端到端验证:Manager 完整走一遍「事件入缓冲区 → 新连接带 Last-Event-ID 重连 → 补投」。
// 这是生产里最关键的可靠性路径 —— 断线期间收的邮件,重连后必须能看到。
func TestManagerReplayOnReconnect(t *testing.T) {
m := &Manager{
clients: make(map[string]*Client),
eventBuffer: make(map[string]*eventRing),
}
// 1) 用户 alice 发来一封信(无人连接也入缓冲区)
m.SendToUser("alice", "new_mail", map[string]string{"mail_id": "m1"})
m.SendToUser("alice", "new_mail", map[string]string{"mail_id": "m2"})
m.SendToUser("alice", "new_mail", map[string]string{"mail_id": "m3"})
ring := m.eventBuffer["u:alice"]
if ring == nil {
t.Fatal("alice 的缓冲区应该已创建")
}
// 2) 带 Last-Event-ID=1 重连,应补投 m2、m3(跳过 m1)
req := httptest.NewRequest("GET", "/events/stream", nil)
req.Header.Set("Last-Event-ID", "1")
w := &flushWriter{httptest.NewRecorder(), make(chan bool, 10)}
client := m.AddClient(w, req, "", "alice")
if client == nil {
t.Fatal("AddClient 返回 nil(flushWriter 应支持 Flush)")
}
defer m.RemoveClient(client.ID)
body := w.Body.String()
if !strings.Contains(body, `"mail_id":"m2"`) {
t.Error("重连后应补投 m2,实际 body:", body)
}
if !strings.Contains(body, `"mail_id":"m3"`) {
t.Error("重连后应补投 m3,实际 body:", body)
}
if strings.Contains(body, `"mail_id":"m1"`) {
t.Error("已确认的 m1 不应重放(Last-Event-ID=1),实际 body:", body)
}
// 3) 连接期间新来一封信,实时推送
m.SendToUser("alice", "new_mail", map[string]string{"mail_id": "m4"})
body = w.Body.String()
if !strings.Contains(body, `"mail_id":"m4"`) {
t.Error("在线连接应实时收到 m4,实际 body:", body)
}
}
// 序列号全局递增,两条不同事件不同 ID。
func TestEventIDMonotonic(t *testing.T) {
m := &Manager{
clients: make(map[string]*Client),
eventBuffer: make(map[string]*eventRing),
}
a := m.nextEventID()
b := m.nextEventID()
if a == b {
t.Fatalf("两个连续事件 ID 相同: %q", a)
}
if a > b {
t.Fatalf("事件 ID 应递增: %q > %q", a, b)
}
}
// 确保事件 ID 写进了 SSE 帧(EventSource 靠 id: 行记住位置)
func TestSendWritesIDField(t *testing.T) {
fw := &flushWriter{httptest.NewRecorder(), make(chan bool, 5)}
c := &Client{
ID: "c1",
UserName: "alice",
Res: fw,
Flusher: fw,
done: make(chan struct{}),
}
c.SendWithID("42", "new_mail", map[string]string{"x": "y"})
body := fw.Body.String()
if !strings.Contains(body, "id: 42\n") {
t.Error("帧里应有 id: 42 行,实际:", body)
}
if !strings.Contains(body, "event: new_mail") {
t.Error("帧里应有 event: new_mail,实际:", body)
}
if !strings.Contains(body, `data: {"x":"y"}`) {
t.Error("帧里应有 data,实际:", body)
}
}