fix(api): show legal document changes on every replica immediately
The footer cache expired after 30 seconds, so other replicas showed old links for that long. A version counter in Redis, bumped after each change, now tells every replica to reload with its next request. Refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
73eb0f8bcd
commit
fad5873879
4 files changed
+96
-33
No files matched your search
@@ -0,0 +1,54 @@
|
||||
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()
|
||||
}
|
||||
Reference in new issue
Block a user