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:
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"feedsystem_video_go/internal/auth"
|
"feedsystem_video_go/internal/auth"
|
||||||
"feedsystem_video_go/internal/config"
|
"feedsystem_video_go/internal/config"
|
||||||
"feedsystem_video_go/internal/db"
|
"feedsystem_video_go/internal/db"
|
||||||
@@ -10,8 +11,11 @@ import (
|
|||||||
rediscache "feedsystem_video_go/internal/middleware/redis"
|
rediscache "feedsystem_video_go/internal/middleware/redis"
|
||||||
"feedsystem_video_go/internal/observability"
|
"feedsystem_video_go/internal/observability"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
@@ -100,10 +104,47 @@ func main() {
|
|||||||
defer pprofServer.Close()
|
defer pprofServer.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 进程生命周期:SIGINT/SIGTERM 后先停止接收新请求,再等在途请求结束。
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
// 设置路由
|
// 设置路由
|
||||||
r := apphttp.SetRouter(sqlDB, cache, rmq)
|
r := apphttp.SetRouter(ctx, sqlDB, cache, rmq)
|
||||||
log.Printf("Server is running on port %d", cfg.Server.Port)
|
srv := &http.Server{
|
||||||
if err := r.Run(":" + strconv.Itoa(cfg.Server.Port)); err != nil {
|
Addr: ":" + strconv.Itoa(cfg.Server.Port),
|
||||||
log.Fatalf("Failed to run server: %v", err)
|
Handler: r,
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ListenAndServe 在 goroutine 里跑,主协程负责等待信号或启动失败。
|
||||||
|
serverErr := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
log.Printf("Server is running on port %d", cfg.Server.Port)
|
||||||
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
serverErr <- err
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case err := <-serverErr:
|
||||||
|
log.Printf("Failed to run server: %v", err)
|
||||||
|
stop()
|
||||||
|
_ = srv.Close()
|
||||||
|
return
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
|
|
||||||
|
// 恢复默认信号处理:第二次 Ctrl-C 立刻强杀,而不是卡在 Shutdown 里。
|
||||||
|
stop()
|
||||||
|
|
||||||
|
log.Printf("API shutting down...")
|
||||||
|
// SSE 长连接由 SSEHub 在 ctx 取消时主动断开,所以这里等的是普通在途请求。
|
||||||
|
// 超时后 Close 兜底:不能因为个别连接不返回就永远不退出。
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||||
|
log.Printf("API graceful shutdown failed (forcing close): %v", err)
|
||||||
|
_ = srv.Close()
|
||||||
|
}
|
||||||
|
log.Printf("API stopped")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,11 +17,12 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
amqp "github.com/rabbitmq/amqp091-go"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
|
// SetRouter 只装配 HTTP 入口。所有队列消费者与 Outbox 轮询都在 cmd/worker,
|
||||||
|
// 这里的 ctx 是进程生命周期:通知订阅器与 SSE 连接都随它一起退出。
|
||||||
|
func SetRouter(ctx context.Context, db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine {
|
||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
if err := r.SetTrustedProxies(nil); err != nil {
|
if err := r.SetTrustedProxies(nil); err != nil {
|
||||||
log.Printf("SetTrustedProxies failed: %v", err)
|
log.Printf("SetTrustedProxies failed: %v", err)
|
||||||
@@ -212,47 +213,20 @@ func SetRouter(db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *g
|
|||||||
protectedMessageGroup.POST("/send", messageHandler.Send)
|
protectedMessageGroup.POST("/send", messageHandler.Send)
|
||||||
protectedMessageGroup.POST("/list", messageHandler.List)
|
protectedMessageGroup.POST("/list", messageHandler.List)
|
||||||
}
|
}
|
||||||
// worker:Outbox 轮询 + Timeline 消费者
|
// SSE notification:本进程只负责把通知推到自己持有的连接上。
|
||||||
// 连接级重连 / 拓扑重放 / channel 重建统一由连接管理器(rabbitmq.RunConsumer)负责
|
// 通知在 Worker 进程里产生并落库,再经 Redis Pub/Sub 跨进程送达——
|
||||||
timelineMQ, err := rabbitmq.NewTimelineMQ(rmq)
|
// 进程内广播会让"用户连在实例 A、消费者在实例 B"变成永远收不到。
|
||||||
if err != nil {
|
sseHub := worker.NewSSEHub(ctx, db)
|
||||||
log.Printf("timelineMQ init failed (mq disabled): %v", err)
|
|
||||||
timelineMQ = nil
|
|
||||||
}
|
|
||||||
worker.StartOutboxPoller(db, timelineMQ)
|
|
||||||
worker.StartConsumer(context.Background(), rmq, rabbitmq.TimelineQueue, cache)
|
|
||||||
|
|
||||||
// SSE notification
|
|
||||||
sseHub := worker.NewSSEHub(db)
|
|
||||||
notifGroup := r.Group("/notification")
|
notifGroup := r.Group("/notification")
|
||||||
notifGroup.Use(sseHub.SSERequireAuth())
|
notifGroup.Use(sseHub.SSERequireAuth())
|
||||||
sseHub.RegisterRoutes(r, notifGroup)
|
sseHub.RegisterRoutes(r, notifGroup)
|
||||||
|
worker.StartNotificationSubscriber(ctx, cache, sseHub)
|
||||||
// 3 个 notification 消费者:拓扑登记后由管理器随每一代连接重放。
|
|
||||||
// 交换机名、队列名、路由键全部复用 rabbitmq 包的导出常量——它们是跨进程的
|
|
||||||
// 线缆契约,在这里再写一遍字面量就会与 Worker 侧悄悄漂移。
|
|
||||||
if rmq != nil {
|
|
||||||
rmq.RegisterTopology(
|
|
||||||
rabbitmq.Topology{Exchange: rabbitmq.LikeExchange, Queue: rabbitmq.NotificationLikeQueue, BindingKey: rabbitmq.LikeLikeRK},
|
|
||||||
rabbitmq.Topology{Exchange: rabbitmq.CommentExchange, Queue: rabbitmq.NotificationCommentQueue, BindingKey: rabbitmq.CommentPublishRK},
|
|
||||||
rabbitmq.Topology{Exchange: rabbitmq.SocialExchange, Queue: rabbitmq.NotificationSocialQueue, BindingKey: rabbitmq.SocialFollowRK},
|
|
||||||
)
|
|
||||||
for _, q := range []string{rabbitmq.NotificationLikeQueue, rabbitmq.NotificationCommentQueue, rabbitmq.NotificationSocialQueue} {
|
|
||||||
queue := q
|
|
||||||
go rabbitmq.RunConsumer(context.Background(), rmq, "notification-"+queue, 10,
|
|
||||||
func(ch *amqp.Channel) error {
|
|
||||||
return worker.NewNotificationWorker(ch, rmq, db, queue, sseHub).Run(context.Background())
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.Printf("Notification SSE disabled (MQ not available)")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
|
// 所有 publisher / consumer 都已登记拓扑:在【当前】连接上立即声明一遍。
|
||||||
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
|
// 重连时管理器会自动重放,因此这里只需处理"首次连接早于拓扑登记"的启动顺序。
|
||||||
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
|
// 用带超时的 ctx,避免连接恰在此刻断开时把 API 启动挂住。
|
||||||
if rmq != nil {
|
if rmq != nil {
|
||||||
initCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
initCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||||
if err := rmq.EnsureTopology(initCtx); err != nil {
|
if err := rmq.EnsureTopology(initCtx); err != nil {
|
||||||
log.Printf("rabbitmq topology init failed (will be redeclared on reconnect): %v", err)
|
log.Printf("rabbitmq topology init failed (will be redeclared on reconnect): %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
@@ -27,7 +28,29 @@ func doGet(t *testing.T, r *gin.Engine, path string) (int, map[string]any) {
|
|||||||
func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine {
|
func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
gin.SetMode(gin.TestMode)
|
gin.SetMode(gin.TestMode)
|
||||||
return SetRouter(nil, nil, rmq)
|
return SetRouter(context.Background(), nil, nil, rmq)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通知路由属于 API 进程:消费者搬到 Worker 之后,SSE 与列表/已读接口必须还在。
|
||||||
|
// 这条回归挡的是"搬家时顺手把整个 notification 域一起删掉"。
|
||||||
|
func TestRouter_NotificationRoutesRegistered(t *testing.T) {
|
||||||
|
r := newRouterForTest(t, nil)
|
||||||
|
|
||||||
|
want := []string{
|
||||||
|
"GET /notification/stream",
|
||||||
|
"POST /notification/list",
|
||||||
|
"POST /notification/markRead",
|
||||||
|
"POST /notification/unreadCount",
|
||||||
|
}
|
||||||
|
registered := make(map[string]bool, len(want))
|
||||||
|
for _, route := range r.Routes() {
|
||||||
|
registered[route.Method+" "+route.Path] = true
|
||||||
|
}
|
||||||
|
for _, route := range want {
|
||||||
|
if !registered[route] {
|
||||||
|
t.Errorf("route %q is not registered", route)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 这是 /readyz 存在的全部意义所在,也是最容易被后人"顺手合并"掉的不变式:
|
// 这是 /readyz 存在的全部意义所在,也是最容易被后人"顺手合并"掉的不变式:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package worker
|
package worker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -21,10 +22,18 @@ type SSEHub struct {
|
|||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
clients map[uint][]chan *notification.Notification
|
clients map[uint][]chan *notification.Notification
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
|
done <-chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewSSEHub(db *gorm.DB) *SSEHub {
|
// NewSSEHub 的 ctx 是进程生命周期。ctx 结束时 SSEHandler 会主动断开连接:
|
||||||
return &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db}
|
// 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) {
|
func (h *SSEHub) Push(userID uint, n *notification.Notification) {
|
||||||
@@ -129,6 +138,8 @@ func (h *SSEHub) SSEHandler(c *gin.Context) {
|
|||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
|
case <-h.done:
|
||||||
|
return
|
||||||
case n, ok := <-ch:
|
case n, ok := <-ch:
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user