Server-run play, part 1: game prerequisites and shared contracts

Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.

- A new network in two halves (beginState/beginShow), the coach split into
  tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
  once-per-load toasts, the five text actions take their text as an
  argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
  new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
  notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
  plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
  page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
  and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
  checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
  the base no longer count as divergences.
This commit is contained in:
jvanvik 2026-11-07 10:26:06 +01:00
parent e25f843526
commit d1e127da67
60 changed files with 2200 additions and 105 deletions

View file

@ -0,0 +1,187 @@
// A stand-in for the server-run engine (scripts/lib/mp-sim-engine.js, track T2), for testing the session host without
// worker threads or a game: the same API, every method a promise of the worker reply that section 4.2 of the
// server-sim design names, made from the canned stream in tests/fixtures/mp-sim/. Each reply passes
// tests/lib/mp-sim-shape.js checkWorker(); an upd or snap inside one passes checkEvent().
//
// const engine = createFakeEngine();
// engine.load(code, nets:[{nid, env?, begin?, lang, prefs}]) → [{t:'loaded', nid, epoch, day, lost, saved?}], one per
// net; a network that did not load is {t:'loaded', nid, err} (broken, 4.7)
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]:{day, lost,
// pause?, err?, retried?, ms}}}
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd} (msg: the request body, 5.8)
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal:{h, c}, ui?}
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?} (views: [{link} | {peer}])
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}
// engine.prefs(code, nid, {prefs}) → undefined; engine.greet(code, nid) → a pulled
// engine.save(code, nid) → {t:'saved', nid, txt, uidN, rt, day, lost}; engine.card(code, nid) → {t:'card', nid, card}
// engine.unload(code, nid?) → {t:'unloaded', code, nid?}; engine.stats() → {workers, realms, sessions} (not a promise)
//
// For the tests of the host: engine.calls (every call, [method, ...args]); engine.outcome = (msg) => outcome to answer
// acts with ('applied' unless set); engine.lose(code, nid) / engine.pause(code, nid) (the next day ends bankrupt / asks
// for a pause); engine.hold(method) keeps that method's answers back until engine.release(method); engine.exit() is a worker
// that died: every pending call rejects and every realm is gone.
// Failures, in the shapes the real engine answers them (4.2, 4.3, 4.7): engine.failNext(method, what, nid?) with what
// 'timeout' or 'throw' (or 'exit': the call rejects, as when the worker died):
// load → that network (every network of the call without nid) answers {t:'loaded', nid, err} and has no realm;
// day → the day failed twice: nets[nid] = {day (unchanged), lost, err, retried:true, ms} and the network is broken
// (left out of later days; acts answer 'stopped'); without nid, the first network of the day;
// other → {t:'err', code, nid, what, msg}.
// A timeout leaves a fresh realm behind (4.2): a new epoch, v from 0. engine.breakNext(code, nid): the next load of that
// network fails (a save that does not migrate). engine.flaky(code, nid): its next day fails once and passes on the retry
// (retried:true, no err).
'use strict';
const { fixture } = require('./mp-sim-shape');
function createFakeEngine(opts = {}) {
const F = { snap: fixture('snap'), day: fixture('upd-day'), act: fixture('upd-act'), sub: fixture('sub'), roster: fixture('roster') };
const realms = new Map(), held = new Map(), fails = new Map(), pending = new Set(), breaks = new Set(), flaky = new Set();
const key = (code, nid) => code + '/' + nid;
let epochN = 0;
const newEpoch = () => 'e' + (++epochN).toString(36);
const realm = (code, nid) => { const r = realms.get(key(code, nid)); if (!r) throw new Error(`no realm ${key(code, nid)}`); return r; };
// A realm the worker had to build again after a timeout: a new epoch, versions from 0.
const rebuilt = (r) => { if (r) { r.epoch = newEpoch(); r.v = 0; r.dirty = false; } };
// Every answer goes through here: held back, failed, or rejected when the worker exits meanwhile. failed(f): the reply
// for an injected failure, when the method has its own shape for one (load, day); else {t:'err'}.
function answer(method, make, code = 'K7Q2XD', nid = 'abcd1234', failed = null) {
return new Promise((ok, no) => {
const job = { ok, no };
const run = () => {
pending.delete(job);
const f = fails.get(method);
if (f) {
fails.delete(method);
if (f.what === 'exit') return no(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
if (failed) { try { return ok(failed(f)); } catch (e) { return no(e); } }
if (f.what === 'timeout') rebuilt(realms.get(key(code, f.nid || nid)));
return ok({ t: 'err', code, nid: f.nid || nid, what: f.what, msg: `injected ${f.what}` });
}
try { ok(make()); } catch (e) { no(e); }
};
job.run = run;
pending.add(job);
const h = held.get(method);
if (h) h.push(job); else if (opts.sync) run(); else setImmediate(run);
});
}
const upd = (r, base, extra = {}) => {
const from = r.v, v = ++r.v;
const s = { ...base.s, day: r.day };
return JSON.stringify({ ...base, from, v, now: Date.now(), day: r.day, s, ...extra });
};
const snapOf = (code, nid, r) => {
const S = { ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } };
return JSON.stringify({ ...F.snap, epoch: r.epoch, v: r.v, now: Date.now(), S, keep: r.keep.splice(0) });
};
const subsOf = (views = []) => {
const o = {};
for (const w of views) {
if (w && typeof w.link === 'string') o['link:' + w.link] = { ef: F.sub.ef, egd: F.sub.egd };
if (w && typeof w.peer === 'string') o['peer:' + w.peer] = { pf: { [w.peer]: Object.values(F.sub.pf)[0] || {} } };
}
return o;
};
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
const engine = {
calls: [],
outcome: () => 'applied',
load(code, nets) {
engine.calls.push(['load', code, nets]);
const one = (n, err) => {
if (err) { realms.delete(key(code, n.nid)); return { t: 'loaded', nid: n.nid, err }; }
const day = n.begin ? 0 : (n.env && Number.isInteger(n.env.day) ? n.env.day : F.snap.S.day);
const r = { epoch: newEpoch(), v: 0, day, lost: false, broken: false, dirty: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
realms.set(key(code, n.nid), r);
return { t: 'loaded', nid: n.nid, epoch: r.epoch, day, lost: false, ...(n.begin ? { saved: savedOf(code, n.nid, r) } : {}) };
};
const bad = (n) => { const k = key(code, n.nid); if (!breaks.has(k)) return null; breaks.delete(k); return 'migrate threw: injected'; };
return answer('load', () => nets.map((n) => one(n, bad(n))), code, nets[0] && nets[0].nid,
(f) => nets.map((n) => one(n, f.nid === undefined || f.nid === n.nid ? `injected ${f.what}` : bad(n))));
},
day(code, { d, nets = [] } = {}) {
engine.calls.push(['day', code, { d, nets }]);
const ids = [...nets].sort();
const run = (f) => {
const out = {};
for (const nid of ids) {
const r = realm(code, nid);
if (r.lost || r.broken) continue;
// Failed twice (f names it): back to the mark, broken at its pre-day state.
if (f && (f.nid || ids.find((x) => !realm(code, x).lost && !realm(code, x).broken)) === nid) {
r.broken = true; if (f.what === 'timeout') rebuilt(r);
out[nid] = { day: r.day, lost: r.lost, err: `injected ${f.what}`, retried: true, ms: 2000 };
continue;
}
const again = flaky.delete(key(code, nid));
r.day++; r.dirty = true;
if (r.loseNext) { r.lost = true; r.loseNext = false; r.keep.push(['modal', 'lose']); }
out[nid] = { day: r.day, lost: r.lost, ms: 1, ...(r.pause ? { pause: true } : {}), ...(again ? { retried: true } : {}) };
r.pause = false;
}
return { t: 'dayDone', code, d, nets: out };
};
return answer('day', () => run(null), code, ids[0], run);
},
act(code, nid, msg) {
engine.calls.push(['act', code, nid, msg]);
return answer('act', () => {
const r = realm(code, nid);
if (r.lost || r.broken) return { t: 'actDone', nid, epoch: r.epoch, rid: msg.rid, outcome: 'stopped', v: r.v, upd: null };
const outcome = engine.outcome(msg);
r.dirty = false;
const u = upd(r, F.act, { acts: [{ rid: msg.rid, dev: msg.dev, ui: {} }] });
return { t: 'actDone', nid, epoch: r.epoch, rid: msg.rid, outcome, ...(outcome === 'error' ? { why: 'the game threw' } : {}), v: r.v, upd: u };
}, code, nid);
},
ask(code, nid, msg) {
engine.calls.push(['ask', code, nid, msg]);
return answer('ask', () => { realm(code, nid); return { t: 'askDone', nid, rid: msg.rid, modal: { h: `<h2>${msg.act}</h2><p>What if…</p>`, c: '' } }; }, code, nid);
},
pull(code, nid, { snap = false, views } = {}) {
engine.calls.push(['pull', code, nid, { snap, views }]);
return answer('pull', () => {
const r = realm(code, nid), o = { t: 'pulled', nid, epoch: r.epoch };
if (r.dirty) { o.upd = upd(r, F.day); r.dirty = false; }
o.v = r.v;
if (snap) o.snap = snapOf(code, nid, r);
if (views) o.subs = subsOf(views);
return o;
}, code, nid);
},
sub(code, nid, { views = [] } = {}) {
engine.calls.push(['sub', code, nid, { views }]);
return answer('sub', () => { const r = realm(code, nid); return { t: 'subbed', nid, epoch: r.epoch, v: r.v, subs: subsOf(views) }; }, code, nid);
},
prefs(code, nid, { prefs } = {}) { engine.calls.push(['prefs', code, nid, { prefs }]); return answer('prefs', () => { realm(code, nid); return undefined; }, code, nid); },
greet(code, nid) {
engine.calls.push(['greet', code, nid]);
return answer('greet', () => { const r = realm(code, nid); r.dirty = true; const o = { t: 'pulled', nid, epoch: r.epoch, upd: upd(r, F.day, { fx: [['told', 'grace']] }) }; r.dirty = false; o.v = r.v; return o; }, code, nid);
},
save(code, nid) { engine.calls.push(['save', code, nid]); return answer('save', () => savedOf(code, nid, realm(code, nid)), code, nid); },
card(code, nid) { engine.calls.push(['card', code, nid]); return answer('card', () => { realm(code, nid); return { t: 'card', nid, card: F.roster.players[0].card }; }, code, nid); },
unload(code, nid) {
engine.calls.push(['unload', code, nid]);
return answer('unload', () => { for (const k of [...realms.keys()]) if (k.startsWith(code + '/') && (nid === undefined || k === key(code, nid))) realms.delete(k); return { t: 'unloaded', code, ...(nid ? { nid } : {}) }; }, code, nid);
},
stats() { return { workers: 1, realms: realms.size, sessions: new Set([...realms.keys()].map((k) => k.split('/')[0])).size }; },
// Test controls.
lose(code, nid) { realm(code, nid).loseNext = true; },
pause(code, nid) { realm(code, nid).pause = true; },
keep(code, nid, fx) { realm(code, nid).keep.push(fx); },
hold(method) { if (!held.has(method)) held.set(method, []); },
release(method) { const h = held.get(method) || []; held.delete(method); for (const j of h) j.run(); },
failNext(method, what = 'throw', nid) { fails.set(method, { what, nid }); },
breakNext(code, nid) { breaks.add(key(code, nid)); },
flaky(code, nid) { flaky.add(key(code, nid)); },
exit() {
const e = Object.assign(new Error('worker exited'), { code: 'EXIT' });
for (const j of [...pending]) { pending.delete(j); j.no(e); }
held.clear(); realms.clear();
},
realms,
};
return engine;
}
module.exports = { createFakeEngine };

View file

@ -0,0 +1,91 @@
// The canned stream of a server-run network (tests/fixtures/mp-sim/*.json): what the session server sends a page, made
// here from a real seeded game the way the server's realm will make it (section 5 of the server-sim design): live S,
// a top-level key diff per update, slim R, the effects a day and two actions leave. The client tests (and the fake
// engine) use these until the integration step records real streams in their place; every one passes
// tests/lib/mp-sim-shape.js. Run `node tests/lib/mp-sim-fixtures.js` to write them again.
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../harness');
const DIR = path.join(__dirname, '..', 'fixtures', 'mp-sim');
const CODE = 'K7Q2XD', PID = 'abcd1234', PID2 = 'efgh5678', EPOCH = 'k3f9', DEV = '9f8e7d6c', NOW = 1731000000000;
const MP = { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
// In the page: the effects the realm would capture (its epilogue rebinds these the same way), and slim R (5.5).
const RIG = `window.__fx=[];
toast=(h,k='',a=[],o=null)=>{if(S)logNote(h,k,a,o);__fx.push(['toast',{h,k,a,o,tick:!!UI.tick}]);};
sfx=n=>{__fx.push(['sfx',n]);};haptic=n=>{__fx.push(['haptic',n]);};
floater=(x,y,t,c)=>{if(__fx.filter(f=>f[0]==='floater').length<40)__fx.push(['floater',[x,y,t,c]]);};
window.__slimR=()=>{const {o}=rwPack(R);for(const k of ['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked'])delete o[k];
const tn={};for(const id in o.tNet)tn[id]=Object.fromEntries(Object.entries(o.tNet[id]).sort((a,b)=>b[1]-a[1]).slice(0,4));o.tNet=tn;
o.tTop8=transitTop(S.transit.map(t=>t.id),8);
const r6=v=>typeof v==='number'?(Number.isInteger(v)||!isFinite(v)?v:+v.toPrecision(6)):Array.isArray(v)?v.map(r6):v&&typeof v==='object'?Object.fromEntries(Object.entries(v).map(([k,x])=>[k,r6(x)])):v;
return r6(JSON.parse(JSON.stringify(o)));};
window.__keys=()=>Object.fromEntries(Object.keys(S).map(k=>[k,JSON.stringify(S[k])]));`;
function make() {
const { ev, errors, dom } = load({ seed: 4242 });
ev(`Date.now=()=>${NOW};`);
// A network of a server session, built the way the server builds one (beginState, then the server's own marks), with
// the intern on every order and a fiber cut it rushes: the snapshot carries a shift's log and the week's tally.
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)}});S.mp.sim=1;S.tut=null;compute();beginHello();
S.nextFail=S.nextEvent=1e9;UI.speed=0;UI.started=true;ACT.charter({k:'global'});
ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});
UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();
S.lvl=Math.max(S.lvl,2);ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
for(let i=0;i<45;i++){if(i===20)dayGo(failureRun('cut'));dayTick();}`);
ev(RIG);
const snapS = JSON.parse(ev('JSON.stringify(S)'));
const r0 = JSON.parse(ev('JSON.stringify(__slimR())'));
const diff = (before) => { const now = JSON.parse(ev('JSON.stringify(__keys())')), s = {}, del = [];
for (const k of Object.keys(now)) if (now[k] !== before[k]) s[k] = JSON.parse(now[k]);
for (const k of Object.keys(before)) if (!(k in now)) del.push(k);
return { s, del, keys: now }; };
const fx = () => JSON.parse(ev('JSON.stringify(__fx.splice(0))'));
const clock = { t: 'clock', speed: 1, eff: 1, run: true, why: null, votes: { [PID2]: 4 }, tally: { 4: 1 }, need: 2, active: [PID, PID2], hold: [], idle: [],
day: 518, last: 1, max: 8, off: { [PID]: S0day(snapS) - 518, [PID2]: 0 } };
const card = JSON.parse(ev('JSON.stringify(mpCard())'));
const roster = { t: 'roster', code: CODE, title: 'Friday', preset: 'oncall', seed: MP.seed, created: NOW - 864e5,
players: [{ pid: PID, name: 'Packet Pals', asn: MP.asn, color: MP.color, card, seen: NOW, joined: NOW - 864e5 },
{ pid: PID2, name: 'Tubular Bells', asn: 207777, color: '#ff4f9a', card: null, seen: NOW - 6e4, joined: NOW - 36e5 }],
feed: [{ k: 'join', pid: PID, name: 'Packet Pals', at: NOW - 864e5 }, { k: 'join', pid: PID2, name: 'Tubular Bells', at: NOW - 36e5 }, { k: 'chat', pid: PID2, name: 'Tubular Bells', at: NOW - 6e4, text: 'peer with me?' }],
on: [PID, PID2] };
const snap = { t: 'snap', epoch: EPOCH, v: 412, now: NOW, S: snapS, r: r0, clock, roster, since: { days: 37, again: 0 }, keep: [['badge', { id: 'firstpop', v: 'oncall' }]] };
// A day: the keys it changed, a new R, what it said.
let base = JSON.parse(ev('JSON.stringify(__keys())'));
ev('UI.tick=false;dayTick();');
const d1 = diff(base), dayFx = fx();
if (!dayFx.length) dayFx.push(['sfx', 'coin']);
const updDay = { t: 'upd', from: 412, v: 413, now: NOW + 2500, day: JSON.parse(ev('S.day')), s: d1.s, del: d1.del, r: JSON.parse(ev('JSON.stringify(__slimR())')), fx: dayFx };
// Two quick taps in one update: a new POP (the panel moves to it) and a transit port there.
base = d1.keys;
ev("ACT.buildPop({city:'par'});");
const ui1 = { sel: { type: 'city', id: 'par' }, tab: 'cust' };
ev("ACT.buyTransit({city:'par',net:'cog',tier:1});");
const d2 = diff(base), actFx = fx();
const updAct = { t: 'upd', from: 413, v: 414, now: NOW + 3100, day: updDay.day, s: d2.s, del: d2.del, r: JSON.parse(ev('JSON.stringify(__slimR())')), fx: actFx,
acts: [{ rid: 'a1b2c3d4e5', dev: DEV, ui: ui1 }, { rid: 'a1b2c3d4e6', dev: DEV, ui: {} }] };
// A stream's flow records: the link it shows and its traffic's ways in, and a city's Peering tab.
const sub = JSON.parse(ev(`(()=>{const l=S.links[0],k=edgeKey(l),rec=R.ef[k],egd={};if(rec)for(const e in rec.eg||{})if(R.egDesc[e])egd[e]=R.egDesc[e];
return JSON.stringify({t:'sub',v:414,ef:rec?{[k]:rec}:{},egd,pf:{fra:pniFlows('fra')}});})()`));
if (errors.length) throw new Error('the game failed while making fixtures: ' + errors.join('; '));
dom.window.close();
return { snap, 'upd-day': updDay, 'upd-act': updAct, sub, clock, roster };
}
// The calendar offset of the network in the fixtures: its own date against the session day (open question 1).
function S0day(S) { return S.day; }
function write() {
fs.mkdirSync(DIR, { recursive: true });
const out = make();
for (const [k, v] of Object.entries(out)) fs.writeFileSync(path.join(DIR, k + '.json'), JSON.stringify(v) + '\n');
return Object.keys(out);
}
module.exports = { make, write, DIR, CODE, PID, PID2, EPOCH, DEV, NOW };
if (require.main === module) console.log('wrote', write().map((k) => `tests/fixtures/mp-sim/${k}.json`).join(', '));

183
tests/lib/mp-sim-shape.js Normal file
View file

@ -0,0 +1,183 @@
// The shapes of server-run play on the wire and between host and worker (the server-sim design, sections 4.2 and 5.3),
// checked: the session server's real output (its tests run every event they write through checkEvent) and the canned
// streams in tests/fixtures/mp-sim/ (the client's tests) must agree on them.
//
// checkEvent(e) problems with one stream event ([] when fine): snap, upd, sub, clock, roster, bye
// checkFx(f) problems with one effect entry, [kind, payload]
// checkWorker(m) problems with one worker → host reply: loaded, dayDone, actDone, askDone, pulled, subbed, saved,
// card, unloaded, err
//
// The epoch (5.10): the worker mints a new one at every realm load (a load, a begin, and the fresh realm it builds
// after a timeout, 4.2) and puts the realm's current one on every reply that carries versions: loaded, pulled, actDone,
// subbed. The host keeps the last one per network and writes it into every event's id (`id: <epoch>.<v>`); a reply with
// another epoch than the host holds means the realm was built again, so v started over and every page takes a snapshot.
// A network that did not load (loaded.err: its save failed, 4.7) has no realm, so no epoch, day or lost.
// A toast effect's k and a may be left out (toastPop's defaults: '' and []): a game call toast(html) has neither.
// parseSse(text) the events of an event-stream text: [{event, id, data (parsed)}], comments and heartbeats skipped
// fixture(name) tests/fixtures/mp-sim/<name>.json, parsed
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
const PID = /^[a-z0-9]{8}$/, RID = /^[a-z0-9]{8,16}$/, EPOCH = /^[a-z0-9]{1,16}$/, CODE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
// What slim R never carries (5.5): compute inputs, internals, and what goes on demand in sub events.
const R_NEVER = ['ef', 'fl', 'efp', 'flc', 'efg', 'egDesc', 'l2route', 'bbF', 'peered', 'cityBlocked'];
const FX_KINDS = ['toast', 'sfx', 'haptic', 'floater', 'track', 'pause', 'modal', 'badge', 'mk', 'told'];
const WHY = [null, 'empty', 'hold', 'slow', 'loading', 'vote'];
const BYE = ['gone', 'old', 'moved', 'slow', 'shutdown'];
const OUTCOMES = ['applied', 'no_effect', 'rejected', 'error', 'stopped'];
const UI_KEYS = ['sel', 'tab', 'left', 'confirm', 'closed', 'modal'];
const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
const int = (v) => Number.isInteger(v);
const nat = (v) => Number.isInteger(v) && v >= 0;
const num = (v) => typeof v === 'number' && Number.isFinite(v);
const str = (v) => typeof v === 'string';
const bool = (v) => typeof v === 'boolean';
// fields: {name: test | [test, 'opt']}; extra keys are problems too (a typo on one side is caught by the other).
function fields(o, spec, where, out, open = false) {
if (!obj(o)) { out.push(`${where}: not an object`); return; }
for (const [k, t] of Object.entries(spec)) {
const [f, opt] = Array.isArray(t) ? t : [t];
if (!(k in o) || o[k] === undefined) { if (!opt) out.push(`${where}.${k}: missing`); continue; }
const r = f(o[k], `${where}.${k}`, out);
if (r === false) out.push(`${where}.${k}: bad value ${JSON.stringify(o[k]).slice(0, 80)}`);
}
if (!open) for (const k of Object.keys(o)) if (!(k in spec)) out.push(`${where}.${k}: unknown field`);
}
const listOf = (t) => (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((x, i) => { if (t(x, `${w}[${i}]`, out) === false) out.push(`${w}[${i}]: bad value ${JSON.stringify(x).slice(0, 60)}`); }); return true; };
const mapOf = (kt, vt) => (v, w, out) => { if (!obj(v)) return false; for (const [k, x] of Object.entries(v)) { if (!kt(k)) out.push(`${w}: bad key ${k}`); if (vt(x, `${w}.${k}`, out) === false) out.push(`${w}.${k}: bad value ${JSON.stringify(x).slice(0, 60)}`); } return true; };
// Live S, as the server's realm holds it: what every page reads first (the full check is the game's own migrate()).
function liveS(S, w, out) {
if (!obj(S)) return false;
if (S.v !== 1 || !nat(S.day) || !num(S.cash) || !obj(S.pops) || !Array.isArray(S.links) || !Array.isArray(S.biz) || !obj(S.stats)) out.push(`${w}: not a game state (v, day, cash, pops, links, biz, stats)`);
if (!obj(S.mp) || !CODE.test(S.mp.code) || !PID.test(S.mp.pid) || S.mp.sim !== 1) out.push(`${w}.mp: not a server network (code, pid, sim:1)`);
if (S.mode !== 'normal') out.push(`${w}.mode: server networks are Normal games`);
return true;
}
function slimR(r, w, out) {
if (!obj(r)) return false;
for (const k of R_NEVER) if (k in r) out.push(`${w}.${k}: slim R never carries it`);
for (const k of ['served', 'demand', 'reach', 'revMo', 'costMo']) if (!num(r[k])) out.push(`${w}.${k}: missing or not a number`);
for (const k of ['load', 'useT', 'tNet', 'cityDem', 'citySrv']) if (!obj(r[k])) out.push(`${w}.${k}: missing`);
if (!Array.isArray(r.ddos)) out.push(`${w}.ddos: missing`);
else r.ddos.forEach((m, i) => { if (m.attack !== null && !str(m.attack)) out.push(`${w}.ddos[${i}].attack: an attack's id (or null)`); });
if (!Array.isArray(r.tTop8) || r.tTop8.length > 8 || !r.tTop8.every((x) => Array.isArray(x) && x.length === 2 && str(x[0]) && num(x[1]))) out.push(`${w}.tTop8: [[net, gbps]] × ≤ 8`);
if (obj(r.tNet)) for (const [id, m] of Object.entries(r.tNet)) if (!obj(m) || Object.keys(m).length > 4) out.push(`${w}.tNet.${id}: at most the top 4 networks`);
return true;
}
const sel = (v) => v === null || (obj(v) && (v.type === 'city' || v.type === 'link') && str(v.id) && Object.keys(v).length === 2);
function actUi(u, w, out) {
fields(u, { sel: [sel, 'opt'], tab: [(v) => v === null || str(v), 'opt'], left: [(v) => v === null || str(v), 'opt'], confirm: [(v) => v === null || str(v), 'opt'],
closed: [(v) => v === 1 || v === true, 'opt'], modal: [(v) => obj(v) && str(v.h) && str(v.c) && Object.keys(v).length === 2, 'opt'] }, w, out);
return true;
}
const actEntry = (a, w, out) => { fields(a, { rid: (v) => RID.test(v), dev: (v) => RID.test(v), ui: actUi }, w, out); return true; };
function checkFx(f, w = 'fx', out = []) {
if (!Array.isArray(f) || f.length !== 2 || !str(f[0])) { out.push(`${w}: an effect is [kind, payload]`); return out; }
const [k, p] = f;
const bad = () => out.push(`${w}: bad ${k} payload ${JSON.stringify(p).slice(0, 80)}`);
switch (k) {
case 'toast': fields(p, { h: str, k: [str, 'opt'], a: [listOf((x) => obj(x) && str(x.l) && str(x.act)), 'opt'], o: [(v) => v === null || obj(v), 'opt'], tick: [bool, 'opt'] }, `${w}.toast`, out); break;
case 'sfx': case 'haptic': if (!str(p)) bad(); break;
case 'floater': if (!Array.isArray(p) || p.length !== 4 || !num(p[0]) || !num(p[1]) || !str(p[2]) || !str(p[3])) bad(); break;
case 'track': if (!Array.isArray(p) || p.length !== 2 || !str(p[0]) || !(p[1] === undefined || p[1] === null || bool(p[1]))) bad(); break;
case 'pause': if (p !== 1) bad(); break;
case 'modal': if (!['win', 'lose', 'baron'].includes(p)) bad(); break;
case 'badge': if (!obj(p) || !str(p.id) || !(p.v === undefined || str(p.v))) bad(); break;
case 'mk': if (!obj(p) || !str(p.e)) bad(); break;
case 'told': break;
default: out.push(`${w}: unknown effect ${k}`);
}
return out;
}
const fxList = (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((f, i) => checkFx(f, `${w}[${i}]`, out)); return true; };
const CLOCK = { t: (v) => v === 'clock', speed: (v) => SPEEDS.includes(v), eff: (v) => num(v) && v >= 0, run: bool, why: (v) => WHY.includes(v),
votes: mapOf((k) => PID.test(k), (v) => v === null || SPEEDS.includes(v)), tally: mapOf((k) => SPEEDS.includes(+k), nat), need: (v) => int(v) && v >= 1,
active: listOf((v) => PID.test(v)), hold: listOf((v) => PID.test(v)), idle: listOf((v) => PID.test(v)), day: nat, last: (v) => SPEEDS.includes(v) && v > 0,
max: (v) => SPEEDS.includes(v) && v > 0,
// The calendar offset of every network of the session: its own S.day minus the session day (open question 1: "own
// date"). One field, so a shared date later only means all zeros.
off: mapOf((k) => PID.test(k), int) };
const PLAYER = { pid: (v) => PID.test(v), name: str, asn: nat, color: (v) => /^#[0-9a-f]{6}$/i.test(v), card: (v) => v === null || obj(v), seen: nat, joined: nat,
lost: [bool, 'opt'], broken: [bool, 'opt'] };
const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str, preset: str, seed: int, created: nat,
players: listOf((p, w, out) => { fields(p, PLAYER, w, out); return true; }),
feed: listOf((f, w, out) => { fields(f, { k: str, pid: str, name: str, at: nat, text: [str, 'opt'] }, w, out); return true; }),
on: listOf((v) => PID.test(v)) };
function checkEvent(e) {
const out = [];
if (!obj(e) || !str(e.t)) return ['an event is an object with t'];
const w = e.t;
if (e.t === 'snap') fields(e, { t: str, epoch: (v) => EPOCH.test(v), v: nat, now: nat, S: liveS, r: slimR,
clock: (v, ww, o) => { fields(v, CLOCK, ww, o); return true; }, roster: (v, ww, o) => { fields(v, ROSTER, ww, o); return true; },
since: (v, ww, o) => { fields(v, { days: nat, again: nat }, ww, o); return true; },
keep: (v, ww, o) => { if (!Array.isArray(v) || v.length > 32) return false; v.forEach((f, i) => { checkFx(f, `${ww}[${i}]`, o); if (f[0] !== 'badge' && f[0] !== 'modal') o.push(`${ww}[${i}]: keep holds only badge and modal`); }); return true; } }, w, out);
else if (e.t === 'upd') {
fields(e, { t: str, from: nat, v: nat, now: nat, day: nat, s: obj, del: [listOf(str), 'opt'], r: [slimR, 'opt'], fx: [fxList, 'opt'], acts: [listOf(actEntry), 'opt'] }, w, out);
if (nat(e.v) && nat(e.from) && e.v !== e.from + 1) out.push('upd: v is from + 1 (only a pull makes a version)');
if (obj(e.s) && Array.isArray(e.del)) for (const k of e.del) if (k in e.s) out.push(`upd: ${k} both changed and deleted`);
if (obj(e.s) && 'day' in e.s && e.s.day !== e.day) out.push('upd: day differs from s.day');
if (Array.isArray(e.fx) && e.fx.length > 60) out.push('upd: more than 60 effects');
} else if (e.t === 'sub') fields(e, { t: str, v: nat, ef: [obj, 'opt'], egd: [obj, 'opt'], pf: [obj, 'opt'] }, w, out);
else if (e.t === 'clock') fields(e, CLOCK, w, out);
else if (e.t === 'roster') fields(e, ROSTER, w, out);
else if (e.t === 'bye') fields(e, { t: str, why: (v) => BYE.includes(v) }, w, out);
else out.push(`unknown event ${e.t}`);
return out;
}
// Worker → host replies (4.2). Big payloads (an update, a snapshot) are JSON text, ready to write to every stream.
const json = (t) => (v, w, out) => { if (!str(v)) return false; let e; try { e = JSON.parse(v); } catch (x) { return false; } for (const p of checkEvent(e)) out.push(`${w}: ${p}`); if (e.t !== t) out.push(`${w}: not a ${t}`); return true; };
const subs = mapOf((k) => /^(link|peer):.{1,40}$/.test(k), (v) => obj(v));
const epoch = (v) => EPOCH.test(v);
const WORKER = {
// epoch, day and lost: required unless err says the network did not load (checkWorker).
loaded: { t: str, nid: (v) => PID.test(v), epoch: [epoch, 'opt'], day: [nat, 'opt'], lost: [bool, 'opt'], err: [str, 'opt'], saved: [(v, w, out) => { for (const p of checkWorker(v)) out.push(`${w}: ${p}`); return true; }, 'opt'] },
// A day that failed twice: err, retried, and day as it was before (the network is broken at its pre-day state, 4.3).
dayDone: { t: str, code: (v) => CODE.test(v), d: nat, nets: mapOf((k) => PID.test(k), (v, w, out) => { fields(v, { day: nat, lost: bool, pause: [bool, 'opt'], err: [str, 'opt'], retried: [bool, 'opt'], ms: (x) => num(x) && x >= 0 }, w, out); return true; }) },
actDone: { t: str, nid: (v) => PID.test(v), epoch, rid: (v) => RID.test(v), outcome: (v) => OUTCOMES.includes(v), why: [str, 'opt'], v: nat, upd: [(v, w, out) => v === null || json('upd')(v, w, out), 'opt'] },
askDone: { t: str, nid: (v) => PID.test(v), rid: (v) => RID.test(v), modal: [(v) => obj(v) && str(v.h) && str(v.c), 'opt'], ui: [obj, 'opt'], err: [str, 'opt'] },
pulled: { t: str, nid: (v) => PID.test(v), epoch, v: nat, upd: [json('upd'), 'opt'], snap: [json('snap'), 'opt'], subs: [subs, 'opt'] },
subbed: { t: str, nid: (v) => PID.test(v), epoch, v: nat, subs },
saved: { t: str, nid: (v) => PID.test(v), txt: str, uidN: nat, rt: obj, day: nat, lost: bool },
card: { t: str, nid: (v) => PID.test(v), card: (v) => v === null || obj(v) },
unloaded: { t: str, code: (v) => CODE.test(v), nid: [(v) => PID.test(v), 'opt'] },
err: { t: str, code: (v) => CODE.test(v), nid: (v) => PID.test(v), rid: [(v) => RID.test(v), 'opt'], what: (v) => ['timeout', 'throw', 'oom', 'exit', 'load'].includes(v), msg: str },
};
function checkWorker(m) {
const out = [];
if (!obj(m) || !str(m.t) || !WORKER[m.t]) return [`unknown worker reply ${obj(m) ? m.t : typeof m}`];
fields(m, WORKER[m.t], m.t, out);
if (m.t === 'loaded' && m.err === undefined) for (const k of ['epoch', 'day', 'lost']) if (m[k] === undefined) out.push(`loaded.${k}: missing`);
if (m.t === 'loaded' && m.err !== undefined && m.saved !== undefined) out.push('loaded: a network that did not load has nothing saved');
if (m.t === 'pulled' && m.snap !== undefined && str(m.snap)) { try { const e = JSON.parse(m.snap); if (e.epoch !== m.epoch) out.push('pulled: the snapshot\'s epoch is not the realm\'s'); } catch (x) { /* reported above */ } }
return out;
}
function parseSse(text) {
const out = [];
for (const block of String(text).split('\n\n')) {
if (!block.trim()) continue;
let event = 'message', id, data = '';
for (const line of block.split('\n')) {
if (!line || line.startsWith(':')) continue;
const i = line.indexOf(':'), k = i < 0 ? line : line.slice(0, i), v = i < 0 ? '' : line.slice(i + 1).replace(/^ /, '');
if (k === 'event') event = v; else if (k === 'id') id = v; else if (k === 'data') data += (data ? '\n' : '') + v;
}
if (data) out.push({ event, id, data: JSON.parse(data) });
}
return out;
}
const DIR = path.join(__dirname, '..', 'fixtures', 'mp-sim');
const fixture = (name) => JSON.parse(fs.readFileSync(path.join(DIR, name + '.json'), 'utf8'));
const FIXTURES = ['snap', 'upd-day', 'upd-act', 'sub', 'clock', 'roster'];
module.exports = { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES, FX_KINDS, R_NEVER, SPEEDS };