Files
VLoop/backend/internal/worker/notificationbus.go
huanghaosheng 5d05c147ed style(backend): 精简 P1-1 期间的说明性注释
代码只留一行不变量。进程分工的动机、退避与重连的细节、测试可验证性的理由,都已在 docs/solutions/P1-1-async-workers-out-of-api.md 里写过,注释不再复述。

保留的是读代码看不出来的约束:超时派生自 poller 的 ctx、坏消息不能打断订阅、SSE 响应永不结束、订阅存活够久要重置退避。

文档补一句退避重置规则。这是删掉的注释里唯一没有落在文档上的细节。

验证:go test -count=1 ./... 全绿。
2026-11-08 15:47:10 +08:00

130 lines
4.0 KiB
Go
Raw Permalink 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"
"log"
"time"
rediscache "feedsystem_video_go/internal/middleware/redis"
"feedsystem_video_go/internal/notification"
)
// 频道名经 cache.Key 加前缀,与环境内其他键共用命名空间。
const notificationBusChannel = "notification:push"
const (
notificationPushTimeout = 500 * time.Millisecond
notificationBusMinBackoff = time.Second
notificationBusMaxBackoff = 30 * time.Second
)
// 跨进程线缆格式:改动它必须同时改生产端与消费端。
type notificationPushEnvelope struct {
UserID uint `json:"user_id"`
Notification *notification.Notification `json:"notification"`
}
// RedisNotificationPublisher 把通知发给 Redis,由各 API 实例转给本地 SSE 连接。
type RedisNotificationPublisher struct {
cache *rediscache.Client
}
func NewRedisNotificationPublisher(cache *rediscache.Client) *RedisNotificationPublisher {
return &RedisNotificationPublisher{cache: cache}
}
// Push 尽力而为:通知已落库,失败只影响实时性。
func (p *RedisNotificationPublisher) Push(userID uint, n *notification.Notification) {
if p == nil || p.cache == nil || n == nil || userID == 0 {
return
}
payload, err := json.Marshal(notificationPushEnvelope{UserID: userID, Notification: n})
if err != nil {
log.Printf("notification push: 序列化失败 notification=%d: %v", n.ID, err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), notificationPushTimeout)
defer cancel()
if err := p.cache.Publish(ctx, p.cache.Key(notificationBusChannel), payload); err != nil {
log.Printf("notification push: 发布失败 notification=%d user=%d(通知已落库,实时推送跳过): %v",
n.ID, userID, err)
}
}
// 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 未初始化")
return
}
go func() {
backoff := notificationBusMinBackoff
for ctx.Err() == nil {
started := time.Now()
err := runNotificationSubscriber(ctx, cache, hub, nil)
if ctx.Err() != nil {
return
}
// 存活够久说明是抖动而非配置错误:重置退避,避免长期停在长退避上。
if time.Since(started) > notificationBusMaxBackoff {
backoff = notificationBusMinBackoff
}
log.Printf("notification push: 订阅中断(%v 后重连): %v", backoff, err)
if !waitOrDone(ctx, backoff) {
return
}
backoff *= 2
if backoff > notificationBusMaxBackoff {
backoff = notificationBusMaxBackoff
}
}
}()
}
// 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 未初始化")
}
sub, err := cache.Subscribe(ctx, cache.Key(notificationBusChannel))
if err != nil {
return err
}
defer func() { _ = sub.Close() }()
if onSubscribed != nil {
onSubscribed()
}
msgs := sub.Channel()
for {
select {
case <-ctx.Done():
return nil
case msg, ok := <-msgs:
if !ok {
return errors.New("订阅通道已关闭")
}
var envelope notificationPushEnvelope
if err := json.Unmarshal([]byte(msg.Payload), &envelope); err != nil {
// 坏消息不能打断订阅:否则一条脏数据会让后续所有通知都送不到。
log.Printf("notification push: 丢弃无法解析的消息: %v", err)
continue
}
if envelope.UserID == 0 || envelope.Notification == nil {
log.Printf("notification push: 丢弃缺少 user_id/notification 的消息")
continue
}
hub.Push(envelope.UserID, envelope.Notification)
}
}
}
var _ NotificationHub = (*RedisNotificationPublisher)(nil)