1
0
Fork 0

perf: cut queries per render and refreshes per realtime event

Under 10-12 concurrent users the app queued behind itself: every SSE
game-event/profile-update made each client run router.refresh(), i.e. a
full layout + page render at ~15-25 queries, and a mission completion
emitted one XP event per attendee row. Measured against production, no
single query is slow and the DB is small, so this targets render count
and per-render query count instead of indexes.

Fewer renders per event:
- GameTickRealtime: 250ms coalescing window -> 1s, hidden tabs skip the
  render and refresh once when shown again.
- Delete OperationsRealtimeRefresher (5 routes) and the duplicate
  useGameTick refreshers in ProductionPanel/SlotsPanel; the global
  subscriber already refreshes those routes.
- Presence heartbeats no longer broadcast (was O(N^2) per channel every
  15s for a lastSeen no surface renders).
- NavCore links opt out of prefetch: the layout is force-dynamic with no
  loading.tsx, so ~35 prefetched links per tab were 35 server renders.

Fewer queries per render:
- Qualification flags go through one cached, single-flight profile read
  instead of one query per auth check; invalidated on profile writes.
- Dedupe DIVISION_ADMIN_QUALIFICATIONS (5 identical lookups -> 1).
- Anchor the permission cache on globalThis so route bundles share it.
- Minigame registry: real TTL cache plus invalidation on write.
- New cachedConfig TTL cache for the shims/game-rules globals, with
  invalidation hooks; bank-account existence check stops hydrating.
- pg pool max 10 -> 20 (node-postgres default throttled concurrent
  renders).

Hot-path per-item work:
- Contribution grant sweep: one status write per batch, one bucket write
  and one name lookup per user, one existence query per source
  collection instead of ~5 queries per entry.
- Notifications bell: coalesced refetch, hidden-tab skip; mark-all-read
  filters by the actor instead of scanning 100 foreign unread rows.
- Polling loops (shipments, ledger, mission reminders, chip bank) pause
  while the tab is hidden.
This commit is contained in:
Jason Fraley 2026-11-22 22:39:10 -05:00
parent 9149b3926f
commit a0f767cc13
32 changed files with 557 additions and 163 deletions

View file

@ -38,6 +38,7 @@ import { DevDashboardGate } from "@/components/frontend/dev/DevDashboardGate";
import { ClarityAnalytics } from "@/components/frontend/analytics/ClarityAnalytics";
import { AnalyticsTracker } from "@/lib/client-analytics/AnalyticsTracker";
import { loadMinigameRegistry } from "@/lib/minigames/loadRegistry";
import { cachedConfig } from "@/lib/config-cache";
import type { RegistryGame } from "@/lib/minigames/registry";
// Skip static prerendering of this layout (and all pages under (frontend)/).
@ -85,7 +86,9 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
let currentRank = "";
let hasPersonalBankAccount = false;
const shimsGlobal = await payload.findGlobal({ slug: "shims" });
const shimsGlobal = await cachedConfig("global:shims", () =>
payload.findGlobal({ slug: "shims" }),
);
const shimEntries = (shimsGlobal.shims ?? []) as NonNullable<Shim["shims"]>;
let announcementEntries: AnnouncementEntry[] = [];
@ -139,8 +142,12 @@ export default async function RootLayout(props: { children: React.ReactNode }) {
and: [{ accountType: { equals: "personal" } }, { ownerUser: { equals: user.id } }],
},
limit: 1,
depth: 0,
// Only the existence of the account is used below, so skip hydrating
// balances, ledgers and the owner relationship.
select: { accountType: true },
}),
payload.findGlobal({ slug: "game-rules" }),
cachedConfig("global:game-rules", () => payload.findGlobal({ slug: "game-rules" })),
payload.find({
collection: "announcements",
where: { enabled: { equals: true } },

View file

@ -7,7 +7,6 @@ import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQu
import {
LedgerRow,
NoticeState,
OperationsRealtimeRefresher,
PageShell,
STATUS_TONE_CLASSES,
type ReadoutCell,
@ -156,8 +155,6 @@ export default async function SupplyBoxesPage() {
</p>
</PageShell>
<OperationsRealtimeRefresher />
{data.capability === false ? (
<NoticeState
variant="error"

View file

@ -8,7 +8,6 @@ import { getOperationAar } from "@/lib/operations/surfaceQuery";
import {
AarView,
NoticeState,
OperationsRealtimeRefresher,
OperationsStrip,
PageShell,
ReconcilePanel,
@ -50,7 +49,6 @@ export default async function OperationAarPage({
return (
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell title={`Operation ${operationId}`} meta="AFTER-ACTION REPORT // PROVENANCE LINKED">
{aar === null ? (
<NoticeState

View file

@ -3,7 +3,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { getPendingExtractions } from "@/app/(frontend)/operations/actions";
import { ExtractionReview, PageShell, OperationsRealtimeRefresher } from "@/components/frontend/operations";
import { ExtractionReview, PageShell } from "@/components/frontend/operations";
import type { PendingExtraction } from "@/lib/operations/surfaceQuery";
export const metadata = {
@ -31,7 +31,6 @@ export default async function PendingExtractionsPage() {
return (
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell
title="Pending extractions"
meta="EXTRACTION RETURNS // REVIEW & DEPOSIT"

View file

@ -5,7 +5,6 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { getOperationLedger } from "@/lib/operations/surfaceQuery";
import {
LedgerTable,
OperationsRealtimeRefresher,
OperationsStrip,
PageShell,
} from "@/components/frontend/operations";
@ -51,7 +50,6 @@ export default async function OperationsLedgerPage({
return (
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell
title="Operations ledger"
meta="SOURCE EVENTS // EFFECT LEDGER"

View file

@ -5,7 +5,6 @@ import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import { getOperationOverview } from "@/lib/operations/surface";
import {
MyExtractionsCard,
OperationsRealtimeRefresher,
OperationsStrip,
PageShell,
PressureCard,
@ -31,7 +30,6 @@ export default async function OperationsPage() {
return (
<div className="mx-auto flex w-full max-w-[96rem] flex-col gap-6 px-4 py-6">
<OperationsRealtimeRefresher />
<PageShell title="Operations" meta="OPERATION FEED // AFTER-ACTION RECORDS" dataTour="page-header">
<p className="max-w-2xl text-sm text-white/70">
Live and historical operation activity: extraction returns, settlements, readiness

View file

@ -1,5 +1,6 @@
import { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { invalidateConfigCache } from "@/lib/config-cache";
export const Shims: GlobalConfig = {
slug: "shims",
@ -7,6 +8,10 @@ export const Shims: GlobalConfig = {
read: requirePermission("shims:read"),
update: requirePermission("shims:update"),
},
hooks: {
// The (frontend) layout caches this global for 60s (lib/config-cache.ts).
afterChange: [() => invalidateConfigCache("global:shims")],
},
fields: [
{
name: "shims",

View file

@ -1,5 +1,6 @@
import { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { invalidateConfigCache } from "@/lib/config-cache";
export const GameRules: GlobalConfig = {
slug: "game-rules",
@ -7,6 +8,10 @@ export const GameRules: GlobalConfig = {
read: requirePermission("game-rules:read"),
update: requirePermission("game-rules:update"),
},
hooks: {
// The (frontend) layout caches this global for 60s (lib/config-cache.ts).
afterChange: [() => invalidateConfigCache("global:game-rules")],
},
fields: [
{
name: "mainCurrency",

View file

@ -1,5 +1,6 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { invalidateMinigameRegistryCache } from "@/lib/minigames/loadRegistry";
/**
* Registry of minigames.
@ -26,6 +27,13 @@ export const Minigames: CollectionConfig = {
update: requirePermission("minigames:update"),
delete: requirePermission("minigames:delete"),
},
hooks: {
// The frontend caches this registry briefly (loadRegistry.ts) because the
// layout reads it on every render. Drop that cache on any write so a status
// flip (upcoming -> active) is visible immediately.
afterChange: [() => invalidateMinigameRegistryCache()],
afterDelete: [() => invalidateMinigameRegistryCache()],
},
fields: [
{
name: "key",

View file

@ -3,6 +3,7 @@ import { Award } from "@/payload-types";
import { broadcastToUser } from "@/lib/realtime/bus";
import { notifyAwardGrants } from "@/lib/awards";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { invalidateQualificationCache } from "@/utils/access-control/qualificationCache";
import { lexicalPlaintextLength } from "@/lib/lexical/text";
export const Profiles: CollectionConfig = {
@ -31,6 +32,10 @@ export const Profiles: CollectionConfig = {
async ({ doc }) => {
const userId = typeof doc.user === "object" ? doc.user?.id : doc.user;
if (typeof userId === "number") {
// Qualification flags gate division nav + admin-page access and are
// cached for 30s; drop the entry so a granted/revoked qualification
// takes effect on the next request instead of up to 30s later.
invalidateQualificationCache(userId);
broadcastToUser("profile-update", userId, { profileId: doc.id });
}
},

View file

@ -6,7 +6,6 @@ import { toast } from "sonner";
import { Pause, Play } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
import { useGameTick } from "@/hooks/useGameTick";
import { toggleProduction } from "@/app/(frontend)/logistics/base/actions";
export interface ProductionRecipeLine {
@ -41,7 +40,6 @@ export function ProductionPanel({
}: ProductionPanelProps) {
const router = useRouter();
const [loading, setLoading] = useState(false);
useGameTick(() => router.refresh());
if (!complete) return null;
if (inputs.length === 0 && outputs.length === 0) return null;

View file

@ -7,7 +7,6 @@ import { Blocks, Plus, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
import { useGameTick } from "@/hooks/useGameTick";
import { installModule, uninstallModule } from "@/app/(frontend)/logistics/base/actions";
export interface ModuleEffectLine {
@ -51,7 +50,6 @@ export function SlotsPanel({
}: SlotsPanelProps) {
const router = useRouter();
const [loading, setLoading] = useState<string | null>(null);
useGameTick(() => router.refresh());
if (slots <= 0 && options.length === 0 && installed.length === 0) return null;

View file

@ -37,6 +37,11 @@ export function NavCore({
}) {
if (items.length === 0) return null;
// `prefetch={false}` on the links below: the (frontend) layout is
// force-dynamic with no loading.tsx, so a prefetched nav link is a full
// server render (auth sweep + layout queries). With ~35 sidebar links per
// open tab, prefetching turned every page load into dozens of renders.
// Navigation itself stays client-side.
return (
<SidebarGroup>
<SidebarGroupLabel>{label}</SidebarGroupLabel>
@ -65,7 +70,7 @@ export function NavCore({
{item.items?.map((subItem) => (
<SidebarMenuSubItem key={subItem.title}>
<SidebarMenuSubButton asChild>
<Link href={subItem.url}>
<Link href={subItem.url} prefetch={false}>
{subItem.icon ? <subItem.icon /> : null}
<span>{subItem.title}</span>
</Link>
@ -77,7 +82,7 @@ export function NavCore({
</>
) : (
<SidebarMenuButton asChild tooltip={item.title}>
<Link href={item.url}>
<Link href={item.url} prefetch={false}>
<item.icon />
<span>{item.title}</span>
</Link>

View file

@ -212,7 +212,10 @@ export function MissionReminderToasts() {
writeReminderDismissals(dismissedRef.current, now);
void fetchReminders();
const interval = setInterval(() => void fetchReminders(), POLL_MS);
const interval = setInterval(() => {
if (document.hidden) return;
void fetchReminders();
}, POLL_MS);
return () => {
mountedRef.current = false;
clearInterval(interval);

View file

@ -62,11 +62,16 @@ export function ShipmentToasts() {
useEffect(() => {
fetchShipments();
const interval = setInterval(fetchShipments, 30_000);
const interval = setInterval(() => {
if (document.hidden) return;
fetchShipments();
}, 30_000);
return () => clearInterval(interval);
}, [fetchShipments]);
useGameTick(() => fetchShipments());
useGameTick(() => {
if (!document.hidden) fetchShipments();
});
if (shipments.length === 0) return null;

View file

@ -75,7 +75,10 @@ export function ChipBankCard({ initialChipBank, initialChipTopUpAt }: ChipBankCa
}, [refreshChipState]);
useEffect(() => {
const poll = window.setInterval(refreshChipState, 5000);
const poll = window.setInterval(() => {
if (document.hidden) return;
refreshChipState();
}, 5000);
return () => window.clearInterval(poll);
}, [refreshChipState]);

View file

@ -81,6 +81,7 @@ export function NotificationsBell() {
const [scope, setScope] = useState<Scope>(readStoredScope);
const [canViewOthers, setCanViewOthers] = useState(false);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const eventTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const unreadCount = notifications.filter((n) => !n.read).length;
@ -106,11 +107,27 @@ export function NotificationsBell() {
useEffect(() => {
void fetchNotifications();
intervalRef.current = setInterval(() => void fetchNotifications(), POLL_MS);
const onNotification = () => void fetchNotifications();
intervalRef.current = setInterval(() => {
// A hidden tab costs a full auth + query per poll while nobody is
// looking; it catches up on the next poll after it becomes visible.
if (document.hidden) return;
void fetchNotifications();
}, POLL_MS);
// A notification burst (e.g. a mission completion granting XP) emits one
// event per recipient row. Coalesce them into at most one refetch per
// second instead of one request per event.
const onNotification = () => {
if (document.hidden) return;
if (eventTimerRef.current) return;
eventTimerRef.current = setTimeout(() => {
eventTimerRef.current = null;
void fetchNotifications();
}, 1000);
};
window.addEventListener(NOTIFICATION_EVENT, onNotification);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
if (eventTimerRef.current) clearTimeout(eventTimerRef.current);
window.removeEventListener(NOTIFICATION_EVENT, onNotification);
};
}, [fetchNotifications]);

View file

@ -1,17 +0,0 @@
"use client";
import { useRouter } from "next/navigation";
import { useGameTick } from "@/hooks/useGameTick";
/**
* Enhancement-only realtime refresh for /operations surfaces. The server
* re-fetch on navigation is the correctness source; this only triggers an
* early refresh when a game tick lands while the page is open.
*/
export function OperationsRealtimeRefresher() {
const router = useRouter();
useGameTick(() => {
router.refresh();
});
return null;
}

View file

@ -7,7 +7,6 @@ export { NoticeState } from "./NoticeState";
export { StrategicSummary } from "./StrategicSummary";
export { PageShell } from "./PageShell";
export { STATUS_TONE_CLASSES, DOSSIER, statusToneFor, type StatusTone } from "./tokens";
export { OperationsRealtimeRefresher } from "./OperationsRealtimeRefresher";
export {
RecentOperationsCard,
MyExtractionsCard,

View file

@ -39,13 +39,40 @@ export function GameTickRealtime() {
useEffect(() => {
const source = new EventSource("/api/realtime");
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
const refresh = (delay = 250) => {
let skippedWhileHidden = false;
/**
* One coalesced refresh per burst. The window used to be 250ms, which real
* bursts walk straight through: a mission completion grants one XP event
* per attendee (40-120 broadcasts in a few seconds), and each broadcast
* re-renders the whole route tree (layout + page, ~20 queries) for every
* connected client. A 1s window keeps the same visible update latency while
* turning a burst into a couple of renders instead of dozens.
*
* Hidden tabs skip the render entirely; they cost the server a full SSR pass
* for a page nobody is looking at. They refresh once when they become
* visible again.
*/
const refresh = (delay = 1000) => {
if (typeof document !== "undefined" && document.hidden) {
skippedWhileHidden = true;
return;
}
if (refreshTimer) return;
refreshTimer = setTimeout(() => {
refreshTimer = null;
if (document.hidden) {
skippedWhileHidden = true;
return;
}
router.refresh();
}, delay);
};
const onVisibility = () => {
if (document.hidden || !skippedWhileHidden) return;
skippedWhileHidden = false;
refresh(0);
};
document.addEventListener("visibilitychange", onVisibility);
source.addEventListener("game-tick", (event) => {
let detail: GameTickDetail = {};
try {
@ -147,6 +174,7 @@ export function GameTickRealtime() {
});
return () => {
if (refreshTimer) clearTimeout(refreshTimer);
document.removeEventListener("visibilitychange", onVisibility);
source.close();
};
}, [router]);

View file

@ -110,12 +110,14 @@ export function EventLedger({
useEffect(() => {
const interval = setInterval(() => {
if (document.hidden) return;
if (initialDone.current) fetchEntries();
}, 30_000);
return () => clearInterval(interval);
}, [fetchEntries]);
useGameTick(() => {
if (document.hidden) return;
if (initialDone.current) fetchEntries();
});

75
src/lib/config-cache.ts Normal file
View file

@ -0,0 +1,75 @@
/**
* Tiny TTL cache for admin-authored configuration reads.
*
* The `(frontend)` layout renders on every navigation and on every realtime
* refresh, and it reads globals that change maybe once a month (shims, game
* rules). Under concurrent load those reads multiply by clients x refreshes for
* data that is identical for everyone.
*
* Only use this for values that are the same for every user and are edited by
* admins, never for anything user-scoped (permissions, presence, balances).
* `globalThis`-anchored so route bundles share one copy, like the SSE bus and
* the minigame registry cache.
*/
const DEFAULT_TTL_MS = 60_000;
interface CacheEntry {
value: unknown;
loadedAt: number;
}
interface CacheHolder {
__ptfConfigCache?: Map<string, CacheEntry>;
__ptfConfigInflight?: Map<string, Promise<unknown>>;
}
function holder(): CacheHolder {
return globalThis as typeof globalThis & CacheHolder;
}
function entries(): Map<string, CacheEntry> {
const store = holder();
return (store.__ptfConfigCache ??= new Map<string, CacheEntry>());
}
function inflight(): Map<string, Promise<unknown>> {
const store = holder();
return (store.__ptfConfigInflight ??= new Map<string, Promise<unknown>>());
}
export async function cachedConfig<T>(
key: string,
load: () => Promise<T>,
ttlMs: number = DEFAULT_TTL_MS,
): Promise<T> {
const now = Date.now();
const hit = entries().get(key);
if (hit && now - hit.loadedAt < ttlMs) return hit.value as T;
const pending = inflight().get(key);
if (pending) return pending as Promise<T>;
const promise = load()
.then((value) => {
entries().set(key, { value, loadedAt: Date.now() });
inflight().delete(key);
return value;
})
.catch((error: unknown) => {
inflight().delete(key);
throw error;
});
inflight().set(key, promise as Promise<unknown>);
return promise;
}
/** Drop one cached key, or the whole cache when no key is given. */
export function invalidateConfigCache(key?: string): void {
if (key === undefined) {
entries().clear();
inflight().clear();
return;
}
entries().delete(key);
}

View file

@ -97,22 +97,6 @@ function actorLabel(userId: number, actorName?: string | null): string {
return actorName && actorName.trim().length > 0 ? actorName : `User #${userId}`;
}
/** Resolve a user's display name for human-readable event messages. */
async function resolveUserName(payload: Payload, userId: number): Promise<string> {
try {
const user = (await payload.findByID({
collection: "users",
id: userId,
depth: 0,
overrideAccess: true,
select: { displayName: true, username: true },
})) as unknown as { displayName?: string | null; username?: string | null };
return user.displayName || user.username || `User #${userId}`;
} catch {
return `User #${userId}`;
}
}
/** Deterministic content hash for deduping wiki edits. Server-only. */
export function contentHash(text: string): string {
return createHash("sha256").update(text).digest("hex").slice(0, 16);
@ -183,23 +167,81 @@ async function missionEntryCount(
return totalDocs;
}
async function sourceStillExists(
payload: Payload,
sourceCollection: ContributionSourceCollection,
sourceId: number,
): Promise<boolean> {
if (sourceCollection === "manual") return true;
async function resolveUserNames(payload: Payload, userIds: number[]): Promise<Map<number, string>> {
const names = new Map<number, string>();
for (const id of userIds) names.set(id, `User #${id}`);
if (userIds.length === 0) return names;
try {
const doc = await payload.findByID({
collection: sourceCollection,
id: sourceId,
const res = (await payload.find({
collection: "users",
where: { id: { in: userIds } },
limit: userIds.length,
depth: 0,
pagination: false,
overrideAccess: true,
});
return Boolean(doc);
select: { displayName: true, username: true },
})) as unknown as {
docs: Array<{ id: number; displayName?: string | null; username?: string | null }>;
};
for (const doc of res.docs) {
names.set(Number(doc.id), doc.displayName || doc.username || `User #${doc.id}`);
}
} catch {
return false;
// Keep the "User #id" fallbacks.
}
return names;
}
function sourceKey(collection: ContributionSourceCollection, id: number): string {
return `${collection}:${id}`;
}
/**
* Resolve which queued entries still have a live source document, using one
* query per source collection instead of one per entry. A mission completes
* with 40-120 queued entries and the old per-entry `findByID` dominated the
* completion sweep.
*/
async function survivingSourceKeys(
payload: Payload,
entries: ContributionEntryDoc[],
): Promise<Set<string>> {
const idsByCollection = new Map<Exclude<ContributionSourceCollection, "manual">, Set<number>>();
for (const entry of entries) {
if (entry.sourceCollection === "manual") continue;
const collection = entry.sourceCollection;
let ids = idsByCollection.get(collection);
if (!ids) {
ids = new Set<number>();
idsByCollection.set(collection, ids);
}
ids.add(entry.sourceId);
}
const surviving = new Set<string>();
await Promise.all(
[...idsByCollection.entries()].map(async ([collection, idSet]) => {
const ids = [...idSet];
try {
const found = await payload.find({
collection,
where: { id: { in: ids } },
limit: ids.length,
depth: 0,
pagination: false,
overrideAccess: true,
});
for (const doc of found.docs) surviving.add(sourceKey(collection, Number(doc.id)));
} catch {
// Previously a failed lookup counted as "source gone" and revoked the
// entry. A single transient failure must not mass-revoke a mission's
// contributions, so treat an unreadable collection as alive.
for (const id of ids) surviving.add(sourceKey(collection, id));
}
}),
);
return surviving;
}
async function emitGranted(
@ -317,31 +359,6 @@ export async function recordContribution(
return { status, points, entryId: created.id };
}
/** Flip a queued entry to granted, applying the bucket delta and notifying. */
async function markGranted(
payload: Payload,
entry: ContributionEntryDoc,
reason: string,
): Promise<void> {
const userId = entryUserId(entry);
const nowIso = new Date().toISOString();
await payload.update({
collection: "contribution-entries",
id: entry.id,
data: { status: "granted", grantedAt: nowIso },
overrideAccess: true,
});
await addContributionXp(payload, userId, entry.points);
await emitGranted(payload, entry, userId, await resolveUserName(payload, userId), entry.points, entry.type);
await notifyUser(payload, {
userId,
type: "contribution:xp-granted",
title: `+${entry.points} XP granted`,
message: reason,
link: "/contributions",
});
}
/**
* Grant every queued entry on a mission whose source marker still exists.
* Entries whose marker was removed are revoked (backstop for a missed delete
@ -359,22 +376,72 @@ export async function grantQueuedEntriesForMission(
overrideAccess: true,
})) as unknown as { docs: ContributionEntryDoc[] };
let granted = 0;
let revoked = 0;
if (res.docs.length === 0) return { granted: 0, revoked: 0 };
// One lookup per source collection instead of one per entry.
const surviving = await survivingSourceKeys(payload, res.docs);
const survivors: ContributionEntryDoc[] = [];
const orphans: ContributionEntryDoc[] = [];
for (const entry of res.docs) {
const survives = await sourceStillExists(payload, entry.sourceCollection, entry.sourceId);
if (!survives) {
await revokeEntry(payload, entry.id, {
reason: "The contribution was removed before the mission completed.",
silent: true,
});
revoked += 1;
continue;
if (
entry.sourceCollection === "manual" ||
surviving.has(sourceKey(entry.sourceCollection, entry.sourceId))
) {
survivors.push(entry);
} else {
orphans.push(entry);
}
await markGranted(payload, entry, `Your contribution was kept in "${entry.summary}".`);
granted += 1;
}
return { granted, revoked };
let revoked = 0;
for (const entry of orphans) {
await revokeEntry(payload, entry.id, {
reason: "The contribution was removed before the mission completed.",
silent: true,
});
revoked += 1;
}
if (survivors.length === 0) return { granted: 0, revoked };
// One status write for the whole batch (the collection has no hooks), then
// one bucket write and one name lookup per distinct user instead of per entry.
const nowIso = new Date().toISOString();
await payload.update({
collection: "contribution-entries",
where: { id: { in: survivors.map((entry) => entry.id) } },
data: { status: "granted", grantedAt: nowIso },
overrideAccess: true,
depth: 0,
});
const entriesByUser = new Map<number, ContributionEntryDoc[]>();
for (const entry of survivors) {
const userId = entryUserId(entry);
const list = entriesByUser.get(userId);
if (list) list.push(entry);
else entriesByUser.set(userId, [entry]);
}
const names = await resolveUserNames(payload, [...entriesByUser.keys()]);
for (const [userId, entries] of entriesByUser) {
const points = entries.reduce((sum, entry) => sum + entry.points, 0);
await addContributionXp(payload, userId, points);
const earnerName = names.get(userId) ?? `User #${userId}`;
for (const entry of entries) {
await emitGranted(payload, entry, userId, earnerName, entry.points, entry.type);
await notifyUser(payload, {
userId,
type: "contribution:xp-granted",
title: `+${entry.points} XP granted`,
message: `Your contribution was kept in "${entry.summary}".`,
link: "/contributions",
});
}
}
return { granted: survivors.length, revoked };
}
/** Expire every queued entry on a mission (Cancelled, or stale drafts). */

View file

@ -18,6 +18,53 @@ import {
* resolved list as a prop and use `RegistryGame` from the pure `registry.ts`.
*/
export async function loadMinigameRegistry(payload: Payload): Promise<BuiltinMinigame[]> {
const cached = readRegistryCache();
if (cached) return cached;
const rows = await fetchMinigameRegistry(payload);
// Only a real DB result is worth caching; the built-in fallback is used when
// the table is empty or the read failed, and should be retried next render.
if (rows.length > 0) writeRegistryCache(rows);
return rows.length > 0 ? rows : [...BUILTIN_MINIGAMES];
}
/**
* The registry is admin-edited configuration, but the layout loads it on every
* render (and the standings/lifecycle helpers load it again per call). A short
* TTL keeps a nav rename visible within half a minute while removing a query
* from every page render. `globalThis`-anchored so route bundles share it.
*/
const REGISTRY_TTL_MS = 30_000;
interface RegistryCacheEntry {
rows: BuiltinMinigame[];
loadedAt: number;
}
interface RegistryCacheHolder {
__ptfMinigameRegistry?: RegistryCacheEntry;
}
function readRegistryCache(): BuiltinMinigame[] | null {
const holder = globalThis as typeof globalThis & RegistryCacheHolder;
const entry = holder.__ptfMinigameRegistry;
if (!entry) return null;
if (Date.now() - entry.loadedAt >= REGISTRY_TTL_MS) return null;
return entry.rows;
}
function writeRegistryCache(rows: BuiltinMinigame[]): void {
const holder = globalThis as typeof globalThis & RegistryCacheHolder;
holder.__ptfMinigameRegistry = { rows, loadedAt: Date.now() };
}
/** Drop the cached registry (tests / after an admin write that must be instant). */
export function invalidateMinigameRegistryCache(): void {
const holder = globalThis as typeof globalThis & RegistryCacheHolder;
delete holder.__ptfMinigameRegistry;
}
async function fetchMinigameRegistry(payload: Payload): Promise<BuiltinMinigame[]> {
try {
const res = await payload.find({
collection: "minigames",
@ -46,7 +93,7 @@ export async function loadMinigameRegistry(payload: Payload): Promise<BuiltinMin
} catch {
// Fall through to the built-in list below.
}
return [...BUILTIN_MINIGAMES];
return [];
}
/**

View file

@ -110,7 +110,10 @@ export async function markAllNotificationsReadForUser(
): Promise<number[]> {
const found = await payload.find({
collection: "user-notifications",
where: { read: { equals: false } },
// Scope the predicate to the actor. The old unscoped `read: false` read up
// to 100 unread rows belonging to anyone (a low-selectivity scan of the
// table) and discarded most of them in JS.
where: { and: [{ user: { equals: actorUserId } }, { read: { equals: false } }] },
limit: 100,
depth: 0,
overrideAccess: true,

View file

@ -41,9 +41,14 @@ export function touchPresence(channel: string, participant: Omit<PresencePartici
const wasPresent = entries.has(participant.id);
const record = { ...participant, lastSeen: new Date(now).toISOString(), expiresAt: now + PRESENCE_TTL_MS };
entries.set(participant.id, record);
// A heartbeat only extends the TTL. Broadcasting an "update" to every
// subscriber on every 15s heartbeat made presence O(N^2) per channel (12
// players = 144 SSE messages per 15s) for a `lastSeen` no surface renders.
// Joins and leaves still broadcast, which is all the participant list needs.
if (wasPresent) return;
broadcast("presence", {
channel,
action: wasPresent ? "update" : "join",
action: "join",
participant: { id: record.id, name: record.name, lastSeen: record.lastSeen },
});
}

View file

@ -521,9 +521,14 @@ export default buildConfig({
db: postgresAdapter({
pool: {
connectionString: process.env.DATABASE_URI || "",
// Test workers cap the pg pool per boot (tests/vitest-worker-setup.ts
// sets TEST_PG_POOL_MAX); unset in dev/prod, zero behavior change there.
...(process.env.TEST_PG_POOL_MAX ? { max: Number(process.env.TEST_PG_POOL_MAX) } : {}),
// node-postgres defaults to 10 connections. A single page render issues
// ~12 queries and 10-12 concurrent users over a POST/SSE refresh burst
// saturate that, so renders queue on the pool instead of on Postgres.
// Test workers cap their own pool (tests/vitest-worker-setup.ts sets
// TEST_PG_POOL_MAX), which overrides this.
max: Number(process.env.TEST_PG_POOL_MAX ?? process.env.PG_POOL_MAX ?? 20),
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 10_000,
},
// push: process.env.NODE_ENV === "development",
// Env-gated drizzle push: only the test-database bootstrap (DB_PUSH=1) uses

View file

@ -208,7 +208,10 @@ export async function canAccessAdminPanel(
): Promise<boolean> {
if (!user) return false;
if (await canAccessAdminPanelByPermissions(payload, user)) return true;
for (const divisionCheck of Object.values(DIVISION_ADMIN_QUALIFICATIONS)) {
// Every entry in the map is currently the same predicate (intelligence owns
// all five tech collections), so dedupe the values: this was five identical
// qualification lookups per auth pass.
for (const divisionCheck of new Set(Object.values(DIVISION_ADMIN_QUALIFICATIONS))) {
if (await divisionCheck(payload, user)) return true;
}
return false;

View file

@ -1,5 +1,6 @@
import type { Payload } from "payload";
import { hasAnyPermission } from "@/utils/access-control/hasPermission";
import { loadQualificationFlags } from "@/utils/access-control/qualificationCache";
// Membership signals only. Read permissions (missions:read, campaigns:read,
// factions:read, technologies:read) must NOT appear here: the standard "user"
@ -31,29 +32,12 @@ export async function hasIntelligenceQualification(
if (await hasAnyPermission(payload, user, ...INTELLIGENCE_PERMISSIONS)) return true;
const profile = (await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
// Only qualifications are needed here. A deeper read recursively
// hydrates Profiles through progression.awards.awardedBy.
depth: 1,
limit: 1,
select: {
progression: {
qualifications: true,
},
},
})) as unknown as { docs: Array<any> };
// Cached + single-flight: `payload.auth()` calls this many times per request
// (once per division-gated collection operation), so the raw profile read
// must not run once per call. See qualificationCache.ts.
const userId = Number(user.id);
if (!Number.isFinite(userId)) return false;
const userProfile = profile.docs[0];
if (!userProfile || !userProfile.progression || !userProfile.progression.qualifications) {
return false;
}
return userProfile.progression.qualifications.some((qualification: any) => {
return typeof qualification === "string"
? qualification.toLowerCase() === "intelligence"
: qualification?.name?.toLowerCase() === "intelligence";
});
const flags = await loadQualificationFlags(payload, userId);
return flags.intelligence;
}

View file

@ -1,5 +1,6 @@
import type { Payload } from "payload";
import { hasAnyPermission } from "@/utils/access-control/hasPermission";
import { loadQualificationFlags } from "@/utils/access-control/qualificationCache";
const LOGISTICS_PERMISSIONS = [
"logistics:manage",
@ -59,26 +60,10 @@ export async function hasLogisticsQualification(
if (await hasAnyPermission(payload, user, ...LOGISTICS_PERMISSIONS)) return true;
const profileRes = await payload.find({
collection: "profiles",
where: { user: { equals: user.id as number } },
limit: 1,
depth: 1,
select: {
progression: {
qualifications: true,
},
},
});
// Cached + single-flight; see qualificationCache.ts.
const userId = Number(user.id);
if (!Number.isFinite(userId)) return false;
const profile = profileRes.docs[0];
if (!profile) return false;
const qualifications = profile.progression?.qualifications ?? [];
return qualifications.some((q) => {
if (typeof q === "object" && q !== null && "name" in q) {
return (q.name as string).toLowerCase().includes("logistics");
}
return false;
});
const flags = await loadQualificationFlags(payload, userId);
return flags.logistics;
}

View file

@ -9,7 +9,19 @@ interface CachedPermissions {
loadedAt: number;
}
const cache = new Map<number, CachedPermissions>();
/**
* `globalThis` anchor, like the SSE bus and the minigame/poker registries: Next
* bundles server packages per route entry, so a module-level Map forks into one
* copy per bundle and the 30s window is effectively never warm across routes.
*/
interface PermissionCacheRegistry {
__ptfPermissionCache?: Map<number, CachedPermissions>;
}
const permissionCacheRegistry = globalThis as typeof globalThis & PermissionCacheRegistry;
const cache = (permissionCacheRegistry.__ptfPermissionCache ??= new Map<
number,
CachedPermissions
>());
interface UserLike {
id: number | string;

View file

@ -0,0 +1,147 @@
import type { Payload } from "payload";
/**
* Per-user division qualification flags, cached for a short TTL.
*
* Why this exists: `payload.auth()` ends with `getAccessResults()`, which
* evaluates access for every collection and global. This app has ~100
* collections and several division-gated access functions that each fall back
* to a profiles read (`requireLogisticsPermission`, `requireIntelligencePermission`,
* `scopedAdminPageAccess`, the wiki field access, and `canAccessAdminPanel`'s
* division loop). That made a single auth pass issue ~31 identical
* `profiles where user = ?` queries, and every page renders auth at least twice
* (layout + page). Under 10-12 concurrent users the profile table became the
* hot spot and renders queued behind it.
*
* Both flags come from the same row and the same query, so they are resolved
* together and memoized:
* - for 30s (same window as `loadUserPermissions`), so a warm request costs no
* query at all;
* - single-flight per user, so the ~31 concurrent calls inside one auth pass
* collapse into one query instead of 31.
*
* The map is anchored on `globalThis` for the same reason as the permission
* cache and the SSE bus: Next bundles server packages per route in dev, and a
* module-level Map would fork into one copy per bundle, missing the cache from
* other entry points.
*
* Invalidation: qualification edits are rare and admin-driven, so the TTL is
* the bound. Call `invalidateQualificationCache(userId)` after a write that
* changes `progression.qualifications` when instant effect matters (tests).
*/
const CACHE_TTL_MS = 30_000;
export interface QualificationFlags {
intelligence: boolean;
logistics: boolean;
}
interface CacheEntry {
flags: QualificationFlags;
loadedAt: number;
}
interface QualificationCacheRegistry {
__ptfQualificationCache?: Map<number, CacheEntry>;
__ptfQualificationInflight?: Map<number, Promise<QualificationFlags>>;
}
const registry = globalThis as typeof globalThis & QualificationCacheRegistry;
const cache = (registry.__ptfQualificationCache ??= new Map<number, CacheEntry>());
const inflight = (registry.__ptfQualificationInflight ??= new Map<
number,
Promise<QualificationFlags>
>());
const NO_QUALIFICATIONS: QualificationFlags = { intelligence: false, logistics: false };
interface QualificationRef {
name?: unknown;
}
/**
* Mirrors the two predicates the callers used before this cache existed:
* - intelligence matches a qualification named exactly "intelligence"
* (string entries included);
* - logistics matches a relationship entry whose name contains "logistics".
*/
function flagsFromQualifications(raw: unknown): QualificationFlags {
if (!Array.isArray(raw)) return NO_QUALIFICATIONS;
let intelligence = false;
let logistics = false;
for (const entry of raw) {
if (typeof entry === "string") {
if (entry.toLowerCase() === "intelligence") intelligence = true;
continue;
}
if (!entry || typeof entry !== "object") continue;
const name = (entry as QualificationRef).name;
if (typeof name !== "string") continue;
const lower = name.toLowerCase();
if (lower === "intelligence") intelligence = true;
if (lower.includes("logistics")) logistics = true;
}
return { intelligence, logistics };
}
async function fetchQualificationFlags(
payload: Payload,
userId: number,
): Promise<QualificationFlags> {
const res = (await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
// depth 1 keeps the qualification relationships populated by name.
depth: 1,
select: { progression: { qualifications: true } },
})) as unknown as {
docs: Array<{ progression?: { qualifications?: unknown } | null }>;
};
return flagsFromQualifications(res.docs[0]?.progression?.qualifications);
}
/** Resolve a user's division qualifications, memoized for 30s. */
export async function loadQualificationFlags(
payload: Payload,
userId: number,
): Promise<QualificationFlags> {
if (!Number.isFinite(userId)) return NO_QUALIFICATIONS;
const cached = cache.get(userId);
if (cached && Date.now() - cached.loadedAt < CACHE_TTL_MS) {
return cached.flags;
}
const pending = inflight.get(userId);
if (pending) return pending;
const promise = fetchQualificationFlags(payload, userId)
// A failed lookup must not break access checks: fall through as "no
// qualifications", matching the previous per-call behavior.
.catch((): QualificationFlags => NO_QUALIFICATIONS)
.then((flags) => {
cache.set(userId, { flags, loadedAt: Date.now() });
inflight.delete(userId);
return flags;
});
inflight.set(userId, promise);
return promise;
}
/** Drop one user's cached flags, or the whole cache when no id is given. */
export function invalidateQualificationCache(userId?: number): void {
if (userId === undefined) {
cache.clear();
inflight.clear();
return;
}
cache.delete(userId);
}