fix(chat): 优化后台限流与 SSE 日志

This commit is contained in:
yml2213
2026-08-25 16:20:58 +08:00
parent 417f7398e4
commit 8f6356a3d7
11 changed files with 344 additions and 47 deletions
+70 -7
View File
@@ -1,6 +1,7 @@
package chathub
import (
"context"
"fmt"
"time"
@@ -8,16 +9,21 @@ import (
"hfb_sys/backend/pkg/response"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
const heartbeatInterval = 30 * time.Second
type Handler struct {
hub *Hub
hub *Hub
logger *zap.Logger
}
func NewHandler(hub *Hub) *Handler {
return &Handler{hub: hub}
func NewHandler(hub *Hub, logger *zap.Logger) *Handler {
if logger == nil {
logger = zap.NewNop()
}
return &Handler{hub: hub, logger: logger}
}
// UserEvents 处理用户端 SSE 连接: GET /api/chats/events
@@ -51,8 +57,23 @@ func (h *Handler) AdminEvents(c *gin.Context) {
}
func (h *Handler) serveSSE(c *gin.Context, pType string, pID uint64) {
startedAt := time.Now()
disconnectReason := "handler_completed"
var disconnectErr error
ch := h.hub.Subscribe(pType, pID)
defer h.hub.Unsubscribe(pType, pID, ch)
h.logger.Info("SSE 连接建立", h.connectionLogFields(c, pType, pID)...)
defer func() {
h.hub.Unsubscribe(pType, pID, ch)
fields := h.connectionLogFields(c, pType, pID)
fields = append(fields,
zap.String("disconnect_reason", disconnectReason),
zap.Float64("lifetime_ms", float64(time.Since(startedAt).Microseconds())/1000),
)
if disconnectErr != nil {
fields = append(fields, zap.Error(disconnectErr))
}
h.logger.Info("SSE 连接断开", fields...)
}()
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
@@ -60,7 +81,11 @@ func (h *Handler) serveSSE(c *gin.Context, pType string, pID uint64) {
c.Header("X-Accel-Buffering", "no")
// 发送初始连接确认
fmt.Fprintf(c.Writer, "event: connected\ndata: {\"ok\":true}\n\n")
if _, err := fmt.Fprintf(c.Writer, "event: connected\ndata: {\"ok\":true}\n\n"); err != nil {
disconnectReason = "initial_write_error"
disconnectErr = err
return
}
c.Writer.Flush()
heartbeat := time.NewTicker(heartbeatInterval)
@@ -71,17 +96,55 @@ func (h *Handler) serveSSE(c *gin.Context, pType string, pID uint64) {
for {
select {
case <-clientGone:
disconnectReason = contextDisconnectReason(c.Request.Context().Err())
return
case <-heartbeat.C:
fmt.Fprintf(c.Writer, ":heartbeat\n\n")
if _, err := fmt.Fprintf(c.Writer, ":heartbeat\n\n"); err != nil {
disconnectReason = "heartbeat_write_error"
disconnectErr = err
return
}
c.Writer.Flush()
case event, ok := <-ch:
if !ok {
disconnectReason = "subscription_closed"
return
}
data := MarshalEvent(event)
fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event.Type, data)
if _, err := fmt.Fprintf(c.Writer, "event: %s\ndata: %s\n\n", event.Type, data); err != nil {
disconnectReason = "event_write_error"
disconnectErr = err
return
}
c.Writer.Flush()
}
}
}
func (h *Handler) connectionLogFields(c *gin.Context, pType string, pID uint64) []zap.Field {
fields := []zap.Field{
zap.String("request_id", middleware.GetRequestID(c)),
zap.String("principal_type", pType),
zap.Uint64("principal_id", pID),
zap.String("client_ip", c.ClientIP()),
zap.Int("active_sse_connections", h.hub.OnlineCount()),
zap.Int("active_principal_type_connections", h.hub.OnlineCountByType(pType)),
}
if pType == "admin" {
fields = append(fields, zap.Uint64("admin_id", pID))
} else {
fields = append(fields, zap.Uint64("user_id", pID))
}
return fields
}
func contextDisconnectReason(err error) string {
switch err {
case context.Canceled:
return "context_canceled"
case context.DeadlineExceeded:
return "context_deadline_exceeded"
default:
return "context_closed"
}
}
@@ -0,0 +1,60 @@
package chathub
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"hfb_sys/backend/internal/middleware"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"go.uber.org/zap/zaptest/observer"
)
func TestSSELifecycleLogsConnectionCountReasonAndLifetime(t *testing.T) {
gin.SetMode(gin.TestMode)
core, observed := observer.New(zap.InfoLevel)
hub := NewHub(nil)
handler := NewHandler(hub, zap.New(core))
requestContext, cancel := context.WithCancel(context.Background())
cancel()
request := httptest.NewRequest(http.MethodGet, "/api/admin/chats/events", nil).WithContext(requestContext)
request.RemoteAddr = "42.49.131.69:34567"
recorder := httptest.NewRecorder()
ginContext, _ := gin.CreateTestContext(recorder)
ginContext.Request = request
ginContext.Set(middleware.ContextAdminID, uint64(88))
ginContext.Set(middleware.ContextRequestID, "sse-test-request")
handler.AdminEvents(ginContext)
connected := observed.FilterMessage("SSE 连接建立").All()
if len(connected) != 1 {
t.Fatalf("connection logs = %d, want 1", len(connected))
}
connectedFields := connected[0].ContextMap()
if connectedFields["admin_id"] != uint64(88) || connectedFields["active_sse_connections"] != int64(1) {
t.Fatalf("unexpected connection fields: %v", connectedFields)
}
disconnected := observed.FilterMessage("SSE 连接断开").All()
if len(disconnected) != 1 {
t.Fatalf("disconnection logs = %d, want 1", len(disconnected))
}
disconnectedFields := disconnected[0].ContextMap()
if disconnectedFields["disconnect_reason"] != "context_canceled" {
t.Fatalf("disconnect reason = %v, want context_canceled", disconnectedFields["disconnect_reason"])
}
if disconnectedFields["active_sse_connections"] != int64(0) {
t.Fatalf("active connections after disconnect = %v, want 0", disconnectedFields["active_sse_connections"])
}
if _, ok := disconnectedFields["lifetime_ms"]; !ok {
t.Fatalf("missing lifetime_ms field: %v", disconnectedFields)
}
if got := hub.OnlineCount(); got != 0 {
t.Fatalf("online connection count = %d, want 0", got)
}
}
+13
View File
@@ -190,3 +190,16 @@ func (h *Hub) OnlineCount() int {
}
return count
}
// OnlineCountByType 返回当前进程内指定主体类型的 SSE 连接数。
func (h *Hub) OnlineCountByType(pType string) int {
h.mu.RLock()
defer h.mu.RUnlock()
count := 0
for key, clients := range h.clients {
if key.Type == pType {
count += len(clients)
}
}
return count
}
+9 -2
View File
@@ -7,6 +7,7 @@ func TestDisconnectUserClosesAllConnections(t *testing.T) {
first := hub.Subscribe("user", 7)
second := hub.Subscribe("user", 7)
hub.Subscribe("user", 8)
hub.Subscribe("admin", 9)
hub.DisconnectUser(7)
for name, ch := range map[string]<-chan *ChatEvent{"first": first, "second": second} {
@@ -19,7 +20,13 @@ func TestDisconnectUserClosesAllConnections(t *testing.T) {
t.Fatalf("%s connection did not close immediately", name)
}
}
if got := hub.OnlineCount(); got != 1 {
t.Fatalf("online connection count = %d, want 1", got)
if got := hub.OnlineCount(); got != 2 {
t.Fatalf("online connection count = %d, want 2", got)
}
if got := hub.OnlineCountByType("user"); got != 1 {
t.Fatalf("online user connection count = %d, want 1", got)
}
if got := hub.OnlineCountByType("admin"); got != 1 {
t.Fatalf("online admin connection count = %d, want 1", got)
}
}