Files
EpicNext-Cms/src/lib/services/cache-warmup.test.ts
T
openhands 203399aab7
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
fix(cache): true LRU, stale-while-revalidate and cross-process invalidation
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.
2026-09-25 18:26:45 +02:00

105 lines
3.3 KiB
TypeScript

// @ts-nocheck
import { beforeEach, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
// These stand in for the real cache, which runs the query on a miss, so a
// failing database really does propagate into the warm-up.
cached: vi.fn(
async (_key: string, _ttl: number, query: () => Promise<unknown>) =>
query(),
),
redisCache: vi.fn(
async (_key: string, _ttl: number, query: () => Promise<unknown>) =>
query(),
),
cacheNews: vi.fn(
async (_key: string, _ttl: number, query: () => Promise<unknown>) =>
query(),
),
warn: vi.fn(),
// Set by a test to make every origin query reject.
failEverything: false,
}));
vi.mock("@/lib/logger", () => ({
logger: { warn: state.warn, error: vi.fn(), info: vi.fn() },
}));
vi.mock("@/lib/cache", () => ({ cached: state.cached }));
vi.mock("@/lib/redis-cache", () => ({
redisCache: state.redisCache,
apiCacheKey: (name: string) => `api:${name}`,
}));
vi.mock("@/lib/services/news-cache", () => ({ cacheNews: state.cacheNews }));
vi.mock("@/lib/services/site-settings", () => ({
siteSettings: { get: vi.fn(async () => "7") },
}));
vi.mock("@/lib/db", () => {
// A chainable stand-in for a drizzle query that always resolves to a row.
const row = { total: 1, username: "a", look: "l", rank: 7, motto: "m" };
// Chainable and awaitable at once, the way a drizzle query builder is.
const chain: any = new Proxy(() => {}, {
get: (_target, prop) => {
if (prop === Symbol.toStringTag) return "Query";
if (prop === "then")
return (resolve: any, reject: any) =>
(state.failEverything
? Promise.reject(Error("database is down"))
: Promise.resolve([row])
).then(resolve, reject);
return () => chain;
},
});
return {
db: { select: () => chain },
User: { online: "online", username: "username", rank: "rank" },
Rooms: {},
CameraWeb: {},
WebsiteTeams: { id: "id", hiddenRank: "hiddenRank" },
};
});
import { warmPublicCaches } from "./cache-warmup";
beforeEach(() => {
state.failEverything = false;
for (const mock of [
state.cached,
state.redisCache,
state.cacheNews,
state.warn,
])
mock.mockClear();
});
it("primes the keys the public pages actually read", async () => {
await warmPublicCaches();
const keys = state.cached.mock.calls.map(([key]) => key);
expect(keys).toContain("online_count");
expect(keys).toContain("total_users");
expect(keys).toContain("total_rooms");
expect(keys).toContain("total_photos");
expect(state.redisCache.mock.calls.map(([key]) => key)).toEqual(
expect.arrayContaining(["api:staff", "api:teams"]),
);
expect(state.cacheNews).toHaveBeenCalled();
});
it("gives every primed key a stale window", async () => {
// Warming without a grace window would leave the first visitor after a deploy
// to still pay for a miss, which is the thing being fixed.
await warmPublicCaches();
for (const call of [
...state.cached.mock.calls,
...state.redisCache.mock.calls,
])
expect(call[3]?.staleMs).toBeGreaterThan(0);
});
it("survives a database that is completely unavailable", async () => {
// register() calls this without awaiting: it must never reject, or an
// unhandled rejection would take the process down on every boot.
state.failEverything = true;
await expect(warmPublicCaches()).resolves.toBeUndefined();
expect(state.warn).toHaveBeenCalled();
});