Adds a dedicated Node 22 + ws arena server (src/arena) that owns live Ordnance Disposal matches: drift-corrected 20Hz tick loop with capped catch-up and tick-drift logging, per-socket snapshot fan-out, 30s jose ticket auth, and awards via the idempotent results callback route. Client gains a transport abstraction (transport.ts): WsTransport first when NEXT_PUBLIC_ARENA_URL is baked into the bundle, HttpTransport (today's actions + SSE + guarded poll, behavior unchanged) as automatic fallback after two connection failures or a 5s setup timeout; absent env var means pure HTTP (kill switch / rollback path). Next actions proxy the match lifecycle to the arena when ARENA_SECRET + ARENA_INTERNAL_URL are set; the in-process registry stays untouched as the default backend. Deploy wiring: runner-arena Dockerfile target, compose service, env docs, DEPLOYMENT.md checklist. Tests: arena module suite (19), live server WS suite (3), prediction harness ws-grade latency scenario.
251 lines
8.1 KiB
TypeScript
251 lines
8.1 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import {
|
|
endBomperatorMatch,
|
|
fetchBomperatorMatch,
|
|
leaveBomperatorMatch,
|
|
startBomperatorMatch,
|
|
type BomperatorView,
|
|
} from "@/app/(frontend)/minigames/bomperator/actions";
|
|
import { toast } from "sonner";
|
|
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
|
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
|
import { BomperatorLobby } from "./BomperatorLobby";
|
|
import { BomperatorGame } from "./BomperatorGame";
|
|
import {
|
|
createBomperatorTransport,
|
|
type BomperatorTransport,
|
|
type TransportKind,
|
|
} from "./transport";
|
|
|
|
export interface BomperatorStats {
|
|
matchesPlayed: number;
|
|
matchWins: number;
|
|
roundsWon: number;
|
|
kills: number;
|
|
xpEarned: number;
|
|
}
|
|
|
|
const STAT_ITEMS = [
|
|
["Drills run", "matchesPlayed"],
|
|
["Drills won", "matchWins"],
|
|
["Rounds won", "roundsWon"],
|
|
["Technicians down", "kills"],
|
|
["XP earned", "xpEarned"],
|
|
] as const satisfies readonly (readonly [string, keyof BomperatorStats])[];
|
|
|
|
type ArenaView = "lobby" | "match";
|
|
|
|
export function BomperatorArena({
|
|
initialStats,
|
|
currentUserId,
|
|
initialMatchId,
|
|
}: {
|
|
initialStats: BomperatorStats;
|
|
currentUserId: number | string;
|
|
initialMatchId?: string;
|
|
}) {
|
|
const [view, setView] = useState<ArenaView>(initialMatchId ? "match" : "lobby");
|
|
const [match, setMatch] = useState<BomperatorView | null>(null);
|
|
const [matchId, setMatchId] = useState<string | null>(initialMatchId ?? null);
|
|
const [error, setError] = useState<string | null>(null);
|
|
/** Highest snapshot version applied; drops stale pushes/polls that arrive late. */
|
|
const lastVersionRef = useRef(-1);
|
|
/** Once we've handled leaving a match (self or remote), suppress repeat toasts. */
|
|
const endedRef = useRef(false);
|
|
|
|
const resetToLobby = useCallback(() => {
|
|
lastVersionRef.current = -1;
|
|
setView("lobby");
|
|
setMatch(null);
|
|
setMatchId(null);
|
|
setError(null);
|
|
if (typeof window !== "undefined") {
|
|
window.history.replaceState(null, "", "/minigames/bomperator");
|
|
}
|
|
}, []);
|
|
|
|
/** Apply a snapshot from any source (push or poll), ignoring stale versions. */
|
|
const applySnapshot = useCallback((next: BomperatorView) => {
|
|
if (next.version <= lastVersionRef.current) return;
|
|
lastVersionRef.current = next.version;
|
|
setMatch(next);
|
|
setMatchId(next.matchId);
|
|
setView("match");
|
|
setError(null);
|
|
}, []);
|
|
|
|
const applyMatch = useCallback((next: BomperatorView) => {
|
|
// Fresh match opened from the lobby: accept it regardless of version history.
|
|
endedRef.current = false;
|
|
lastVersionRef.current = next.version;
|
|
setMatch(next);
|
|
setMatchId(next.matchId);
|
|
setView("match");
|
|
setError(null);
|
|
if (typeof window !== "undefined" && next.matchId) {
|
|
window.history.replaceState(
|
|
null,
|
|
"",
|
|
`/minigames/bomperator?match=${encodeURIComponent(next.matchId)}`,
|
|
);
|
|
}
|
|
}, []);
|
|
|
|
/**
|
|
* Leave the current match with an explanatory toast, at most once per match.
|
|
* Used by both the host-ended SSE event and the poll's "not found" fallback, so
|
|
* whichever lands first wins and the other is ignored.
|
|
*/
|
|
const handleEnded = useCallback(
|
|
(message: string) => {
|
|
if (endedRef.current) return;
|
|
endedRef.current = true;
|
|
toast.info(message);
|
|
resetToLobby();
|
|
},
|
|
[resetToLobby],
|
|
);
|
|
|
|
// Deep link into a match (as a player or a spectator).
|
|
useEffect(() => {
|
|
if (!initialMatchId) return;
|
|
let cancelled = false;
|
|
void fetchBomperatorMatch(initialMatchId)
|
|
.then((result) => {
|
|
if (cancelled) return;
|
|
if (result.success && result.data) {
|
|
endedRef.current = false;
|
|
applySnapshot(result.data);
|
|
if (typeof window !== "undefined") {
|
|
window.history.replaceState(
|
|
null,
|
|
"",
|
|
`/minigames/bomperator?match=${encodeURIComponent(initialMatchId)}`,
|
|
);
|
|
}
|
|
} else {
|
|
setError(result.error ?? "This match was not found.");
|
|
}
|
|
})
|
|
.catch(() => undefined);
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [initialMatchId, applySnapshot]);
|
|
|
|
/* ---- snapshot delivery: one transport, WS-first with HTTP fallback ---- */
|
|
|
|
const [transport, setTransport] = useState<BomperatorTransport | null>(null);
|
|
/** Surfaced as a data-attribute for prod verification ("transport=ws"). */
|
|
const [transportKind, setTransportKind] = useState<TransportKind>("http");
|
|
|
|
useEffect(() => {
|
|
if (view !== "match" || matchId === null) return;
|
|
// The transport owns every snapshot source: SSE bus + guarded poll on HTTP,
|
|
// the arena socket on WS (see ./transport.ts). Version dedup in
|
|
// applySnapshot keeps them consistent however they interleave.
|
|
const next = createBomperatorTransport(matchId);
|
|
const offSnapshot = next.onSnapshot(applySnapshot);
|
|
const offTerminated = next.onTerminated((info) => {
|
|
const message =
|
|
info.reason === "host-ended"
|
|
? info.hostName
|
|
? `${info.hostName} ended the drill.`
|
|
: "The host ended the drill."
|
|
: "This drill has ended.";
|
|
handleEnded(message);
|
|
});
|
|
const offKind = next.onKindChange?.(setTransportKind);
|
|
setTransportKind(next.kind);
|
|
setTransport(next);
|
|
next.start();
|
|
return () => {
|
|
offSnapshot();
|
|
offTerminated();
|
|
offKind?.();
|
|
next.close();
|
|
setTransport(null);
|
|
};
|
|
}, [view, matchId, applySnapshot, handleEnded]);
|
|
|
|
const start = useCallback(async () => {
|
|
if (!matchId) return;
|
|
const result = await startBomperatorMatch(matchId);
|
|
if (result.success && result.data) applySnapshot(result.data);
|
|
else setError(result.error ?? "Could not start the drill.");
|
|
}, [matchId, applySnapshot]);
|
|
|
|
const leave = useCallback(async () => {
|
|
endedRef.current = true; // self-initiated exit: no "ended" toast for us
|
|
if (matchId) {
|
|
try {
|
|
await leaveBomperatorMatch(matchId);
|
|
} catch {
|
|
// Leaving is best-effort; resetting the view is what matters.
|
|
}
|
|
}
|
|
resetToLobby();
|
|
}, [matchId, resetToLobby]);
|
|
|
|
const end = useCallback(async () => {
|
|
endedRef.current = true; // we are the host ending it; no toast for us
|
|
if (matchId) {
|
|
try {
|
|
await endBomperatorMatch(matchId);
|
|
} catch {
|
|
// Best-effort; the host is leaving regardless.
|
|
}
|
|
}
|
|
resetToLobby();
|
|
}, [matchId, resetToLobby]);
|
|
|
|
const inMatch = view === "match" && matchId !== null;
|
|
const operatorsOnline = useRealtimePresence("bomperator", inMatch, true);
|
|
|
|
return (
|
|
<div className="flex flex-col gap-6" data-transport={inMatch ? transportKind : undefined}>
|
|
<Card>
|
|
<CardHeader className="border-b p-4">
|
|
<CardTitle className="text-sm">Your disposal record</CardTitle>
|
|
<p className="text-sm text-muted-foreground">
|
|
Rewards are granted when a drill ends. Free-for-all, 2-8 technicians.
|
|
</p>
|
|
</CardHeader>
|
|
<CardContent className="grid grid-cols-2 gap-3 p-4 sm:grid-cols-5">
|
|
{STAT_ITEMS.map(([label, key]) => (
|
|
<div key={key} className="flex flex-col gap-1 rounded-lg border border-border p-3">
|
|
<span className="text-xs uppercase tracking-wider text-muted-foreground">{label}</span>
|
|
<span className="font-mono text-lg font-semibold tabular-nums">
|
|
{initialStats[key].toLocaleString()}
|
|
</span>
|
|
</div>
|
|
))}
|
|
</CardContent>
|
|
</Card>
|
|
|
|
{error && (
|
|
<p className="text-sm text-destructive" role="alert">
|
|
{error}
|
|
</p>
|
|
)}
|
|
|
|
{view === "lobby" ? (
|
|
<BomperatorLobby onOpenMatch={applyMatch} currentUserId={currentUserId} />
|
|
) : match && transport ? (
|
|
<BomperatorGame
|
|
match={match}
|
|
transport={transport}
|
|
currentUserId={currentUserId}
|
|
onLeave={leave}
|
|
onEnd={end}
|
|
onStart={start}
|
|
operatorsOnline={operatorsOnline.map((participant) => participant.name)}
|
|
/>
|
|
) : (
|
|
<p className="text-sm text-muted-foreground">Loading match…</p>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|