Files
VLoop/backend/internal/worker/ssehub.go
huanghaosheng 101f46f927 feat(api): 接进程 ctx 并停止启动异步链路
API 只装配 HTTP 入口。SetRouter 增加 ctx,删除 Outbox 轮询、Timeline 消费者与三个通知消费者的启动,改调 StartNotificationSubscriber。

SSEHub 记录进程 ctx。ctx 结束时 SSEHandler 主动断开。Shutdown 只关空闲连接、不取消在途请求,而 SSE 响应永不结束。少了这条路径,每次停机都要耗满 10 秒超时。

cmd/main 改用 signal.NotifyContext 与 http.Server。ListenAndServe 放进 goroutine,主协程等信号或启动失败,再以 10 秒上界 Shutdown,超时才 Close 兜底。

router_test 适配新签名,并新增用例守住四条通知路由仍注册。
2026-11-08 14:44:32 +08:00

234 lines
5.7 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.
package worker
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"sync"
"time"
"feedsystem_video_go/internal/auth"
"feedsystem_video_go/internal/notification"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
type SSEHub struct {
mu sync.RWMutex
clients map[uint][]chan *notification.Notification
db *gorm.DB
done <-chan struct{}
}
// NewSSEHub 的 ctx 是进程生命周期。ctx 结束时 SSEHandler 会主动断开连接:
// http.Server.Shutdown 只关空闲连接,不取消在途请求,而 SSE 响应永不结束,
// 少了这条退出路径,每次停机都要把 Shutdown 的超时耗满。
func NewSSEHub(ctx context.Context, db *gorm.DB) *SSEHub {
h := &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
if ctx != nil {
h.done = ctx.Done()
}
return h
}
func (h *SSEHub) Push(userID uint, n *notification.Notification) {
h.mu.RLock()
defer h.mu.RUnlock()
chs, ok := h.clients[userID]
if !ok {
return
}
for _, ch := range chs {
select {
case ch <- n:
default:
}
}
}
func (h *SSEHub) Subscribe(userID uint) chan *notification.Notification {
ch := make(chan *notification.Notification, 20)
h.mu.Lock()
h.clients[userID] = append(h.clients[userID], ch)
h.mu.Unlock()
return ch
}
func (h *SSEHub) Unsubscribe(userID uint, ch chan *notification.Notification) {
h.mu.Lock()
defer h.mu.Unlock()
chs := h.clients[userID]
for i, c := range chs {
if c == ch {
chs = append(chs[:i], chs[i+1:]...)
if len(chs) == 0 {
delete(h.clients, userID)
} else {
h.clients[userID] = chs
}
close(c)
return
}
}
}
func sseAccountID(c *gin.Context) (uint, bool) {
accountID, ok := c.Get("accountID")
if !ok {
return 0, false
}
userID, ok := accountID.(uint)
return userID, ok && userID != 0
}
func (h *SSEHub) SSERequireAuth() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.Query("token")
if token == "" {
token = c.GetHeader("Authorization")
if len(token) > 7 && token[:7] == "Bearer " {
token = token[7:]
}
}
if token == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
return
}
claims, err := auth.ParseToken(token)
if err != nil {
// 与 middleware/jwt 保持一致:密钥未配置属服务端故障(500),不是客户端凭证问题。
if errors.Is(err, auth.ErrSecretNotConfigured) {
log.Printf("FATAL: JWT secret not configured; SSE %s rejected", c.Request.URL.Path)
c.AbortWithStatusJSON(http.StatusInternalServerError,
gin.H{"error": "server auth misconfigured"})
return
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
c.Set("accountID", claims.AccountID)
c.Next()
}
}
func (h *SSEHub) SSEHandler(c *gin.Context) {
userID, ok := sseAccountID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid account"})
return
}
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.WriteHeader(http.StatusOK)
ch := h.Subscribe(userID)
defer h.Unsubscribe(userID, ch)
ctx := c.Request.Context()
flusher, _ := c.Writer.(http.Flusher)
for {
select {
case <-ctx.Done():
return
case <-h.done:
return
case n, ok := <-ch:
if !ok {
return
}
b, _ := json.Marshal(n)
fmt.Fprintf(c.Writer, "data: %s\n\n", b)
if flusher != nil {
flusher.Flush()
}
case <-time.After(30 * time.Second):
fmt.Fprintf(c.Writer, ": keepalive\n\n")
if flusher != nil {
flusher.Flush()
}
}
}
}
func (h *SSEHub) ListHandler(c *gin.Context) {
userID, ok := sseAccountID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid account"})
return
}
var notifications []notification.Notification
if err := h.db.WithContext(c.Request.Context()).
Where("recipient_id = ?", userID).
Order("created_at desc").
Limit(50).
Find(&notifications).Error; err != nil {
c.JSON(500, gin.H{"error": err.Error()})
return
}
if notifications == nil {
notifications = []notification.Notification{}
}
c.JSON(200, gin.H{"notifications": notifications})
}
func (h *SSEHub) MarkReadHandler(c *gin.Context) {
userID, ok := sseAccountID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid account"})
return
}
var req struct {
ID *uint `json:"id"`
}
if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var err error
if req.ID != nil {
err = h.db.WithContext(c.Request.Context()).Model(&notification.Notification{}).Where("id = ? AND recipient_id = ?", *req.ID, userID).Update("is_read", true).Error
} else {
err = h.db.WithContext(c.Request.Context()).Model(&notification.Notification{}).Where("recipient_id = ?", userID).Update("is_read", true).Error
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"message": "ok"})
}
func (h *SSEHub) UnreadCountHandler(c *gin.Context) {
userID, ok := sseAccountID(c)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid account"})
return
}
var count int64
if err := h.db.WithContext(c.Request.Context()).Model(&notification.Notification{}).Where("recipient_id = ? AND is_read = ?", userID, false).Count(&count).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(200, gin.H{"count": count})
}
func (h *SSEHub) RegisterRoutes(r *gin.Engine, group *gin.RouterGroup) {
group.GET("/stream", h.SSEHandler)
group.POST("/list", h.ListHandler)
group.POST("/markRead", h.MarkReadHandler)
group.POST("/unreadCount", h.UnreadCountHandler)
}
var _ NotificationHub = (*SSEHub)(nil)