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).
This commit is contained in:
Benjamin Oezcan
2026-11-19 14:25:46 +01:00
parent 3dc770e34a
commit 593d69714b
6 changed files with 46 additions and 9 deletions

View File

@@ -24,7 +24,7 @@
// client -> server message schemas: field -> check // client -> server message schemas: field -> check
const C2S = { const C2S = {
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) }, 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' }, room: { room: v => FLAGS.includes(v) || v === 'all' },
challenge: { to: v => isStr(v) }, challenge: { to: v => isStr(v) },
'challenge.cancel': {}, 'challenge.cancel': {},
@@ -89,6 +89,7 @@
robots, robots,
ack: snap.ack ? snap.ack[seat] : 0, ack: snap.ack ? snap.ack[seat] : 0,
away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined, 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), result: localResult(seat, snap.result),
crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }), crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }),
rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })), rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })),

View File

@@ -104,6 +104,7 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) {
id, seed, id, seed,
players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })), 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), send: (seat, msg) => tell(seats[seat].uid, msg),
rttOf: seat => { const p = players.get(seats[seat].uid); return p ? p.rtt : 0; },
onEnd: finish, onEnd: finish,
}); });
if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now()); 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 // the profile changed (robot, flag, fame): show it to everyone
function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); } 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 }; module.exports = { createLobby, CHALLENGE_TTL };

View File

@@ -25,6 +25,7 @@ class Room {
this.seed = opt.seed || 1; this.seed = opt.seed || 1;
this.players = opt.players; // [{ uid, name, build, paint, flag }] this.players = opt.players; // [{ uid, name, build, paint, flag }]
this.send = opt.send || (() => {}); this.send = opt.send || (() => {});
this.rttOf = opt.rttOf || (() => 0); // seat -> ping in ms (measured by the WebSocket hub)
this.onEnd = opt.onEnd || (() => {}); this.onEnd = opt.onEnd || (() => {});
const ids = RC.ARENAS.map(a => a.id); const ids = RC.ARENAS.map(a => a.id);
this.arena = opt.arena || ids[this.seed % ids.length]; 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]++; for (const k of [0, 1]) if (this.away[k]) this.away[k]++;
if (this.tickN <= COUNTDOWN) return; if (this.tickN <= COUNTDOWN) return;
const s = this.s; const s = this.s;
const t0 = process.hrtime.bigint();
RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]); 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 (!this.evBuf) this.evBuf = [];
if (s.events.length) this.evBuf.push(...s.events); if (s.events.length) this.evBuf.push(...s.events);
s.events.length = 0; s.events.length = 0;
@@ -95,7 +99,10 @@ class Room {
const snap = RC.Proto.packSnap(s, this.tickN, this.acks); const snap = RC.Proto.packSnap(s, this.tickN, this.acks);
s.events = []; this.evBuf.length = 0; s.events = []; this.evBuf.length = 0;
const away = [!!this.away[0], !!this.away[1]]; 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) { finish(result) {

View File

@@ -46,6 +46,16 @@ test('old protocol version is told to reload', async () => {
assert.equal((await c.closed).code, 4002); 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 () => { test('invalid messages get an error, the socket stays open', async () => {
const a = await S.account(); const a = await S.account();
const c = await S.client(a.idToken); 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; 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'); if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out');
assert.equal(eb.save.games, 1); 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 // rewards were booked on the server
const sA = await S.json('GET', '/api/online', undefined, a.idToken); const sA = await S.json('GET', '/api/online', undefined, a.idToken);

View File

@@ -7,15 +7,20 @@ const auth = require('../auth');
const HELLO_MS = 5000; const HELLO_MS = 5000;
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby) 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 }) { function attach(server, { lobby }) {
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG }); const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG });
wss.on('connection', ws => { wss.on('connection', ws => {
let user = null, tokens = RATE, last = Date.now(); let user = null, tokens = RATE, last = Date.now();
ws.alive = true; ws.lastPong = Date.now();
ws.on('pong', () => { ws.alive = true; }); 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 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 bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } };
const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS); const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS);
@@ -48,7 +53,10 @@ function attach(server, { lobby }) {
}); });
const beat = setInterval(() => { 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); }, PING_MS);
if (beat.unref) beat.unref(); if (beat.unref) beat.unref();
wss.on('close', () => clearInterval(beat)); wss.on('close', () => clearInterval(beat));

View File

@@ -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: 'hello', v: 1, token: 'abc' }).ok);
assert.ok(P.check({ t: 'challenge', to: 'u1' }).ok); assert.ok(P.check({ t: 'challenge', to: 'u1' }).ok);
assert.ok(P.check({ t: 'challenge.cancel' }).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: 'room', room: 'DE' }).ok);
assert.ok(P.check({ t: 'input', seq: 3, throttle: 1, turn: -0.5, fire: true, fire2: false, fire3: false }).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() { function fakeSnap() {
return { 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' }, result: { winner: 0, reason: 'ko' },
press: { st: 'idle', y: 1 }, crane: { st: 'grab', x: 0, z: 0, who: 1 }, 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 }], 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.result.winner, 1, 'seat 0 won -> for seat 1 the winner is the opponent (local 1)');
assert.equal(l.ack, 7); assert.equal(l.ack, 7);
assert.deepEqual(l.away, [true, false], 'own connection first'); 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.crane.who, 0);
assert.equal(l.rockets[0].owner, 1); assert.equal(l.rockets[0].owner, 1);
assert.equal(l.mines[0].owner, 0); assert.equal(l.mines[0].owner, 0);