Stage 2 of the int-suite speedup: pool=forks with fileParallelism and a default cap of 8 (VITEST_MAX_FORKS), each fork cloning the template into ptf_*_test_w<ID> via tests/vitest-worker-setup.ts; environment defaults to node with jsdom opt-in docblocks on the six DOM-consuming specs; a tiny reporter writes a failure marker so post-run cleanup keeps clones after red runs (KEEP_TEST_DBS=1 forces keeping); pg pools cap at TEST_PG_POOL_MAX=3 per boot in workers mode. Legacy serial mode stays reachable by setting TEST_DATABASE_URI. Notes from the gate G2 runs (Vitest 4.0.16): globalTeardown config was removed in Vitest 4 entirely - cleanup now returns from globalSetup. The pool scheduler only reuses worker processes when isolate:false, so this per-file-fork stage lands short of the wall-time target and is expected to be superseded by the gated isolate:false stage. Gate G2 warm serial equivalent stays green via TEST_DATABASE_URI bisect mode.
233 lines
8.3 KiB
TypeScript
233 lines
8.3 KiB
TypeScript
|
|
// Node realm on purpose: this drives the real http/ws server, and jose's
|
|
// key-type checks are realm-sensitive (a jsdom realm's Uint8Array intrinsics
|
|
// differ from the externalized jose module's).
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { WebSocket } from "ws";
|
|
import { SignJWT } from "jose";
|
|
import { INTER_ROUND_COUNTDOWN_TICKS, TICK_MS } from "@/lib/minigames/bomperator/constants";
|
|
import type { BomperatorView } from "@/lib/minigames/bomperator/types";
|
|
import type { ServerMessage } from "@/arena/protocol";
|
|
import { startArena, type ArenaHandle } from "@/arena/server";
|
|
|
|
/**
|
|
* End-to-end arena test: boots the real server on an ephemeral port with its
|
|
* wall-clock tick loop running, connects two real WebSocket clients with real
|
|
* minted tickets, plays a scripted round, and asserts snapshot progression +
|
|
* input application over the sockets. This is the proof the WS path works
|
|
* against the same module the unit suite pins.
|
|
*/
|
|
|
|
const TEST_SECRET = "test-arena-secret-0123456789";
|
|
|
|
let handle: ArenaHandle;
|
|
let base: string;
|
|
|
|
beforeAll(async () => {
|
|
handle = await startArena({ port: 0, secret: TEST_SECRET, autoTick: true });
|
|
base = `http://127.0.0.1:${handle.port}`;
|
|
}, 30_000);
|
|
|
|
afterAll(async () => {
|
|
await handle?.close();
|
|
});
|
|
|
|
async function mintTicket(uid: number, matchId: string): Promise<string> {
|
|
// Buffer key: realm-safe under vitest's jsdom (see src/arena/tickets.ts).
|
|
const key = Buffer.from(TEST_SECRET, "utf8");
|
|
return new SignJWT({ uid, matchId })
|
|
.setProtectedHeader({ alg: "HS256" })
|
|
.setIssuedAt()
|
|
.setExpirationTime("30s")
|
|
.sign(key);
|
|
}
|
|
|
|
interface Envelope<T> {
|
|
success: boolean;
|
|
data?: T;
|
|
error?: string;
|
|
}
|
|
|
|
async function arenaPost<T>(path: string, body: unknown): Promise<Envelope<T>> {
|
|
const response = await fetch(`${base}${path}`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-arena-secret": TEST_SECRET },
|
|
body: JSON.stringify(body),
|
|
});
|
|
return (await response.json()) as Envelope<T>;
|
|
}
|
|
|
|
/** A connected socket that records every server frame it receives. */
|
|
class TestClient {
|
|
readonly ws: WebSocket;
|
|
readonly messages: ServerMessage[] = [];
|
|
private waiters: Array<() => void> = [];
|
|
|
|
constructor(ws: WebSocket) {
|
|
this.ws = ws;
|
|
ws.on("message", (raw: Buffer) => {
|
|
this.messages.push(JSON.parse(raw.toString("utf8")) as ServerMessage);
|
|
for (const wake of this.waiters.splice(0)) wake();
|
|
});
|
|
}
|
|
|
|
snapshots(): BomperatorView[] {
|
|
return this.messages
|
|
.filter((m): m is Extract<ServerMessage, { t: "snapshot" }> => m.t === "snapshot")
|
|
.map((m) => m.view);
|
|
}
|
|
|
|
latest(): BomperatorView | undefined {
|
|
const all = this.snapshots();
|
|
return all[all.length - 1];
|
|
}
|
|
|
|
send(message: object): void {
|
|
this.ws.send(JSON.stringify(message));
|
|
}
|
|
|
|
/** Resolve on the next frame matching the predicate (already-arrived ones count). */
|
|
async waitForFrame(predicate: (m: ServerMessage) => boolean, timeoutMs = 10_000): Promise<ServerMessage> {
|
|
const deadline = Date.now() + timeoutMs;
|
|
for (;;) {
|
|
const found = this.messages.find(predicate);
|
|
if (found) return found;
|
|
if (Date.now() > deadline) throw new Error("timed out waiting for frame");
|
|
await new Promise<void>((resolve) => {
|
|
const timer = setTimeout(resolve, Math.min(50, deadline - Date.now()));
|
|
this.waiters.push(() => {
|
|
clearTimeout(timer);
|
|
resolve();
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Resolve once a snapshot with version > `above` arrives. */
|
|
async nextSnapshot(above: number, timeoutMs = 10_000): Promise<BomperatorView> {
|
|
const frame = await this.waitForFrame(
|
|
(m) => m.t === "snapshot" && m.view.version > above,
|
|
timeoutMs,
|
|
);
|
|
return (frame as Extract<ServerMessage, { t: "snapshot" }>).view;
|
|
}
|
|
|
|
close(): void {
|
|
this.ws.close();
|
|
}
|
|
}
|
|
|
|
async function connectClient(uid: number, matchId: string, ticket?: string): Promise<TestClient> {
|
|
const jwt = ticket ?? (await mintTicket(uid, matchId));
|
|
const ws = new WebSocket(`${base.replace("http", "ws")}/ws?ticket=${jwt}`);
|
|
const client = new TestClient(ws);
|
|
await new Promise<void>((resolve, reject) => {
|
|
ws.once("open", resolve);
|
|
ws.once("error", () => reject(new Error("socket rejected")));
|
|
ws.once("close", () => reject(new Error("socket closed during handshake")));
|
|
});
|
|
client.send({ t: "join" });
|
|
return client;
|
|
}
|
|
|
|
describe("arena server over real websockets", () => {
|
|
it(
|
|
"plays a scripted round: join, start, tick progression, input application, ping",
|
|
async () => {
|
|
// Health first.
|
|
const health = await fetch(`${base}/health`);
|
|
expect(health.ok).toBe(true);
|
|
|
|
// Lifecycle through the REST surface (what the Next actions proxy to).
|
|
const created = await arenaPost<{ matchId: string }>("/matches", {
|
|
userId: 7001,
|
|
name: "Host",
|
|
roundTarget: 1,
|
|
});
|
|
expect(created.success).toBe(true);
|
|
const matchId = created.data!.matchId;
|
|
|
|
const joined = await arenaPost<BomperatorView>("/matches/join", {
|
|
matchId,
|
|
userId: 7002,
|
|
name: "Guest",
|
|
});
|
|
expect(joined.success).toBe(true);
|
|
expect(joined.data!.players).toHaveLength(2);
|
|
|
|
const started = await arenaPost<BomperatorView>("/matches/start", {
|
|
matchId,
|
|
userId: 7001,
|
|
});
|
|
expect(started.success).toBe(true);
|
|
expect(started.data!.phase).toBe("countdown");
|
|
|
|
// Two real sockets with real tickets.
|
|
const host = await connectClient(7001, matchId);
|
|
const guest = await connectClient(7002, matchId);
|
|
|
|
const first = await host
|
|
.waitForFrame((m) => m.t === "snapshot")
|
|
.then((f) => (f as Extract<ServerMessage, { t: "snapshot" }>).view);
|
|
expect(first.yourSeat).toBe(0);
|
|
expect(["countdown", "battle"]).toContain(first.phase);
|
|
|
|
// Snapshot progression: the wall-clock loop advances versions on its own.
|
|
const progressed = await host.nextSnapshot(first.version);
|
|
expect(progressed.version).toBeGreaterThan(first.version);
|
|
|
|
// Wait for the countdown to end (real time, ~3s at 20 Hz).
|
|
let view = progressed;
|
|
const battleDeadline = Date.now() + (INTER_ROUND_COUNTDOWN_TICKS + 60) * TICK_MS;
|
|
while (view.phase !== "battle" && Date.now() < battleDeadline) {
|
|
view = await host.nextSnapshot(view.version);
|
|
}
|
|
expect(view.phase).toBe("battle");
|
|
|
|
// Input over the socket: move right, expect ack and applied movement.
|
|
const seq = 7;
|
|
const beforeX = view.players[0]!.x;
|
|
host.send({ t: "input", dir: "right", seq });
|
|
const ack = await host.waitForFrame((m) => m.t === "ack" && m.seq === seq);
|
|
expect(ack.t).toBe("ack");
|
|
|
|
// Poll snapshots until the move shows up in server truth (movement is
|
|
// grid-locked: leaving the spawn cell takes a few ticks).
|
|
let moved = view;
|
|
const moveDeadline = Date.now() + 3_000;
|
|
while (Date.now() < moveDeadline) {
|
|
moved = await host.nextSnapshot(moved.version);
|
|
if (moved.players[0]!.x > beforeX + 0.2 && (moved.players[0]!.lastInputSeq ?? 0) >= seq) break;
|
|
}
|
|
expect(moved.players[0]!.x).toBeGreaterThan(beforeX + 0.2);
|
|
expect(moved.players[0]!.lastInputSeq).toBeGreaterThanOrEqual(seq);
|
|
|
|
// Guest sees the host move too (fan-out to both sockets).
|
|
let guestView = guest.latest()!;
|
|
const guestDeadline = Date.now() + 3_000;
|
|
while (guestView.players[0]!.x <= beforeX + 0.2 && Date.now() < guestDeadline) {
|
|
guestView = await guest.nextSnapshot(guestView.version);
|
|
}
|
|
expect(guestView.players[0]!.x).toBeGreaterThan(beforeX + 0.2);
|
|
|
|
// Ping/pong RTT probe echoes the client timestamp.
|
|
const t0 = Date.now();
|
|
host.send({ t: "ping", ts: t0 });
|
|
const pong = await host.waitForFrame((m) => m.t === "pong");
|
|
expect(pong.t === "pong" && pong.ts).toBe(t0);
|
|
|
|
host.close();
|
|
guest.close();
|
|
},
|
|
60_000,
|
|
);
|
|
|
|
it("rejects an unverifiable ticket at connect time", async () => {
|
|
await expect(connectClient(7001, "00000000-0000-4000-8000-000000000000", "garbage")).rejects.toThrow();
|
|
});
|
|
|
|
it("refuses REST calls without the shared secret", async () => {
|
|
const response = await fetch(`${base}/matches`, { method: "POST", body: "{}" });
|
|
expect(response.status).toBe(401);
|
|
});
|
|
});
|