From 593d69714bba0665e01ee6a1c0d3d8920b0975ac Mon Sep 17 00:00:00 2001 From: Benjamin Oezcan Date: Thu, 19 Nov 2026 14:25:46 +0100 Subject: [PATCH] feat(net): server measures every player's ping and its own step cost, sent with each snapshot Also fixes the ping message schema (it checked the field t, which is the message type). --- game/protocol.js | 3 ++- server/lobby.js | 6 +++++- server/match/room.js | 9 ++++++++- server/test/lobby.test.js | 16 +++++++++++++++- server/ws/hub.js | 16 ++++++++++++---- tests/protocol.test.js | 5 ++++- 6 files changed, 46 insertions(+), 9 deletions(-) diff --git a/game/protocol.js b/game/protocol.js index 5d8845b..fb15c37 100644 --- a/game/protocol.js +++ b/game/protocol.js @@ -24,7 +24,7 @@ // client -> server message schemas: field -> check const C2S = { hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) }, - ping: { t: v => v === undefined || isNum(v) }, + ping: { t0: v => v === undefined || isNum(v) }, // (t is the message type itself) room: { room: v => FLAGS.includes(v) || v === 'all' }, challenge: { to: v => isStr(v) }, 'challenge.cancel': {}, @@ -89,6 +89,7 @@ robots, ack: snap.ack ? snap.ack[seat] : 0, away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined, + rtt: snap.rtt ? (seat === 0 ? snap.rtt.slice() : [snap.rtt[1], snap.rtt[0]]) : undefined, // ping of [me, opponent] result: localResult(seat, snap.result), crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }), rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })), diff --git a/server/lobby.js b/server/lobby.js index 927b199..bf3f5eb 100644 --- a/server/lobby.js +++ b/server/lobby.js @@ -104,6 +104,7 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) { id, seed, players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })), send: (seat, msg) => tell(seats[seat].uid, msg), + rttOf: seat => { const p = players.get(seats[seat].uid); return p ? p.rtt : 0; }, onEnd: finish, }); if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now()); @@ -143,10 +144,13 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) { } } + // ping of a player, measured by the hub (WebSocket ping/pong) + function setRtt(uid, ms) { const p = players.get(uid); if (p) p.rtt = p.rtt ? p.rtt * 0.7 + ms * 0.3 : ms; } + // the profile changed (robot, flag, fame): show it to everyone function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); } - return { join, leave, handle, refresh, startMatch, players, pending, inMatch }; + return { join, leave, handle, refresh, setRtt, startMatch, players, pending, inMatch }; } module.exports = { createLobby, CHALLENGE_TTL }; diff --git a/server/match/room.js b/server/match/room.js index 96befef..c4d361f 100644 --- a/server/match/room.js +++ b/server/match/room.js @@ -25,6 +25,7 @@ class Room { this.seed = opt.seed || 1; this.players = opt.players; // [{ uid, name, build, paint, flag }] this.send = opt.send || (() => {}); + this.rttOf = opt.rttOf || (() => 0); // seat -> ping in ms (measured by the WebSocket hub) this.onEnd = opt.onEnd || (() => {}); const ids = RC.ARENAS.map(a => a.id); this.arena = opt.arena || ids[this.seed % ids.length]; @@ -80,7 +81,10 @@ class Room { for (const k of [0, 1]) if (this.away[k]) this.away[k]++; if (this.tickN <= COUNTDOWN) return; const s = this.s; + const t0 = process.hrtime.bigint(); RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]); + const ms = Number(process.hrtime.bigint() - t0) / 1e6; + this.tickMs = this.tickMs ? this.tickMs * 0.9 + ms * 0.1 : ms; // smoothed cost of one step (server load) if (!this.evBuf) this.evBuf = []; if (s.events.length) this.evBuf.push(...s.events); s.events.length = 0; @@ -95,7 +99,10 @@ class Room { const snap = RC.Proto.packSnap(s, this.tickN, this.acks); s.events = []; this.evBuf.length = 0; const away = [!!this.away[0], !!this.away[1]]; - for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away }, snap)); + // network diagnostics for the F3 overlay: each player's ping to the server (measured here) + server step cost + const rtt = [0, 1].map(k => Math.round(this.rttOf(k) || 0)); + const tickMs = Math.round((this.tickMs || 0) * 100) / 100; + for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away, rtt, tickMs, sent: Date.now() }, snap)); } finish(result) { diff --git a/server/test/lobby.test.js b/server/test/lobby.test.js index c8903a6..6d0e451 100644 --- a/server/test/lobby.test.js +++ b/server/test/lobby.test.js @@ -46,6 +46,16 @@ test('old protocol version is told to reload', async () => { assert.equal((await c.closed).code, 4002); }); +test('ping is answered with pong (for the latency overlay)', async () => { + const a = await S.account(); + const c = await S.client(a.idToken); + c.send({ t: 'ping', t0: 42 }); + const p = await c.next('pong'); + assert.equal(p.t0, 42); + assert.equal(typeof p.serverTime, 'number'); + c.close(); +}); + test('invalid messages get an error, the socket stays open', async () => { const a = await S.account(); const c = await S.client(a.idToken); @@ -112,7 +122,11 @@ test('full live match over WebSocket: both get start, snapshots, and mirrored re const winner = la === 0 ? ea : lb === 0 ? eb : null; if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out'); assert.equal(eb.save.games, 1); - assert.ok(ca.inbox.some(m => m.t === 'snap'), 'snapshots arrived before the end'); + const snap = ca.inbox.find(m => m.t === 'snap'); + assert.ok(snap, 'snapshots arrived before the end'); + assert.ok(Array.isArray(snap.rtt) && snap.rtt.length === 2, 'snapshot carries both pings'); + assert.equal(typeof snap.tickMs, 'number', 'snapshot carries the server step cost'); + assert.equal(typeof snap.sent, 'number'); // rewards were booked on the server const sA = await S.json('GET', '/api/online', undefined, a.idToken); diff --git a/server/ws/hub.js b/server/ws/hub.js index 6524230..44fc300 100644 --- a/server/ws/hub.js +++ b/server/ws/hub.js @@ -7,15 +7,20 @@ const auth = require('../auth'); const HELLO_MS = 5000; const RATE = 80; // messages per second per socket (inputs ~30/s + lobby) -const PING_MS = 15000; +const PING_MS = 2000; // ws ping every 2 s: keepalive + ping measurement +const DEAD_MS = 15000; // no pong for this long -> connection is dead function attach(server, { lobby }) { const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG }); wss.on('connection', ws => { let user = null, tokens = RATE, last = Date.now(); - ws.alive = true; - ws.on('pong', () => { ws.alive = true; }); + ws.lastPong = Date.now(); + ws.on('pong', () => { + ws.lastPong = Date.now(); + if (ws.pingSent && user) lobby.setRtt(user.uid, Number(process.hrtime.bigint() - ws.pingSent) / 1e6); + ws.pingSent = 0n; + }); const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); }; const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } }; const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS); @@ -48,7 +53,10 @@ function attach(server, { lobby }) { }); const beat = setInterval(() => { - for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closed */ } } + for (const ws of wss.clients) { + if (Date.now() - ws.lastPong > DEAD_MS) { ws.terminate(); continue; } + try { ws.pingSent = process.hrtime.bigint(); ws.ping(); } catch (e) { /* closed */ } + } }, PING_MS); if (beat.unref) beat.unref(); wss.on('close', () => clearInterval(beat)); diff --git a/tests/protocol.test.js b/tests/protocol.test.js index 82c981e..40e514b 100644 --- a/tests/protocol.test.js +++ b/tests/protocol.test.js @@ -10,6 +10,8 @@ test('check accepts valid client messages', () => { assert.ok(P.check({ t: 'hello', v: 1, token: 'abc' }).ok); assert.ok(P.check({ t: 'challenge', to: 'u1' }).ok); assert.ok(P.check({ t: 'challenge.cancel' }).ok); + assert.ok(P.check({ t: 'ping', t0: 123.4 }).ok, 'ping with a timestamp (regression: t was checked instead of t0)'); + assert.ok(P.check({ t: 'ping' }).ok); assert.ok(P.check({ t: 'room', room: 'DE' }).ok); assert.ok(P.check({ t: 'input', seq: 3, throttle: 1, turn: -0.5, fire: true, fire2: false, fire3: false }).ok); }); @@ -34,7 +36,7 @@ test('input clamps ranges and coerces flags', () => { function fakeSnap() { return { - tick: 10, ack: [4, 7], away: [false, true], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0, + tick: 10, ack: [4, 7], away: [false, true], rtt: [20, 140], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0, result: { winner: 0, reason: 'ko' }, press: { st: 'idle', y: 1 }, crane: { st: 'grab', x: 0, z: 0, who: 1 }, rockets: [{ kind: 'rocket', owner: 0, x: 1, z: 2, y: 0.5, a: 0 }], @@ -62,6 +64,7 @@ test('toLocal for seat 1 mirrors every robot index', () => { assert.equal(l.result.winner, 1, 'seat 0 won -> for seat 1 the winner is the opponent (local 1)'); assert.equal(l.ack, 7); assert.deepEqual(l.away, [true, false], 'own connection first'); + assert.deepEqual(l.rtt, [140, 20], 'own ping first'); assert.equal(l.crane.who, 0); assert.equal(l.rockets[0].owner, 1); assert.equal(l.mines[0].owner, 0);