fix(api): 管理后台成功写入后递增缓存代次 (#40)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
fu500f
2026-10-31 00:45:55 +00:00
co-authored by Devin AI
parent 36f9c95fa7
commit d0ad1b85f3
6 changed files with 161 additions and 13 deletions
+24 -4
View File
@@ -6,9 +6,9 @@
// so the cache can never take the API down or serve stale data after Redis loss.
//
// Invalidation is global and O(1): keys are namespaced by an epoch counter
// stored in Redis (og:cache:epoch). The Python ingestion bumps that counter
// after a write run, which logically invalidates every cached entry at once
// while old keys age out via their TTL. The epoch is read at most once per
// stored in Redis (og:cache:epoch). Python ingestion and successful admin
// writes bump that counter, logically invalidating cached entries at once while
// old keys age out via their TTL. The epoch is read at most once per
// refresh interval per process, so it adds no per-request round trip.
package cache
@@ -35,7 +35,7 @@ const epochRefresh = 10 * time.Second
const opTimeout = 150 * time.Millisecond
// Cache wraps a Redis client. A nil-backed Cache (Redis unconfigured) disables
// caching: every Get misses and every Set is a no-op.
// caching: every Get misses, every Set is a no-op, and Bump succeeds.
type Cache struct {
rdb *redis.Client
@@ -59,6 +59,26 @@ func New(redisURL string) *Cache {
// Enabled reports whether a Redis backend is configured.
func (c *Cache) Enabled() bool { return c != nil && c.rdb != nil }
// Bump increments the global cache epoch to invalidate existing entries.
func (c *Cache) Bump(ctx context.Context) error {
if !c.Enabled() {
return nil
}
cctx, cancel := context.WithTimeout(ctx, opTimeout)
defer cancel()
epoch, err := c.rdb.Incr(cctx, epochKey).Result()
if err != nil {
return err
}
c.mu.Lock()
c.epoch = epoch
c.epochSetAt = time.Now()
c.epochOK = true
c.mu.Unlock()
return nil
}
// epochNow returns the current cache generation, reading it from Redis at most
// once per epochRefresh. On any Redis error it keeps the last known value and
// throttles re-reads so a down backend cannot slow the hot path.