diff --git a/backend/cmd/main.go b/backend/cmd/main.go index 6bf5ab9..454a136 100644 --- a/backend/cmd/main.go +++ b/backend/cmd/main.go @@ -138,8 +138,7 @@ func main() { stop() log.Printf("API shutting down...") - // SSE 长连接由 SSEHub 在 ctx 取消时主动断开,所以这里等的是普通在途请求。 - // 超时后 Close 兜底:不能因为个别连接不返回就永远不退出。 + // SSE 连接已随 ctx 断开,这里等的是普通在途请求;超时则 Close 兜底。 shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { diff --git a/backend/cmd/worker/main.go b/backend/cmd/worker/main.go index 8b2251a..66e7b43 100644 --- a/backend/cmd/worker/main.go +++ b/backend/cmd/worker/main.go @@ -24,8 +24,7 @@ import ( "gorm.io/gorm" ) -// workerShutdownTimeout 是等待消费者退出的上界:正常路径是毫秒级, -// 超时说明某个 handler 卡在 DB/MQ I/O 上,此时不再无限等待。 +// 消费者正常毫秒级退出;超时说明 handler 卡在 I/O 上,不再无限等待。 const workerShutdownTimeout = 10 * time.Second // 带重试机制的基础设施连接函数 @@ -138,16 +137,14 @@ func main() { defer pprofServer.Close() } - // 通知与时间线链路的拓扑:这两类事件最终由本进程消费,所以由本进程声明。 - // 名字一律取自 rabbitmq 包的导出常量——它们是跨进程的线缆契约。 + // 这两类事件最终由本进程消费,拓扑因此在这里声明。 rmqMgr.RegisterTopology( mqrabbit.Topology{Exchange: mqrabbit.LikeExchange, Queue: mqrabbit.NotificationLikeQueue, BindingKey: mqrabbit.LikeLikeRK}, mqrabbit.Topology{Exchange: mqrabbit.CommentExchange, Queue: mqrabbit.NotificationCommentQueue, BindingKey: mqrabbit.CommentPublishRK}, mqrabbit.Topology{Exchange: mqrabbit.SocialExchange, Queue: mqrabbit.NotificationSocialQueue, BindingKey: mqrabbit.SocialFollowRK}, ) - // Outbox 投递必须只有一个执行者:写 outbox 行的是 API,投递跟着 Worker 走, - // 不随 API 实例数复制。 + // Outbox 投递只有 Worker 一个执行者,不随 API 实例数复制。 timelineMQ, err := mqrabbit.NewTimelineMQ(rmqMgr) if err != nil { log.Printf("timelineMQ init failed (timeline consumer disabled): %v", err) @@ -202,11 +199,10 @@ func main() { }) } - // Outbox 轮询与 timeline 消费是阻塞函数,各自占一个 goroutine。 run(func() { worker.StartOutboxPoller(ctx, sqlDB, timelineMQ) }) run(func() { worker.StartConsumer(ctx, rmqMgr, mqrabbit.TimelineQueue, cache) }) - // 等待退出信号:不再用固定 sleep 猜"消息处理完了没有",真正等到消费者返回。 + // 等消费者真正返回,而不是用固定 sleep 猜。 <-ctx.Done() log.Printf("Worker shutting down...") diff --git a/backend/internal/http/router.go b/backend/internal/http/router.go index b403594..5fbda08 100644 --- a/backend/internal/http/router.go +++ b/backend/internal/http/router.go @@ -20,8 +20,7 @@ import ( "gorm.io/gorm" ) -// SetRouter 只装配 HTTP 入口。所有队列消费者与 Outbox 轮询都在 cmd/worker, -// 这里的 ctx 是进程生命周期:通知订阅器与 SSE 连接都随它一起退出。 +// SetRouter 只装配 HTTP 入口;ctx 是进程生命周期,订阅器与 SSE 连接随它退出。 func SetRouter(ctx context.Context, db *gorm.DB, cache *rediscache.Client, rmq *rabbitmq.RabbitMQ) *gin.Engine { r := gin.Default() if err := r.SetTrustedProxies(nil); err != nil { @@ -213,9 +212,7 @@ func SetRouter(ctx context.Context, db *gorm.DB, cache *rediscache.Client, rmq * protectedMessageGroup.POST("/send", messageHandler.Send) protectedMessageGroup.POST("/list", messageHandler.List) } - // SSE notification:本进程只负责把通知推到自己持有的连接上。 - // 通知在 Worker 进程里产生并落库,再经 Redis Pub/Sub 跨进程送达—— - // 进程内广播会让"用户连在实例 A、消费者在实例 B"变成永远收不到。 + // 通知由 Worker 落库并发布到 Redis,本进程只把它推给本地连接。 sseHub := worker.NewSSEHub(ctx, db) notifGroup := r.Group("/notification") notifGroup.Use(sseHub.SSERequireAuth()) diff --git a/backend/internal/http/router_test.go b/backend/internal/http/router_test.go index ae6ff0a..78734aa 100644 --- a/backend/internal/http/router_test.go +++ b/backend/internal/http/router_test.go @@ -31,8 +31,7 @@ func newRouterForTest(t *testing.T, rmq *mqrabbit.RabbitMQ) *gin.Engine { return SetRouter(context.Background(), nil, nil, rmq) } -// 通知路由属于 API 进程:消费者搬到 Worker 之后,SSE 与列表/已读接口必须还在。 -// 这条回归挡的是"搬家时顺手把整个 notification 域一起删掉"。 +// 消费者搬到 Worker 之后,SSE 与列表/已读接口仍必须留在 API。 func TestRouter_NotificationRoutesRegistered(t *testing.T) { r := newRouterForTest(t, nil) diff --git a/backend/internal/middleware/redis/redis.go b/backend/internal/middleware/redis/redis.go index a8d5fd0..8fe9fca 100644 --- a/backend/internal/middleware/redis/redis.go +++ b/backend/internal/middleware/redis/redis.go @@ -103,8 +103,7 @@ func (c *Client) Unlock(ctx context.Context, key string, token string) error { return err } -// Publish 向频道发布一条消息。频道名由调用方用 Key 统一加前缀, -// 同一 Redis 上的多套环境才不会互相收到对方的消息。 +// 频道名由调用方用 Key 加前缀,多环境共享同一 Redis 时不串台。 func (c *Client) Publish(ctx context.Context, channel string, payload []byte) error { if c == nil || c.rdb == nil { return errors.New("redis client not initialized") @@ -112,9 +111,7 @@ func (c *Client) Publish(ctx context.Context, channel string, payload []byte) er return c.rdb.Publish(ctx, channel, payload).Err() } -// Subscribe 订阅频道,并在返回前等到 broker 确认订阅生效: -// 否则"订阅建立"与"第一条消息到达"之间有一个静默丢消息的窗口。 -// 返回的 PubSub 由调用方负责 Close。 +// Subscribe 返回前等 broker 确认订阅生效,避免丢第一批消息;PubSub 由调用方 Close。 func (c *Client) Subscribe(ctx context.Context, channel string) (*redis.PubSub, error) { if c == nil || c.rdb == nil { return nil, errors.New("redis client not initialized") diff --git a/backend/internal/worker/notificationbus.go b/backend/internal/worker/notificationbus.go index 83b0ab8..ec10e99 100644 --- a/backend/internal/worker/notificationbus.go +++ b/backend/internal/worker/notificationbus.go @@ -11,8 +11,7 @@ import ( "feedsystem_video_go/internal/notification" ) -// notificationBusChannel 是跨进程推送通道。真实频道名由 cache.Key 加前缀, -// 与其他键共用一套命名空间,同一 Redis 上的多套环境才不会串台。 +// 频道名经 cache.Key 加前缀,与环境内其他键共用命名空间。 const notificationBusChannel = "notification:push" const ( @@ -21,18 +20,13 @@ const ( notificationBusMaxBackoff = 30 * time.Second ) -// notificationPushEnvelope 是线缆格式。它与 rabbitmq 包的 exchange/queue 常量同级: -// 改动它等于改动跨进程协议,必须同时改生产端与消费端。 +// 跨进程线缆格式:改动它必须同时改生产端与消费端。 type notificationPushEnvelope struct { UserID uint `json:"user_id"` Notification *notification.Notification `json:"notification"` } -// RedisNotificationPublisher 是 NotificationHub 在 Worker 侧的实现。 -// -// Worker 进程不持有任何 SSE 连接,本地广播没有意义:通知交给 Redis, -// 由每个 API 实例推给自己手里那些连接。这样"通知消费者在哪个进程"与 -// "用户连在哪个实例"彻底解耦,API 才能水平扩容。 +// RedisNotificationPublisher 把通知发给 Redis,由各 API 实例转给本地 SSE 连接。 type RedisNotificationPublisher struct { cache *rediscache.Client } @@ -41,8 +35,7 @@ func NewRedisNotificationPublisher(cache *rediscache.Client) *RedisNotificationP return &RedisNotificationPublisher{cache: cache} } -// Push 尽力而为:通知已经落库,推送失败只影响"在线时立即看到", -// 所以这里不重试,也不把错误抛回消费循环。 +// Push 尽力而为:通知已落库,失败只影响实时性。 func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notification) { if p == nil || p.cache == nil || n == nil || userID == 0 { return @@ -54,7 +47,6 @@ func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notificat return } - // 独立超时:推送是"锦上添花",不允许它把消费循环挂住。 ctx, cancel := context.WithTimeout(context.Background(), notificationPushTimeout) defer cancel() if err := p.cache.Publish(ctx, p.cache.Key(notificationBusChannel), payload); err != nil { @@ -63,9 +55,7 @@ func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notificat } } -// StartNotificationSubscriber 在 API 进程订阅推送通道,把通知转给本进程的 SSE 客户端。 -// -// Redis 不可用时只记日志:SSE 连接与历史通知仍可用,实时推送降级为"刷新后可见"。 +// StartNotificationSubscriber 订阅推送通道并转给本地 SSE;Redis 不可用时只降级实时推送。 func StartNotificationSubscriber(ctx context.Context, cache *rediscache.Client, hub NotificationHub) { if cache == nil || hub == nil { log.Printf("Notification push disabled: redis 或 hub 未初始化") @@ -80,8 +70,7 @@ func StartNotificationSubscriber(ctx context.Context, cache *rediscache.Client, if ctx.Err() != nil { return } - // 订阅维持过一段时间再断,说明是偶发断连而非配置错误: - // 重置退避,避免 Redis 抖动一次后长期停在长退避上。 + // 存活够久说明是抖动而非配置错误:重置退避,避免长期停在长退避上。 if time.Since(started) > notificationBusMaxBackoff { backoff = notificationBusMinBackoff } @@ -97,9 +86,7 @@ func StartNotificationSubscriber(ctx context.Context, cache *rediscache.Client, }() } -// runNotificationSubscriber 订阅并转发,直到 ctx 取消(返回 nil)或订阅断开(返回原因)。 -// -// onSubscribed 可为 nil;测试用它确认订阅已生效再投递消息,避免用 sleep 猜时序。 +// runNotificationSubscriber 转发到 ctx 取消或订阅断开;onSubscribed 供测试确认订阅生效。 func runNotificationSubscriber(ctx context.Context, cache *rediscache.Client, hub NotificationHub, onSubscribed func()) error { if cache == nil || hub == nil { return errors.New("notification subscriber: redis 或 hub 未初始化") diff --git a/backend/internal/worker/notificationbus_test.go b/backend/internal/worker/notificationbus_test.go index 7f963d3..f11eecb 100644 --- a/backend/internal/worker/notificationbus_test.go +++ b/backend/internal/worker/notificationbus_test.go @@ -85,8 +85,7 @@ func TestNotificationBus_PublishReachesSubscriber(t *testing.T) { } } -// 线上可能存在旧版本发布的消息或脏数据:一条坏消息不能让订阅器退出, -// 否则之后所有合法通知都送不到。 +// 一条坏消息不能让订阅器退出,否则后续合法通知都送不到。 func TestNotificationSubscriber_SkipsMalformedPayload(t *testing.T) { client := newTestRedisClient(t) hub := newRecordingHub() diff --git a/backend/internal/worker/outboxworker.go b/backend/internal/worker/outboxworker.go index 6c5fcd4..23914e4 100644 --- a/backend/internal/worker/outboxworker.go +++ b/backend/internal/worker/outboxworker.go @@ -16,23 +16,16 @@ import ( "gorm.io/gorm" ) -// outboxPublishTimeout 限制单条 outbox 消息的发布时间。 -// 连接管理器在断连期间会阻塞等待重连,这里加超时可以保持"失败即进入下一轮轮询" -// 的既有语义,而不是把整个轮询器挂在一条消息上。 +// 断连期间 Publish 会阻塞等待重连,超时让它失败并进入下一轮轮询。 const outboxPublishTimeout = 5 * time.Second const ( - // outboxPollInterval 是空批次后的等待时间。 + // 空批次后的等待时间。 outboxPollInterval = time.Second - // outboxBatchSize 是单轮最多投递的行数。 - outboxBatchSize = 100 + outboxBatchSize = 100 ) -// StartOutboxPoller 轮询 outbox 表并把待投递消息发布到 timeline exchange, -// 阻塞到 ctx 取消;调用方负责把它放进自己的 goroutine。 -// -// 它跑在 Worker 进程而不是 API 进程:随 API 实例数复制会让同一行被投递多次, -// 而 API 的退出路径也不该等待一个数据库轮询器。 +// StartOutboxPoller 阻塞轮询 outbox 表;调用方负责起 goroutine。 func StartOutboxPoller(ctx context.Context, db *gorm.DB, tmq *rabbitmq.TimelineMQ) { if db == nil || tmq == nil { log.Printf("Outbox poller disabled: timeline mq is not initialized") @@ -74,9 +67,7 @@ func StartOutboxPoller(ctx context.Context, db *gorm.DB, tmq *rabbitmq.TimelineM } } -// waitOrDone 等待 d 或 ctx 取消;返回 true 表示等满间隔,false 表示被取消。 -// -// 抽成独立函数是为了让"轮询间隔可被退出信号打断"能被单测直接验证——它不碰数据库。 +// waitOrDone 等待 d 到点;ctx 取消则提前返回 false。 func waitOrDone(ctx context.Context, d time.Duration) bool { t := time.NewTimer(d) defer t.Stop() @@ -88,11 +79,7 @@ func waitOrDone(ctx context.Context, d time.Duration) bool { } } -// StartConsumer 消费 timeline 事件并写入 Redis ZSet,阻塞到 ctx 取消; -// 调用方负责把它放进自己的 goroutine。 -// -// 连接级重连、拓扑重放、channel 重建全部交给连接管理器(rabbitmq.RunConsumer), -// 这里只关心"一条消息应该怎么被处理"。 +// StartConsumer 阻塞消费 timeline 事件;调用方负责起 goroutine。 func StartConsumer(ctx context.Context, rmq *rabbitmq.RabbitMQ, queueName string, redisClient *rediscache.Client) { if rmq == nil { log.Printf("Timeline consumer disabled: rabbitmq is not initialized") diff --git a/backend/internal/worker/ssehub.go b/backend/internal/worker/ssehub.go index a3268f6..086ffbb 100644 --- a/backend/internal/worker/ssehub.go +++ b/backend/internal/worker/ssehub.go @@ -25,9 +25,7 @@ type SSEHub struct { done <-chan struct{} } -// NewSSEHub 的 ctx 是进程生命周期。ctx 结束时 SSEHandler 会主动断开连接: -// http.Server.Shutdown 只关空闲连接,不取消在途请求,而 SSE 响应永不结束, -// 少了这条退出路径,每次停机都要把 Shutdown 的超时耗满。 +// ctx 结束时 SSEHandler 主动断开:Shutdown 不取消在途请求,而 SSE 响应永不结束。 func NewSSEHub(ctx context.Context, db *gorm.DB) *SSEHub { h := &SSEHub{clients: make(map[uint][]chan *notification.Notification), db: db} if ctx != nil { diff --git a/docs/solutions/P1-1-async-workers-out-of-api.md b/docs/solutions/P1-1-async-workers-out-of-api.md index a44b5f1..dab4f42 100644 --- a/docs/solutions/P1-1-async-workers-out-of-api.md +++ b/docs/solutions/P1-1-async-workers-out-of-api.md @@ -134,7 +134,7 @@ API 侧 `StartNotificationSubscriber(ctx, cache, hub)`: - 订阅 → `Receive` 确认订阅生效(避免"订阅尚未建立就返回"导致丢第一批消息)→ 逐条反序列化 → `hub.Push`。 - 坏 JSON、`user_id == 0`、`notification == nil` 一律跳过并记日志,不退出循环。 -- 订阅断开(Redis 重启、连接被踢)后按 1s→2s→…→30s 退避重连;`ctx` 取消即返回。订阅失败不影响 HTTP 服务启动。 +- 订阅断开(Redis 重启、连接被踢)后按 1s→2s→…→30s 退避重连;`ctx` 取消即返回。订阅失败不影响 HTTP 服务启动。本次连接存活超过 30 秒时把退避重置回 1 秒——否则一次网络抖动就会让后续重连长期停在长退避上。 - `cache == nil`(Redis 未配置或启动时 ping 失败)时直接返回:SSE 仍可建立连接、仍可拉历史通知,只是收不到实时推送,日志说明原因。 `rediscache.Client` 补两个原语,保持"Redis 细节不外泄"的既有风格: