fix: broadcast channel cache invalidations

This commit is contained in:
haruka committed 2026-08-26 11:16:32 +08:00
1 parent 6ca1e15b0a
commit 1ee929e4b9
12 files changed
+210 -13

No files matched your search

@@ -0,0 +1,53 @@
package repository
import (
"context"
"log/slog"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/redis/go-redis/v9"
)
const channelCachePubSubKey = "channel_cache_updated"
type channelCache struct {
rdb *redis.Client
}
// NewChannelCache creates the Redis-backed channel cache invalidation bus.
func NewChannelCache(rdb *redis.Client) service.ChannelCachePubSub {
return &channelCache{rdb: rdb}
}
// NotifyUpdate notifies all instances to invalidate their local channel cache.
func (c *channelCache) NotifyUpdate(ctx context.Context) error {
return c.rdb.Publish(ctx, channelCachePubSubKey, "refresh").Err()
}
// SubscribeUpdates subscribes to channel cache invalidation notifications.
func (c *channelCache) SubscribeUpdates(ctx context.Context, handler func()) {
go func() {
pubsub := c.rdb.Subscribe(ctx, channelCachePubSubKey)
defer func() {
if err := pubsub.Close(); err != nil {
slog.Warn("failed to close channel cache subscriber", "error", err)
}
}()
messages := pubsub.Channel()
for {
select {
case <-ctx.Done():
return
case message, ok := <-messages:
if !ok {
slog.Warn("channel cache subscriber stopped", "reason", "channel_closed")
return
}
if message != nil {
handler()
}
}
}
}()
}
@@ -0,0 +1,44 @@
package repository
import (
"context"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
func TestChannelCachePubSub(t *testing.T) {
redisServer := miniredis.RunT(t)
publisherRedis := redis.NewClient(&redis.Options{Addr: redisServer.Addr()})
subscriberRedis := redis.NewClient(&redis.Options{Addr: redisServer.Addr()})
t.Cleanup(func() {
_ = publisherRedis.Close()
_ = subscriberRedis.Close()
})
publisher := NewChannelCache(publisherRedis)
subscriber := NewChannelCache(subscriberRedis)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
received := make(chan struct{}, 1)
subscriber.SubscribeUpdates(ctx, func() {
select {
case received <- struct{}{}:
default:
}
})
require.Eventually(t, func() bool {
return redisServer.PubSubNumSub(channelCachePubSubKey)[channelCachePubSubKey] == 1
}, time.Second, 10*time.Millisecond)
require.NoError(t, publisher.NotifyUpdate(context.Background()))
select {
case <-received:
case <-time.After(time.Second):
t.Fatal("channel cache invalidation notification was not received")
}
}
+1
View File
@@ -137,6 +137,7 @@ var ProviderSet = wire.NewSet(
NewRefreshTokenCache,
NewErrorPassthroughCache,
NewTLSFingerprintProfileCache,
NewChannelCache,
NewContentModerationHashCache,
// Encryptors