seriesoftubes/tests/lib/mp-sim-play.js
jvanvik 9597d89079 Server-run engine: review fixes
The review of track T2 found these; each has a test in tests/mp-sim-*.

- Built-ins: an arg, array entry or draft that is '__proto__', 'constructor'
  or 'prototype' is refused by the envelope check and again by the realm
  (free text may still say them). After every realm call the trampoline
  checks the realm's built-ins against what they were at load; a realm
  whose built-ins changed answers {srvErr, polluted} and is replaced from
  the worker's mark like one that timed out. S as one JSON per key is a
  null-prototype object, so the epilogue's for…in never reads a prototype.
- A realm that cannot be built again is never used again: rebuild() tries
  once more without the packed R, and when that fails too the network is
  dropped (NO_REALM), and the engine tells the host (opts.onLost).
- A mark that fails or runs out of time changes nothing: it clears the old
  mark first, the realm is built again from its own save, never from an
  older mark, and the reply names the mark. A day rebuilds only from its
  own attempt's mark.
- A day whose alone or nets is not a list is refused whole (ERR); a throw
  in a load or day step answers that call, never ends the worker.
- An exit counts against the session the worker was running (the worker
  says so before each job and step), else as before. Workers of their own
  are capped (opts.maxOwn, 4): past that a session is given up.
- A worker that exits before it is ready is started again after a pause
  that doubles; after 5 in a row every call answers SIM_DOWN.
- The game text is read and compiled once, in createEngine: a src/ that
  does not compile throws there, and every worker, also one started after
  an exit, runs the game engine.simId names.
- A damaged route memory never breaks a save that loads (routed from
  nothing, logged), and only a server network loads (S.mp.sim, Normal).
- Routing memory (UI.rk, UI.rkR) is kept by the in-place restore and
  carried in rt (rk), so a reloaded or rolled-back network skips the same
  routings as the one that kept going.
- A fresh realm takes over the fx of the one it replaces (the mark's after
  a failed call, all of them after a read): badges, windows and toasts
  waiting for a page are not lost to a timeout.
- Windows: the stand-in elements answer querySelector from what was
  written (a [data-x] marker) and have a working classList, never the
  inert proxy that said every window is open. A request's ctx may name the
  open window, ctx.win = {k, ui} (mp-sim-acts.js WINDOWS: bstd, routing,
  charter, ops, pie), with the view state only the page holds (the
  intern's POP, the pie window's tab and POP), checked in the realm. This
  is an addition to the contract of design 5.8 that the page (T4) sends.
  The stand-in is hidden again after an act.
- xpBuild's via is a TEXT arg (256): a six-span express fits.
- actDone, askDone and pulled carry ms, the worker time of the call;
  engine.mem() and engine.has(code, nid) are public; prefs() passes a
  realm's err through; after close() every call rejects CLOSED.
- The fake engine fails as the engine does (NO_REALM, ERR, a load without
  a save, a day of an unknown session or naming an unloaded network,
  GAVE_UP, SIM_DOWN, CLOSED, onLost), its greet says its one-shots once and
  never 'told'; a test runs the same edge calls on both.
- SIM_DRAFT is built from DRAFT_TYPES.
2026-11-09 22:16:52 +01:00

91 lines
5.8 KiB
JavaScript

// What the engine's tests share (tests/mp-sim-engine.test.js, mp-sim-determinism.test.js, mp-sim-acts.test.js): the
// networks they play, the requests a page sends, and the page's side of a comparison, run in jsdom by the click path.
//
// page({save}) a jsdom page holding a network as the server's realm holds it (pinned clock, seeded): {ev, …}
// bigScenic() the big fixture as a server network (session marks, dice, its L2 customers on scenic routes),
// as live S text; the route-memory problem only shows with scenic circuits (design 4.7, 11)
// msg(act, args, more) an act or ask request as a page sends it (envelope-checked, ctx clamped)
// ctxOf(ev, o) the page's ctx: its selection, tab and left list, a desktop viewport; with modal:true also the
// open window as the page names it (winOf)
// winOf(ev) the page's ctx.win: the open window by mp-sim-acts.js WINDOWS (the first entry whose class is
// the window's and whose marker, when it has one, is inside it), with its view state; or null
// begin(nid, o) a new network's begin entry for engine.load()
// RSIG R with its lazy parts read out, attacks by id (as tests/route-worker.test.js reads it)
// checked(r) r, after checkWorker (and checkEvent of the upd/snap inside) found nothing
// differs(a, b) the first differing top-level keys of two JSON texts (compare texts, never a deep-equal)
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
const { load } = require('../harness');
const { lit } = require('../../scripts/lib/js-literal');
const { simId } = require('../../scripts/lib/page');
const A = require('../../scripts/lib/mp-sim-acts');
const { checkWorker, checkEvent } = require('./mp-sim-shape');
const CODE = 'K7Q2XD', PID = 'abcd1234', DEV = '9f8e7d6c', T0 = 1.7e12, STEP = 2500;
const MP = { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
const TEST = { seed: 4242, now: T0, step: STEP };
// Time limits for engines whose tests inject no timeout: a busy machine (every test file at once) must not time out a
// big network's day or action that takes 40 ms when it is quiet. The tests of timeouts use the engine's own limits.
const ROOMY = { day: 20000, act: 20000, ask: 20000, pull: 20000, save: 20000, mark: 20000, small: 20000 };
let SIM;
const sim = () => SIM || (SIM = simId());
const BIG = path.join(__dirname, '..', 'fixtures', 'big-network.json');
// A jsdom page whose clock and dice are the realm's (TEST): a day there is __t+=STEP; dayTick(); and the day's end render.
function page({ save, uidN = 1000 } = {}) {
const h = load({ seed: TEST.seed });
h.ev(`window.__t=${T0};Date.now=()=>__t;UI.started=true;UI.pitched=true;UI.speed=0;closeModal();`);
if (save) h.ev(`S=migrate(JSON.parse(${lit(save)}));uidN=${uidN};R=emptyR();compute();`);
h.day = () => h.ev('__t+=' + STEP + ';dayTick();UI.ticking=true;renderHUD();UI.ticking=false;');
h.close = () => h.dom.window.close();
return h;
}
let BIGS = null;
function bigScenic() {
if (BIGS) return BIGS;
const h = load({ seed: TEST.seed });
h.ev(`S=migrate(JSON.parse(${lit(fs.readFileSync(BIG, 'utf8'))}));S.rng=${MP.seed};S.mp={...${JSON.stringify(MP)},seq:0,sim:1};
for(const b of S.biz)if(BIZ_T[b.type].l2)b.route='scenic';`);
BIGS = h.ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))))');
h.dom.window.close();
return BIGS;
}
let n = 0;
function msg(act, args = {}, more = {}) {
const body = JSON.parse(JSON.stringify({ rid: 'r' + (++n).toString(36).padStart(8, '0'), dev: DEV, sim: sim(), act, args, ...more }));
const r = A.checkEnvelope(A.ASK.includes(act) ? 'ask' : 'act', body, { sim: sim() });
assert.ok(r.ok, `${act}: the page would not send this (${r.error})`);
return body;
}
const winOf = (ev) => JSON.parse(ev(`(()=>{const W=${JSON.stringify(A.WINDOWS)},m=$('modal'),c=$('modalCard');if(m.hidden)return 'null';
for(const [k,w] of Object.entries(W))if(m.className===w.c&&(!w.sel||c.querySelector(w.sel))){const ui={};for(const u of w.ui||[])if(typeof UI[u]==='string')ui[u]=UI[u];
return JSON.stringify(Object.keys(ui).length?{k,ui}:{k});}
return 'null';})()`));
const ctxOf = (ev, o = {}) => {
const c = { sel: JSON.parse(ev('JSON.stringify(UI.sel)')), tab: ev('UI.tab'), left: ev('UI.left'), modal: false, w: 1024, h: 768, coarse: false, ...o };
if (c.modal && !('win' in o)) { const w = winOf(ev); if (w) c.win = w; }
return c;
};
const begin = (nid, o = {}) => ({ nid, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: MP.asn, mp: { ...MP, pid: nid }, tut: false, ...o }, lang: 'en', prefs: {} });
const RSIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()";
function checked(r) {
const p = checkWorker(r);
assert.deepEqual(p, [], `${r && r.t}: ${p.join('; ')}`);
if (r && typeof r.upd === 'string') assert.deepEqual(checkEvent(JSON.parse(r.upd)), [], 'the update');
return r;
}
// The first top-level keys whose JSON differs, with a glimpse of each side: for a failing comparison's message.
function differs(a, b) {
const A2 = JSON.parse(a), B2 = JSON.parse(b);
return Object.keys({ ...A2, ...B2 }).filter((k) => JSON.stringify(A2[k]) !== JSON.stringify(B2[k]))
.slice(0, 4).map((k) => `${k}: ${String(JSON.stringify(A2[k])).slice(0, 300)} ≠ ${String(JSON.stringify(B2[k])).slice(0, 300)}`).join('\n');
}
module.exports = { CODE, PID, DEV, MP, T0, STEP, TEST, ROOMY, sim, page, bigScenic, msg, ctxOf, winOf, begin, RSIG, checked, differs };