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 适配新签名,并新增用例守住四条通知路由仍注册。
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -21,10 +22,18 @@ type SSEHub struct {
|
||||
mu sync.RWMutex
|
||||
clients map[uint][]chan *notification.Notification
|
||||
db *gorm.DB
|
||||
done <-chan struct{}
|
||||
}
|
||||
|
||||
func NewSSEHub(db *gorm.DB) *SSEHub {
|
||||
return &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
|
||||
// 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) {
|
||||
@@ -129,6 +138,8 @@ func (h *SSEHub) SSEHandler(c *gin.Context) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-h.done:
|
||||
return
|
||||
case n, ok := <-ch:
|
||||
if !ok {
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user