Files
Epicnabbo-Catalogus-Updated…/src/app/api/online/count/stream/route.ts
T
openhands 203399aab7 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

110 lines
2.8 KiB
TypeScript

// Server-Sent Events stream of the live online user count for the in-game
// client toolbar. Pushes { count } every ~5s so the counter updates in
// real-time without the client polling. Closes cleanly when the client
// disconnects.
//
// The first event is sent immediately; subsequent events push the cached
// count (10s TTL in the REST endpoint) so repeated reads share one query.
import { count, eq } from "drizzle-orm";
import { cached } from "@/lib/cache";
import { db, User } from "@/lib/db";
import { rcon } from "@/lib/services/rcon";
async function fetchOnlineCount(): Promise<number> {
try {
return await cached(
"online_count",
10_000,
async () => {
const [row] = await db
.select({ total: count() })
.from(User)
.where(eq(User.online, "1"));
return row?.total ?? 0;
},
// A subscriber must never wait on a COUNT(*) to get its next event.
{ staleMs: 15_000 },
);
} catch {
return 0;
}
}
// Emulator (RCON) reachability, cached and shared across all subscribers so an
// N-client toolbar doesn't fire N pings every interval. Falls back to graceful
// degradation on failure so the stream never errors out.
async function fetchEmulatorStatus(): Promise<boolean> {
try {
return await cached(
"emulator_rcon_status",
15_000,
() => rcon.send("ping", null).catch(() => false),
// Reachability is reported, never acted on, so a previous answer is
// good enough while the ping is re-run.
{ staleMs: 15_000 },
);
} catch {
return false;
}
}
export async function GET(req: Request) {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let closed = false;
const send = async () => {
if (closed) return;
const [count, emulator] = await Promise.all([
fetchOnlineCount(),
fetchEmulatorStatus(),
]);
try {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ count, emulator })}\n\n`),
);
} catch {
closed = true;
}
};
// Initial event immediately, then on an interval.
await send();
const interval = setInterval(() => void send(), 5_000);
// SSE comment as a keep-alive ping between data events.
const ping = setInterval(() => {
if (!closed) {
try {
controller.enqueue(encoder.encode(": ping\n\n"));
} catch {
closed = true;
}
}
}, 25_000);
const stop = () => {
closed = true;
clearInterval(interval);
clearInterval(ping);
try {
controller.close();
} catch {
/* already closed */
}
};
req.signal.addEventListener("abort", stop);
},
});
return new Response(stream, {
headers: {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-store, no-transform",
connection: "keep-alive",
},
});
}