perf(cache): single-flight avatar renders, cacheable public reads, cheap row counts
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 30s
CI / tests-integration (push) Successful in 1m38s
CI / tests-unit (push) Successful in 1m43s
CI / tests-ui (push) Successful in 2m30s
CI / preflight (push) Skipped
CI / deploy (push) Successful in 2m7s
Gitea Actions Runner Test / test-job (push) Successful in 0s
CI / check (push) Successful in 30s
CI / tests-integration (push) Successful in 1m38s
CI / tests-unit (push) Successful in 1m43s
CI / tests-ui (push) Successful in 2m30s
CI / preflight (push) Skipped
CI / deploy (push) Successful in 2m7s
Three separate things that were each costing more than they needed to on the hot path. - Single-flight avatar renders. The disk cache was checked first and a miss went straight to the upstream, with nothing shared between callers, so a page requesting dozens of avatars at once turned N concurrent requests for one figure into N renders. A render is the most expensive operation this app does, and the duplication happened exactly when the cache had nothing to offer. Eight concurrent requests now cause one render instead of eight. The map lives on globalThis because Next can evaluate the module more than once per process, and two copies would each start their own render. - Let public read-only routes be cached by a shared cache. Every JSON response was `cache-control: no-store`, so a CDN in front of the app could not answer any of it and every request reached the origin. publicCacheControl() opts a route in with s-maxage and stale-while-revalidate, using the same TTL as the server-side cache so the two layers cannot disagree. The default stays no-store: most routes here are personalised, admin-only or auth-dependent. /api/badges/leaderboard is deliberately left alone because it returns per-viewer rank entries to signed-in callers. Note this only takes effect once a cache rule exists for /api/* at the CDN, or the explicit `cache: "no-store"` is dropped from the client fetches (24 files do that today, including the /api/online poll). The headers alone are inert until one of those happens. - Take the homepage row counts from the storage engine estimate instead of COUNT(*), which walks an index and gets slower as the tables grow. A missing or zero estimate falls back to the exact count rather than ever showing a wrong zero. The online count stays exact: it is an indexed read over a small subset and a few seconds of drift reads as broken rather than approximate. The counters move into one module because the homepage and the boot warm-up populate the same cache keys, so two implementations would race to write different values into the same entry. 3223 tests pass.
This commit is contained in:
1 parent
203399aab7
commit
f81b114b69
23 files changed
+514
-87
No files matched your search
@@ -0,0 +1,83 @@
|
||||
// @ts-nocheck
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({ upstreamCalls: 0 }));
|
||||
|
||||
vi.mock("@/lib/imager-cache", () => ({
|
||||
avatarCacheDir: () => "/tmp/imager-test",
|
||||
imagingCacheKey: (value: string) => value,
|
||||
// Nothing is ever cached on disk, so every call reaches the render path and
|
||||
// the in-flight map is the only thing that can dedupe it.
|
||||
readImagingCache: vi.fn(async () => null),
|
||||
writeImagingCache: vi.fn(async () => {}),
|
||||
}));
|
||||
vi.mock("@/lib/runtime-asset-config", () => ({
|
||||
resolveImagerBase: (origin: string) => `${origin}/imager`,
|
||||
}));
|
||||
|
||||
import { fetchAvatarImage, ImagerUnavailableError } from "./imager-upstream";
|
||||
|
||||
const params = new URLSearchParams({ figure: "hr-1", direction: "2" });
|
||||
|
||||
beforeEach(() => {
|
||||
state.upstreamCalls = 0;
|
||||
globalThis.imagingInFlight?.clear();
|
||||
// A render is not instantaneous, so every caller launched in the same tick
|
||||
// is genuinely in flight at the same time. That overlap is what the
|
||||
// in-flight map has to collapse.
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => {
|
||||
state.upstreamCalls += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
return new Response(new Uint8Array([1, 2, 3]), {
|
||||
headers: { "content-type": "image/png" },
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("renders once for many concurrent requests of the same figure", async () => {
|
||||
// This is the whole point: a page asks for dozens of avatars at once and
|
||||
// repeats figures, and a render is the most expensive thing this app does.
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 8 }, () =>
|
||||
fetchAvatarImage("https://site.test", params),
|
||||
),
|
||||
);
|
||||
|
||||
expect(state.upstreamCalls).toBe(1);
|
||||
for (const result of results) {
|
||||
expect([...result.body]).toEqual([1, 2, 3]);
|
||||
expect(result.source).toBe("primary");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not dedupe different figures", async () => {
|
||||
const other = new URLSearchParams({ figure: "hr-2", direction: "2" });
|
||||
await Promise.all([
|
||||
fetchAvatarImage("https://site.test", params),
|
||||
fetchAvatarImage("https://site.test", other),
|
||||
]);
|
||||
expect(state.upstreamCalls).toBe(2);
|
||||
});
|
||||
|
||||
it("clears the in-flight entry so a later request reads the cache again", async () => {
|
||||
// A leaked entry would pin one promise per figure for the process lifetime
|
||||
// and serve the same body forever.
|
||||
await fetchAvatarImage("https://site.test", params);
|
||||
expect(globalThis.imagingInFlight?.size ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
it("clears the in-flight entry when the render fails", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => {
|
||||
throw Error("upstream down");
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
fetchAvatarImage("https://habbo.com/habbo-imaging/avatarimage", params),
|
||||
).rejects.toThrow(ImagerUnavailableError);
|
||||
expect(globalThis.imagingInFlight?.size ?? 0).toBe(0);
|
||||
});
|
||||
Reference in new issue
Block a user