1
0
Fork 0
polaris-task-force/src/components/frontend/baseManagement/SlotsPanel.tsx
Z8MB1E a0f767cc13 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.
2026-11-22 22:39:10 -05:00

149 lines
5.2 KiB
TypeScript

"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
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 { installModule, uninstallModule } from "@/app/(frontend)/logistics/base/actions";
export interface ModuleEffectLine {
readonly type: string;
readonly value: number;
}
export interface ModuleOptionLine {
readonly name: string;
readonly category: string;
readonly description: string | null;
readonly effects: readonly ModuleEffectLine[];
readonly materials: readonly { name: string; amount: number }[];
}
export interface SlotsPanelProps {
readonly gameStructureId: number;
readonly slots: number;
readonly installed: readonly { name: string; installedAt: string | null }[];
readonly options: readonly ModuleOptionLine[];
readonly canManage: boolean;
}
const EFFECT_LABELS: Record<string, (value: number) => string> = {
capacity_mass: (value) => `+${value.toLocaleString()} kg storage`,
storage_slots: (value) => `+${value} grid slots`,
production_multiplier: (value) => `+${Math.round(value * 100)}% production`,
};
function effectLabel(effect: ModuleEffectLine): string {
const formatter = EFFECT_LABELS[effect.type];
return formatter ? formatter(effect.value) : `${effect.type} ${effect.value}`;
}
export function SlotsPanel({
gameStructureId,
slots,
installed,
options,
canManage,
}: SlotsPanelProps) {
const router = useRouter();
const [loading, setLoading] = useState<string | null>(null);
if (slots <= 0 && options.length === 0 && installed.length === 0) return null;
const run = async (action: typeof installModule, moduleName: string, successMessage: string) => {
setLoading(moduleName);
try {
const result = await action(gameStructureId, moduleName);
if (result.success) {
toast.success(successMessage);
router.refresh();
} else {
toast.error(result.error ?? "Could not change modules.");
}
} finally {
setLoading(null);
}
};
const installedNames = new Set(installed.map((entry) => entry.name));
const available = slots - installed.length;
return (
<Item className="rounded-none">
<ItemContent>
<div className="flex items-center justify-between gap-3">
<ItemTitle className="flex items-center gap-2">
<Blocks className="size-4 text-muted-foreground" />
Modules
</ItemTitle>
<span
className={`text-xs tabular-nums ${available > 0 ? "text-muted-foreground" : "text-amber-400"}`}
>
{installed.length} / {slots} slots
</span>
</div>
{installed.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{installed.map((entry) => (
<Badge key={entry.name} variant="outline" className="gap-1 pr-1">
{entry.name}
{canManage && (
<button
type="button"
aria-label={`Uninstall ${entry.name}`}
disabled={loading !== null}
onClick={() => run(uninstallModule, entry.name, `${entry.name} uninstalled.`)}
className="ml-0.5 rounded-sm p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground"
>
<X className="size-3" />
</button>
)}
</Badge>
))}
</div>
)}
{canManage && available > 0 && options.length > 0 && (
<div className="flex flex-col gap-1.5">
{options
.filter((option) => !installedNames.has(option.name))
.map((option) => (
<div
key={option.name}
className="flex items-center justify-between gap-3 rounded-md bg-muted/40 px-3 py-2"
>
<div className="min-w-0">
<p className="truncate text-sm">{option.name}</p>
<p className="truncate text-xs text-muted-foreground">
{option.effects.map(effectLabel).join(", ") || "No effects"}
{option.materials.length > 0 &&
` | needs ${option.materials
.map((material) => `${material.amount} ${material.name}`)
.join(", ")}`}
</p>
</div>
<Button
size="sm"
variant="outline"
disabled={loading !== null}
onClick={() => run(installModule, option.name, `${option.name} installed.`)}
>
<Plus className="size-3.5" />
Install
</Button>
</div>
))}
</div>
)}
{slots > 0 && installed.length === 0 && options.length === 0 && (
<ItemDescription>No modules are defined for this structure type.</ItemDescription>
)}
</ItemContent>
</Item>
);
}