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.
119 lines
3.3 KiB
TypeScript
119 lines
3.3 KiB
TypeScript
import "server-only";
|
|
|
|
import { asc, desc, eq, gte } from "drizzle-orm";
|
|
import { cached } from "@/lib/cache";
|
|
import { db, User, WebsiteTeams } from "@/lib/db";
|
|
import { logger } from "@/lib/logger";
|
|
import { apiCacheKey, redisCache } from "@/lib/redis-cache";
|
|
import { cacheNews } from "@/lib/services/news-cache";
|
|
import {
|
|
countOnline,
|
|
countPhotos,
|
|
countRooms,
|
|
countUsers,
|
|
} from "@/lib/services/public-counters";
|
|
import { siteSettings } from "@/lib/services/site-settings";
|
|
|
|
/**
|
|
* Prime the hot public cache keys right after boot.
|
|
*
|
|
* Every deploy starts with an empty in-process cache, and any key that also
|
|
* expired while the old process was down has to be recomputed from the database.
|
|
* With no warm-up, the first visitor after each deploy pays for a burst of
|
|
* simultaneous misses; with it, the site is already warm before traffic arrives.
|
|
*
|
|
* Warming works by cache *key*, not by call site: these use exactly the keys the
|
|
* routes and pages read, so priming an entry serves every reader of it. Failures
|
|
* are logged and ignored — a warm-up that cannot reach the database must never
|
|
* stop the server from serving.
|
|
*/
|
|
|
|
const COUNTER_TTL_MS = 300_000;
|
|
const ONLINE_TTL_MS = 10_000;
|
|
|
|
async function warm<T>(name: string, load: () => Promise<T>): Promise<void> {
|
|
try {
|
|
await load();
|
|
} catch (error) {
|
|
logger.warn("[cache] warm-up failed", {
|
|
key: name,
|
|
error: String(error),
|
|
});
|
|
}
|
|
}
|
|
|
|
export async function warmPublicCaches(): Promise<void> {
|
|
// Small delays between groups: a boot-time burst of COUNT(*) queries against
|
|
// a database that is still opening connections helps nobody.
|
|
await warm("online_count", () =>
|
|
cached("online_count", ONLINE_TTL_MS, countOnline, { staleMs: 15_000 }),
|
|
);
|
|
await warm("total_users", () =>
|
|
cached("total_users", COUNTER_TTL_MS, countUsers, {
|
|
staleMs: COUNTER_TTL_MS,
|
|
}),
|
|
);
|
|
await warm("total_rooms", () =>
|
|
cached("total_rooms", COUNTER_TTL_MS, countRooms, {
|
|
staleMs: COUNTER_TTL_MS,
|
|
}),
|
|
);
|
|
await warm("total_photos", () =>
|
|
cached("total_photos", COUNTER_TTL_MS, countPhotos, {
|
|
staleMs: COUNTER_TTL_MS,
|
|
}),
|
|
);
|
|
await warm("online_users", () =>
|
|
cached("online_users", ONLINE_TTL_MS, listOnlineUsers, {
|
|
staleMs: 15_000,
|
|
}),
|
|
);
|
|
await warm("api:staff", () =>
|
|
redisCache(apiCacheKey("staff"), 300, loadStaff, { staleMs: 300 }),
|
|
);
|
|
await warm("api:teams", () =>
|
|
redisCache(apiCacheKey("teams"), 300, loadTeams, { staleMs: 600 }),
|
|
);
|
|
await warm("news:home", () =>
|
|
cacheNews(apiCacheKey("home"), 15_000, async () => ({ primed: true })),
|
|
);
|
|
}
|
|
|
|
async function listOnlineUsers() {
|
|
return db
|
|
.select({ username: User.username, look: User.look })
|
|
.from(User)
|
|
.where(eq(User.online, "1"))
|
|
.limit(100);
|
|
}
|
|
|
|
async function loadStaff() {
|
|
const minStaffRank =
|
|
Number(await siteSettings.get("min_staff_rank", "7")) || 7;
|
|
return db
|
|
.select({
|
|
username: User.username,
|
|
look: User.look,
|
|
rank: User.rank,
|
|
motto: User.motto,
|
|
})
|
|
.from(User)
|
|
.where(gte(User.rank, minStaffRank))
|
|
.orderBy(desc(User.rank), asc(User.username))
|
|
.limit(100);
|
|
}
|
|
|
|
async function loadTeams() {
|
|
return db
|
|
.select({
|
|
id: WebsiteTeams.id,
|
|
rankName: WebsiteTeams.rankName,
|
|
badge: WebsiteTeams.badge,
|
|
jobDescription: WebsiteTeams.jobDescription,
|
|
staffColor: WebsiteTeams.staffColor,
|
|
})
|
|
.from(WebsiteTeams)
|
|
.where(eq(WebsiteTeams.hiddenRank, false))
|
|
.orderBy(asc(WebsiteTeams.id));
|
|
}
|