diff --git a/backend/internal/worker/notificationbus.go b/backend/internal/worker/notificationbus.go new file mode 100644 index 0000000..83b0ab8 --- /dev/null +++ b/backend/internal/worker/notificationbus.go @@ -0,0 +1,142 @@ +package worker + +import ( + "context" + "encoding/json" + "errors" + "log" + "time" + + rediscache "feedsystem_video_go/internal/middleware/redis" + "feedsystem_video_go/internal/notification" +) + +// notificationBusChannel 是跨进程推送通道。真实频道名由 cache.Key 加前缀, +// 与其他键共用一套命名空间,同一 Redis 上的多套环境才不会串台。 +const notificationBusChannel = "notification:push" + +const ( + notificationPushTimeout = 500 * time.Millisecond + notificationBusMinBackoff = time.Second + 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 才能水平扩容。 +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 在 API 进程订阅推送通道,把通知转给本进程的 SSE 客户端。 +// +// Redis 不可用时只记日志:SSE 连接与历史通知仍可用,实时推送降级为"刷新后可见"。 +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 + } + // 订阅维持过一段时间再断,说明是偶发断连而非配置错误: + // 重置退避,避免 Redis 抖动一次后长期停在长退避上。 + 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 取消(返回 nil)或订阅断开(返回原因)。 +// +// onSubscribed 可为 nil;测试用它确认订阅已生效再投递消息,避免用 sleep 猜时序。 +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) diff --git a/backend/internal/worker/notificationbus_test.go b/backend/internal/worker/notificationbus_test.go new file mode 100644 index 0000000..7f963d3 --- /dev/null +++ b/backend/internal/worker/notificationbus_test.go @@ -0,0 +1,146 @@ +package worker + +import ( + "context" + "testing" + "time" + + rediscache "feedsystem_video_go/internal/middleware/redis" + "feedsystem_video_go/internal/notification" + + miniredis "github.com/alicebob/miniredis/v2" + goredis "github.com/redis/go-redis/v9" +) + +// recordingHub 用带缓冲的 channel 记录推送:测试靠 channel 同步,不靠 sleep 猜时序。 +type recordingHub struct { + pushes chan recordedPush +} + +type recordedPush struct { + userID uint + n *notification.Notification +} + +func newRecordingHub() *recordingHub { + return &recordingHub{pushes: make(chan recordedPush, 8)} +} + +func (h *recordingHub) Push(userID uint, n *notification.Notification) { + h.pushes <- recordedPush{userID: userID, n: n} +} + +func newTestRedisClient(t *testing.T) *rediscache.Client { + t.Helper() + mr, err := miniredis.Run() + if err != nil { + t.Fatalf("start miniredis: %v", err) + } + client := rediscache.NewClient(goredis.NewClient(&goredis.Options{Addr: mr.Addr()}), "v1:") + t.Cleanup(func() { + _ = client.Close() + mr.Close() + }) + return client +} + +// startSubscriber 起一个订阅器,并等到订阅真正建立(SUBSCRIBE 确认返回)再返回。 +func startSubscriber(t *testing.T, ctx context.Context, client *rediscache.Client, hub NotificationHub) <-chan error { + t.Helper() + subscribed := make(chan struct{}) + errCh := make(chan error, 1) + go func() { + errCh <- runNotificationSubscriber(ctx, client, hub, func() { close(subscribed) }) + }() + select { + case <-subscribed: + return errCh + case <-time.After(5 * time.Second): + t.Fatal("订阅器未在 5s 内建立订阅") + return nil + } +} + +func TestNotificationBus_PublishReachesSubscriber(t *testing.T) { + client := newTestRedisClient(t) + hub := newRecordingHub() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + startSubscriber(t, ctx, client, hub) + + want := ¬ification.Notification{ID: 7, RecipientID: 42, Type: "like", TargetID: 9} + NewRedisNotificationPublisher(client).Push(42, want) + + select { + case got := <-hub.pushes: + if got.userID != 42 { + t.Fatalf("user_id = %d, want 42(投递给错误的 SSE 连接等于通知丢失)", got.userID) + } + if got.n == nil || got.n.ID != want.ID || got.n.Type != want.Type || got.n.TargetID != want.TargetID { + t.Fatalf("notification = %+v, want %+v", got.n, want) + } + case <-time.After(5 * time.Second): + t.Fatal("通知没有穿过 Redis Pub/Sub:worker 落库后 API 侧收不到推送") + } +} + +// 线上可能存在旧版本发布的消息或脏数据:一条坏消息不能让订阅器退出, +// 否则之后所有合法通知都送不到。 +func TestNotificationSubscriber_SkipsMalformedPayload(t *testing.T) { + client := newTestRedisClient(t) + hub := newRecordingHub() + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + startSubscriber(t, ctx, client, hub) + + channel := client.Key(notificationBusChannel) + pubCtx, pubCancel := context.WithTimeout(context.Background(), time.Second) + defer pubCancel() + if err := client.Publish(pubCtx, channel, []byte(`{"user_id":`)); err != nil { + t.Fatalf("publish malformed: %v", err) + } + + good := ¬ification.Notification{ID: 11, RecipientID: 5, Type: "follow"} + NewRedisNotificationPublisher(client).Push(5, good) + + select { + case got := <-hub.pushes: + if got.n == nil || got.n.ID != good.ID { + t.Fatalf("收到 %+v,坏消息没有被跳过", got.n) + } + case <-time.After(5 * time.Second): + t.Fatal("坏消息之后的合法通知没有送达:订阅循环已退出") + } +} + +func TestNotificationSubscriber_StopsOnContextCancel(t *testing.T) { + client := newTestRedisClient(t) + ctx, cancel := context.WithCancel(context.Background()) + errCh := startSubscriber(t, ctx, client, newRecordingHub()) + + cancel() + + select { + case err := <-errCh: + if err != nil { + t.Fatalf("ctx 取消应视为正常退出,got err = %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("ctx 取消后订阅器没有退出:API 无法优雅停机") + } +} + +// Redis 未配置时 SSE 仍要能建立连接并读历史通知,只是没有实时推送。 +func TestRedisNotificationPublisher_NilClientIsNoop(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("Redis 不可用时 Push 不允许 panic: %v", r) + } + }() + + NewRedisNotificationPublisher(nil).Push(1, ¬ification.Notification{ID: 1}) + (*RedisNotificationPublisher)(nil).Push(1, ¬ification.Notification{ID: 1}) + NewRedisNotificationPublisher(nil).Push(1, nil) +}