Files
memby/server/internal/cache/cache.go
T

98 lines
2.9 KiB
Go
Raw Normal View History

// Package cache wraps Redis with the small surface the gateway needs.
//
// Every cached value is scoped to an Emby user id, because "what's on the home screen"
// is per-user. Mutations (favourite, watched, playback stopped) drop that user's keys
// so the next request re-reads Emby rather than serving a stale row.
package cache
import (
"context"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
// ErrMiss means the key was absent — an ordinary outcome, not a failure.
var ErrMiss = errors.New("cache: miss")
type Cache struct {
rdb *redis.Client
}
func Open(redisURL string) (*Cache, error) {
opts, err := redis.ParseURL(redisURL)
if err != nil {
return nil, fmt.Errorf("cache: parse url: %w", err)
}
return &Cache{rdb: redis.NewClient(opts)}, nil
}
func (c *Cache) Close() error { return c.rdb.Close() }
func (c *Cache) Ping(ctx context.Context) error { return c.rdb.Ping(ctx).Err() }
func (c *Cache) Get(ctx context.Context, key string) ([]byte, error) {
b, err := c.rdb.Get(ctx, key).Bytes()
if errors.Is(err, redis.Nil) {
return nil, ErrMiss
}
if err != nil {
return nil, err
}
return b, nil
}
func (c *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
return c.rdb.Set(ctx, key, value, ttl).Err()
}
func (c *Cache) Delete(ctx context.Context, keys ...string) error {
if len(keys) == 0 {
return nil
}
return c.rdb.Del(ctx, keys...).Err()
}
// InvalidateUser drops every cached view belonging to one Emby user.
//
// SCAN rather than KEYS so a large keyspace never blocks Redis; the key count here is
// small, but the habit costs nothing.
func (c *Cache) InvalidateUser(ctx context.Context, userID string) error {
pattern := fmt.Sprintf("u:%s:*", userID)
var cursor uint64
for {
keys, next, err := c.rdb.Scan(ctx, cursor, pattern, 200).Result()
if err != nil {
return err
}
if len(keys) > 0 {
if err := c.rdb.Del(ctx, keys...).Err(); err != nil {
return err
}
}
if next == 0 {
return nil
}
cursor = next
}
}
// UserKey builds the namespaced key used by everything user-scoped.
func UserKey(userID, view string) string { return fmt.Sprintf("u:%s:%s", userID, view) }
// RecommendationsKey sits in its own `r:` namespace on purpose.
//
// Recommendations cost several Emby queries to build, so they must survive the cache
// wipe that every favourite toggle triggers. Only a genuine change in viewing history
// — a finished playback — retires them, via [Cache.InvalidateRecommendations].
2026-07-29 15:26:27 +12:00
func RecommendationsKey(userID string) string { return fmt.Sprintf("r:%s:rows:v3", userID) }
func (c *Cache) InvalidateRecommendations(ctx context.Context, userID string) error {
return c.Delete(ctx, RecommendationsKey(userID))
}
// SessionKey caches a token→session lookup, keyed by token hash (never the token).
func SessionKey(tokenHashHex string) string { return "sess:" + tokenHashHex }