package api import ( "context" "errors" "sync" "github.com/redis/go-redis/v9" ) // versioned caches a value derived from the database on every replica. A // counter in Redis names the current version; writers bump it after their // change committed, and readers reload when it moved. A change is thus // visible on every replica with the next request, at the cost of one Redis // GET per read. type versioned[T any] struct { key string mu sync.Mutex loaded bool version int64 value T } func newVersioned[T any](name string) *versioned[T] { return &versioned[T]{key: "version:" + name} } // get returns the cached value, loading it when the version changed. If // Redis is unreachable it keeps serving what it has. func (v *versioned[T]) get(ctx context.Context, rdb redis.UniversalClient, load func(context.Context) (T, error)) (T, error) { current, err := rdb.Get(ctx, v.key).Int64() if errors.Is(err, redis.Nil) { current, err = 0, nil } v.mu.Lock() defer v.mu.Unlock() if v.loaded && (err != nil || current == v.version) { return v.value, nil } value, lerr := load(ctx) if lerr != nil { return v.value, lerr } // Remembering the version read before loading errs on the side of one // extra reload, never of missing a change. v.value, v.version, v.loaded = value, current, err == nil return value, nil } // bump announces a committed change to every replica. func (v *versioned[T]) bump(ctx context.Context, rdb redis.UniversalClient) error { return rdb.Incr(ctx, v.key).Err() }