Files
EpicNext-Cms/src/lib/runtime-avatar-route.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

126 lines
4.6 KiB
TypeScript

// @ts-nocheck
import { rm } from "node:fs/promises";
import { NextRequest } from "next/server";
import { afterAll, afterEach, beforeEach, expect, it, vi } from "vitest";
import { GET } from "../app/api/imaging/avatar/route";
// One scratch root for the whole file, removed afterwards: a per-test root left a
// new directory behind for every test, polluting the runtime cache tree.
const SCRATCH_ROOT = `${process.cwd()}/storage/imaging/test-route-${process.pid}`;
beforeEach(() => {
// Isolated cache root so the disk cache can never leak state between runs or
// into the runtime cache.
vi.stubEnv("IMAGING_CACHE_ROOT", SCRATCH_ROOT);
});
afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
afterAll(async () => {
await rm(SCRATCH_ROOT, { recursive: true, force: true });
});
it("forwards multicolor figures and preserves configured query options at runtime", async () => {
const figure = "hr-11782-40-40.hd-180-7-14.ch-11592-66.lg-10726-79-1408";
const fetcher = vi.fn(
async (_input: string | URL) =>
new Response(new Uint8Array([1, 2, 3]), {
headers: { "content-type": "image/png" },
}),
);
vi.stubGlobal("fetch", fetcher);
for (const hotel of ["alpha", "beta"]) {
vi.stubEnv("IMAGER_URL", `https://${hotel}.test/avatar?renderer=custom`);
const result = await GET(
new NextRequest(
`https://hotel.test/api/imaging/avatar?figure=${figure}&headonly=1&effect=0`,
),
);
expect(result.status).toBe(200);
const target = new URL(String(fetcher.mock.calls.at(-1)?.[0]));
expect(target.origin).toBe(`https://${hotel}.test`);
expect(target.searchParams.get("figure")).toBe(figure);
expect(target.searchParams.get("renderer")).toBe("custom");
expect(target.searchParams.get("headonly")).toBe("1");
}
});
it("rejects malformed figure input without contacting a renderer", async () => {
const fetcher = vi.fn();
vi.stubGlobal("fetch", fetcher);
expect(
(
await GET(
new NextRequest("https://hotel.test/api/imaging/avatar?figure=../bad"),
)
).status,
).toBe(400);
expect(fetcher).not.toHaveBeenCalled();
});
it("falls back to the public Habbo renderer when the configured imager is down", async () => {
const fetcher = vi.fn(async (input: string | URL) => {
const url = new URL(String(input));
if (url.origin === "https://hotel.test")
return new Response("unavailable", { status: 503 });
return new Response(new Uint8Array([4, 5, 6]), {
headers: { "content-type": "image/png" },
});
});
vi.stubGlobal("fetch", fetcher);
vi.stubEnv("IMAGER_URL", "https://hotel.test/avatarimage");
const result = await GET(
new NextRequest(
"https://hotel.test/api/imaging/avatar?figure=hd-180-1&img_format=apng&effect=0",
),
);
expect(result.status).toBe(200);
expect(result.headers.get("x-imager-source")).toBe("fallback");
expect(result.headers.get("cache-control")).toContain("max-age=300");
const target = new URL(String(fetcher.mock.calls.at(-1)?.[0]));
expect(target.host).toBe("www.habbo.com");
expect(target.searchParams.get("img_format")).toBe("png");
expect(target.searchParams.has("effect")).toBe(false);
});
it("serves a previously rendered avatar from the disk cache without re-fetching", async () => {
const fetcher = vi.fn(
async (_input: string | URL) =>
new Response(new Uint8Array([9, 8, 7]), {
headers: { "content-type": "image/png" },
}),
);
vi.stubGlobal("fetch", fetcher);
vi.stubEnv("IMAGER_URL", "https://cache.test/avatarimage");
const request = new NextRequest(
"https://hotel.test/api/imaging/avatar?figure=hd-123-1",
);
const first = await GET(request);
expect(first.status).toBe(200);
const callsAfterFirst = fetcher.mock.calls.length;
expect(callsAfterFirst).toBeGreaterThan(0);
const second = await GET(request);
expect(second.status).toBe(200);
expect(second.headers.get("x-imager-source")).toBe("cache");
expect(second.headers.get("cache-control")).toContain("max-age=3600");
// The cached render must not touch the upstream again.
expect(fetcher.mock.calls.length).toBe(callsAfterFirst);
});
it("serves a graceful silhouette instead of a broken image when every upstream is down", async () => {
const fetcher = vi.fn(
async (_input: string | URL) =>
new Response("renderer unreachable", { status: 503 }),
);
vi.stubGlobal("fetch", fetcher);
vi.stubEnv("IMAGER_URL", "https://down.test/avatarimage");
const result = await GET(
new NextRequest("https://hotel.test/api/imaging/avatar?figure=xd-900-1"),
);
expect(result.status).toBe(200);
expect(result.headers.get("content-type")).toBe("image/svg+xml");
expect(result.headers.get("x-imager-source")).toBe("unavailable");
expect(result.headers.get("cache-control")).toContain("no-cache");
});