diff --git a/src/app/(frontend)/layout.tsx b/src/app/(frontend)/layout.tsx index 7bfa289b..d047a35a 100644 --- a/src/app/(frontend)/layout.tsx +++ b/src/app/(frontend)/layout.tsx @@ -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; 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 } }, diff --git a/src/app/(frontend)/logistics/supply-boxes/page.tsx b/src/app/(frontend)/logistics/supply-boxes/page.tsx index 8694f002..a6263bc7 100644 --- a/src/app/(frontend)/logistics/supply-boxes/page.tsx +++ b/src/app/(frontend)/logistics/supply-boxes/page.tsx @@ -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() {

- - {data.capability === false ? ( - {aar === null ? ( - - -

Live and historical operation activity: extraction returns, settlements, readiness diff --git a/src/collections/Shims.ts b/src/collections/Shims.ts index 98cc768a..735603da 100644 --- a/src/collections/Shims.ts +++ b/src/collections/Shims.ts @@ -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", diff --git a/src/collections/game/GameRules.ts b/src/collections/game/GameRules.ts index a5033f86..79f2e655 100644 --- a/src/collections/game/GameRules.ts +++ b/src/collections/game/GameRules.ts @@ -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", diff --git a/src/collections/minigames/Minigames.ts b/src/collections/minigames/Minigames.ts index cdf1b015..38e0e949 100644 --- a/src/collections/minigames/Minigames.ts +++ b/src/collections/minigames/Minigames.ts @@ -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", diff --git a/src/collections/users/Profiles.ts b/src/collections/users/Profiles.ts index cd76010a..b579fba4 100644 --- a/src/collections/users/Profiles.ts +++ b/src/collections/users/Profiles.ts @@ -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 }); } }, diff --git a/src/components/frontend/baseManagement/ProductionPanel.tsx b/src/components/frontend/baseManagement/ProductionPanel.tsx index 61a0206a..46834af4 100644 --- a/src/components/frontend/baseManagement/ProductionPanel.tsx +++ b/src/components/frontend/baseManagement/ProductionPanel.tsx @@ -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; diff --git a/src/components/frontend/baseManagement/SlotsPanel.tsx b/src/components/frontend/baseManagement/SlotsPanel.tsx index 4fdb0a71..f4fb53cc 100644 --- a/src/components/frontend/baseManagement/SlotsPanel.tsx +++ b/src/components/frontend/baseManagement/SlotsPanel.tsx @@ -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(null); - useGameTick(() => router.refresh()); if (slots <= 0 && options.length === 0 && installed.length === 0) return null; diff --git a/src/components/frontend/blocks/NavCore.tsx b/src/components/frontend/blocks/NavCore.tsx index 70587be3..c141db27 100644 --- a/src/components/frontend/blocks/NavCore.tsx +++ b/src/components/frontend/blocks/NavCore.tsx @@ -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 ( {label} @@ -65,7 +70,7 @@ export function NavCore({ {item.items?.map((subItem) => ( - + {subItem.icon ? : null} {subItem.title} @@ -77,7 +82,7 @@ export function NavCore({ ) : ( - + {item.title} diff --git a/src/components/frontend/intelligence/MissionReminderToasts.tsx b/src/components/frontend/intelligence/MissionReminderToasts.tsx index 7b36dec4..6bef1f5c 100644 --- a/src/components/frontend/intelligence/MissionReminderToasts.tsx +++ b/src/components/frontend/intelligence/MissionReminderToasts.tsx @@ -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); diff --git a/src/components/frontend/logistics/ShipmentToasts.tsx b/src/components/frontend/logistics/ShipmentToasts.tsx index 699bc1ce..519ce03b 100644 --- a/src/components/frontend/logistics/ShipmentToasts.tsx +++ b/src/components/frontend/logistics/ShipmentToasts.tsx @@ -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; diff --git a/src/components/frontend/minigames/ChipBankCard.tsx b/src/components/frontend/minigames/ChipBankCard.tsx index 7d732d8e..47a016d3 100644 --- a/src/components/frontend/minigames/ChipBankCard.tsx +++ b/src/components/frontend/minigames/ChipBankCard.tsx @@ -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]); diff --git a/src/components/frontend/notifications/NotificationsBell.tsx b/src/components/frontend/notifications/NotificationsBell.tsx index 7af59589..6c995fbf 100644 --- a/src/components/frontend/notifications/NotificationsBell.tsx +++ b/src/components/frontend/notifications/NotificationsBell.tsx @@ -81,6 +81,7 @@ export function NotificationsBell() { const [scope, setScope] = useState(readStoredScope); const [canViewOthers, setCanViewOthers] = useState(false); const intervalRef = useRef | null>(null); + const eventTimerRef = useRef | 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]); diff --git a/src/components/frontend/operations/OperationsRealtimeRefresher.tsx b/src/components/frontend/operations/OperationsRealtimeRefresher.tsx deleted file mode 100644 index 0110f93b..00000000 --- a/src/components/frontend/operations/OperationsRealtimeRefresher.tsx +++ /dev/null @@ -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; -} diff --git a/src/components/frontend/operations/index.ts b/src/components/frontend/operations/index.ts index 9907b6d4..3e5d49ef 100644 --- a/src/components/frontend/operations/index.ts +++ b/src/components/frontend/operations/index.ts @@ -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, diff --git a/src/components/frontend/realtime/GameTickRealtime.tsx b/src/components/frontend/realtime/GameTickRealtime.tsx index 93214a51..fffc80ff 100644 --- a/src/components/frontend/realtime/GameTickRealtime.tsx +++ b/src/components/frontend/realtime/GameTickRealtime.tsx @@ -39,13 +39,40 @@ export function GameTickRealtime() { useEffect(() => { const source = new EventSource("/api/realtime"); let refreshTimer: ReturnType | 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]); diff --git a/src/components/frontend/storage/EventLedger.tsx b/src/components/frontend/storage/EventLedger.tsx index 066e2701..fd25a9dd 100644 --- a/src/components/frontend/storage/EventLedger.tsx +++ b/src/components/frontend/storage/EventLedger.tsx @@ -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(); }); diff --git a/src/lib/config-cache.ts b/src/lib/config-cache.ts new file mode 100644 index 00000000..c4e5881a --- /dev/null +++ b/src/lib/config-cache.ts @@ -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; + __ptfConfigInflight?: Map>; +} + +function holder(): CacheHolder { + return globalThis as typeof globalThis & CacheHolder; +} + +function entries(): Map { + const store = holder(); + return (store.__ptfConfigCache ??= new Map()); +} + +function inflight(): Map> { + const store = holder(); + return (store.__ptfConfigInflight ??= new Map>()); +} + +export async function cachedConfig( + key: string, + load: () => Promise, + ttlMs: number = DEFAULT_TTL_MS, +): Promise { + 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; + + 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); + 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); +} diff --git a/src/lib/contributions/index.ts b/src/lib/contributions/index.ts index 76b8e6b6..eadd015c 100644 --- a/src/lib/contributions/index.ts +++ b/src/lib/contributions/index.ts @@ -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 { - 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 { - if (sourceCollection === "manual") return true; +async function resolveUserNames(payload: Payload, userIds: number[]): Promise> { + const names = new Map(); + 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> { + const idsByCollection = new Map, Set>(); + for (const entry of entries) { + if (entry.sourceCollection === "manual") continue; + const collection = entry.sourceCollection; + let ids = idsByCollection.get(collection); + if (!ids) { + ids = new Set(); + idsByCollection.set(collection, ids); + } + ids.add(entry.sourceId); + } + + const surviving = new Set(); + 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 { - 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(); + 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). */ diff --git a/src/lib/minigames/loadRegistry.ts b/src/lib/minigames/loadRegistry.ts index 84cfda0a..fa5af41e 100644 --- a/src/lib/minigames/loadRegistry.ts +++ b/src/lib/minigames/loadRegistry.ts @@ -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 { + 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 { try { const res = await payload.find({ collection: "minigames", @@ -46,7 +93,7 @@ export async function loadMinigameRegistry(payload: Payload): Promise { 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, diff --git a/src/lib/realtime/presence.ts b/src/lib/realtime/presence.ts index 20d8aca4..ed50156d 100644 --- a/src/lib/realtime/presence.ts +++ b/src/lib/realtime/presence.ts @@ -41,9 +41,14 @@ export function touchPresence(channel: string, participant: Omit { 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; diff --git a/src/utils/access-control/hasIntelligenceQualification.ts b/src/utils/access-control/hasIntelligenceQualification.ts index 6acc5d70..1b9c25ec 100644 --- a/src/utils/access-control/hasIntelligenceQualification.ts +++ b/src/utils/access-control/hasIntelligenceQualification.ts @@ -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 }; + // 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; } diff --git a/src/utils/access-control/hasLogisticsQualification.ts b/src/utils/access-control/hasLogisticsQualification.ts index abca30d4..b121de35 100644 --- a/src/utils/access-control/hasLogisticsQualification.ts +++ b/src/utils/access-control/hasLogisticsQualification.ts @@ -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; } diff --git a/src/utils/access-control/loadUserPermissions.ts b/src/utils/access-control/loadUserPermissions.ts index 33babb1a..78c92804 100644 --- a/src/utils/access-control/loadUserPermissions.ts +++ b/src/utils/access-control/loadUserPermissions.ts @@ -9,7 +9,19 @@ interface CachedPermissions { loadedAt: number; } -const cache = new Map(); +/** + * `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; +} +const permissionCacheRegistry = globalThis as typeof globalThis & PermissionCacheRegistry; +const cache = (permissionCacheRegistry.__ptfPermissionCache ??= new Map< + number, + CachedPermissions +>()); interface UserLike { id: number | string; diff --git a/src/utils/access-control/qualificationCache.ts b/src/utils/access-control/qualificationCache.ts new file mode 100644 index 00000000..f4ee6634 --- /dev/null +++ b/src/utils/access-control/qualificationCache.ts @@ -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; + __ptfQualificationInflight?: Map>; +} + +const registry = globalThis as typeof globalThis & QualificationCacheRegistry; +const cache = (registry.__ptfQualificationCache ??= new Map()); +const inflight = (registry.__ptfQualificationInflight ??= new Map< + number, + Promise +>()); + +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 { + 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 { + 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); +}