Files
Robot-Clash/server/ws/hub.js
Benjamin Oezcan 593d69714b 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).
2026-11-19 14:25:46 +01:00

67 lines
3.2 KiB
JavaScript

/* WebSocket endpoint /ws. Every socket must say { t:'hello', v, token } within HELLO_MS, then its messages
are validated (RC.Proto.check), rate limited and handed to the lobby. Keepalive via ws ping/pong. */
'use strict';
const { WebSocketServer } = require('ws');
const RC = require('../../game/protocol.js');
const auth = require('../auth');
const HELLO_MS = 5000;
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby)
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.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);
ws.on('message', (data, isBinary) => {
// token bucket
const now = Date.now(); tokens = Math.min(RATE, tokens + (now - last) * RATE / 1000); last = now;
if (--tokens < 0) return bye(4008, 'RATE_LIMIT');
let msg;
try { msg = JSON.parse(isBinary ? data : data.toString()); } catch (e) { return send({ t: 'error', code: 'BAD_JSON' }); }
const c = RC.Proto.check(msg);
if (!c.ok) return send({ t: 'error', code: c.error });
if (!user) {
if (msg.t !== 'hello') return bye(4001, 'HELLO_FIRST');
if (msg.v !== RC.Proto.VERSION) { send({ t: 'error', code: 'OUTDATED', need: RC.Proto.VERSION }); return bye(4002, 'OUTDATED'); }
const u = auth.verify(msg.token);
if (!u) { send({ t: 'error', code: 'UNAUTH' }); return bye(4003, 'UNAUTH'); }
clearTimeout(helloTimer);
user = u;
send({ t: 'welcome', uid: u.uid, name: u.name, serverTime: Date.now(), v: RC.Proto.VERSION });
try { lobby.join({ uid: u.uid, name: u.name, admin: u.admin, send }); } catch (e) { console.error('[ws] join failed', e); bye(1011, 'SERVER_ERROR'); }
return;
}
if (msg.t === 'hello') return;
try { lobby.handle(user.uid, msg); } catch (e) { console.error('[ws] handler failed for', msg.t, e); send({ t: 'error', code: 'SERVER_ERROR' }); }
});
ws.on('close', () => { clearTimeout(helloTimer); if (user) { try { lobby.leave(user.uid, send); } catch (e) { console.error('[ws] leave failed', e); } } });
ws.on('error', () => {});
});
const beat = setInterval(() => {
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));
return wss;
}
module.exports = { attach };