mirror of
https://github.com/openfrontio/OpenFrontIO.git
synced 2026-07-22 16:37:31 +00:00
## Description: Implements 2v2 ranked matchmaking end-to-end against the matchmaking API's 2v2 queues (API PR #419): core team pinning, the server's second checkin loop and game creation, and the client UI. ## Core — deterministic team pinning The matcher's assignment specifies exactly who plays with whom (`teams: [[a,d],[b,c]]`), but team assignment previously only did clan/friend balancing and could scramble the ELO-balanced split. - `PlayerSchema`/`PlayerInfo` gain an optional **`teamIndex`** — a server-stamped index into the game's team list, part of `GameStartInfo` so it's identical on every client (same category as `clanTag`/`friends`, which already feed deterministic team assignment). - `assignTeams` honors pins **unconditionally** — before clan/friend grouping and past `maxTeamSize` (the matcher's balancing is authoritative) — and seeds the counts that balancing of any unpinned players sees. Pinned players still participate in the friend graph, so an unpinned friend is pulled toward a pinned player's team. - publicIds never enter core: the game server resolves publicId → teamIndex per client at game start. ## Server - **One checkin long-poll per mode.** Both loops send `mode` explicitly (the API deployed ahead of the client, so no omit-for-back-compat needed). - **`get2v2Config()`**: Team mode, `playerTeams: 2`, `maxPlayers: 4`, always-compact map, donations enabled (matching public team games), `rankedType: "2v2"` (the API's 2v2 ingestion has shipped; `RankedType` gains `TwoVTwo`). - **The assignment payload is now used** (it was previously discarded): `players` → `allowedPublicIds` so only the matched accounts can take the slots (also hardens 1v1), and `teams` → `teamIndex` stamps at game start. A malformed assignment logs a warning and falls back to creating the game without pins rather than stranding matched players. - The 3-clients-per-IP cap on public games applies to matchmade games too (an allowlist doesn't stop one person multi-tabbing multiple accounts). It is now skipped in dev, where local testing (multi-tab, the 4-player e2e) is inherently same-IP — matching the existing dev/prod gating of Turnstile and the duplicate-account kick. ## Client - Ranked modal's 2v2 card is enabled; it passes the mode through `open-matchmaking` (dispatchers without a detail — homepage button, requeue URL — still mean 1v1). - Matchmaking modal joins with `&mode=1v1`/`&mode=2v2`, shows a 2v2 title (`matchmaking_modal.title_2v2` in en.json), and shows the real 2v2 ELO from the new `leaderboard.twoVtwo` field in `/users/@me` (the ranked modal's 2v2 card does too). - WinModal shows requeue for any ranked game and carries the mode back into the right queue (`/?requeue=2v2`). - 2v2 ranked stats surface in the player stats tree (labeled via `player_stats_tree.ranked_2v2`). ## Harnesses (`tests/matchmaking/`) - Contained: the fake server captures the `mode` query param; asserts each queue sends its mode explicitly. **10/10.** - E2E: `MM_MODE=2v2` runs four real browser players through the real local worker's 2v2 queue and rides the flow into the started game. Asserts same gameId for all four, the 2v2 config, allowlist admission, and a **deterministic 2 vs 2 in-game split read from each client's GameView** (the software-WebGL gate is spoofed in test pages only). **8/8.** 1v1 e2e still **6/6.** ## Verification - `npm test`: 2,053 tests pass, including 7 new (6 `assignTeams` pinning unit tests + a full-game pinned-split test through `setup()`). - `npx tsc --noEmit`, ESLint clean. - Live e2e against a local `wrangler dev` API worker: 1v1 (6/6) and 2v2 (8/8) as above. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Please complete the following: - [x] I have added screenshots for all UI updates - [x] I process any text displayed to the user through translateText() and I've added it to the en.json file - [x] I have added relevant tests to the test directory (UI changes — the ranked modal's 1v1/2v2 cards — were verified with before/after screenshots in the live app during development.) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
111 lines
3.7 KiB
JavaScript
111 lines
3.7 KiB
JavaScript
// Fake matchmaking server implementing the API worker's documented protocol
|
|
// (see the matchmaking integration handoff): WS /matchmaking/join, the
|
|
// {type:"join", jwt} message, {type:"match-assignment", gameId}, and the
|
|
// close-code contract (1008 invalid session, 1000 replaced by newer
|
|
// connection). A control API lets tests trigger each server-side behavior.
|
|
|
|
import http from "node:http";
|
|
import { WebSocketServer } from "ws";
|
|
|
|
export async function startFakeMatchmakingServer() {
|
|
const state = {
|
|
joins: [], // every {type:"join"} ever received: { jwt, at }
|
|
sockets: new Map(), // jwt -> ws holding the queue slot
|
|
rejectNextJoin: false,
|
|
};
|
|
|
|
const server = http.createServer((req, res) => {
|
|
let body = "";
|
|
req.on("data", (c) => (body += c));
|
|
req.on("end", () => {
|
|
const send = (obj) => {
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(JSON.stringify(obj));
|
|
};
|
|
switch (new URL(req.url, "http://localhost").pathname) {
|
|
case "/control/state":
|
|
return send({
|
|
joins: state.joins,
|
|
queued: [...state.sockets.keys()],
|
|
});
|
|
case "/control/reject-next": // next join gets 1008 Invalid session
|
|
state.rejectNextJoin = true;
|
|
return send({ ok: true });
|
|
case "/control/kill": // abrupt drop (deploy/restart) -> client sees 1006
|
|
for (const ws of state.sockets.values()) ws.terminate();
|
|
state.sockets.clear();
|
|
return send({ ok: true });
|
|
case "/control/replace": // queue slot taken by a newer connection
|
|
for (const ws of state.sockets.values()) {
|
|
ws.close(1000, "Replaced by newer connection");
|
|
}
|
|
state.sockets.clear();
|
|
return send({ ok: true });
|
|
case "/control/assign": {
|
|
const { gameId } = JSON.parse(body || "{}");
|
|
for (const ws of state.sockets.values()) {
|
|
ws.send(JSON.stringify({ type: "match-assignment", gameId }));
|
|
}
|
|
return send({ ok: true });
|
|
}
|
|
default:
|
|
res.statusCode = 404;
|
|
return res.end();
|
|
}
|
|
});
|
|
});
|
|
|
|
const wss = new WebSocketServer({
|
|
server,
|
|
// Real worker rejects a missing instance_id or an unknown mode with
|
|
// HTTP 400 pre-upgrade. mode is optional; omitted means 1v1.
|
|
verifyClient: ({ req }) => {
|
|
const params = new URL(req.url, "http://localhost").searchParams;
|
|
const mode = params.get("mode");
|
|
return (
|
|
params.has("instance_id") &&
|
|
(mode === null || mode === "1v1" || mode === "2v2")
|
|
);
|
|
},
|
|
});
|
|
|
|
wss.on("connection", (ws, req) => {
|
|
// Raw mode param (null when omitted) so tests can assert 1v1 omits it.
|
|
const mode = new URL(req.url, "http://localhost").searchParams.get("mode");
|
|
ws.on("message", (raw) => {
|
|
let msg;
|
|
try {
|
|
msg = JSON.parse(raw.toString());
|
|
} catch {
|
|
return;
|
|
}
|
|
if (msg.type !== "join") return;
|
|
state.joins.push({ jwt: msg.jwt, mode, at: Date.now() });
|
|
if (state.rejectNextJoin) {
|
|
state.rejectNextJoin = false;
|
|
ws.close(1008, "Invalid session");
|
|
return;
|
|
}
|
|
const prev = state.sockets.get(msg.jwt);
|
|
if (prev && prev !== ws) {
|
|
prev.close(1000, "Replaced by newer connection");
|
|
}
|
|
state.sockets.set(msg.jwt, ws);
|
|
});
|
|
ws.on("close", () => {
|
|
for (const [jwt, s] of state.sockets) {
|
|
if (s === ws) state.sockets.delete(jwt);
|
|
}
|
|
});
|
|
});
|
|
|
|
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
|
const port = server.address().port;
|
|
return {
|
|
port,
|
|
wsUrl: `ws://127.0.0.1:${port}`,
|
|
controlUrl: `http://127.0.0.1:${port}/control`,
|
|
close: () => new Promise((r) => server.close(r)),
|
|
};
|
|
}
|