Files
VLoop/backend/internal/worker/notificationbus_test.go
huanghaosheng b2d2e3d473 feat(notification): 增加跨进程推送桥
Worker 不持有 SSE 连接,进程内广播送不到用户。RedisNotificationPublisher 实现 NotificationHub,把 {user_id, notification} 发布到 v1:notification:push。

Push 尽力而为。失败只记日志,因为通知已经落库,推送不是送达路径。

StartNotificationSubscriber 在每个 API 实例订阅该频道,再转给本地 SSEHub。订阅断开按 1 秒到 30 秒退避重连。订阅维持超过 30 秒再断,视为抖动并重置退避。

坏 JSON 或缺少 user_id/notification 只跳过该条。一条脏数据不能杀死订阅循环。

测试用 miniredis 走通"发布 → 订阅 → hub.Push"。等订阅生效靠 onSubscribed 回调,不用 sleep。
2026-11-08 14:44:29 +08:00

147 lines
4.4 KiB
Go
Raw 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"
"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 := &notification.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 := &notification.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, &notification.Notification{ID: 1})
(*RedisNotificationPublisher)(nil).Push(1, &notification.Notification{ID: 1})
NewRedisNotificationPublisher(nil).Push(1, nil)
}