fix(cache): true LRU, stale-while-revalidate and cross-process invalidation
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 32s
CI / tests-integration (push) Successful in 1m38s
CI / tests-unit (push) Successful in 1m42s
CI / tests-ui (push) Successful in 2m33s
CI / preflight (push) Skipped
CI / deploy (push) Successful in 2m43s
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 32s
CI / tests-integration (push) Successful in 1m38s
CI / tests-unit (push) Successful in 1m42s
CI / tests-ui (push) Successful in 2m33s
CI / preflight (push) Skipped
CI / deploy (push) Successful in 2m43s
The in-process cache was a FIFO of 500 entries that was never touched on a read, so a key polled on every request could be evicted by an unrelated burst of dynamic keys. That looked exactly like the cache being cleared at random, and it is what made the site fall back to the database unpredictably. - Evict least-recently-used instead, and raise the default budget to 2000 (CACHE_MEMORY_MAX_ENTRIES). Reading a key now marks it as used, so a hot key only leaves when a hotter one takes its place. - Add opt-in stale-while-revalidate (CachedOptions.staleMs). The grace window lives on the entry, so one call site opting in protects every reader of that key. A failed background refresh keeps serving the last good value instead of falling through to the origin, and is reported once rather than per read. - Invalidate across processes. invalidateKey() now clears memory, deletes the Redis key and publishes a signal, so a value written by one process is no longer served stale by the others for the rest of its TTL. A failed Redis delete no longer skips the broadcast. - Guard against a refresh that started before an invalidation writing its outdated result back into the cache. - Read the news revision at most once a second per process instead of on every call, with a pub/sub signal to drop the local copy when it rotates. A Redis outage now degrades to the in-process cache rather than to no cache at all. - Warm the hot public keys on boot, so the first visitors after a deploy do not each pay for a miss. - Count hits, misses, stale serves, errors and evictions per key, exposed at GET /api/admin/devops/cache. Without it a wrong REDIS_URL, a full budget and a dead origin all look identical from the outside. - Enforce the imaging cache budget for real: records are .img/.json pairs, so the old cap counted files and never removed anything while entries were fresh. Sweeps are throttled per directory and prune to a low-water mark. - Cap the JWT version map, and stop per-test scratch roots from littering the runtime imaging cache. Public read-only endpoints get grace windows; admin, account and auth data deliberately stays fresh. Redis TTLs get a little jitter so keys written together no longer expire together. 3209 tests pass. next build could not be verified on this host: the optimized build is OOM-killed before prerender, so this has not run in a real Next runtime yet.
This commit is contained in:
1 parent
f490fcc9da
commit
203399aab7
43 files changed
+1737
-212
No files matched your search
@@ -0,0 +1,139 @@
|
||||
import "server-only";
|
||||
|
||||
import type Redis from "ioredis";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
/**
|
||||
* Cross-process cache signals over Redis pub/sub.
|
||||
*
|
||||
* Every process keeps its own in-process fast path, so writing a value to Redis
|
||||
* is not enough: without a signal, every *other* instance keeps serving its own
|
||||
* copy until the full TTL elapses. Publishing on a channel lets all instances
|
||||
* react immediately, which is what makes an invalidation actually take effect.
|
||||
*
|
||||
* This is strictly an optimisation. If the subscription never comes up, callers
|
||||
* still behave correctly and fall back to TTL-based expiry.
|
||||
*/
|
||||
|
||||
/** Carries a cache key that must be dropped everywhere. */
|
||||
export const INVALIDATE_CHANNEL = "cache:invalidate";
|
||||
|
||||
type Handler = (message: string) => void;
|
||||
|
||||
const handlers = new Map<string, Set<Handler>>();
|
||||
|
||||
// `undefined` = not started yet, `null` = unavailable in this process.
|
||||
let subscriber: Redis | null | undefined;
|
||||
let warnedUnavailable = false;
|
||||
|
||||
function canSubscribe(): boolean {
|
||||
// Never open a connection in the browser, and never during `next build`
|
||||
// prerendering: a live socket would keep the build process from exiting.
|
||||
if (typeof window !== "undefined") return false;
|
||||
if (process.env.NEXT_PHASE === "phase-production-build") return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function dispatch(channel: string, message: string): void {
|
||||
for (const handler of handlers.get(channel) ?? []) {
|
||||
try {
|
||||
handler(message);
|
||||
} catch (error) {
|
||||
logger.warn("[cache] signal handler failed", {
|
||||
channel,
|
||||
error: String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ensureSubscriber(): Redis | null {
|
||||
if (subscriber !== undefined) return subscriber;
|
||||
subscriber = null;
|
||||
if (!redis || !canSubscribe()) return null;
|
||||
try {
|
||||
const client: Redis = redis.duplicate();
|
||||
client.on("error", (error) => {
|
||||
logger.warn("[cache] subscriber error", { error: String(error) });
|
||||
});
|
||||
client.on("message", dispatch);
|
||||
subscriber = client;
|
||||
} catch (error) {
|
||||
logger.warn("[cache] subscriber unavailable", { error: String(error) });
|
||||
}
|
||||
return subscriber;
|
||||
}
|
||||
|
||||
async function subscribe(channel: string): Promise<void> {
|
||||
const client = ensureSubscriber();
|
||||
if (!client) return;
|
||||
try {
|
||||
await client.subscribe(channel);
|
||||
} catch (error) {
|
||||
logger.warn("[cache] subscribe failed", {
|
||||
channel,
|
||||
error: String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const subscribed = new Set<string>();
|
||||
|
||||
/**
|
||||
* Run `handler` for every message published on `channel` by any process.
|
||||
* Returns an unsubscribe function. Safe to call when Redis is absent — the
|
||||
* handler simply never fires and TTL expiry remains the fallback.
|
||||
*/
|
||||
export function onCacheSignal(channel: string, handler: Handler): () => void {
|
||||
let set = handlers.get(channel);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
handlers.set(channel, set);
|
||||
}
|
||||
set.add(handler);
|
||||
if (!subscribed.has(channel)) {
|
||||
subscribed.add(channel);
|
||||
void subscribe(channel);
|
||||
}
|
||||
return () => {
|
||||
set.delete(handler);
|
||||
if (set.size === 0) handlers.delete(channel);
|
||||
};
|
||||
}
|
||||
|
||||
function warnUnavailable(reason: string): void {
|
||||
if (warnedUnavailable || process.env.NODE_ENV !== "production") return;
|
||||
warnedUnavailable = true;
|
||||
logger.warn(
|
||||
"[cache] Signals cannot reach other instances; entries fall back to TTL expiry.",
|
||||
{ reason },
|
||||
);
|
||||
}
|
||||
|
||||
/** Publish a message on `channel` for every other process to react to. */
|
||||
export async function publishCacheSignal(
|
||||
channel: string,
|
||||
message: string,
|
||||
): Promise<void> {
|
||||
if (!redis) return;
|
||||
if (redis.status === "end") {
|
||||
warnUnavailable("connection closed");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await redis.publish(channel, message);
|
||||
} catch (error) {
|
||||
warnUnavailable(String(error));
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop `key` from the in-process cache of every process. */
|
||||
export function onCacheInvalidated(handler: Handler): () => void {
|
||||
return onCacheSignal(INVALIDATE_CHANNEL, handler);
|
||||
}
|
||||
|
||||
/** Tell every other process to drop `key` from its in-process cache. */
|
||||
export async function publishCacheInvalidation(key: string): Promise<void> {
|
||||
await publishCacheSignal(INVALIDATE_CHANNEL, key);
|
||||
}
|
||||
Reference in new issue
Block a user