1
0
Fork 0

feat(arena): websocket match replication for Ordnance Disposal

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.
This commit is contained in:
Jason Fraley 2026-10-19 12:27:17 -04:00
parent 70378b23e8
commit 394db6dfa1
20 changed files with 2651 additions and 97 deletions

View file

@ -83,6 +83,25 @@ APP_PORT=3000
# DISCORD_NPC_EVENT_CHANNEL_ID=
# DISCORD_NPC_EVENT_POLL_MS=
# --- Arena (real-time match server, src/arena) ---
# Dedicated Node process hosting live Ordnance Disposal matches over WebSockets.
# Everything is opt-in: with these unset the game runs on the in-process
# registry + SSE exactly as before (kill switch / rollback path).
ARENA_PORT=4100
# Shared secret for: ticket verification (Next mints, arena verifies), arena
# REST auth (Next proxies the lifecycle), and the results callback header
# (arena -> Next). Generate with: openssl rand -hex 32. Set the SAME value for
# both services.
ARENA_SECRET=YOUR_ARENA_SECRET
# Server-side base URL the Next actions use to reach the arena (compose:
# http://arena:4100; Coolify: the arena service's internal URL). Setting this
# plus ARENA_SECRET switches match ownership to the arena backend.
ARENA_INTERNAL_URL=
# Client-side public WebSocket origin baked into the browser bundle at build
# time (prod: wss://arena.onyxsimple.com; local compose: ws://localhost:4100).
# Changing it requires a rebuild. Absent = pure HTTP transport.
NEXT_PUBLIC_ARENA_URL=
# --- Usage analytics (Microsoft Clarity) ---
# Project ID from clarity.microsoft.com (Settings > Project ID). Optional;
# leave unset to disable analytics entirely. The script only loads in

View file

@ -90,6 +90,10 @@ The Dockerfile pins Bun 1.3.11 (**build-time only**) and Node 22 alpine (runtime
| `EMAIL_PORT` | — | `587` |
| `EMAIL_USERNAME` | — | SMTP user |
| `EMAIL_PASSWORD` | — | SMTP password / API key |
| `ARENA_SECRET` | iff arena enabled | Shared secret for the arena (`src/arena`): ticket signing/verification, arena REST auth, results callback header. **Same value in both services.** `openssl rand -hex 32`. |
| `ARENA_INTERNAL_URL` | iff arena enabled | Server-side base URL of the arena service as the app container reaches it (e.g. `http://arena:4100`). Setting this plus `ARENA_SECRET` switches Ordnance Disposal match ownership to the arena; unset keeps the in-process registry (rollback path). |
| `ARENA_PORT` | — | Arena listen port; default `4100`. |
| `NEXT_PUBLIC_ARENA_URL` | iff WS transport enabled | Public WebSocket origin baked into the client bundle at build time (prod: `wss://arena.onyxsimple.com`). Changing it requires a rebuild. Absent = pure HTTP transport (kill switch). |
| `DISCORD_TOKEN` | iff bot enabled in this env | Set in **prod only** — presence activates the bot (activation gate below). |
| `DISCORD_GUILD_ID` | iff `DISCORD_TOKEN` set | Config throws at import if the token is set and this is missing. |
| `DISCORD_OPS_CHANNEL_ID` | — | Ops channel for attendance RSVP embeds. |
@ -114,6 +118,24 @@ The bot ships inside the same app image and starts **only when `DISCORD_TOKEN` i
> ⚠️ The bot shares the single-instance constraint (Sec. 1): **running 2 replicas = two bot instances** — duplicate command registration, double embeds/DMs. Notifications generated while the container is down are **not backfilled** (in-memory cursor).
### Arena service (real-time match server, Ordnance Disposal)
The arena (`src/arena/`) is a **second Coolify service built from the same repo**: Docker build target `runner-arena`, start command baked into the image (`node --import tsx src/arena/server.ts`), domain `arena.onyxsimple.com` with Coolify's automatic TLS. Node-only like the runner (the host CPU lacks AVX/AVX2; never Bun).
Setup checklist:
1. **DNS + service**: point `arena.onyxsimple.com` at the Coolify proxy, create the service from this repo with build target `runner-arena`, and expose port 4100.
2. **Arena env**: `ARENA_SECRET` (fresh `openssl rand -hex 32`), `APP_URL` (so results callbacks reach the app), `ARENA_PORT` optional. No database needed.
3. **App env**: the same `ARENA_SECRET` plus `ARENA_INTERNAL_URL` (the arena's internal URL on the shared network) and `NEXT_PUBLIC_ARENA_URL=wss://arena.onyxsimple.com`. Remember `NEXT_PUBLIC_*` is baked into the client bundle: changing it requires an app rebuild/redeploy.
4. **Rollback**: unset `NEXT_PUBLIC_ARENA_URL` (client stops attempting WS after a rebuild) or `ARENA_INTERNAL_URL` (matches go back to the in-process registry). Clients also self-fallback to HTTP after two WS connection failures or a 5s setup timeout.
Operational notes:
- **Restarting the arena kills live drills** (match state is process memory, like the SSE bus it replaces). Acceptable for ~90s matches; schedule restarts off-peak.
- **Single instance only.** Two replicas split the lobby in half.
- **Verification**: `GET /health` is unauthenticated; the lobby listing and lifecycle endpoints require the `x-arena-secret` header. The arena logs a `tick-drift match=... maxInterval=...ms` line every 30s per live match; a healthy arena keeps maxInterval under ~5ms above the 50ms tick even while the main site is loaded. On the client, the match container carries `data-transport="ws"|"http"` for at-a-glance confirmation.
- **Awards flow**: the arena POSTs final results to `/api/minigames/bomperator/results` (same secret header); that route is idempotent by matchId, so an arena crash-replay cannot double-award.
---
## 6. Scheduled jobs (game-tick, market-tick, server-tick)

View file

@ -207,3 +207,37 @@ USER node
# (Next is shipped and tested on Node).
ENTRYPOINT ["/bin/sh", "/docker-entrypoint.sh"]
CMD ["node", "server.js"]
# ───────────────────────── runner-arena ────────────────────────────
# Arena: standalone real-time match server (src/arena/) hosting live Ordnance
# Disposal drills over WebSockets. Coolify builds this target as a SECOND
# service from the same repo (different build target + start command). Node-only
# like the runner: the production host CPU lacks AVX/AVX2, so never Bun. Runs
# via tsx so the @/ tsconfig path alias resolves, same trick as the Discord bot.
# Deliberately does NOT depend on the builder stage: the arena imports only the
# pure engine + ws + jose, so its image needs no Next build (src ships straight
# from the build context).
FROM node:22-alpine AS runner-arena
RUN apk add --no-cache libc6-compat wget
WORKDIR /app
ENV NODE_ENV=production \
ARENA_PORT=4100
# The `node` user already exists in `node:*-alpine` images.
RUN mkdir -p /app && chown -R node:node /app
# Full prod deps (ws, jose, tsx live here) from the shared prod-deps stage.
COPY --from=prod-deps --chown=node:node /app/node_modules ./node_modules
# Source + tsconfig (tsx path alias resolution) + package.json.
COPY --chown=node:node src ./src
COPY --chown=node:node package.json tsconfig.json ./
EXPOSE 4100
# Liveness probe on the arena's own /health (no DB, no Next dependency).
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
CMD wget -qO- "http://127.0.0.1:${ARENA_PORT:-4100}/health" >/dev/null 2>&1 || exit 1
USER node
CMD ["node", "--import", "tsx", "src/arena/server.ts"]

View file

@ -52,6 +52,7 @@
"discord.js": "^14.27.0",
"dotenv": "17.2.3",
"graphql": "^16.14.2",
"jose": "^6.2.12",
"leaflet": "^1.9.4",
"lexical": "0.41.0",
"lucide-react": "^0.561.0",
@ -75,6 +76,7 @@
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3",
"tsx": "^4.23.12",
"ws": "^8.22.0",
},
"devDependencies": {
"@playwright/test": "1.57.0",
@ -82,6 +84,7 @@
"@types/node": "^25.9.5",
"@types/react": "19.2.7",
"@types/react-dom": "19.2.3",
"@types/ws": "^8.18.2",
"@vitejs/plugin-react": "5.1.2",
"drizzle-kit": "^0.31.10",
"eslint": "^9.39.5",
@ -1058,7 +1061,7 @@
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.50.0", "", { "dependencies": { "@eslint-community/regexpp": "4.12.1", "@typescript-eslint/scope-manager": "8.50.0", "@typescript-eslint/type-utils": "8.50.0", "@typescript-eslint/utils": "8.50.0", "@typescript-eslint/visitor-keys": "8.50.0", "ignore": "7.0.5", "natural-compare": "1.4.0", "ts-api-utils": "2.1.0" }, "peerDependencies": { "@typescript-eslint/parser": "8.50.0", "eslint": "9.39.2", "typescript": "5.9.3" } }, "sha512-O7QnmOXYKVtPrfYzMolrCTfkezCJS9+ljLdKW/+DCvRsc3UAz+sbH6Xcsv7p30+0OwUbeWfUDAQE0vpabZ3QLg=="],
@ -1836,7 +1839,7 @@
"jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
"jose": ["jose@5.10.0", "", {}, "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg=="],
"jose": ["jose@6.2.12", "", {}, "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw=="],
"joycon": ["joycon@3.1.1", "", {}, "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw=="],
@ -2676,7 +2679,7 @@
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"ws": ["ws@8.18.3", "", {}, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],
"ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="],
"xml-name-validator": ["xml-name-validator@5.0.0", "", {}, "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg=="],
@ -2734,6 +2737,8 @@
"@discordjs/ws/@discordjs/collection": ["@discordjs/collection@2.1.1", "", {}, "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg=="],
"@discordjs/ws/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"@discordjs/ws/ws": ["ws@8.21.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw=="],
"@emotion/babel-plugin/convert-source-map": ["convert-source-map@1.9.0", "", {}, "sha512-ASFBup0Mz1uyiIjANan1jzLQami9z1PoYSZCiiYW2FczPbenXc45FZdBZLzOT+r6+iciuEModtmCti+hjaAk0A=="],
@ -2822,8 +2827,6 @@
"@types/pg/@types/node": ["@types/node@25.0.3", "", { "dependencies": { "undici-types": "7.16.0" } }, "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA=="],
"@types/ws/@types/node": ["@types/node@25.0.3", "", { "dependencies": { "undici-types": "7.16.0" } }, "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA=="],
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
"@typescript-eslint/typescript-estree/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "2.0.2" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
@ -2904,6 +2907,8 @@
"happy-dom/@types/node": ["@types/node@25.0.3", "", { "dependencies": { "undici-types": "7.16.0" } }, "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA=="],
"happy-dom/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
"happy-dom/entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
"happy-dom/whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="],
@ -2912,6 +2917,8 @@
"hoist-non-react-statics/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
"jsdom/ws": ["ws@8.18.3", "", {}, "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg=="],
"json-schema-to-typescript/js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
"json-schema-to-typescript/prettier": ["prettier@3.7.4", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-v6UNi1+3hSlVvv8fSaoUbggEM5VErKmmpGA7Pl3HF8V6uKY7rvClBOJlH6yNwQtfTueNkGVpOv/mtWL9L4bgRA=="],
@ -2936,6 +2943,8 @@
"payload/ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"payload/jose": ["jose@5.10.0", "", {}, "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg=="],
"payload/tsx": ["tsx@4.22.4", "", { "dependencies": { "esbuild": "~0.28.0" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "bin": { "tsx": "dist/cli.mjs" } }, "sha512-X8EX+XV4QR5xCsrgxaED954zTDfY8KqlDtskKEL0cHhyS/P8b4IFOvGDQpsC9Q1XnLq915wEfwwY/zzskCtmhg=="],
"payload/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
@ -3022,6 +3031,8 @@
"@babel/helper-module-transforms/@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"@discordjs/ws/@types/ws/@types/node": ["@types/node@25.0.3", "", { "dependencies": { "undici-types": "7.16.0" } }, "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="],
@ -3100,8 +3111,6 @@
"@types/pg/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"@types/ws/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@2.0.2", "", { "dependencies": { "balanced-match": "1.0.2" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="],
"accepts/mime-types/mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
@ -3238,6 +3247,8 @@
"@aws-crypto/util/@smithy/util-utf8/@smithy/util-buffer-from/@smithy/is-array-buffer": ["@smithy/is-array-buffer@2.2.0", "", { "dependencies": { "tslib": "2.8.1" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],
"@discordjs/ws/@types/ws/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
"@payloadcms/graphql/tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.28.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ=="],
"@payloadcms/graphql/tsx/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.28.2", "", { "os": "android", "cpu": "arm" }, "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg=="],

View file

@ -45,6 +45,35 @@ services:
retries: 3
restart: unless-stopped
# Arena: dedicated real-time match server for Ordnance Disposal (src/arena).
# Optional: with ARENA_SECRET/ARENA_INTERNAL_URL unset the app runs exactly
# as before on its in-process registry. When set (see .env), the app proxies
# the match lifecycle here and browsers connect over ws://localhost:4100/ws
# (set NEXT_PUBLIC_ARENA_URL=ws://localhost:4100 in .env for local WS tests).
arena:
build:
context: .
dockerfile: Dockerfile
target: runner-arena
image: polaris-task-force-arena:local
container_name: polaris-task-force-arena
env_file:
- .env
environment:
# Results callbacks go back into the app container by service name.
APP_URL: http://app:3000
ports:
- "${ARENA_PORT:-4100}:4100"
depends_on:
- app
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:4100/health"]
interval: 30s
timeout: 10s
start_period: 20s
retries: 3
restart: unless-stopped
postgres:
image: postgres:17-alpine
container_name: polaris-task-force-pg

View file

@ -5,6 +5,7 @@
"license": "MIT",
"type": "module",
"scripts": {
"arena": "bun run src/arena/server.ts",
"bot": "bun run src/bot/index.ts",
"build": "bun run generate:version-info && cross-env NODE_OPTIONS=\"--no-deprecation --max-old-space-size=8000\" next build --webpack",
"dev": "bun run generate:version-info && cross-env NODE_OPTIONS=--no-deprecation next dev --webpack",
@ -80,6 +81,7 @@
"discord.js": "^14.27.0",
"dotenv": "17.2.3",
"graphql": "^16.14.2",
"jose": "^6.2.12",
"leaflet": "^1.9.4",
"lexical": "0.41.0",
"lucide-react": "^0.561.0",
@ -102,7 +104,8 @@
"sonner": "^2.0.8",
"tailwind-merge": "^3.6.0",
"tailwindcss": "^4.3.3",
"tsx": "^4.23.12"
"tsx": "^4.23.12",
"ws": "^8.22.0"
},
"devDependencies": {
"@playwright/test": "1.57.0",
@ -110,6 +113,7 @@
"@types/node": "^25.9.5",
"@types/react": "19.2.7",
"@types/react-dom": "19.2.3",
"@types/ws": "^8.18.2",
"@vitejs/plugin-react": "5.1.2",
"drizzle-kit": "^0.31.10",
"eslint": "^9.39.5",

View file

@ -2,13 +2,22 @@
/**
* Server-action surface for Ordnance Disposal (internal key `bomperator`).
* All match logic lives in the registry
* (src/lib/minigames/bomperator/registry.ts). The userId is always taken from
* the session, never from a client payload.
*
* Two backends sit behind these actions, selected by server env:
* - Default (no ARENA_INTERNAL_URL/ARENA_SECRET): the in-process registry
* (src/lib/minigames/bomperator/registry.ts), exactly as before the arena.
* - Arena mode: every lifecycle call proxies to the arena server (the same
* game logic, running in its own process with a drift-corrected tick loop).
* The browser's latency path (inputs + snapshots) then rides the arena
* WebSocket directly; these actions keep serving the lobby lifecycle, the
* correctness-fallback poll, and the HTTP transport.
*
* The userId is always taken from the session, never from a client payload.
*/
import config from "@payload-config";
import { getPayload } from "payload";
import { SignJWT } from "jose";
import { isSuperuser } from "@/utils/access-control/hasPermission";
import type {
BomperatorMatchSummary,
@ -72,11 +81,85 @@ function userName(user: UserLike): string {
return `Operator ${user.id}`;
}
/* ------------------------------------------------------------------ arena */
/** Internal (server-reachable) base URL of the arena process. */
const ARENA_INTERNAL_URL = (process.env.ARENA_INTERNAL_URL ?? "").replace(/\/+$/, "");
const ARENA_SECRET = process.env.ARENA_SECRET ?? "";
/**
* Arena mode is a server-side switch: with both vars set, matches live in the
* arena and these actions proxy to it. The client-side kill switch is the
* separate NEXT_PUBLIC_ARENA_URL (WS vs HTTP transport); configure them
* together. With either server var unset everything runs on the local registry
* exactly as before.
*/
const ARENA_ENABLED = Boolean(ARENA_INTERNAL_URL && ARENA_SECRET);
async function arenaCall<T>(
method: "GET" | "POST",
path: string,
body?: Record<string, unknown>,
): Promise<ActionResult<T>> {
try {
const response = await fetch(`${ARENA_INTERNAL_URL}${path}`, {
method,
headers: {
"content-type": "application/json",
"x-arena-secret": ARENA_SECRET,
},
...(body ? { body: JSON.stringify(body) } : {}),
signal: AbortSignal.timeout(5000),
});
return (await response.json()) as ActionResult<T>;
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
return { success: false, error: `Arena unreachable: ${message}` };
}
}
/**
* Mint a short-lived (30s) ticket for the browser to open its arena socket.
* Signed with ARENA_SECRET; carries {uid, matchId, iat}. No replay store by
* design: expiry plus the narrow uid+matchId scope is the defense (see the
* arena plan). When no matchId is passed one is generated for a fresh drill.
*/
export async function createArenaTicket(
matchId?: string,
): Promise<ActionResult<{ ticket: string; matchId: string }>> {
try {
const { user } = await authenticate();
if (!ARENA_SECRET || !process.env.NEXT_PUBLIC_ARENA_URL) {
return { success: false, error: "Arena is not enabled." };
}
const mid =
typeof matchId === "string" && matchId ? matchId : crypto.randomUUID();
const key = new TextEncoder().encode(ARENA_SECRET);
const ticket = await new SignJWT({ uid: Number(user.id), matchId: mid })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("30s")
.sign(key);
return { success: true, data: { ticket, matchId: mid } };
} catch (error) {
return toError(error);
}
}
/* ----------------------------------------------------------------- actions */
export async function createBomperatorMatch(
roundTarget?: number,
): Promise<ActionResult<{ matchId: string }>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
return await arenaCall<{ matchId: string }>("POST", "/matches", {
userId: Number(user.id),
name: userName(user),
roundTarget,
});
}
const matchId = createMatch(Number(user.id), userName(user), roundTarget);
return { success: true, data: { matchId } };
} catch (error) {
@ -87,6 +170,12 @@ export async function createBomperatorMatch(
export async function listBomperatorMatches(): Promise<ActionResult<BomperatorMatchSummary[]>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
return await arenaCall<BomperatorMatchSummary[]>(
"GET",
`/matches?viewerId=${encodeURIComponent(String(Number(user.id)))}`,
);
}
return { success: true, data: listMatchSummaries(Number(user.id)) };
} catch (error) {
return toError(error);
@ -96,6 +185,13 @@ export async function listBomperatorMatches(): Promise<ActionResult<BomperatorMa
export async function joinBomperatorMatch(matchId: string): Promise<ActionResult<BomperatorView>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
return await arenaCall<BomperatorView>("POST", "/matches/join", {
matchId,
userId: Number(user.id),
name: userName(user),
});
}
return { success: true, data: joinMatch(matchId, Number(user.id), userName(user)) };
} catch (error) {
return toError(error);
@ -107,6 +203,12 @@ export async function fetchBomperatorMatch(
): Promise<ActionResult<BomperatorView>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
return await arenaCall<BomperatorView>("POST", "/matches/snapshot", {
matchId,
userId: Number(user.id),
});
}
return { success: true, data: getSnapshotFor(matchId, Number(user.id)) };
} catch (error) {
return toError(error);
@ -116,6 +218,12 @@ export async function fetchBomperatorMatch(
export async function startBomperatorMatch(matchId: string): Promise<ActionResult<BomperatorView>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
return await arenaCall<BomperatorView>("POST", "/matches/start", {
matchId,
userId: Number(user.id),
});
}
return { success: true, data: startMatch(matchId, Number(user.id)) };
} catch (error) {
return toError(error);
@ -128,6 +236,14 @@ export async function sendBomperatorInput(
): Promise<ActionResult<undefined>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
await arenaCall("POST", "/matches/input", {
matchId,
userId: Number(user.id),
input,
});
return { success: true };
}
submitInput(matchId, Number(user.id), input);
return { success: true };
} catch (error) {
@ -138,6 +254,10 @@ export async function sendBomperatorInput(
export async function leaveBomperatorMatch(matchId: string): Promise<ActionResult<undefined>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
await arenaCall("POST", "/matches/leave", { matchId, userId: Number(user.id) });
return { success: true };
}
leaveMatch(matchId, Number(user.id));
return { success: true };
} catch (error) {
@ -148,6 +268,10 @@ export async function leaveBomperatorMatch(matchId: string): Promise<ActionResul
export async function endBomperatorMatch(matchId: string): Promise<ActionResult<undefined>> {
try {
const { user } = await authenticate();
if (ARENA_ENABLED) {
await arenaCall("POST", "/matches/end", { matchId, userId: Number(user.id) });
return { success: true };
}
endMatch(matchId, Number(user.id));
return { success: true };
} catch (error) {
@ -164,6 +288,10 @@ export async function forceExpireBomperatorMatch(
if (!allowed) {
return { success: false, error: "Only administrators can force-end matches." };
}
if (ARENA_ENABLED) {
await arenaCall("POST", "/matches/force-expire", { matchId });
return { success: true };
}
forceExpireMatch(matchId);
return { success: true };
} catch (error) {

View file

@ -0,0 +1,94 @@
import { NextRequest, NextResponse } from "next/server";
import config from "@payload-config";
import { getPayload } from "payload";
import {
awardBomperatorResult,
type BomperatorMatchResult,
} from "@/lib/minigames/bomperator/stats";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Results callback for the arena server (mirrors the /api/game-tick/notify
* shared-secret pattern): the arena POSTs final match results here instead of
* touching Payload itself. Auth is the `x-arena-secret` header.
*
* Idempotent by matchId: the arena's per-match `awarded` flag dies with an
* arena crash, so a restarted arena could replay results. The seen-set lives
* on globalThis (dev bundles duplicate modules) and prunes itself.
*/
interface SeenRegistry {
__bomperatorAwardedMatches?: Map<string, number>;
}
const globalSeen = globalThis as typeof globalThis & SeenRegistry;
const seen = (globalSeen.__bomperatorAwardedMatches ??= new Map<string, number>());
const SEEN_TTL_MS = 60 * 60_000;
const SEEN_MAX = 500;
function remember(matchId: string): void {
const now = Date.now();
seen.set(matchId, now);
if (seen.size > SEEN_MAX) {
for (const [id, at] of seen) {
if (now - at > SEEN_TTL_MS) seen.delete(id);
}
}
}
interface ResultsBody {
matchId?: unknown;
results?: unknown;
}
function parseResults(value: unknown): BomperatorMatchResult[] | null {
if (!Array.isArray(value)) return null;
const out: BomperatorMatchResult[] = [];
for (const entry of value) {
if (typeof entry !== "object" || entry === null) return null;
const e = entry as Record<string, unknown>;
if (typeof e.userId !== "number" || typeof e.won !== "boolean") return null;
out.push({
userId: e.userId,
won: e.won,
kills: typeof e.kills === "number" ? e.kills : 0,
roundsWon: typeof e.roundsWon === "number" ? e.roundsWon : 0,
});
}
return out;
}
export async function POST(req: NextRequest) {
const secret = process.env.ARENA_SECRET;
if (!secret) {
return NextResponse.json({ ok: false, error: "Arena disabled." }, { status: 503 });
}
if (req.headers.get("x-arena-secret") !== secret) {
return NextResponse.json({ ok: false, error: "Bad arena credentials." }, { status: 401 });
}
let body: ResultsBody;
try {
body = (await req.json()) as ResultsBody;
} catch {
return NextResponse.json({ ok: false, error: "Invalid JSON body." }, { status: 400 });
}
const matchId = typeof body.matchId === "string" ? body.matchId : "";
const results = parseResults(body.results);
if (!matchId || !results || results.length === 0) {
return NextResponse.json({ ok: false, error: "matchId and results are required." }, { status: 400 });
}
if (seen.has(matchId)) {
return NextResponse.json({ ok: true, duplicate: true });
}
// Claim the matchId before awaiting so concurrent retries cannot double-award.
remember(matchId);
const payload = await getPayload({ config: await config });
await awardBomperatorResult(payload, matchId, results);
return NextResponse.json({ ok: true, awarded: results.length });
}

View file

@ -0,0 +1,684 @@
/**
* Ordnance Disposal as an arena-hosted real-time game module.
*
* This is the match registry (`src/lib/minigames/bomperator/registry.ts`)
* ported to own live matches inside the dedicated arena process. The lifecycle,
* presence, rate-limiting, seq-guard, dissolve and award rules are deliberately
* identical to the registry so both transports drive the same game; what
* changes is delivery and timing:
*
* - Snapshots go out through the injected `deliver` callback (direct per-socket
* sends), not the in-process SSE bus.
* - Awards leave via the injected `onResults` callback (the arena POSTs them to
* the Next results route); this module never touches Payload.
* - The tick loop is a drift-corrected `setTimeout` chain recomputed against
* `performance.now()` with capped catch-up, replacing the bare `setInterval`
* whose dropped callbacks were the root cause of the v0.12 teleport-back bug.
*
* Only the PURE engine is imported ({engine,views,types,constants} + the pure
* table-name generator). No Payload, no Next, no SSE bus.
*/
import { generateTableName } from "@/lib/minigames/tableNames";
import {
BOMP_MATCH_EXPIRY_MS,
BOMP_MAX_MATCHES,
BOMP_SWEEP_INTERVAL_MS,
DEFAULT_ROUND_TARGET,
INPUT_RATE_LIMIT_PER_S,
MAX_SEATS,
MIN_TO_START,
RECONNECT_WINDOW_MS,
ROUND_TARGET_OPTIONS,
TICK_MS,
} from "@/lib/minigames/bomperator/constants";
import {
applyInput,
createMatchState,
dissolveMatch,
eliminateSeat,
startRound,
tick as engineTick,
type BomperatorInput,
} from "@/lib/minigames/bomperator/engine";
import type { BomperatorMatchSummary, BomperatorState, BomperatorView } from "@/lib/minigames/bomperator/types";
import { buildBomperatorView } from "@/lib/minigames/bomperator/views";
import type { ServerMessage } from "../protocol";
import type { RealtimeGameModule } from "./types";
/** Final per-player outcome handed to the awards callback (mirrors stats.ts). */
export interface BomperatorFinalResult {
userId: number;
won: boolean;
kills: number;
roundsWon: number;
}
export interface BomperatorModuleOptions {
/** Push one protocol message to every socket currently held by this user. */
deliver: (userId: number, message: ServerMessage) => void;
/**
* Fire-and-forget awards handoff when a match completes or is disposed with
* rounds banked. The Next results route is idempotent by matchId because
* this module's `awarded` flag dies with an arena crash.
*/
onResults: (matchId: string, results: BomperatorFinalResult[]) => void;
/** When false, no wall-clock timers run; tests drive `advance()` manually. */
autoTick?: boolean;
}
interface RosterEntry {
readonly userId: number;
readonly name: string;
}
interface RoomRecord {
id: string;
name: string | null;
version: number;
hostUserId: number;
roster: RosterEntry[];
/** Seats whose occupant left permanently (window expired or lobby leave). */
leftSeats: Set<number>;
roundTarget: number;
seed: number;
state: BomperatorState;
awarded: boolean;
createdAt: string;
lastActivityAt: number;
/** Per-seat input rate limiting: rolling one-second window. */
inputWindow: Map<number, { count: number; windowStart: number }>;
/** Per-seat highest client input seq applied (rejects out-of-order frames). */
lastInputSeq: Map<number, number>;
/** userId -> last time they attached/polled, for snapshot fan-out targets. */
viewers: Map<number, number>;
/* ---- drift-corrected scheduler state ---- */
timer: ReturnType<typeof setTimeout> | null;
/** performance.now() instant the next tick is scheduled for. */
nextTickAt: number;
lastFireAt: number;
/** Drift telemetry, reset by `driftReport()`. */
ticksRun: number;
maxIntervalMs: number;
}
/** Cap on catch-up steps after a stall: repay up to two dropped ticks, no more. */
const TICK_CATCHUP_CAP = 2;
function seatOf(record: RoomRecord, userId: number): number | null {
const index = record.roster.findIndex((entry) => entry.userId === userId);
return index === -1 ? null : index;
}
/** Seats still in the match (roster minus those who left permanently). */
function activeSeatCount(record: RoomRecord): number {
return record.roster.length - record.leftSeats.size;
}
function rosterDescriptors(record: RoomRecord) {
return record.roster.map((entry, seat) => ({ seat, userId: entry.userId, name: entry.name }));
}
/** Patch a seat's presence flags without disturbing engine rules. */
function withPresence(
state: BomperatorState,
seat: number,
connected: boolean,
disconnectedAt: number | null,
): BomperatorState {
const players = [...state.players];
if (!players[seat]) return state;
players[seat] = { ...players[seat], connected, disconnectedAt };
return { ...state, players };
}
export class BomperatorGameModule implements RealtimeGameModule {
readonly key = "bomperator";
private readonly matches = new Map<string, RoomRecord>();
private readonly opts: BomperatorModuleOptions;
private autoTickEnabled: boolean;
private sweepTimer: ReturnType<typeof setInterval> | null = null;
constructor(opts: BomperatorModuleOptions) {
this.opts = opts;
this.autoTickEnabled = opts.autoTick ?? true;
if (this.autoTickEnabled) {
this.sweepTimer = setInterval(() => this.sweepExpired(), BOMP_SWEEP_INTERVAL_MS);
this.sweepTimer.unref?.();
}
}
/* --------------------------------------------------------------- helpers */
private buildViewFor(record: RoomRecord, userId: number | null): BomperatorView {
const yourSeat = userId === null ? null : seatOf(record, userId);
const view = buildBomperatorView(record.state, {
matchId: record.id,
name: record.name,
version: record.version,
yourSeat,
});
// Echo each seat's last applied input seq so the owning client can reconcile
// its local prediction against what the server has actually consumed.
const players = view.players.map((p) => ({
...p,
lastInputSeq: record.lastInputSeq.get(p.seat) ?? 0,
}));
return { ...view, players };
}
/** Push a fresh per-user snapshot to every seated technician and active viewer. */
private pushSnapshots(record: RoomRecord): void {
const now = Date.now();
const recipients = new Set<number>();
for (const entry of record.roster) recipients.add(entry.userId);
for (const [userId, seen] of record.viewers) {
if (now - seen > 30_000) record.viewers.delete(userId);
else recipients.add(userId);
}
for (const userId of recipients) {
this.opts.deliver(userId, { t: "snapshot", view: this.buildViewFor(record, userId) });
}
}
/** Rebuild the inert lobby state after a membership change (contiguous seats). */
private rebuildLobbyState(record: RoomRecord): void {
record.state = createMatchState(rosterDescriptors(record), record.roundTarget, record.seed);
}
/* ---------------------------------------------------------------- awards */
private matchResults(state: BomperatorState): BomperatorFinalResult[] {
return state.players.map((player) => ({
userId: player.userId,
won: state.matchWinnerSeat !== null && state.players[state.matchWinnerSeat]?.userId === player.userId,
kills: player.kills,
roundsWon: player.roundsWon,
}));
}
/** Fire-and-forget rewards handoff for a completed match; idempotent per room. */
private awardCompleted(record: RoomRecord): void {
if (record.awarded || record.state.phase !== "complete") return;
record.awarded = true;
const results = this.matchResults(record.state);
if (results.length === 0) return;
this.opts.onResults(record.id, results);
}
/* ----------------------------------------------------------- tick scheduler */
private startTickLoop(record: RoomRecord): void {
if (!this.autoTickEnabled || record.timer) return;
const now = performance.now();
record.nextTickAt = now + TICK_MS;
record.lastFireAt = now;
this.armNext(record);
}
private armNext(record: RoomRecord): void {
const delay = Math.max(0, record.nextTickAt - performance.now());
record.timer = setTimeout(() => this.onTickFire(record), delay);
record.timer.unref?.();
}
/**
* One scheduler firing: run the scheduled tick plus capped catch-up for any
* ticks the event loop dropped, then re-anchor the schedule so debt never
* stacks. `maxIntervalMs` is the starvation metric the deploy verification
* reads: on a healthy arena it stays well under one extra tick period.
*/
private onTickFire(record: RoomRecord): void {
const now = performance.now();
const scheduledFor = record.nextTickAt;
const interval = now - record.lastFireAt;
if (interval > record.maxIntervalMs) record.maxIntervalMs = interval;
record.lastFireAt = now;
this.step(record);
record.ticksRun += 1;
if (!record.timer) return; // step completed or disposed the room
const extra = Math.min(Math.floor((now - scheduledFor) / TICK_MS), TICK_CATCHUP_CAP);
for (let i = 0; i < extra; i += 1) {
this.step(record);
record.ticksRun += 1;
if (!record.timer) return;
}
const nextIdeal = scheduledFor + (1 + extra) * TICK_MS;
record.nextTickAt = nextIdeal > now ? nextIdeal : now + TICK_MS;
this.armNext(record);
}
private stopTickLoop(record: RoomRecord): void {
if (record.timer) clearTimeout(record.timer);
record.timer = null;
}
/** One simulation step: expire disconnects, advance the engine, resolve ends. */
private step(record: RoomRecord, now: number = Date.now()): void {
let state = record.state;
// Expire seats whose reconnect window has elapsed: eliminate + mark left.
for (let seat = 0; seat < record.roster.length; seat += 1) {
if (record.leftSeats.has(seat)) continue;
const player = state.players[seat];
if (player && !player.connected && player.disconnectedAt !== null) {
if (now - player.disconnectedAt > RECONNECT_WINDOW_MS) {
state = eliminateSeat(state, seat);
record.leftSeats.add(seat);
}
}
}
const prevRound = state.roundIndex;
state = engineTick(state);
record.version += 1;
// A technician still disconnected when a fresh round opens has left the match.
if (state.roundIndex > prevRound) {
for (let seat = 0; seat < record.roster.length; seat += 1) {
if (record.leftSeats.has(seat)) continue;
const player = state.players[seat];
if (player && !player.connected) {
state = eliminateSeat(state, seat);
record.leftSeats.add(seat);
}
}
}
// Dissolve once fewer than two technicians remain in the match.
if (activeSeatCount(record) < MIN_TO_START && state.phase !== "complete") {
state = dissolveMatch(state);
}
record.state = state;
// Push the fresh snapshot to seated players + spectators (low-latency path).
this.pushSnapshots(record);
if (state.phase === "complete") {
this.stopTickLoop(record);
this.awardCompleted(record);
}
}
/* ------------------------------------------------------------------ public */
createRoom(hostUserId: number, hostName: string, options?: Record<string, unknown>): string {
if (this.matches.size >= BOMP_MAX_MATCHES) {
throw new Error("The maximum number of live matches exists. Try again later.");
}
for (const existing of this.matches.values()) {
// A finished match never blocks starting a new one (it clears on its own).
if (seatOf(existing, hostUserId) !== null && existing.state.phase !== "complete") {
throw new Error("You are already in a match. Leave it first.");
}
}
const requested = Number(options?.roundTarget ?? DEFAULT_ROUND_TARGET);
const target = (ROUND_TARGET_OPTIONS as readonly number[]).includes(requested)
? requested
: DEFAULT_ROUND_TARGET;
const seed = (Date.now() ^ Math.floor(Math.random() * 0xffffffff)) >>> 0;
const record: RoomRecord = {
id: crypto.randomUUID(),
name: generateTableName(),
version: 1,
hostUserId,
roster: [{ userId: hostUserId, name: hostName }],
leftSeats: new Set(),
roundTarget: target,
seed,
state: createMatchState([{ seat: 0, userId: hostUserId, name: hostName }], target, seed),
awarded: false,
createdAt: new Date().toISOString(),
lastActivityAt: Date.now(),
inputWindow: new Map(),
lastInputSeq: new Map(),
viewers: new Map(),
timer: null,
nextTickAt: 0,
lastFireAt: 0,
ticksRun: 0,
maxIntervalMs: 0,
};
this.matches.set(record.id, record);
return record.id;
}
/** Seat a user (lobby) or restore their held seat; mirrors registry.joinMatch. */
join(matchId: string, userId: number, name: string): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
const existing = seatOf(record, userId);
if (existing !== null) {
// Rejoin: restore a held seat within the reconnect window.
if (!record.state.players[existing]?.connected) {
record.state = withPresence(record.state, existing, true, null);
record.version += 1;
}
record.lastActivityAt = Date.now();
record.viewers.set(userId, Date.now());
this.pushSnapshots(record);
return;
}
for (const other of this.matches.values()) {
if (
other.id !== record.id &&
seatOf(other, userId) !== null &&
other.state.phase !== "complete"
) {
throw new Error("You are already in another match. Leave it first.");
}
}
if (record.roster.length >= MAX_SEATS) throw new Error("This match is full.");
if (record.state.phase !== "lobby") throw new Error("This match has already started.");
record.roster.push({ userId, name });
this.rebuildLobbyState(record);
record.lastActivityAt = Date.now();
record.version += 1;
record.viewers.set(userId, Date.now());
this.pushSnapshots(record);
}
/** Snapshot for a poller or the WS attach handshake. */
snapshotFor(matchId: string, userId: number): BomperatorView {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
record.lastActivityAt = Date.now();
// Register as a viewer so subsequent ticks push snapshots to us too (players
// are always recipients; this is how spectators opt in).
record.viewers.set(userId, Date.now());
return this.buildViewFor(record, userId);
}
/**
* A WebSocket attached to this match (ticket already verified). Restores a
* held seat once the drill is live, or registers a spectator; returns the
* current view to send back on the socket.
*/
attach(matchId: string, userId: number): BomperatorView | null {
const record = this.matches.get(matchId);
if (!record) return null;
record.lastActivityAt = Date.now();
record.viewers.set(userId, Date.now());
const seat = seatOf(record, userId);
let presenceChanged = false;
if (seat !== null && record.state.phase !== "lobby" && !record.state.players[seat]?.connected) {
record.state = withPresence(record.state, seat, true, null);
record.version += 1;
presenceChanged = true;
}
if (presenceChanged) this.pushSnapshots(record);
return this.buildViewFor(record, userId);
}
/**
* A WebSocket dropped. Mid-drill this holds the seat for the reconnect
* window (mobile NATs evict idle sockets constantly), so unlike an explicit
* leave it never dissolves the match early; `step()` expires the seat only
* after the window lapses.
*/
detach(matchId: string, userId: number): void {
const record = this.matches.get(matchId);
if (!record) return;
if (record.state.phase === "lobby" || record.state.phase === "complete") return;
const seat = seatOf(record, userId);
if (seat === null) {
record.viewers.delete(userId);
return;
}
if (record.state.players[seat]?.connected) {
record.state = withPresence(record.state, seat, false, Date.now());
record.version += 1;
this.pushSnapshots(record);
}
}
start(matchId: string, userId: number): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
if (seatOf(record, userId) === null) throw new Error("You are not in this match.");
if (record.state.phase !== "lobby") throw new Error("This match has already started.");
if (record.roster.length < MIN_TO_START) {
throw new Error(`Need at least ${MIN_TO_START} technicians to start.`);
}
this.rebuildLobbyState(record);
record.state = startRound(record.state);
record.lastActivityAt = Date.now();
record.version += 1;
this.startTickLoop(record);
this.pushSnapshots(record);
}
input(matchId: string, userId: number, input: BomperatorInput): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
const seat = seatOf(record, userId);
if (seat === null) throw new Error("You are not in this match.");
if (!record.state.players[seat]?.connected) throw new Error("Your seat is not active.");
// Rate limit: reject more than INPUT_RATE_LIMIT_PER_S inputs in a second.
const now = Date.now();
const window = record.inputWindow.get(seat) ?? { count: 0, windowStart: now };
if (now - window.windowStart >= 1000) {
window.count = 0;
window.windowStart = now;
}
window.count += 1;
if (window.count > INPUT_RATE_LIMIT_PER_S) {
record.inputWindow.set(seat, window);
throw new Error("Too many inputs. Slow down.");
}
record.inputWindow.set(seat, window);
// Sequence guard: direction frames fire immediately, so frames can arrive
// out of order. Only the newest intent may win; anything at or below the
// last applied seq is a stale echo and is dropped silently.
if (typeof input.seq === "number") {
const last = record.lastInputSeq.get(seat) ?? -1;
if (input.seq <= last) return;
record.lastInputSeq.set(seat, input.seq);
}
record.state = applyInput(record.state, seat, input);
record.lastActivityAt = now;
}
/** Public single-step driver (the scheduler calls `step` internally). */
tick(matchId: string): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
this.step(record);
}
leave(matchId: string, userId: number): void {
const record = this.matches.get(matchId);
if (!record) return;
const seat = seatOf(record, userId);
if (seat === null) return;
// A finished drill has nothing to reconnect to: remove it outright so nobody
// stays "joined" and blocked from starting a new one until the idle sweep.
if (record.state.phase === "complete") {
this.disposeMatch(record);
return;
}
if (record.state.phase === "lobby") {
record.roster.splice(seat, 1);
this.rebuildLobbyState(record);
record.version += 1;
if (record.roster.length === 0) {
this.disposeMatch(record);
return;
}
record.lastActivityAt = Date.now();
this.pushSnapshots(record);
return;
}
// Mid-match: hold the seat for a reconnect rather than dropping it outright.
record.state = withPresence(record.state, seat, false, Date.now());
record.version += 1;
record.lastActivityAt = Date.now();
this.pushSnapshots(record);
// If that was the last connected technician, end the match now instead of
// leaving a zombie board that only clears after the reconnect window lapses.
if (!record.state.players.some((player) => player.connected)) {
record.state = dissolveMatch(record.state);
this.disposeMatch(record);
}
}
/**
* Hard stop: dissolve and remove the match immediately so nobody is stranded.
* Any seated technician may call it (a forfeit beats being stuck); spectators
* may not. Awards whatever has been earned.
*/
end(matchId: string, userId: number): void {
const record = this.matches.get(matchId);
if (!record) return; // already gone
if (seatOf(record, userId) === null && record.hostUserId !== userId) {
throw new Error("Only a technician in the drill can end it.");
}
this.notifyTerminated(record, userId, "host-ended");
if (record.state.phase !== "complete") {
record.state = dissolveMatch(record.state);
}
// `notified`: end() already sent the host-ended frame; don't double-send.
this.disposeMatch(record, true);
}
forceExpire(matchId: string): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
this.disposeMatch(record);
}
listSummaries(viewerId?: number): BomperatorMatchSummary[] {
return [...this.matches.values()].map((record) => ({
matchId: record.id,
name: record.name,
hostName: record.roster[0]?.name ?? "Unknown",
seatedCount: record.roster.length,
maxSeats: MAX_SEATS,
phase:
record.roster.length < MIN_TO_START && record.state.phase === "lobby"
? "waiting"
: record.state.phase,
roundTarget: record.roundTarget,
createdAt: record.createdAt,
joined: viewerId !== undefined && seatOf(record, viewerId) !== null,
}));
}
hasMatch(matchId: string): boolean {
return this.matches.has(matchId);
}
/* -------------------------------------------------------------- internals */
/**
* Tell every seated technician and active viewer (except the actor for a
* host-ended drill) that the match is over, then remove it. The HTTP client
* learns the same thing from its poll's "not found"; WS clients get the
* explicit frame so the toast lands immediately.
*/
private notifyTerminated(
record: RoomRecord,
actorUserId: number | null,
reason: "host-ended" | "ended",
): void {
const hostName =
(actorUserId !== null
? record.roster.find((entry) => entry.userId === actorUserId)?.name
: undefined) ??
record.roster.find((entry) => entry.userId === record.hostUserId)?.name ??
null;
const recipients = new Set<number>();
for (const entry of record.roster) recipients.add(entry.userId);
for (const viewerId of record.viewers.keys()) recipients.add(viewerId);
if (actorUserId !== null) recipients.delete(actorUserId); // they initiated it
for (const recipient of recipients) {
this.opts.deliver(recipient, {
t: "terminated",
matchId: record.id,
reason,
hostName,
});
}
}
/**
* Remove a room. Every disposal path ends WS clients with a `terminated`
* frame (the parity behavior on HTTP is the poll's "not found" toast), except
* when the caller already sent a richer one (`notified`, e.g. endMatch).
*/
private disposeMatch(record: RoomRecord, notified = false): void {
this.stopTickLoop(record);
this.awardCompleted(record);
if (!notified) this.notifyTerminated(record, null, "ended");
this.matches.delete(record.id);
}
private sweepExpired(): void {
const now = Date.now();
for (const record of [...this.matches.values()]) {
if (now - record.lastActivityAt <= BOMP_MATCH_EXPIRY_MS) continue;
this.disposeMatch(record);
}
}
/* ------------------------------------------------------------ observability */
/**
* Per-room tick telemetry since the last call (or since the room started).
* The periodic drift log in server.ts reads this; a max interval near TICK_MS
* is the direct proof the starvation fix works.
*/
driftReport(): { matchId: string; ticksRun: number; maxIntervalMs: number }[] {
const rows = [...this.matches.values()].map((record) => ({
matchId: record.id,
ticksRun: record.ticksRun,
maxIntervalMs: Math.round(record.maxIntervalMs * 100) / 100,
}));
for (const record of this.matches.values()) {
record.ticksRun = 0;
record.maxIntervalMs = 0;
}
return rows;
}
/* ------------------------------------------------------------------ tests */
/** Drop every room and timer without awards. */
clear(): void {
for (const record of this.matches.values()) this.stopTickLoop(record);
this.matches.clear();
if (this.sweepTimer) {
clearInterval(this.sweepTimer);
this.sweepTimer = null;
}
}
/** Disable wall-clock ticking so tests can drive steps manually. */
setAutoTick(enabled: boolean): void {
this.autoTickEnabled = enabled;
}
/** Run N simulation steps for a room, optionally at a fixed clock. */
advance(matchId: string, ticks = 1, now?: number): void {
const record = this.matches.get(matchId);
if (!record) throw new Error("Match not found.");
for (let i = 0; i < ticks; i += 1) this.step(record, now ?? Date.now());
}
}

38
src/arena/games/types.ts Normal file
View file

@ -0,0 +1,38 @@
/**
* Seam between the arena server and a real-time game it hosts.
*
* The arena owns the live match: the tick scheduler drives `tick()` at a fixed
* rate, and every mutation the connected players make arrives through the
* other methods. Everything a game needs to plug in lives here; the server
* never touches engine internals.
*
* Only one implementation exists today (Ordnance Disposal, `./bomperator`).
* The seam exists so another real-time game could follow someday; design
* nothing further for that without a concrete second tenant.
*/
export interface RealtimeGameModule {
/** Stable key used in logs and route prefixes. */
readonly key: string;
/** Create a new room with `hostUserId` in seat zero. Returns the match id. */
createRoom(hostUserId: number, hostName: string, options?: Record<string, unknown>): string;
/** Seat a user in an existing room (or restore their held seat). Throws on rejection. */
join(matchId: string, userId: number, name: string): void;
/** Explicit leave: hold the seat mid-match, remove it in the lobby. */
leave(matchId: string, userId: number): void;
/** Start the match (host-gated rules live inside the module). */
start(matchId: string, userId: number): void;
/** Submit one player input. Rate limiting and seq guards live inside. */
input(matchId: string, userId: number, input: unknown): void;
/** Advance the simulation exactly one tick (fan-out happens here too). */
tick(matchId: string): void;
/** Current per-user snapshot for fan-out / polling. */
snapshotFor(matchId: string, userId: number): unknown;
}

38
src/arena/protocol.ts Normal file
View file

@ -0,0 +1,38 @@
/**
* Arena wire protocol for Ordnance Disposal over WebSocket.
*
* Shared by the arena server (`src/arena/server.ts`) and the browser
* transport (`src/components/frontend/minigames/bomperator/transport.ts`) so
* the two ends cannot drift apart. All frames are JSON text messages.
*/
import type { BomperatorView, Dir } from "@/lib/minigames/bomperator/types";
/* ------------------------------------------------------------- client -> server */
export type ClientMessage =
/**
* Attach this socket to the ticket's match (restores a held seat, or
* registers a spectator). Seating itself always happens through the
* lifecycle actions (create/join), which proxy to the arena over REST; the
* socket only carries the latency-critical path.
*/
| { t: "join" }
/** Level-triggered movement intent with the client seq guard. */
| { t: "input"; dir?: Dir | null; seq?: number }
/** Edge-triggered charge placement. */
| { t: "drop" }
/** RTT probe + NAT keepalive; the server echoes `ts` straight back in pong. */
| { t: "ping"; ts: number };
/* ------------------------------------------------------------- server -> client */
export type ServerMessage =
/** Per-user snapshot (same shape the HTTP path serves, incl. lastInputSeq echo). */
| { t: "snapshot"; view: BomperatorView }
/** Echo of an applied input seq; the client reconciles its pending ledger on it. */
| { t: "ack"; seq: number }
| { t: "error"; code: string; message: string }
/** The match ended (host-ended, dissolved, or expired); clients drop to the lobby. */
| { t: "terminated"; matchId: string; reason: "host-ended" | "ended"; hostName: string | null }
| { t: "pong"; ts: number };

416
src/arena/server.ts Normal file
View file

@ -0,0 +1,416 @@
/**
* Arena: dedicated real-time match server for Ordnance Disposal.
*
* A plain Node 22 process (never Bun: the prod host CPU lacks AVX/AVX2, see
* the Dockerfile header) running an `http` server plus a `ws` upgrade handler.
* It owns live matches end to end: the drift-corrected 20 Hz tick loop, input
* application, and snapshot fan-out over sockets. It imports ONLY the pure
* engine ({engine,views,types,constants}); auth comes from short-lived tickets
* minted by Next, and awards travel back to Next via the results callback
* route. Topology and rationale: the arena plan document.
*
* Endpoints
* GET /health liveness (no auth)
* GET /matches?viewerId=<n> lobby listing (x-arena-secret)
* POST /matches create (x-arena-secret)
* POST /matches/join|snapshot|input lifecycle + inputs (x-arena-secret)
* WS /ws?ticket=<jwt> latency path for one verified user
*
* The REST endpoints exist so the Next server actions can proxy the lifecycle
* when the arena is enabled; the browser reaches them only through those
* actions. The WebSocket carries join/input/drop/ping both ways' worth of
* traffic (see ./protocol), which is the whole point of the arena: those
* frames skip the Next request pipeline entirely.
*
* SINGLE-INSTANCE ONLY (like the SSE bus it replaces): live match state is
* process memory; an arena restart kills in-flight drills. Acceptable for
* ~90s matches, documented in src/lib/minigames/AGENTS.md.
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { timingSafeEqual } from "node:crypto";
import { pathToFileURL } from "node:url";
import { WebSocketServer, type WebSocket } from "ws";
import type { BomperatorInput } from "@/lib/minigames/bomperator/engine";
import { verifyArenaTicket } from "./tickets";
import { BomperatorGameModule, type BomperatorFinalResult } from "./games/bomperator";
import type { ClientMessage, ServerMessage } from "./protocol";
export interface ArenaOptions {
port?: number;
host?: string;
/** Ticket verification + REST auth secret. Required outside tests. */
secret?: string;
/** Base URL of the Next app for the results callback. */
appUrl?: string;
/** Override the awards handoff (tests stub this). */
onResults?: (matchId: string, results: BomperatorFinalResult[]) => void;
autoTick?: boolean;
}
export interface ArenaHandle {
server: Server;
/** Resolved listening port (useful with port 0 in tests). */
port: number;
game: BomperatorGameModule;
close(): Promise<void>;
}
const MAX_BODY_BYTES = 64 * 1024;
const DRIFT_LOG_INTERVAL_MS = 30_000;
function log(line: string): void {
console.log(`[arena ${new Date().toISOString()}] ${line}`);
}
function secretsMatch(header: string | undefined, expected: string): boolean {
if (!header) return false;
const a = Buffer.from(header);
const b = Buffer.from(expected);
return a.length === b.length && timingSafeEqual(a, b);
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
const json = JSON.stringify(body);
res.writeHead(status, { "content-type": "application/json" });
res.end(json);
}
function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let size = 0;
req.on("data", (chunk: Buffer) => {
size += chunk.length;
if (size > MAX_BODY_BYTES) {
reject(new Error("Payload too large."));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on("end", () => {
if (chunks.length === 0) {
resolve({});
return;
}
try {
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record<string, unknown>);
} catch {
reject(new Error("Invalid JSON body."));
}
});
req.on("error", reject);
});
}
/** POST the final results to the Next route; retry a few times, then give up loudly. */
function makeResultsPoster(appUrl: string, secret: string) {
return function postResults(matchId: string, results: BomperatorFinalResult[]): void {
const url = `${appUrl.replace(/\/+$/, "")}/api/minigames/bomperator/results`;
const attempt = (remaining: number, delayMs: number): void => {
void fetch(url, {
method: "POST",
headers: { "content-type": "application/json", "x-arena-secret": secret },
body: JSON.stringify({ matchId, results }),
signal: AbortSignal.timeout(10_000),
})
.then(async (response) => {
if (!response.ok) throw new Error(`status ${response.status}`);
})
.catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
if (remaining > 0) {
log(`results POST failed for ${matchId.slice(0, 8)} (${message}); retrying in ${delayMs}ms`);
setTimeout(() => attempt(remaining - 1, delayMs * 2), delayMs).unref?.();
} else {
log(`RESULTS LOST for match ${matchId}: ${message}`);
}
});
};
attempt(3, 500);
};
}
export async function startArena(options: ArenaOptions = {}): Promise<ArenaHandle> {
const secret = options.secret ?? process.env.ARENA_SECRET ?? "";
if (!secret) {
throw new Error("ARENA_SECRET is required (ticket verification + results callback auth).");
}
const appUrl = options.appUrl ?? process.env.APP_URL ?? "http://localhost:3000";
/* ----------------------------------------------------------- socket hub */
/** userId -> every attached socket (multiple tabs / devices). */
const socketsByUser = new Map<number, Set<WebSocket>>();
interface SocketMeta {
matchId: string;
userId: number;
}
const socketMeta = new WeakMap<WebSocket, SocketMeta>();
const deliver = (userId: number, message: ServerMessage): void => {
const sockets = socketsByUser.get(userId);
if (!sockets || sockets.size === 0) return;
const frame = JSON.stringify(message);
for (const socket of sockets) {
if (socket.readyState === socket.OPEN) {
try {
socket.send(frame);
} catch {
/* close handler cleans up */
}
}
}
};
const game = new BomperatorGameModule({
deliver,
onResults: options.onResults ?? makeResultsPoster(appUrl, secret),
autoTick: options.autoTick,
});
/* --------------------------------------------------------------- REST */
async function handleHttp(req: IncomingMessage, res: ServerResponse): Promise<void> {
const url = new URL(req.url ?? "/", "http://arena");
if (url.pathname === "/health" && req.method === "GET") {
sendJson(res, 200, { ok: true, matches: game.listSummaries().length });
return;
}
if (!secretsMatch(req.headers["x-arena-secret"] as string | undefined, secret)) {
sendJson(res, 401, { success: false, error: "Bad arena credentials." });
return;
}
// Wrap every lifecycle call: thrown domain errors become ActionResult-shaped
// failures so the Next proxy can hand them straight to its caller.
const run = async (fn: () => unknown): Promise<void> => {
try {
const data = await fn();
sendJson(res, 200, { success: true, ...(data === undefined ? {} : { data }) });
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
sendJson(res, 200, { success: false, error: message });
}
};
const body = req.method === "POST" ? await readBody(req) : {};
const str = (key: string): string => String(body[key] ?? "");
const num = (key: string): number => Number(body[key]);
if (url.pathname === "/matches" && req.method === "GET") {
const viewerRaw = url.searchParams.get("viewerId");
const viewerId = viewerRaw !== null && viewerRaw !== "" ? Number(viewerRaw) : undefined;
await run(() => game.listSummaries(Number.isFinite(viewerId) ? viewerId : undefined));
return;
}
if (url.pathname === "/matches" && req.method === "POST") {
await run(() => ({
matchId: game.createRoom(num("userId"), str("name"), { roundTarget: body.roundTarget }),
}));
return;
}
if (url.pathname === "/matches/join" && req.method === "POST") {
await run(() => {
game.join(str("matchId"), num("userId"), str("name"));
return game.snapshotFor(str("matchId"), num("userId"));
});
return;
}
if (url.pathname === "/matches/snapshot" && req.method === "POST") {
await run(() => game.snapshotFor(str("matchId"), num("userId")));
return;
}
if (url.pathname === "/matches/start" && req.method === "POST") {
await run(() => {
game.start(str("matchId"), num("userId"));
return game.snapshotFor(str("matchId"), num("userId"));
});
return;
}
if (url.pathname === "/matches/input" && req.method === "POST") {
await run(() => {
game.input(str("matchId"), num("userId"), (body.input ?? {}) as BomperatorInput);
});
return;
}
if (url.pathname === "/matches/leave" && req.method === "POST") {
await run(() => game.leave(str("matchId"), num("userId")));
return;
}
if (url.pathname === "/matches/end" && req.method === "POST") {
await run(() => game.end(str("matchId"), num("userId")));
return;
}
if (url.pathname === "/matches/force-expire" && req.method === "POST") {
await run(() => game.forceExpire(str("matchId")));
return;
}
sendJson(res, 404, { success: false, error: "Not found." });
}
const server = createServer((req, res) => {
void handleHttp(req, res).catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
log(`http error: ${message}`);
if (!res.headersSent) sendJson(res, 500, { success: false, error: "Arena internal error." });
});
});
/* --------------------------------------------------------------- WS */
const wss = new WebSocketServer({ noServer: true });
server.on("upgrade", (req, socket, head) => {
const url = new URL(req.url ?? "/", "http://arena");
if (url.pathname !== "/ws") {
socket.write("HTTP/1.1 404 Not Found\r\n\r\n");
socket.destroy();
return;
}
void (async () => {
const claims = await verifyArenaTicket(url.searchParams.get("ticket") ?? "", secret);
if (!claims) {
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
socketMeta.set(ws, { matchId: claims.mid, userId: claims.uid });
let sockets = socketsByUser.get(claims.uid);
if (!sockets) {
sockets = new Set();
socketsByUser.set(claims.uid, sockets);
}
sockets.add(ws);
ws.on("message", (raw: Buffer) => {
void handleWsMessage(ws, raw).catch(() => undefined);
});
ws.on("close", () => {
const meta = socketMeta.get(ws);
if (!meta) return;
const set = socketsByUser.get(meta.userId);
if (set) {
set.delete(ws);
if (set.size === 0) socketsByUser.delete(meta.userId);
}
// Only hold the seat when this was the user's last socket on THIS
// match; a second tab closing must not disconnect the first one.
const stillAttached =
set !== undefined &&
[...set].some((other) => socketMeta.get(other)?.matchId === meta.matchId);
if (!stillAttached) game.detach(meta.matchId, meta.userId);
});
});
})().catch(() => {
socket.destroy();
});
});
async function handleWsMessage(ws: WebSocket, raw: Buffer): Promise<void> {
const meta = socketMeta.get(ws);
if (!meta) return;
let message: ClientMessage;
try {
message = JSON.parse(raw.toString("utf8")) as ClientMessage;
} catch {
return;
}
const send = (message: ServerMessage): void => {
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message));
};
const fail = (code: string, errMessage: string): void => {
send({ t: "error", code, message: errMessage });
};
switch (message.t) {
case "join": {
const view = game.attach(meta.matchId, meta.userId);
if (!view) {
fail("match-gone", "Match not found.");
ws.close(4000, "match-gone");
return;
}
send({ t: "snapshot", view });
return;
}
case "input": {
try {
game.input(meta.matchId, meta.userId, { dir: message.dir ?? null, seq: message.seq });
if (typeof message.seq === "number") send({ t: "ack", seq: message.seq });
} catch (error) {
fail("input-rejected", error instanceof Error ? error.message : String(error));
}
return;
}
case "drop": {
try {
game.input(meta.matchId, meta.userId, { drop: true });
} catch (error) {
fail("input-rejected", error instanceof Error ? error.message : String(error));
}
return;
}
case "ping": {
send({ t: "pong", ts: Number(message.ts) || 0 });
return;
}
default:
return;
}
}
/* ------------------------------------------------------- drift telemetry */
let driftTimer: ReturnType<typeof setInterval> | null = null;
if (options.autoTick !== false) {
driftTimer = setInterval(() => {
for (const row of game.driftReport()) {
if (row.ticksRun > 0) {
log(
`tick-drift match=${row.matchId.slice(0, 8)} ticks=${row.ticksRun} ` +
`maxInterval=${row.maxIntervalMs.toFixed(2)}ms window=${DRIFT_LOG_INTERVAL_MS / 1000}s`,
);
}
}
}, DRIFT_LOG_INTERVAL_MS);
driftTimer.unref?.();
}
/* ------------------------------------------------------------- lifecycle */
await new Promise<void>((resolve) => server.listen(options.port ?? Number(process.env.ARENA_PORT ?? 4100), options.host ?? "0.0.0.0", resolve));
const address = server.address();
const port = typeof address === "object" && address !== null ? address.port : 0;
const close = async (): Promise<void> => {
if (driftTimer) clearInterval(driftTimer);
game.clear();
for (const client of wss.clients) client.terminate();
await new Promise<void>((resolve) => server.close(() => resolve()));
};
return { server, port, game, close };
}
/* ------------------------------------------------------------------ main */
/** Direct-run guard so tests can import startArena without booting. */
const isMain =
typeof process.argv[1] === "string" && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
void startArena().then((handle) => {
log(`listening on :${handle.port} (ws path /ws, results -> ${process.env.APP_URL ?? "http://localhost:3000"})`);
const shutdown = (signal: NodeJS.Signals): void => {
log(`${signal} received, shutting down`);
void handle.close().then(() => process.exit(0));
};
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
});
}

54
src/arena/tickets.ts Normal file
View file

@ -0,0 +1,54 @@
/**
* Arena connection tickets.
*
* A ticket is a short-lived (30s) JWT minted by the Next app
* (`createArenaTicket` in the bomperator actions) and carried in the WebSocket
* connect query string, because browsers cannot attach custom headers to a WS
* handshake. It proves "this logged-in user id wants to watch/play this match
* id" without exposing the Payload session to the arena process.
*
* Deliberate tradeoff (agreed in the plan): there is no single-use replay
* store. The 30s expiry plus the narrow uid+matchId scope is the defense; a
* stolen ticket can only impersonate its own seat in its own match for half a
* minute.
*/
import { jwtVerify } from "jose";
export interface ArenaTicketClaims {
/** User id of the connecting player. */
uid: number;
/** Match the ticket grants access to. */
mid: string;
}
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/**
* Verify a ticket signature + expiry and check that the uid/matchId pair is
* coherent (positive integer id, uuid match). Returns the claims or null;
* never throws.
*/
export async function verifyArenaTicket(
token: string,
secret: string,
): Promise<ArenaTicketClaims | null> {
if (!token || !secret) return null;
try {
// Buffer (not TextEncoder) so the key is a plain Node Uint8Array even when
// this runs inside a jsdom test realm with its own intrinsics (jose's
// instanceof checks are realm-sensitive).
const key = Buffer.from(secret, "utf8");
const { payload } = await jwtVerify(token, key, {
algorithms: ["HS256"],
clockTolerance: 5,
});
const uid = typeof payload.uid === "number" ? payload.uid : Number(payload.uid);
const mid = payload.matchId;
if (!Number.isInteger(uid) || uid <= 0) return null;
if (typeof mid !== "string" || !UUID_RE.test(mid)) return null;
return { uid, mid };
} catch {
return null;
}
}

View file

@ -10,15 +10,14 @@ import {
} from "@/app/(frontend)/minigames/bomperator/actions";
import { toast } from "sonner";
import { useRealtimePresence } from "@/hooks/useRealtimePresence";
import {
BOMP_STATE_EVENT,
BOMP_TERMINATED_EVENT,
type BomperatorStateDetail,
type BomperatorTerminatedDetail,
} from "@/hooks/useGameTick";
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;
@ -38,17 +37,6 @@ const STAT_ITEMS = [
type ArenaView = "lobby" | "match";
/**
* Snapshot delivery is push-first: the server broadcasts a per-user snapshot over
* the SSE bus on every tick (see registry.pushSnapshots). This poll is only a
* correctness fallback for dropped pushes / dev module reloads, so it runs far
* slower than a tick and skips entirely while a request is already in flight.
* 500ms is deliberately conservative: it is ~50x lighter than the old 40ms flood
* (which saturated the dev server and delayed inputs by seconds), yet still bounds
* staleness to half a second even if the push path never lands.
*/
const FALLBACK_POLL_MS = 500;
export function BomperatorArena({
initialStats,
currentUserId,
@ -147,68 +135,38 @@ export function BomperatorArena({
};
}, [initialMatchId, applySnapshot]);
// Push-first: apply snapshots the server broadcasts over the SSE bus for this
// match. The bus is globalThis-anchored so it reaches us from the action/tick
// bundles; version dedup keeps it consistent with the fallback poll below.
useEffect(() => {
if (view !== "match" || matchId === null) return;
const handleState = (event: Event) => {
const detail = (event as CustomEvent<BomperatorStateDetail>).detail;
if (!detail || detail.matchId !== matchId || !detail.snapshot) return;
applySnapshot(detail.snapshot);
};
window.addEventListener(BOMP_STATE_EVENT, handleState);
return () => window.removeEventListener(BOMP_STATE_EVENT, handleState);
}, [view, matchId, 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");
// The host ended the drill: tell everyone else why, then drop to the lobby.
useEffect(() => {
if (view !== "match" || matchId === null) return;
const handleTerminated = (event: Event) => {
const detail = (event as CustomEvent<BomperatorTerminatedDetail>).detail;
if (!detail || detail.matchId !== matchId) 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 =
detail.reason === "host-ended"
? detail.hostName
? `${detail.hostName} ended the drill.`
info.reason === "host-ended"
? info.hostName
? `${info.hostName} ended the drill.`
: "The host ended the drill."
: "This drill has ended.";
handleEnded(message);
};
window.addEventListener(BOMP_TERMINATED_EVENT, handleTerminated);
return () => window.removeEventListener(BOMP_TERMINATED_EVENT, handleTerminated);
}, [view, matchId, handleEnded]);
// Slow, in-flight-guarded fallback poll: recovers dropped pushes and detects a
// dissolved match. Not the latency path (the push is), so it stays gentle and
// never stacks requests behind an outstanding one.
useEffect(() => {
if (view !== "match" || matchId === null) return;
let cancelled = false;
let inFlight = false;
const run = () => {
if (inFlight) return;
inFlight = true;
void fetchBomperatorMatch(matchId)
.then((result) => {
if (cancelled) return;
if (result.success && result.data) {
applySnapshot(result.data);
} else if (result.error === "Match not found.") {
// Fallback for a missed host-ended push: neutral wording, since the
// poll alone cannot tell why the match disappeared.
handleEnded("This drill has ended.");
}
})
.catch(() => undefined)
.finally(() => {
if (!cancelled) inFlight = false;
});
};
const poll = window.setInterval(run, FALLBACK_POLL_MS);
const offKind = next.onKindChange?.(setTransportKind);
setTransportKind(next.kind);
setTransport(next);
next.start();
return () => {
cancelled = true;
window.clearInterval(poll);
offSnapshot();
offTerminated();
offKind?.();
next.close();
setTransport(null);
};
}, [view, matchId, applySnapshot, handleEnded]);
@ -247,7 +205,7 @@ export function BomperatorArena({
const operatorsOnline = useRealtimePresence("bomperator", inMatch, true);
return (
<div className="flex flex-col gap-6">
<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>
@ -275,9 +233,10 @@ export function BomperatorArena({
{view === "lobby" ? (
<BomperatorLobby onOpenMatch={applyMatch} currentUserId={currentUserId} />
) : match ? (
) : match && transport ? (
<BomperatorGame
match={match}
transport={transport}
currentUserId={currentUserId}
onLeave={leave}
onEnd={end}

View file

@ -10,7 +10,7 @@ import {
PRED_DEADZONE,
PRED_ENVELOPE_BUDGET_MS,
} from "@/lib/minigames/bomperator/prediction";
import { sendBomperatorInput } from "@/app/(frontend)/minigames/bomperator/actions";
import type { BomperatorTransport } from "./transport";
import { BomperatorHud, seatColor } from "./BomperatorHud";
import { BomperatorTouchControls } from "./BomperatorTouchControls";
import { useBomperatorSounds } from "./sounds";
@ -347,6 +347,7 @@ function drawPlayer(ctx: CanvasRenderingContext2D, pos: RenderPos, player: Playe
export function BomperatorGame({
match,
transport,
currentUserId,
onLeave,
onEnd,
@ -354,6 +355,8 @@ export function BomperatorGame({
operatorsOnline,
}: {
match: BomperatorView;
/** Snapshot/input delivery (WS to the arena, or HTTP + SSE fallback). */
transport: BomperatorTransport;
currentUserId: number | string;
onLeave: () => void;
onEnd: () => void;
@ -426,19 +429,30 @@ export function BomperatorGame({
}
}
try {
await sendBomperatorInput(match.matchId, { drop: true });
await transport.sendDrop();
} catch {
// Ignore transient failures.
}
}, [match.matchId, playPlace]);
}, [transport, playPlace]);
/* ---- latency source: POST timing on HTTP, ping/pong timing on WS ---- */
useEffect(
() =>
transport.onRttSample((ms) => {
rttAvgRef.current = rttAvgRef.current * 0.8 + ms * 0.2;
}),
[transport],
);
/**
* Fire a direction change immediately with a monotonic seq. The server drops
* anything at or below the last applied seq, so there is no reason to queue
* behind an in-flight POST: the newest intent always wins on the wire, and a
* behind an in-flight send: the newest intent always wins on the wire, and a
* direction change costs one round trip instead of up to two. Human key edges
* are inherently rate-limited, so this cannot flood the way the old unbounded
* intervals did. Each send also feeds a rolling RTT estimate for prediction.
* intervals did. The transport feeds the rolling RTT estimate separately
* (POST timing on HTTP, ping/pong on WS).
*/
const sendDir = useCallback(
(dir: Dir | null) => {
@ -446,14 +460,9 @@ export function BomperatorGame({
const pending = pendingRef.current;
pending.push({ seq, dir, sentAt: performance.now() });
if (pending.length > 64) pending.splice(0, pending.length - 64);
const t0 = performance.now();
void sendBomperatorInput(match.matchId, { dir, seq })
.catch(() => undefined)
.finally(() => {
rttAvgRef.current = rttAvgRef.current * 0.8 + (performance.now() - t0) * 0.2;
});
void transport.sendInput(dir, seq).catch(() => undefined);
},
[match.matchId],
[transport],
);
/**
@ -522,7 +531,7 @@ export function BomperatorGame({
window.clearInterval(keepalive);
heldKeysRef.current = [];
};
}, [canControl, match.matchId, pressDir, releaseDir, sendDir, sendDrop]);
}, [canControl, pressDir, releaseDir, sendDir, sendDrop]);
/* ---- board swipes (touch): swipe sets direction, tap stops ---- */

View file

@ -0,0 +1,485 @@
"use client";
/**
* Snapshot/input delivery transports for Ordnance Disposal.
*
* Two implementations behind one small interface:
* - `HttpTransport`: today's path, unchanged behavior. Inputs POST through the
* `sendBomperatorInput` action, snapshots arrive over the SSE bus
* (`bomperator-state`) with the slow guarded poll as correctness fallback.
* - `WsTransport`: the arena path. A short-lived ticket is minted per connect
* attempt, then inputs/drops/pings ride one WebSocket and snapshots are
* pushed straight back. Reconnect uses capped exponential backoff plus
* jitter; a seat resumes within `RECONNECT_WINDOW_MS` automatically because
* the arena holds it while the socket is gone.
*
* Selection lives in `createBomperatorTransport`: try WS first when
* `NEXT_PUBLIC_ARENA_URL` is baked into the bundle, fall back to HTTP after two
* connection failures or a 5s first-snapshot timeout. An absent
* `NEXT_PUBLIC_ARENA_URL` means pure HTTP: that is the kill switch and the
* rollback path.
*
* The seq/lastInputSeq pending ledger and reconcile logic in BomperatorGame
* work unchanged over both transports: both deliver the same `BomperatorView`
* snapshots with the same `lastInputSeq` echo, and both feed `rttAvgRef` via
* `onRttSample` (POST timing on HTTP, ping/pong timing on WS).
*/
import type { BomperatorView, Dir } from "@/lib/minigames/bomperator/types";
import { RECONNECT_WINDOW_MS } from "@/lib/minigames/bomperator/constants";
import {
createArenaTicket,
fetchBomperatorMatch,
sendBomperatorInput,
} from "@/app/(frontend)/minigames/bomperator/actions";
import {
BOMP_STATE_EVENT,
BOMP_TERMINATED_EVENT,
type BomperatorStateDetail,
type BomperatorTerminatedDetail,
} from "@/hooks/useGameTick";
import type { ClientMessage, ServerMessage } from "@/arena/protocol";
export type TransportKind = "ws" | "http";
export interface BomperatorTermination {
reason: string;
hostName?: string | null;
}
export interface BomperatorTransport {
readonly kind: TransportKind;
/** Begin delivering snapshots / accepting sends. Idempotent. */
start(): void;
/** Tear down all listeners/timers/sockets. Idempotent. */
close(): void;
sendInput(dir: Dir | null, seq: number): Promise<void>;
sendDrop(): Promise<void>;
onSnapshot(cb: (view: BomperatorView) => void): () => void;
onTerminated(cb: (info: BomperatorTermination) => void): () => void;
onRttSample(cb: (ms: number) => void): () => void;
/** Fires when the active transport changes (WS -> HTTP fallback). */
onKindChange?(cb: (kind: TransportKind) => void): () => void;
}
/** Minimal listener set shared by both transports. */
function listeners<T>() {
const set = new Set<(value: T) => void>();
return {
on(cb: (value: T) => void): () => void {
set.add(cb);
return () => set.delete(cb);
},
emit(value: T): void {
for (const cb of [...set]) cb(value);
},
};
}
/* ------------------------------------------------------------------- HTTP */
/**
* Snapshot delivery is push-first over the SSE bus; this poll is only the
* correctness fallback for dropped pushes / dev module reloads, so it runs far
* slower than a tick and skips while a request is in flight. Same 500ms the
* arena component used before transports existed.
*/
const FALLBACK_POLL_MS = 500;
export class HttpTransport implements BomperatorTransport {
readonly kind = "http" as const;
private readonly matchId: string;
private readonly snapshotBus = listeners<BomperatorView>();
private readonly terminatedBus = listeners<BomperatorTermination>();
private readonly rttBus = listeners<number>();
private pollTimer: number | null = null;
private teardowns: Array<() => void> = [];
private started = false;
private closed = false;
constructor(matchId: string) {
this.matchId = matchId;
}
start(): void {
if (this.closed || this.started) return;
this.started = true;
const handleState = (event: Event) => {
const detail = (event as CustomEvent<BomperatorStateDetail>).detail;
if (!detail || detail.matchId !== this.matchId || !detail.snapshot) return;
this.snapshotBus.emit(detail.snapshot);
};
const handleTerminated = (event: Event) => {
const detail = (event as CustomEvent<BomperatorTerminatedDetail>).detail;
if (!detail || detail.matchId !== this.matchId) return;
this.terminatedBus.emit({ reason: detail.reason ?? "ended", hostName: detail.hostName });
};
window.addEventListener(BOMP_STATE_EVENT, handleState);
window.addEventListener(BOMP_TERMINATED_EVENT, handleTerminated);
let inFlight = false;
this.pollTimer = window.setInterval(() => {
if (inFlight) return;
inFlight = true;
void fetchBomperatorMatch(this.matchId)
.then((result) => {
if (this.closed) return;
if (result.success && result.data) {
this.snapshotBus.emit(result.data);
} else if (result.error === "Match not found.") {
// Fallback for a missed host-ended push: neutral wording, since the
// poll alone cannot tell why the match disappeared.
this.terminatedBus.emit({ reason: "ended" });
}
})
.catch(() => undefined)
.finally(() => {
inFlight = false;
});
}, FALLBACK_POLL_MS);
this.teardowns.push(() => {
window.removeEventListener(BOMP_STATE_EVENT, handleState);
window.removeEventListener(BOMP_TERMINATED_EVENT, handleTerminated);
if (this.pollTimer !== null) window.clearInterval(this.pollTimer);
this.pollTimer = null;
});
}
close(): void {
if (this.closed) return;
this.closed = true;
for (const fn of this.teardowns) fn();
this.teardowns = [];
}
async sendInput(dir: Dir | null, seq: number): Promise<void> {
const t0 = performance.now();
try {
await sendBomperatorInput(this.matchId, { dir, seq });
} catch {
// Ignore transient failures; the keepalive re-asserts held directions.
} finally {
this.rttBus.emit(performance.now() - t0);
}
}
async sendDrop(): Promise<void> {
try {
await sendBomperatorInput(this.matchId, { drop: true });
} catch {
// Ignore transient failures.
}
}
onSnapshot = this.snapshotBus.on;
onTerminated = this.terminatedBus.on;
onRttSample = this.rttBus.on;
}
/* --------------------------------------------------------------------- WS */
/** Reconnect backoff: 1s, 2s, 4s ... capped at 30s, plus +/-20% jitter. */
const WS_BACKOFF_BASE_MS = 1000;
const WS_BACKOFF_CAP_MS = 30_000;
/** Give up on WS (and fall back to HTTP) if the first snapshot hasn't landed. */
const WS_FIRST_SNAPSHOT_TIMEOUT_MS = 5000;
/** Ping cadence: feeds rttAvgRef and keeps NAT bindings alive on mobile. */
const WS_PING_INTERVAL_MS = 2000;
export class WsTransport implements BomperatorTransport {
readonly kind = "ws" as const;
private readonly matchId: string;
private readonly baseUrl: string;
private readonly snapshotBus = listeners<BomperatorView>();
private readonly terminatedBus = listeners<BomperatorTermination>();
private readonly rttBus = listeners<number>();
private socket: WebSocket | null = null;
private reconnectTimer: number | null = null;
private watchdogTimer: number | null = null;
private pingTimer: number | null = null;
private attempt = 0;
private connectedOnce = false;
/** Instant the current outage began (0 while connected). */
private downSince = 0;
private closed = false;
/** Called at most once when this transport gives up in favor of HTTP. */
private onFallback: () => void;
constructor(matchId: string, baseUrl: string, onFallback: () => void) {
this.matchId = matchId;
this.baseUrl = baseUrl.replace(/\/+$/, "");
this.onFallback = onFallback;
}
start(): void {
if (this.closed) return;
this.watchdogTimer = window.setTimeout(() => {
if (!this.connectedOnce) this.giveUp("no snapshot within setup window");
}, WS_FIRST_SNAPSHOT_TIMEOUT_MS);
void this.connect();
}
private scheduleReconnect(): void {
if (this.closed || this.reconnectTimer !== null) return;
const base = Math.min(WS_BACKOFF_BASE_MS * 2 ** Math.max(0, this.attempt - 1), WS_BACKOFF_CAP_MS);
const delay = base * (0.8 + Math.random() * 0.4); // jitter so tabs don't sync
this.reconnectTimer = window.setTimeout(() => {
this.reconnectTimer = null;
void this.connect();
}, delay);
}
private giveUp(reason: string): void {
if (this.closed) return;
this.closed = true;
this.cleanup();
console.info(`[bomperator] websocket transport disabled (${reason}); falling back to HTTP`);
this.onFallback();
}
private cleanup(): void {
if (this.reconnectTimer !== null) window.clearTimeout(this.reconnectTimer);
if (this.watchdogTimer !== null) window.clearTimeout(this.watchdogTimer);
if (this.pingTimer !== null) window.clearInterval(this.pingTimer);
this.reconnectTimer = null;
this.watchdogTimer = null;
this.pingTimer = null;
const socket = this.socket;
this.socket = null;
if (socket) {
socket.onopen = socket.onmessage = socket.onerror = socket.onclose = null;
try {
socket.close();
} catch {
/* already gone */
}
}
}
private async connect(): Promise<void> {
if (this.closed) return;
this.attempt += 1;
let ticket: string;
try {
const minted = await createArenaTicket(this.matchId);
if (!minted.success || !minted.data) throw new Error(minted.error ?? "ticket rejected");
ticket = minted.data.ticket;
} catch (error) {
// Ticket mint failures count like connection failures.
if (this.attempt >= 2 && !this.connectedOnce) {
this.giveUp(`ticket mint failed: ${error instanceof Error ? error.message : "unknown"}`);
return;
}
this.scheduleReconnect();
return;
}
if (this.closed) return;
let socket: WebSocket;
try {
socket = new WebSocket(`${this.baseUrl}/ws?ticket=${encodeURIComponent(ticket)}`);
} catch {
if (this.attempt >= 2 && !this.connectedOnce) this.giveUp("socket construction failed");
else this.scheduleReconnect();
return;
}
this.socket = socket;
socket.onopen = () => {
// NOTE: `attempt` resets only once a snapshot has actually landed (see
// onmessage): an open/close cycle that never delivers one still counts
// toward the two-failure fallback budget.
this.sendMessage({ t: "join" });
this.pingTimer = window.setInterval(() => {
this.sendMessage({ t: "ping", ts: Date.now() });
}, WS_PING_INTERVAL_MS);
};
socket.onmessage = (event: MessageEvent<string>) => {
let message: ServerMessage;
try {
message = JSON.parse(event.data) as ServerMessage;
} catch {
return;
}
switch (message.t) {
case "snapshot":
if (!this.connectedOnce) {
this.connectedOnce = true;
this.attempt = 0;
if (this.watchdogTimer !== null) {
window.clearTimeout(this.watchdogTimer);
this.watchdogTimer = null;
}
}
this.downSince = 0;
this.snapshotBus.emit(message.view);
return;
case "pong":
// Ping/pong replaces POST timing as the RTT source on WS.
this.rttBus.emit(Math.max(0, Date.now() - message.ts));
return;
case "terminated":
this.terminatedBus.emit({ reason: message.reason, hostName: message.hostName });
return;
case "ack":
case "error":
// acks are informational (reconcile rides snapshot lastInputSeq);
// input errors are transient by design and the client self-heals.
return;
default:
return;
}
};
const onDown = () => {
if (this.closed) return;
if (this.pingTimer !== null) {
window.clearInterval(this.pingTimer);
this.pingTimer = null;
}
if (!this.connectedOnce) {
if (this.attempt >= 2) this.giveUp("connection failed twice");
else this.scheduleReconnect();
return;
}
// Was working before: keep resuming (the arena holds the seat) until the
// outage itself has run past the reconnect window, then hand over to
// HTTP. Measured from the first drop, not the last snapshot: a quiet
// lobby pushes snapshots far apart without meaning anything is down.
const now = Date.now();
if (this.downSince === 0) this.downSince = now;
if (now - this.downSince > RECONNECT_WINDOW_MS) {
this.giveUp("outage exceeded the reconnect window");
return;
}
this.scheduleReconnect();
};
socket.onclose = onDown;
socket.onerror = () => {
/* onclose follows ondown; nothing extra to do */
};
}
private sendMessage(message: ClientMessage): void {
if (this.socket?.readyState === WebSocket.OPEN) {
try {
this.socket.send(JSON.stringify(message));
} catch {
/* onclose handles recovery */
}
}
}
close(): void {
if (this.closed) return;
this.closed = true;
this.cleanup();
}
async sendInput(dir: Dir | null, seq: number): Promise<void> {
// While the socket is down inputs are dropped on purpose: the arena holds
// the seat, and the keepalive re-asserts the held direction on reconnect.
this.sendMessage({ t: "input", dir, seq });
}
async sendDrop(): Promise<void> {
this.sendMessage({ t: "drop" });
}
onSnapshot = this.snapshotBus.on;
onTerminated = this.terminatedBus.on;
onRttSample = this.rttBus.on;
}
/* --------------------------------------------------------------- selection */
/**
* Transport manager with automatic WS -> HTTP fallback. The component talks to
* this facade only; a fallback swaps the inner transport while preserving all
* subscriptions, so BomperatorGame/Arena never notice the handover.
*/
class TransportManager implements BomperatorTransport {
private active: BomperatorTransport;
private readonly snapshotBus = listeners<BomperatorView>();
private readonly terminatedBus = listeners<BomperatorTermination>();
private readonly rttBus = listeners<number>();
private readonly kindBus = listeners<TransportKind>();
private readonly subs: Array<() => void> = [];
private started = false;
private closedFlag = false;
constructor(initial: BomperatorTransport) {
this.active = initial;
this.wire(initial);
}
get kind(): TransportKind {
return this.active.kind;
}
get closed(): boolean {
return this.closedFlag;
}
private wire(transport: BomperatorTransport): void {
this.subs.push(transport.onSnapshot((view) => this.snapshotBus.emit(view)));
this.subs.push(transport.onTerminated((info) => this.terminatedBus.emit(info)));
this.subs.push(transport.onRttSample((ms) => this.rttBus.emit(ms)));
}
start(): void {
if (this.started || this.closedFlag) return;
this.started = true;
this.active.start();
}
/** Replace the inner transport (WS fallback to HTTP). */
fallbackTo(next: BomperatorTransport): void {
if (this.closedFlag) return;
for (const off of this.subs) off();
this.subs.length = 0;
this.active.close();
this.active = next;
this.wire(next);
this.kindBus.emit(next.kind);
next.start();
}
close(): void {
if (this.closedFlag) return;
this.closedFlag = true;
for (const off of this.subs) off();
this.subs.length = 0;
this.active.close();
}
sendInput(dir: Dir | null, seq: number): Promise<void> {
return this.active.sendInput(dir, seq);
}
sendDrop(): Promise<void> {
return this.active.sendDrop();
}
onSnapshot = this.snapshotBus.on;
onTerminated = this.terminatedBus.on;
onRttSample = this.rttBus.on;
onKindChange = this.kindBus.on;
}
/**
* Build the transport for a match. Absent `NEXT_PUBLIC_ARENA_URL` means pure
* HTTP without ever attempting WS: that is the kill switch and rollback path.
*/
export function createBomperatorTransport(matchId: string): BomperatorTransport {
const base = process.env.NEXT_PUBLIC_ARENA_URL;
if (!base) return new HttpTransport(matchId);
let managerRef: TransportManager | null = null;
const ws = new WsTransport(matchId, base, () => {
if (managerRef && !managerRef.closed) managerRef.fallbackTo(new HttpTransport(matchId));
});
const manager = new TransportManager(ws);
managerRef = manager;
return manager;
}

View file

@ -0,0 +1,275 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import {
INTER_ROUND_COUNTDOWN_TICKS,
MAX_SEATS,
MIN_TO_START,
RECONNECT_WINDOW_MS,
} from "@/lib/minigames/bomperator/constants";
import type { BomperatorView } from "@/lib/minigames/bomperator/types";
import type { ServerMessage } from "@/arena/protocol";
import {
BomperatorGameModule,
type BomperatorFinalResult,
} from "@/arena/games/bomperator";
/**
* Arena game-module suite: the registry scenarios (tests/int/
* bomperator-registry.int.spec.ts) ported to the arena module with delivery
* and awards injected/stubbed. The Next-side registry keeps its own suite
* because the HTTP transport fallback still runs it.
*/
interface Delivered {
userId: number;
message: ServerMessage;
}
function makeModule(): {
mod: BomperatorGameModule;
delivered: Delivered[];
awards: Array<{ matchId: string; results: BomperatorFinalResult[] }>;
} {
const delivered: Delivered[] = [];
const awards: Array<{ matchId: string; results: BomperatorFinalResult[] }> = [];
const mod = new BomperatorGameModule({
deliver: (userId, message) => delivered.push({ userId, message }),
onResults: (matchId, results) => awards.push({ matchId, results }),
autoTick: false, // drive the sim manually; no wall-clock timers
});
return { mod, delivered, awards };
}
function viewOf(mod: BomperatorGameModule, matchId: string, userId: number): BomperatorView {
return mod.snapshotFor(matchId, userId);
}
/** Bring a freshly started match out of the countdown and into battle. */
function toBattle(mod: BomperatorGameModule, matchId: string): void {
mod.advance(matchId, INTER_ROUND_COUNTDOWN_TICKS + 1);
}
let ctx: ReturnType<typeof makeModule>;
beforeEach(() => {
ctx = makeModule();
});
afterEach(() => ctx.mod.clear());
describe("arena bomperator module: lobby", () => {
it("seats the host and reports a waiting match", () => {
const matchId = ctx.mod.createRoom(9001, "Host");
const summary = ctx.mod.listSummaries(9001).find((row) => row.matchId === matchId);
expect(summary?.phase).toBe("waiting");
expect(summary?.seatedCount).toBe(1);
expect(summary?.joined).toBe(true);
expect(ctx.mod.listSummaries(9002).find((row) => row.matchId === matchId)?.joined).toBe(false);
});
it("fills seats up to the cap and rejects an extra player", () => {
const matchId = ctx.mod.createRoom(9101, "Host");
for (let seat = 1; seat < MAX_SEATS; seat += 1) ctx.mod.join(matchId, 9101 + seat, `P${seat}`);
expect(() => ctx.mod.join(matchId, 9999, "Overflow")).toThrow("full");
});
it("stops a user seating at two matches at once", () => {
ctx.mod.createRoom(9201, "Host");
const second = ctx.mod.createRoom(9202, "Other");
expect(() => ctx.mod.join(second, 9201, "Host")).toThrow("already in another match");
});
it("lets a non-seated user read a spectator snapshot with no seat", () => {
const matchId = ctx.mod.createRoom(9301, "Host");
const view = viewOf(ctx.mod, matchId, 9302);
expect(view.yourSeat).toBeNull();
expect(view.players[0].name).toBe("Host");
});
});
describe("arena bomperator module: start gating", () => {
it("refuses to start below the minimum and starts at the minimum", () => {
const matchId = ctx.mod.createRoom(9401, "Host");
expect(() => ctx.mod.start(matchId, 9401)).toThrow(`at least ${MIN_TO_START}`);
ctx.mod.join(matchId, 9402, "Guest");
ctx.mod.start(matchId, 9401);
expect(viewOf(ctx.mod, matchId, 9401).phase).toBe("countdown");
});
it("rejects starting twice", () => {
const matchId = ctx.mod.createRoom(9501, "Host");
ctx.mod.join(matchId, 9502, "Guest");
ctx.mod.start(matchId, 9501);
expect(() => ctx.mod.start(matchId, 9501)).toThrow("already started");
});
});
describe("arena bomperator module: input + ticking", () => {
it("applies a queued movement input over subsequent ticks", () => {
const matchId = ctx.mod.createRoom(9601, "Host");
ctx.mod.join(matchId, 9602, "Guest");
ctx.mod.start(matchId, 9601);
toBattle(ctx.mod, matchId);
const before = viewOf(ctx.mod, matchId, 9601);
expect(before.phase).toBe("battle");
expect(before.players[before.yourSeat!].x).toBeCloseTo(1, 3);
ctx.mod.input(matchId, 9601, { dir: "right" });
ctx.mod.advance(matchId, 6);
const after = viewOf(ctx.mod, matchId, 9601);
expect(after.players[after.yourSeat!].x).toBeGreaterThan(1.5);
});
it("rejects inputs from a non-seated user", () => {
const matchId = ctx.mod.createRoom(9701, "Host");
ctx.mod.join(matchId, 9702, "Guest");
ctx.mod.start(matchId, 9701);
expect(() => ctx.mod.input(matchId, 9799, { dir: "left" })).toThrow("not in this match");
});
it("fans snapshots out through the deliver callback on every tick", () => {
const matchId = ctx.mod.createRoom(9711, "Host");
ctx.mod.join(matchId, 9712, "Guest");
ctx.mod.start(matchId, 9711);
ctx.delivered.length = 0;
ctx.mod.advance(matchId, 1);
const snapshots = ctx.delivered.filter((d) => d.message.t === "snapshot");
// Both seated technicians receive one snapshot per tick.
expect(new Set(snapshots.map((d) => d.userId))).toEqual(new Set([9711, 9712]));
});
});
describe("arena bomperator module: input sequencing", () => {
it("applies only the newest seq and ignores stale out-of-order frames", () => {
const matchId = ctx.mod.createRoom(9751, "Host");
ctx.mod.join(matchId, 9752, "Guest");
ctx.mod.start(matchId, 9751);
toBattle(ctx.mod, matchId);
ctx.mod.input(matchId, 9751, { dir: "right", seq: 1 });
ctx.mod.advance(matchId, 6);
const right = viewOf(ctx.mod, matchId, 9751);
const rightX = right.players[right.yourSeat!].x;
expect(rightX).toBeGreaterThan(1.5);
// A stale echo of an older intent must never resurrect it.
ctx.mod.input(matchId, 9751, { dir: "left", seq: 3 });
ctx.mod.input(matchId, 9751, { dir: "right", seq: 2 });
ctx.mod.advance(matchId, 6);
const after = viewOf(ctx.mod, matchId, 9751);
expect(after.players[after.yourSeat!].x).toBeLessThan(rightX);
});
it("echoes each seat's last applied input seq in the snapshot", () => {
const matchId = ctx.mod.createRoom(9761, "Host");
ctx.mod.join(matchId, 9762, "Guest");
ctx.mod.start(matchId, 9761);
toBattle(ctx.mod, matchId);
expect(viewOf(ctx.mod, matchId, 9761).players[0].lastInputSeq).toBe(0);
ctx.mod.input(matchId, 9761, { dir: "down", seq: 5 });
ctx.mod.input(matchId, 9761, { dir: "up", seq: 4 }); // stale: ignored
const view = viewOf(ctx.mod, matchId, 9761);
expect(view.players[0].lastInputSeq).toBe(5);
expect(view.players[1].lastInputSeq).toBe(0);
});
});
describe("arena bomperator module: disconnect and dissolve", () => {
it("holds a seat on socket detach and restores it on re-attach", () => {
const matchId = ctx.mod.createRoom(9801, "Host");
ctx.mod.join(matchId, 9802, "Guest");
ctx.mod.start(matchId, 9801);
toBattle(ctx.mod, matchId);
ctx.mod.detach(matchId, 9801); // socket dropped
expect(viewOf(ctx.mod, matchId, 9802).players[0].connected).toBe(false);
ctx.mod.attach(matchId, 9801); // reconnect within the window
expect(viewOf(ctx.mod, matchId, 9802).players[0].connected).toBe(true);
});
it("dissolves the match once a held seat's reconnect window lapses", () => {
const matchId = ctx.mod.createRoom(9901, "Host");
ctx.mod.join(matchId, 9902, "Guest");
ctx.mod.start(matchId, 9901);
toBattle(ctx.mod, matchId);
ctx.mod.leave(matchId, 9901); // host walks away
// Advance with a clock past the reconnect window: the seat expires and the
// match drops below two active technicians.
ctx.mod.advance(matchId, 1, Date.now() + RECONNECT_WINDOW_MS + 5_000);
const view = viewOf(ctx.mod, matchId, 9902);
expect(view.phase).toBe("complete");
expect(view.endReason).toBe("dissolved");
});
});
describe("arena bomperator module: exit paths", () => {
it("ends the match as soon as the last connected technician leaves", () => {
const matchId = ctx.mod.createRoom(9951, "Host");
ctx.mod.join(matchId, 9952, "Guest");
ctx.mod.start(matchId, 9951);
toBattle(ctx.mod, matchId);
ctx.mod.leave(matchId, 9951); // host walks; guest still connected -> alive
expect(() => viewOf(ctx.mod, matchId, 9952)).not.toThrow();
ctx.mod.leave(matchId, 9952); // last connected leaves -> dissolve + dispose now
expect(() => viewOf(ctx.mod, matchId, 9952)).toThrow("Match not found.");
});
it("lets a seated technician end the drill, but not a stranger", () => {
const matchId = ctx.mod.createRoom(9961, "Host");
ctx.mod.join(matchId, 9962, "Guest");
ctx.mod.start(matchId, 9961);
toBattle(ctx.mod, matchId);
expect(() => ctx.mod.end(matchId, 9999)).toThrow("Only a technician");
ctx.mod.end(matchId, 9962); // guest can end it
expect(() => viewOf(ctx.mod, matchId, 9961)).toThrow("Match not found.");
});
it("tells attached clients when the drill is ended by its host", () => {
const matchId = ctx.mod.createRoom(9971, "Host");
ctx.mod.join(matchId, 9972, "Guest");
ctx.mod.start(matchId, 9971);
toBattle(ctx.mod, matchId);
ctx.mod.attach(matchId, 9972);
ctx.mod.end(matchId, 9971); // host ends it
const frames = ctx.delivered.filter((d) => d.message.t === "terminated");
// The actor gets no frame; the guest does, naming the host.
expect(frames.map((f) => f.userId)).toEqual([9972]);
const frame = frames[0]!.message;
expect(frame.t === "terminated" && frame.reason).toBe("host-ended");
expect(frame.t === "terminated" && frame.hostName).toBe("Host");
});
});
describe("arena bomperator module: disposal + awards handoff", () => {
it("force-expiring removes the match", () => {
const matchId = ctx.mod.createRoom(9911, "Host");
ctx.mod.forceExpire(matchId);
expect(() => viewOf(ctx.mod, matchId, 9911)).toThrow("Match not found.");
});
it("clearing for tests isolates subsequent specs", () => {
ctx.mod.createRoom(9921, "Host");
ctx.mod.clear();
expect(ctx.mod.listSummaries()).toHaveLength(0);
});
it("hands final results to the awards callback exactly once per match", () => {
const matchId = ctx.mod.createRoom(9931, "Host");
ctx.mod.join(matchId, 9932, "Guest");
ctx.mod.start(matchId, 9931);
// Dissolve below two active seats by walking away with a lapsed window.
toBattle(ctx.mod, matchId);
ctx.mod.leave(matchId, 9931);
ctx.mod.advance(matchId, 1, Date.now() + RECONNECT_WINDOW_MS + 5_000);
// Completion fired the handoff; disposing again must not repeat it.
ctx.mod.forceExpire(matchId);
expect(ctx.awards).toHaveLength(1);
expect(ctx.awards[0]!.matchId).toBe(matchId);
expect(ctx.awards[0]!.results.map((r) => r.userId).sort()).toEqual([9931, 9932]);
});
});

View file

@ -0,0 +1,233 @@
// @vitest-environment node
// 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);
});
});

View file

@ -690,6 +690,21 @@ describe("bomperator prediction harness", () => {
expect(tel.snaps).toHaveLength(0);
});
it("ws-grade latency: the arena transport's low end stays teleport-free", () => {
// The other end of the latency range from the prod-trace replay: a
// dedicated-server WebSocket round trip (single-digit RTT, low jitter, no
// Next request pipeline in the snapshot path). The envelope must ride this
// calm distribution untouched too - corrections that only look smooth at
// high latency are still corrections.
const cfg: ScenarioConfig = { ...BASE, oneWayMs: 4, jitterMs: 2, pipelineMs: 5, rttTrueMs: 9 };
const tel = runScenario(cfg);
report("ws-low-latency", tel);
expect(tel.resetBranch).toBe(0);
expect(tel.deaths).toBe(0);
expect(tel.completedMs).toBeGreaterThanOrEqual(cfg.durationMs);
expect(tel.snaps).toHaveLength(0);
});
it("tight zigzag: rapid turns never hard-snap or rubber-band", () => {
const cfg: ScenarioConfig = { ...BASE, legMs: 350 };
const tel = runScenario(cfg);

View file

@ -1,3 +1,10 @@
/**
* In-process registry suite (the HTTP transport backend). The arena port of
* this game logic has its own suites: tests/int/arena-bomperator.int.spec.ts
* (module, awards/delivery stubbed) and tests/int/arena-server.int.spec.ts
* (live server + real sockets). This file stays because the registry remains
* live behind the HttpTransport fallback until prod proves the arena.
*/
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { getPayload, type Payload } from "payload";
import config from "@payload-config";