Server-run play, part 2: the engine

The engine that runs every network of a server session (server-sim design,
section 4): each network in its own vm realm, realms in a small pool of
worker threads, a promise API for the session host. Nothing uses it yet;
the plain build and the game are unchanged (no file under src/).

- scripts/lib/mp-sim-realm.js: one network in a DONT_CONTEXTIFY realm
  running the plain page's game (never the MP page's client folder), with
  recording DOM stand-ins, no-op timers that count, and the srv... calls:
  load from a checkpoint (route memory seeded, then routed), begin a new
  network, marks and restores, the day as a page runs it, the action
  pipeline with drafts, arming, the sanitize gate and rollback, what-ifs
  that put S, R, the dice and uidN back, pulls with top-level key diffs,
  slim R and flow records on demand, fx captured and bounded, saves, cards.
- scripts/lib/mp-sim-worker.js: realms per session in one worker, days one
  network at a time with other messages between them, loads and unloads
  waiting for a session's day, time limits; a throw goes back to the mark
  in place, a timeout gets a fresh realm (new epoch) carrying the old R, a
  day is retried once and the network broken after a second failure.
- scripts/lib/mp-sim-engine.js: createEngine() with the fake engine's API,
  placement by realm count, every pending call rejected when its worker
  exits, a worker of its own after two exits in an hour; snapWith() joins
  the host's clock, roster and since to a realm's snapshot.
- Contract: a pulled snapshot is the realm's half (the host adds clock,
  roster, since); haptic fx carry milliseconds; the fake engine follows,
  with close() and snapWith(). The button crawl moved to tests/lib.
- Tests: realm vs jsdom byte for byte over 60 scenic big-network days with
  actions; restore; retry after a throw or a timeout; realm order; a timer
  audit and the gate over a sweep of sent buttons (SIM_LONG=1: a year and
  every button); captures, rollbacks, asks, selection reports, ordering,
  bounds, pollution, worker exits; the act tables against the game.

The gate found two keys the game writes in a shape a reload repairs (buyTE's
S.te, mkLeave's S.monkey): game fixes for the integrator, kept visible as a
todo test and a list in the audit.

Rebased onto the 3.3.0 merge (61e31c5): the engine itself needed no change. A
realm still routes in the game's own code (no route worker, no saves), the
route cache that now keeps list orders from day to day leaves a checkpoint and a
retry the same, and the capacity market and moved customers play in a realm as
on a page, under the strict gate. The tests needed three things: an old save's
first days earn the new traffic badges, which the unwatched network's snapshot
keeps; the restore test compares JSON text with sorted keys instead of a
deep-equal of two networks (a diff of gigabytes when they differ); and the crawl
opens the windows that move a customer, with a new test playing the market's and
the path moves' acts, 40 days of sales and a checkpoint against the page.
This commit is contained in:
jvanvik 2026-11-07 11:21:23 +01:00
parent 61e31c53d3
commit 065c922287
12 changed files with 1906 additions and 29 deletions

View file

@ -32,7 +32,10 @@
"tests/modes.test.js": 41.1,
"tests/more-cables.test.js": 14.3,
"tests/moscow-premium.test.js": 12.0,
"tests/mp-sim-acts.test.js": 14.0,
"tests/mp-sim-contract.test.js": 7.0,
"tests/mp-sim-determinism.test.js": 40.0,
"tests/mp-sim-engine.test.js": 9.0,
"tests/networks-list.test.js": 6.4,
"tests/new-game-speed.test.js": 10.1,
"tests/optic-counts.test.js": 9.7,

28
tests/lib/mp-sim-crawl.js Normal file
View file

@ -0,0 +1,28 @@
// Every button and drop-down a rich game shows, as the page would send it: [act, args]. Runs in a jsdom page of the
// game (tests/harness.js load()) on whatever network it holds: city panels and their tabs, link panels, the left
// lists, every dashboard tab, the bank, the sheets the big buttons open, the link window, the windows that move a
// customer to another path, and armed two-click buttons.
// Used by the envelope check (tests/mp-sim-contract.test.js) and the engine's timer audit and gate
// (tests/mp-sim-determinism.test.js), which send them to a server realm.
'use strict';
function crawl(ev) {
ev(`window.__btns=[];window.__grab=()=>{for(const el of document.querySelectorAll('[data-act],[data-chg]')){const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){a={bad:el.dataset.args};}
if(el.dataset.chg){a={...a,v:el.value}}__btns.push([act,a]);}};`);
const views = [
"for(const c of ['fra','ams','nyc','sin','syd']){for(const tab of ['cust','up','peer','infra','links']){UI.sel={type:'city',id:c};UI.tab=tab;renderPanel();__grab();}}",
"for(const l of S.links.slice(0,40)){UI.sel={type:'link',id:l.id};renderPanel();__grab();}",
"UI.leftOpen=true;for(const k of ['goals','deals','noc','nets']){UI.left=k;renderLeft();__grab();}",
"$('dash').hidden=false;for(const k of DTABS){UI.dtab=k;renderDash();__grab();}$('dash').hidden=true;",
'ACT.bank();__grab();ACT.bankClose();',
"for(const [a,x] of [['opsOpen',{}],['utilities',{city:'fra'}],['bstdOpen',{}],['pniAllOpen',{net:null}],['pniAllOpen',{net:'cog'}],['salesOpen',{}],['routingOpen',{}],['ip4Open',{}],['models',{}],['decomOpen',{}],['teEdit',{}]]){try{ACT[a](x);}catch(e){}__grab();closeModal();}",
"openLinkModal('fra','nyc');__grab();closeModal();openLinkModal('fra','ams');__grab();closeModal();",
// Moving a customer to another path (3.3.0): its buttons are only in that window.
'for(const b of S.biz.filter(b=>pathKind(b)).slice(0,6)){ACT.pathOpen({id:b.id});__grab();closeModal();}',
"UI.confirm=null;for(const t of S.transit.slice(0,3)){UI.sel={type:'city',id:t.city};UI.tab='up';UI.confirm=t.id;renderPanel();__grab();}UI.confirm=null;",
];
for (const v of views) ev(v);
return JSON.parse(ev('JSON.stringify(__btns)'));
}
module.exports = { crawl };

View file

@ -10,11 +10,14 @@
// 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.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?} (views: [{link} | {peer}]);
// snap is the realm's half (t, epoch, v, now, S, r, keep): engine.snapWith(snap, {clock,
// roster, since}) makes the stream event
// 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)
// engine.unload(code, nid?) → {t:'unloaded', code, nid?}; engine.stats() → {workers, realms, sessions} (not a promise);
// engine.close() → stops it (every pending call rejects)
//
// 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
@ -31,6 +34,7 @@
// (retried:true, no err).
'use strict';
const { fixture } = require('./mp-sim-shape');
const { snapWith } = require('../../scripts/lib/mp-sim-engine');
function createFakeEngine(opts = {}) {
const F = { snap: fixture('snap'), day: fixture('upd-day'), act: fixture('upd-act'), sub: fixture('sub'), roster: fixture('roster') };
@ -69,9 +73,10 @@ function createFakeEngine(opts = {}) {
const s = { ...base.s, day: r.day };
return JSON.stringify({ ...base, from, v, now: Date.now(), day: r.day, s, ...extra });
};
// The realm's half of a snapshot: the host adds clock, roster and since with snapWith().
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) });
return JSON.stringify({ t: 'snap', epoch: r.epoch, v: r.v, now: Date.now(), S, r: F.snap.r, keep: r.keep.splice(0) });
};
const subsOf = (views = []) => {
const o = {};
@ -165,6 +170,8 @@ function createFakeEngine(opts = {}) {
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 }; },
close() { engine.exit(); return Promise.resolve(); },
snapWith,
// Test controls.
lose(code, nid) { realm(code, nid).loseNext = true; },
pause(code, nid) { realm(code, nid).pause = true; },

85
tests/lib/mp-sim-play.js Normal file
View file

@ -0,0 +1,85 @@
// 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) the page's ctx: its selection, tab and left list, a desktop viewport
// 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), canon(s) the first differing top-level keys of two JSON texts; a JSON text with its keys sorted
'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 ctxOf = (ev, o = {}) => ({ 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 });
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');
}
// JSON text with every object's keys sorted (arrays keep their order): two networks that differ only in key order are
// the same text. Compare these strings, never the parsed objects with a deep-equal.
const sortK = (v) => (Array.isArray(v) ? v.map(sortK) : v && typeof v === 'object' ? Object.keys(v).sort().reduce((o, k) => ((o[k] = sortK(v[k])), o), {}) : v);
const canon = (s) => JSON.stringify(sortK(JSON.parse(s)));
module.exports = { CODE, PID, DEV, MP, T0, STEP, TEST, ROOMY, sim, page, bigScenic, msg, ctxOf, begin, RSIG, checked, differs, canon };

View file

@ -83,7 +83,9 @@ function checkFx(f, w = 'fx', out = []) {
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 'sfx': if (!str(p)) bad(); break;
// The game's haptic(ms) takes how long to buzz.
case 'haptic': if (!(num(p) && p >= 0)) 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;
@ -111,14 +113,18 @@ const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str
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)) };
/* A snapshot is made in two halves: the realm's (the network: S, r, keep, at its epoch and version) and the host's
(clock, roster, since: the session and this stream). A worker's pulled.snap is the realm's half as text; the engine's
snapWith() joins the host's to it (scripts/lib/mp-sim-engine.js). */
const SNAP_REALM = { t: str, epoch: (v) => EPOCH.test(v), v: nat, now: nat, S: liveS, r: slimR,
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; } };
const SNAP_HOST = { 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; } };
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);
if (e.t === 'snap') fields(e, { ...SNAP_REALM, ...SNAP_HOST }, 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)');
@ -135,6 +141,8 @@ function checkEvent(e) {
// 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; };
// The realm's half of a snapshot (above): the host's three fields come later, so here they are unknown.
const snapPart = (v, w, out) => { if (!str(v)) return false; let e; try { e = JSON.parse(v); } catch (x) { return false; } if (!obj(e) || e.t !== 'snap') { out.push(`${w}: not a snap`); return true; } fields(e, SNAP_REALM, w, out); return true; };
const subs = mapOf((k) => /^(link|peer):.{1,40}$/.test(k), (v) => obj(v));
const epoch = (v) => EPOCH.test(v);
const WORKER = {
@ -144,7 +152,7 @@ const WORKER = {
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'] },
pulled: { t: str, nid: (v) => PID.test(v), epoch, v: nat, upd: [json('upd'), 'opt'], snap: [snapPart, '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) },
@ -157,7 +165,7 @@ function checkWorker(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 */ } }
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'); if (e.v !== m.v) out.push('pulled: the snapshot is not at the version pulled'); } catch (x) { /* reported above */ } }
return out;
}

220
tests/mp-sim-acts.test.js Normal file
View file

@ -0,0 +1,220 @@
// The act tables of server-run play (scripts/lib/mp-sim-acts.js) against the game itself (the server-sim design, 5.8):
// SEND is the agent's game commands, adjusted; the CONFIRM table is how each two-click button arms (SRV_ARM is the key
// its first click writes); DRAFTS are the page-held UI values each act reads, all of them; and for every draft and text
// act, and every two-click one, the server's pipeline (drafts and arming from the request, then one run) leaves the same
// network as the page's clicks in jsdom.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const A = require('../scripts/lib/mp-sim-acts');
const { createEngine } = require('../scripts/lib/mp-sim-engine');
const { crawl } = require('./lib/mp-sim-crawl');
const { TEST, ROOMY, page, bigScenic, msg, ctxOf, begin, checked, differs } = require('./lib/mp-sim-play');
const E = createEngine({ workers: 1, test: TEST, timeouts: ROOMY });
test.after(() => E.close());
test('SEND is the agent\'s game commands without the puzzles, teCheck, traceRun and closeModal, with connCancel, pieRename and tutSkip', (t) => {
const { ev, errors, dom } = load({ agent: true });
t.after(() => dom.window.close());
const cmd = JSON.parse(ev('JSON.stringify(Object.keys(API_CMD))'));
const want = cmd.filter((k) => !/^pz[A-Z]/.test(k) && !['teCheck', 'traceRun', 'closeModal'].includes(k)).concat(['connCancel', 'pieRename', 'tutSkip']).sort();
assert.deepEqual(A.SEND, want);
for (const a of [...A.SEND, ...A.ASK]) assert.equal(ev(`typeof ACT[${JSON.stringify(a)}]`), 'function', a);
assert.deepEqual(errors, []);
});
/* A rich network with something behind every two-click button: the big fixture, an intern, a sales head, a scrubbing
center, a teleport, an own exchange. Its S also goes to the realm, so both sides start the same. */
function rich() {
const P = page({ save: bigScenic() });
P.ev(`S.lvl=Math.max(S.lvl,6);ACT.opsHire({id:'kevin'});closeModal();ACT.salesHire({id:'eng'});closeModal();
ACT.buildScrub({city:'fra'});closeModal();ACT.teleBuild({city:'sea'});closeModal();UI.confirm=null;UI.sel=null;
S.day=Math.max(S.day,IP4_HOLD+30);S=migrate(JSON.parse(JSON.stringify(S)));compute();`);
// (Address blocks are held two years before they may be sold: these were bought long ago.)
return P;
}
// Pie in the Sky: a network that won (a Tier 1 club in Frankfurt, as tests/pie-in-the-sky.test.js builds it) and
// founded a rocket company with a factory, a pad in Singapore and pies on the shelf.
function pieCo() {
const P = page();
P.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e11;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=500");
P.ev("S.transit=[];S.ixp={};S.peers={};S.pni=[];S.grace=null;for(const n of t1Need())S.pni.push({id:'p'+n.id,net:n.id,city:'fra',tier:2});S.nextFail=1e9;S.nextEvent=1e9;compute()");
P.ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute();checkGoals();");
P.ev("ACT.buildPop({city:'sin'});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});S.pie.stock=400;closeModal();S.rng=99;uidN=1000;S=migrate(JSON.parse(JSON.stringify(S)));compute();");
return P;
}
const loadInto = async (code, nid, P) => checked((await E.load(code, [{ nid, env: { s: P.ev('JSON.stringify(S)'), uidN: +P.ev('uidN'), rt: null }, lang: 'en', prefs: {} }]))[0]);
test('two-click buttons: the first click arms SRV_ARM\'s key (or waits for ok), and confirmed:true on the server is both clicks', async (t) => {
const P = rich();
t.after(() => P.close());
const { ev } = P;
const code = 'C0NF1R', nid = 'conf0001';
await loadInto(code, nid, P);
// Each act's args as its button carries them, from a crawl; the rest made here (they arm before any check).
const found = {};
for (const [a, args] of crawl(ev)) if (A.CONFIRM[a] && !found[a]) found[a] = args;
ev('UI.confirm=null;UI.sel=null;closeModal();');
Object.assign(found, { rmScrub: { city: 'fra' }, teleRm: { city: 'sea' }, cancelVxc: found.cancelVxc || { id: 'nolink' }, dkOptOut: found.dkOptOut || { city: 'fra', n: 'Nobody' } }, found);
const missing = Object.keys(A.CONFIRM).filter((a) => !found[a] && a !== 'repayLoan');
assert.deepEqual(missing, [], 'a button for every two-click act');
const changed = {};
for (const [a, args] of Object.entries(found)) {
const kind = A.CONFIRM[a];
// The first click: the page's own (a view change), never sent. S stays; the button is armed.
ev('UI.confirm=null;');
const s0 = ev('JSON.stringify(S)');
ev(`ACT[${JSON.stringify(a)}](${JSON.stringify(args)})`);
assert.equal(ev('JSON.stringify(S)'), s0, `${a}: the first click changes nothing`);
const armed = JSON.parse(ev('JSON.stringify(UI.confirm)'));
if (kind === 'arg') assert.notEqual(armed, null, `${a}: armed`);
else assert.equal(armed, A.armKey(a, args), `${a}: SRV_ARM's key is what the first click writes`);
// The second click on the page, and the same click on the server, sent with confirmed:true.
const ctx = ctxOf(ev);
if (kind === 'arg') ev(`UI.confirm=null;ACT[${JSON.stringify(a)}](${JSON.stringify({ ...args, ok: 1 })})`);
else ev(`ACT[${JSON.stringify(a)}](${JSON.stringify(args)})`);
closeAll(ev);
const r = checked(await E.act(code, nid, msg(a, args, { confirmed: true, ctx })));
changed[a] = ev('JSON.stringify(S)') !== s0;
const want = ev('JSON.stringify(S)'), got = (await E.eval(code, nid, 'return JSON.stringify(S)')).value;
assert.ok(want === got, `${a} ${JSON.stringify(args)} (${r.outcome}${r.why ? ': ' + r.why : ''}):\n${want === got ? '' : differs(want, got)}`);
if (changed[a]) assert.equal(r.outcome, 'applied', a);
}
// The ones with a real target were really done.
for (const a of ['cancelTransit', 'cancelIx', 'cancelPni', 'rmLink', 'rmSite', 'dropBiz', 'salesFire', 'opsFire', 'rmScrub', 'teleRm', 'connCancel']) if (found[a]) assert.equal(changed[a], true, `${a} did its thing`);
assert.deepEqual(P.errors, []);
});
const closeAll = (ev) => ev('closeModal();');
test('repayLoan: armed by its id, repaid by the second click (a network small enough to borrow)', async (t) => {
const P = page();
t.after(() => P.close());
P.ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:{code:'K7Q2XD',pid:'loan0001',asn:201234,seed:5,preset:'oncall',color:'#3a86ff',title:'x'}});S.mp.sim=1;S.tut=null;compute();
ACT.launchBB({city:'fra'});spawnLoanOffer(false);ACT.takeLoan({id:S.loanOffers[0].id});closeModal();S.cash+=5e6;uidN=1000;`);
const id = P.ev('S.loans[0].id');
const code = 'L0ANS0', nid = 'loan0001';
await loadInto(code, nid, P);
P.ev('UI.confirm=null');
const s0 = P.ev('JSON.stringify(S)');
P.ev(`ACT.repayLoan({id:'${id}'})`);
assert.equal(P.ev('JSON.stringify(S)'), s0);
assert.equal(P.ev('UI.confirm'), A.armKey('repayLoan', { id }));
P.ev(`ACT.repayLoan({id:'${id}'})`);
assert.equal(P.ev('S.loans.length'), 0, 'repaid');
const r = checked(await E.act(code, nid, msg('repayLoan', { id }, { confirmed: true })));
assert.equal(r.outcome, 'applied');
assert.equal((await E.eval(code, nid, 'return JSON.stringify(S)')).value, P.ev('JSON.stringify(S)'));
});
/* The UI values an act reads, recorded while it runs (its redraw, after(), and windows left out: they read the page's
own state to draw it). Every page-held value it reads must be one of its DRAFTS; each of its DRAFTS is read on one of
the paths played here, except the few named with the reason they are not played. */
const PAGE_HELD = [...new Set([...Object.keys(A.DRAFT_TYPES), 'lmode', 'dfMode', 'drag', 'snap', 'hover', 'vp', 'nf', 'dtab'])];
const UNPLAYED = { cnPrem: 'buildLink reads it only on a link into Hong Kong across the border', slop: 'teDeploy reads it only when the script cost a tenth of the traffic' };
test('DRAFTS: the page-held UI values each act reads, all of them', (t) => {
const P = rich();
t.after(() => P.close());
const SPY = `window.__reads=new Set();window.__spy=()=>{for(const k of new Set(${JSON.stringify(PAGE_HELD)}.concat(Object.keys(UI)))){let v=UI[k];Object.defineProperty(UI,k,{get(){__reads.add(k);return v;},set(x){v=x;},configurable:true,enumerable:true});}};
window.__unspy=()=>{const r=[...__reads];for(const k of Object.keys(UI)){const d=Object.getOwnPropertyDescriptor(UI,k);const v=d.get?d.get():d.value;Object.defineProperty(UI,k,{value:v,writable:true,configurable:true,enumerable:true});}return r;};`;
const { ev } = P;
ev(SPY);
const near = ev("Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((a,b)=>kmBetween('ams',a)-kmBetween('ams',b))[0]");
const sib = ev("(()=>{const l=S.links.find(l=>l.kind==='wave'&&landTrenches(l.a,l.b).length);return l.a+'|'+l.b;})()").split('|');
const runs = [
['buildLink', `openLinkModal('fra','${near}')`, { tier: 1 }],
['buildLink', `openLinkModal('${sib[0]}','${sib[1]}');UI.route='same';`, { tier: 1 }],
['buildLink', `openLinkModal('lon','nyc');UI.via='land';`, { tier: 1 }],
['orderDf', "UI.pending={a:'fra',b:'muc'};UI.dfSrc='lease';UI.dfSys='lite';", {}],
['orderDf', "UI.pending={a:'fra',b:'muc'};UI.dfSrc='build';UI.dfSys='lite';", {}],
['orderCable', "UI.pending={a:'lon',b:'nyc'};UI.seaDesign='express';UI.seaterminal=true;UI.seaengineering=false;", {}],
['decomGo', "UI.decom=new Set(['bet']);", {}],
['teDeploy', "S.te={on:true,day:S.day,script:''};UI.slop=undefined;", { script: 'prefer cog at fra' }],
['pieLaunch', 'UI.pieIns=true;UI.pieLas=false;', { rk: 'falcon', cr: 'short' }, pieCo()],
];
const reads = {};
for (const [act, setup, args, other] of runs) {
const ev = other ? other.ev : P.ev;
if (other) { t.after(() => other.close()); ev(SPY); }
ev(setup);
ev(`window.__keep=[after,openModal,renderAll,renderPanel,renderLeft,renderHUD,renderHint,renderDash,renderBank];
after=openModal=renderAll=renderPanel=renderLeft=renderHUD=renderHint=renderDash=renderBank=()=>{};__spy();__reads.clear();`);
try { ev(`ACT.${act}(${JSON.stringify(args)})`); } finally {
reads[act] = new Set([...(reads[act] || []), ...JSON.parse(ev('JSON.stringify(__unspy())'))]);
ev('[after,openModal,renderAll,renderPanel,renderLeft,renderHUD,renderHint,renderDash,renderBank]=__keep;closeModal();');
}
const extra = [...reads[act]].filter((k) => PAGE_HELD.includes(k) && !A.DRAFTS[act].includes(k));
assert.deepEqual(extra, [], `${act} reads page-held UI that is not in its DRAFTS`);
}
for (const act of Object.keys(A.DRAFTS)) {
assert.ok(reads[act], `${act} was played`);
for (const k of A.DRAFTS[act]) if (!UNPLAYED[k]) assert.ok(reads[act].has(k), `${act} reads ${k}`);
}
assert.deepEqual(P.errors, []);
});
test('drafts and texts: the server\'s run of each draft and text act leaves the network the page\'s clicks leave', async (t) => {
const P = rich();
t.after(() => P.close());
const { ev } = P;
ev("S.te={on:true,day:S.day,script:''};closeModal();UI.sel=null;compute();");
const code = 'DRAFT5', nid = 'drft0001';
await loadInto(code, nid, P);
const near = ev("Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((a,b)=>kmBetween('ams',a)-kmBetween('ams',b))[0]");
const script = ev('TE_EXAMPLE'), metric = ev("S.links.find(l=>l.kind==='wave'&&l.a!=='bet'&&l.b!=='bet').id");
// [act, args, what the page did before the click (its drafts), the drafts sent]
const plays = [
['buildLink', { tier: 1 }, `openLinkModal('fra','${near}')`, () => pick(ev, ['pending', 'route', 'via', 'cnPrem'])],
['orderDf', {}, "UI.pending={a:'fra',b:'muc'};UI.dfSrc='lease';UI.dfSys='lite';", () => pick(ev, ['pending', 'dfSrc', 'dfSys'])],
['orderCable', {}, "UI.pending={a:'lon',b:'nyc'};UI.seaDesign='express';UI.seaterminal=true;UI.seaengineering=false;", () => pick(ev, ['pending', 'seaDesign', 'seaterminal', 'seaengineering'])],
['decomGo', {}, "UI.decom=new Set(['bet']);", () => ({ decom: JSON.parse(ev('JSON.stringify([...UI.decom])')) })],
['teDeploy', { script }, 'UI.slop=undefined;', () => ({ slop: false })],
['setMetric', { id: metric, v: 'custom' }, '', null],
['metricSet', { id: metric, v: '42' }, '', null],
['renameGo', { name: 'Tubular Bells' }, '', null],
];
await play(code, nid, ev, plays);
// A what-if with its text: the window, and the network as it was.
const K = checked(await E.ask(code, nid, msg('teCheck', { script })));
assert.match(K.modal.h, /term/);
assert.equal((await E.eval(code, nid, 'return JSON.stringify(S)')).value, ev('JSON.stringify(S)'));
assert.deepEqual(P.errors, []);
// The rocket company's acts, on a network that won and founded one.
const Q = pieCo();
t.after(() => Q.close());
await loadInto('P1EC0S', 'piec0001', Q);
await play('P1EC0S', 'piec0001', Q.ev, [
['pieRename', { name: 'Pie Hard' }, '', null],
['pieLaunch', { rk: 'falcon', cr: 'short' }, 'UI.pieIns=true;UI.pieLas=false;', () => pick(Q.ev, ['pieIns', 'pieLas'])],
]);
assert.deepEqual(Q.errors, []);
});
async function play(code, nid, ev, plays) {
for (const [act, args, before, ui] of plays) {
ev(before);
const ctx = ctxOf(ev), drafts = ui ? ui() : null;
const s0 = ev('JSON.stringify(S)');
ev(`ACT.${act}(${JSON.stringify(args)});closeModal();`);
const r = checked(await E.act(code, nid, msg(act, args, { ...(drafts ? { ui: drafts } : {}), ctx })));
const want = ev('JSON.stringify(S)'), got = (await E.eval(code, nid, 'return JSON.stringify(S)')).value;
assert.notEqual(want, s0, `${act} did something on the page`);
assert.equal(r.outcome, 'applied', `${act}: ${r.why || ''}`);
assert.ok(want === got, `${act}:\n${want === got ? '' : differs(want, got)}`);
}
}
const pick = (ev, keys) => JSON.parse(ev(`JSON.stringify(Object.fromEntries(${JSON.stringify(keys)}.filter(k=>UI[k]!==undefined&&UI[k]!==null).map(k=>[k,UI[k]])))`));
// The gate (5.8 step 6) is right about buyTE: it writes S.te without the script a reload gives it. A todo until the game
// writes it in its saved shape (src/game/90-actions/30-route-script-and-tools.js, buyTE: script:''; see the T2 report).
test('buyTE leaves S.te as a reload makes it', { todo: 'game fix for the integrator: buyTE writes S.te={on:true,day:S.day,script:\'\'}' }, async (t) => {
const P = page({ save: bigScenic() });
t.after(() => P.close());
const code = 'B0YTE0', nid = 'buyt0001';
await loadInto(code, nid, P);
for (const a of ['coreUp', 'coreUp']) checked(await E.act(code, nid, msg(a, {})));
const r = checked(await E.act(code, nid, msg('buyTE', {})));
assert.equal(r.outcome, 'applied', r.why);
});

View file

@ -10,6 +10,7 @@ const { lit } = require('../scripts/lib/js-literal');
const A = require('../scripts/lib/mp-sim-acts');
const { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES } = require('./lib/mp-sim-shape');
const { createFakeEngine } = require('./lib/mp-sim-fake-engine');
const { crawl } = require('./lib/mp-sim-crawl');
const fs = require('node:fs');
const path = require('node:path');
@ -44,24 +45,6 @@ test('every ACT is classified once: SEND, ASK, VOTE, LOCAL or PUZZLE; SEND is th
assert.deepEqual(errors, []);
});
// Every button and drop-down a rich game shows, as the page would send it: [act, args].
function crawl(ev) {
ev(`window.__btns=[];window.__grab=()=>{for(const el of document.querySelectorAll('[data-act],[data-chg]')){const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){a={bad:el.dataset.args};}
if(el.dataset.chg){a={...a,v:el.value}}__btns.push([act,a]);}};`);
const views = [
"for(const c of ['fra','ams','nyc','sin','syd']){for(const tab of ['cust','up','peer','infra','links']){UI.sel={type:'city',id:c};UI.tab=tab;renderPanel();__grab();}}",
"for(const l of S.links.slice(0,40)){UI.sel={type:'link',id:l.id};renderPanel();__grab();}",
"UI.leftOpen=true;for(const k of ['goals','deals','noc','nets']){UI.left=k;renderLeft();__grab();}",
"$('dash').hidden=false;for(const k of DTABS){UI.dtab=k;renderDash();__grab();}$('dash').hidden=true;",
'ACT.bank();__grab();ACT.bankClose();',
"for(const [a,x] of [['opsOpen',{}],['utilities',{city:'fra'}],['bstdOpen',{}],['pniAllOpen',{net:null}],['pniAllOpen',{net:'cog'}],['salesOpen',{}],['routingOpen',{}],['ip4Open',{}],['models',{}],['decomOpen',{}],['teEdit',{}]]){try{ACT[a](x);}catch(e){}__grab();closeModal();}",
"openLinkModal('fra','nyc');__grab();closeModal();openLinkModal('fra','ams');__grab();closeModal();",
"UI.confirm=null;for(const t of S.transit.slice(0,3)){UI.sel={type:'city',id:t.city};UI.tab='up';UI.confirm=t.id;renderPanel();__grab();}UI.confirm=null;",
];
for (const v of views) ev(v);
return JSON.parse(ev('JSON.stringify(__btns)'));
}
test('the envelope check passes every button a rich game shows for a sent act, as the page sends it', (t) => {
const fsx = require('node:fs');
const BIG = fsx.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
@ -74,7 +57,7 @@ test('the envelope check passes every button a rich game shows for a sent act, a
assert.ok(sent.length > 200, `a real sweep: ${sent.length} sent buttons of ${btns.length}`);
const acts = new Set(sent.map(([a]) => a));
assert.ok(acts.size > 40, `${acts.size} different acts`);
for (const q of ['pniAll', 'bstdApply', 'utilityKit']) assert.ok(acts.has(q), `the sweep found ${q}`);
for (const q of ['pniAll', 'bstdApply', 'utilityKit', 'mktCfg', 'pathPin']) assert.ok(acts.has(q), `the sweep found ${q}`);
for (const [act, args] of sent) {
// The page adds the drafts the act reads, as they are, and confirms a two-click act's second click.
const ui = A.DRAFTS[act] ? JSON.parse(ev(`JSON.stringify({pending:UI.pending||{a:'fra',b:'ams'},route:UI.route||'',via:UI.via||'',cnPrem:!!UI.cnPrem,dfSrc:'lease',dfSys:'lite',seaDesign:'standard',
@ -207,6 +190,11 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
// The worker built that realm again: a new epoch, versions from 0, so every page of it takes a snapshot.
const P3 = await e.pull(code, a, { snap: true });
assert.notEqual(P3.epoch, L[0].epoch); assert.equal(P3.v, 0); assert.equal(JSON.parse(P3.snap).epoch, P3.epoch);
// A pulled snapshot is the realm's half; with the host's clock, roster and since it is the stream event.
const host = { clock: fixture('clock'), roster: fixture('roster'), since: { days: 0, again: 0 } };
assert.match(checkEvent(JSON.parse(P3.snap)).join(), /clock: missing/, 'the realm\'s half alone is no stream event');
assert.deepEqual(checkEvent(JSON.parse(e.snapWith(P3.snap, host))), []);
assert.deepEqual(JSON.parse(e.snapWith(P3.snap, host)).clock, host.clock);
all.push(D2, D3, tmo, P3);
for (const m of all) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
// Held answers wait; a worker that dies rejects everything pending.

View file

@ -0,0 +1,314 @@
// The server's realm plays a network exactly as the page does (the server-sim design, sections 4.1-4.3, 4.7, 11).
// - Realm vs jsdom: the big network with its L2 customers on scenic routes, 60 days with actions in between, the
// page's arm clicking as a player does (each click ending in after()) and rendering the HUD after every day: S and R
// byte for byte the same.
// - Restore: 20 days straight, or 10, a checkpoint, a fresh realm and 10 more: the same network.
// - Retry: a day that fails once (a throw, and a timeout, both after the day's DDoS step with an attack on) leaves the
// same network as no failure.
// - Order: three networks of a session, in two different realm orders, each the same.
// - Market and moved customers (3.2.0, 3.3.0): the market's settings and a customer moved to another fiber or pinned
// to a path, then days of sales, against the page and under the strict gate; a checkpoint of it plays on the same.
// - Timer audit and gate: days with failures, events, the intern on every order and the sales desk on auto, then every
// sent button a rich crawl finds: no timer is ever scheduled on these paths, nothing changes after them, and no
// action is rolled back by the sanitize gate (which also runs after every day here, SIM_STRICT).
// SIM_LONG=1 plays the audit for a year, as section 11 asks (a few minutes); by default it plays 60 days.
const test = require('node:test');
const assert = require('node:assert/strict');
const { createEngine } = require('../scripts/lib/mp-sim-engine');
const { crawl } = require('./lib/mp-sim-crawl');
const A = require('../scripts/lib/mp-sim-acts');
const { load } = require('./harness');
const { CODE, MP, TEST, ROOMY, T0, STEP, page, bigScenic, msg, ctxOf, begin, RSIG, checked, differs, canon } = require('./lib/mp-sim-play');
const LONG = process.env.SIM_LONG === '1';
/* Acts the gate refuses because the game leaves a key in a shape sanitize() repairs: game fixes for the integrator (the
T2 report has each patch). Take an entry out once its fix is in; any other refusal fails the audit.
buyTE writes S.te without its script; mkBanana (mkLeave) keeps a finished visit's fields in S.monkey. */
const PENDING = { buyTE: 'te', mkBanana: 'monkey' };
const E = createEngine({ workers: 2, test: TEST, timeouts: ROOMY });
test.after(() => E.close());
const on = (X) => ({
day: (code, d, nets, o = {}) => X.day(code, { d, speed: 1, last: 1, alone: [], nets, ...o }).then(checked),
realmS: async (code, nid) => (await X.eval(code, nid, 'return JSON.stringify(S)')).value,
realmR: async (code, nid) => (await X.eval(code, nid, `return ${RSIG}`)).value,
});
const { day, realmS, realmR } = on(E);
const loadBig = async (code, nid) => checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
test('realm vs jsdom: 60 days of the scenic big network with actions in between, S and R byte for byte', async (t) => {
const P = page({ save: bigScenic() });
t.after(() => P.close());
const code = 'D3T3RM', nid = 'detr0001';
await loadBig(code, nid);
const ev = P.ev;
const near = ev("Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((a,b)=>kmBetween('fra',a)-kmBetween('fra',b))[0]");
const net = ev(`NETS.filter(n=>sellsAt(n,${JSON.stringify(near)}))[0].id`);
const script = ev('TE_EXAMPLE');
const gone = ev("S.links.find(l=>l.kind==='wave'&&l.a==='fra').id");
// On a day: what the player clicks, the page's way, and the request the same click sends the server.
const PLAN = {
5: () => ({ act: 'buildPop', args: { city: near }, page: () => ev(`ACT.buildPop({city:${JSON.stringify(near)}})`) }),
6: () => { ev(`openLinkModal('fra',${JSON.stringify(near)})`);
const ui = JSON.parse(ev("JSON.stringify(Object.fromEntries(['pending','route','via','cnPrem'].filter(k=>UI[k]!==undefined&&UI[k]!==null||k==='pending').map(k=>[k,UI[k]])))"));
return { act: 'buildLink', args: { tier: 1 }, ui, page: () => ev('ACT.buildLink({tier:1})') }; },
8: () => ({ act: 'buyTransit', args: { city: near, net, tier: 1 }, page: () => ev(`ACT.buyTransit({city:${JSON.stringify(near)},net:'${net}',tier:1})`) }),
12: () => { ev(`UI.sel={type:'link',id:'${gone}'};`); return { act: 'rmLink', args: { id: gone }, confirmed: true, page: () => ev(`ACT.rmLink({id:'${gone}'});ACT.rmLink({id:'${gone}'})`) }; },
15: () => ({ act: 'renameGo', args: { name: 'Tubular Bells' }, page: () => ev("ACT.renameGo({name:'Tubular Bells'})") }),
18: () => ({ act: 'coreUp', args: {}, page: () => ev('ACT.coreUp()') }),
19: () => ({ act: 'coreUp', args: {}, page: () => ev('ACT.coreUp()') }),
// Auto-TE as buyTE makes it once the game writes S.te in its saved shape (script:'', see the T2 report): today the
// gate refuses buyTE, rightly, as a reload adds that script (tests/mp-sim-acts.test.js keeps it as a todo).
21: () => ({ setup: "S.te={on:true,day:S.day,script:''};" }),
22: () => ({ act: 'teDeploy', args: { script }, ui: { slop: false }, page: () => ev(`ACT.teDeploy({script:${JSON.stringify(script)}})`) }),
};
const outcomes = {};
for (let d = 1; d <= 60; d++) {
if (PLAN[d] && PLAN[d]().setup) { const x = PLAN[d]().setup; ev(x); await E.eval(code, nid, x + 'return 1;'); }
else if (PLAN[d]) {
const p = PLAN[d]();
const ctx = ctxOf(ev);
p.page();
const r = checked(await E.act(code, nid, msg(p.act, p.args, { ...(p.ui ? { ui: p.ui } : {}), ...(p.confirmed ? { confirmed: true } : {}), ctx })));
outcomes[p.act + '@' + d] = r.outcome + (r.why ? ': ' + r.why : '');
const a = ev('JSON.stringify(S)'), b = await realmS(code, nid);
assert.ok(a === b, `after ${p.act} on day ${d}:\n${a === b ? '' : differs(a, b)}`);
}
P.day();
const D = await day(code, d, [nid]);
assert.equal(D.nets[nid].err, undefined, `day ${d}`);
if (d % 20 === 0) {
const a = ev('JSON.stringify(S)'), b = await realmS(code, nid);
assert.ok(a === b, `S on day ${d}:\n${a === b ? '' : differs(a, b)}`);
assert.ok(ev(RSIG) === await realmR(code, nid), `R on day ${d}`);
}
}
// The plan really played: the network grew, a link went, the script is live.
for (const k of ['buildPop@5', 'buildLink@6', 'buyTransit@8', 'rmLink@12', 'renameGo@15', 'teDeploy@22']) assert.equal(outcomes[k], 'applied', k);
assert.equal(ev('S.name'), 'Tubular Bells');
assert.equal(ev('!!(S.te&&S.te.on&&S.te.script)'), true, 'RouteScript is deployed');
assert.equal(ev('S.biz.filter(b=>b.route===\'scenic\').length') > 0, true, 'scenic circuits played');
assert.deepEqual(P.errors, []);
});
test('restore: 20 days straight, or 10, a checkpoint, a fresh realm and 10 more, is the same network', async () => {
const code = 'R3ST0R', a = 'rsta0001', b = 'rstb0002', c = 'rstc0003';
await loadBig(code, a); await loadBig(code, b);
for (let d = 1; d <= 10; d++) await day(code, d, [a, b]);
// b's checkpoint: the envelope a server writes (4.6), into a fresh realm; the network's clock goes on.
const sv = checked(await E.save(code, b));
const env = { s: sv.txt, uidN: sv.uidN, rt: sv.rt, last: 10, day: sv.day };
await E.unload(code, b);
checked((await E.load(code, [{ nid: c, env: JSON.parse(JSON.stringify(env)), lang: 'en', prefs: {} }]))[0]);
await E.eval(code, c, `__srvClock(${T0 + 10 * STEP})`);
for (let d = 11; d <= 20; d++) await day(code, d, [a, c]);
// The same play: every value the same. (Only the order of a customer's keys can differ: the save drops the defaults
// that sanitize() puts back, at the end. A page takes a snapshot of a reloaded realm anyway, a new epoch.)
// Compared as text, keys sorted: a deep-equal of two big networks that differ builds a diff of gigabytes.
const sa = canon(await realmS(code, a)), sc = canon(await realmS(code, c));
assert.ok(sc === sa, `S after 20 days:\n${sc === sa ? '' : differs(sa, sc)}`);
const ra = canon(await realmR(code, a)), rc = canon(await realmR(code, c));
assert.ok(rc === ra, `R after 20 days:\n${rc === ra ? '' : differs(ra, rc)}`);
assert.ok(JSON.parse(sa).biz.some((x) => x.route === 'scenic'), 'with scenic circuits');
await E.unload(code);
});
test('retry: a day that throws, or times out, once after the DDoS step with an attack on, leaves the same network', async (t) => {
// An engine with the server's own time limits: the injected endless loop is stopped by them.
const E = createEngine({ workers: 1, test: TEST });
t.after(() => E.close());
const { day, realmS, realmR } = on(E);
const code = 'R3TRYX', clean = 'rtya0001', thrown = 'rtyb0002', slow = 'rtyc0003', nets = [clean, thrown, slow];
const L = await E.load(code, nets.map((nid) => ({ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} })));
L.forEach(checked);
for (let d = 1; d <= 3; d++) await day(code, d, nets);
// An attack that is still on during day 4 (the same one in each).
for (const nid of nets) assert.ok((await E.eval(code, nid, 'const a=ddosAttack(true);a.until=S.day+3;return ddosAll().length')).value > 0, 'an attack is on');
const epoch = async (nid) => checked(await E.pull(code, nid, {})).epoch;
const e0 = { thrown: await epoch(thrown), slow: await epoch(slow) };
// Day 4 fails once in two of them, right after the DDoS step, while the attack is on.
const fault = (what) => `{const f=ddosTick;let once=true;ddosTick=function(){f();if(once&&ddosAll().length){once=false;${what}}};}return 1;`;
await E.eval(code, thrown, fault("throw new Error('injected failure')"));
await E.eval(code, slow, fault('for(;;){}'));
const D = await day(code, 4, nets);
assert.deepEqual([D.nets[clean].retried, D.nets[thrown].retried, D.nets[slow].retried], [undefined, true, true]);
for (const nid of nets) assert.equal(D.nets[nid].err, undefined, `${nid} played day 4`);
assert.equal(await epoch(thrown), e0.thrown, 'a throw is put back in place: the same realm');
assert.notEqual(await epoch(slow), e0.slow, 'a timeout gets a fresh realm: a new epoch');
for (let d = 5; d <= 8; d++) await day(code, d, nets);
const s0 = await realmS(code, clean), r0 = await realmR(code, clean);
for (const nid of [thrown, slow]) {
const s = await realmS(code, nid);
assert.ok(s === s0, `${nid}:\n${s === s0 ? '' : differs(s0, s)}`);
assert.ok(await realmR(code, nid) === r0, `${nid}: R`);
}
// A day that fails twice: broken at its state before the day; it gets no more days, its actions stop.
await E.eval(code, thrown, "{const f=ddosTick;ddosTick=function(){f();throw new Error('broken for good');};}return 1;");
const before = JSON.parse(await realmS(code, thrown)).day;
const D2 = await day(code, 9, nets);
assert.equal(D2.nets[thrown].retried, true);
assert.match(D2.nets[thrown].err, /broken for good/);
assert.equal(D2.nets[thrown].day, before, 'at its state before the day');
assert.equal(JSON.parse(await realmS(code, thrown)).day, before);
const D3 = await day(code, 10, nets);
assert.equal(D3.nets[thrown], undefined, 'no more days');
assert.equal(checked(await E.act(code, thrown, msg('buildPop', { city: 'dus' }))).outcome, 'stopped');
await E.unload(code);
});
test('order: three networks of a session play the same in either realm order', async () => {
// The same three networks under ids that sort the other way round: X, Y, Z here are Z, Y, X there.
const X = { home: 'fra' }, Y = { home: 'nyc', preset: 'bgp' }, Z = { home: 'sin', preset: 'freeze' };
const one = { aaaa0001: X, mmmm0002: Y, zzzz0003: Z }, two = { zzzz0001: X, mmmm0002: Y, aaaa0003: Z };
const play = async (code, ids) => {
const nids = Object.keys(ids);
(await E.load(code, nids.map((nid, i) => ({ ...begin(nid, ids[nid]), begin: { ...begin(nid, ids[nid]).begin, mp: { code: 'S4M3C0', pid: 'same000' + i, asn: 201234, seed: 777, preset: ids[nid].preset || 'oncall', color: '#3a86ff', title: 'Order' } } })))).forEach(checked);
for (const nid of nids) {
const c = ids[nid].home;
for (const [act, args] of [['launchBB', { city: c }], ['buyTransit', { city: c, net: (await E.eval(code, nid, `return NETS.filter(n=>sellsAt(n,'${c}'))[0].id`)).value, tier: 1 }]]) checked(await E.act(code, nid, msg(act, args)));
}
for (let d = 1; d <= 40; d++) await day(code, d, nids.slice().reverse());
const out = {};
for (const nid of nids) out[ids[nid].home] = await realmS(code, nid);
await E.unload(code);
return out;
};
const a = await play('0RDER1', one), b = await play('0RDER2', two);
for (const k of Object.keys(a)) assert.ok(a[k] === b[k], `${k}:\n${a[k] === b[k] ? '' : differs(a[k], b[k])}`);
assert.notEqual(a.fra, a.nyc);
});
// The capacity market and moving customers came after the engine (3.2.0, 3.3.0): their acts and the market's days, on a
// network with fiber to sell (the big fixture has none), against the page, under the strict gate, then from a checkpoint.
test('market and moved customers: realm and page the same, the strict gate passes, a checkpoint plays on the same', async (t) => {
// New York to Ashburn three times (two fibers in one trench), the way round through Boston, Chicago; a wave, a managed
// wave and a circuit to move.
const fib = (id, a, z, km, tr, n = 8) => `S.links.push({id:'${id}',a:'${a}',b:'${z}',kind:'df',own:true,sys:'roadm',pairs:2,ch:Array(${n}).fill('zr4'),km:${km},sub:false,cable:null,mo:1,trench:'${tr}',cut:0,day:0,ready:0,spares:false});`;
const cust = (id, type, more) => `S.biz.push({id:'${id}',type:'${type}',name:'Customer ${id}',city:'nyc',city2:'ash',bw:1,rate:9000,reqs:[],mood:80,since:0,day:0,route:'normal'${more}});`;
const h = load({ seed: TEST.seed });
h.ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;UI.speed=0;" +
"for(const c of ['nyc','ash','bos','chi'])if(!S.pops[c])S.pops[c]={day:0,bb:null,boost:0,down:0,routers:4,gen:false,rgen:RG.length-3};" +
fib('a', 'nyc', 'ash', 350, 'ta') + fib('b', 'nyc', 'ash', 350, 'ta') + fib('c', 'ash', 'nyc', 420, 'tc') + fib('d', 'nyc', 'bos', 130, 'td') +
fib('e', 'bos', 'ash', 220, 'te') + fib('f', 'chi', 'nyc', 1200, 'tf', 16) +
cust('w', 'wwave', ",link:'a',slots:2,what:'x'") + cust('m', 'mwave', ",link:'b',slots:1,g:100,what:'x'") + cust('k', 'l2vpn', '') +
`S.rng=${MP.seed};S.mp={...${JSON.stringify(MP)},seq:0,sim:1};compute();`);
const save = h.ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))))');
h.dom.window.close();
const P = page({ save }), ev = P.ev;
t.after(() => P.close());
const S2 = createEngine({ workers: 1, test: TEST, strict: true, timeouts: ROOMY });
t.after(() => S2.close());
const code = 'MKTPTH', nid = 'mktp0001', nid2 = 'mktp0002';
checked((await S2.load(code, [{ nid, env: { s: save, uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const realm = async (n, src) => (await S2.eval(code, n, src)).value;
const same = async (what) => {
const x = ev('JSON.stringify(S)'), y = await realm(nid, 'return JSON.stringify(S)');
assert.ok(x === y, `${what}:\n${x === y ? '' : differs(x, y)}`);
};
const outcomes = [];
const act = async (a, args) => {
const ctx = ctxOf(ev);
ev(`ACT.${a}(${JSON.stringify(args)})`);
outcomes.push(a + ' ' + checked(await S2.act(code, nid, msg(a, args, { ctx }))).outcome);
await same(`after ${a}`);
};
let d = 0;
const days = async (n, nets, pg = true) => {
for (let i = 0; i < n; i++) {
if (pg) P.day();
const D = checked(await S2.day(code, { d: ++d, speed: 1, last: 1, alone: [], nets }));
for (const x of nets) assert.equal(D.nets[x].err, undefined, `${x} day ${d}: ${D.nets[x].err}`);
}
};
await act('mktHold', { v: 0 });
for (const p of ev('CM_P.join()').split(',')) { await act('mktCfg', { p, k: 'on', v: true }); await act('mktCfg', { p, k: 'floor', v: 60 }); }
await act('mktCfg', { p: 'w100', k: 'min', v: 1 });
await act('mktRoute', { k: 'ash|nyc' });
await act('mktRoute', { k: 'ash|nyc' });
const to = (id) => ev(`fiberTargets(S.biz.find(b=>b.id==='${id}')).filter(x=>!x.no).map(x=>x.l.id)[0]`);
await act('pathMove', { id: 'w', link: to('w') });
await act('pathMove', { id: 'm', link: to('m') });
const via = ev("circuitTargets(S.biz.find(b=>b.id==='k')).alts[0].p.join()");
await act('pathPin', { id: 'k', via });
await days(1, [nid]);
await act('pathAuto', { id: 'k' });
await act('pathPin', { id: 'k', via });
assert.deepEqual(outcomes.filter((o) => !o.endsWith(' applied')), [], 'every one applied');
for (let k = 0; k < 2; k++) {
await days(20, [nid]);
await same(`S on day ${d}`);
assert.ok(ev(RSIG) === await realm(nid, `return ${RSIG}`), `R on day ${d}`);
}
// What the days said (sales, news) reaches a page as fx of the next update, in the contract's shapes.
const U = JSON.parse(checked(await S2.pull(code, nid, {})).upd);
assert.ok(U.fx.some(([k, p]) => k === 'toast' && p.k === 'good'), 'the sales were told');
const sold = ev('S.stats.cmSold');
assert.ok(sold > 20 && ev("S.biz.find(b=>b.id==='k').pin.join()") === via, `the market sold (${sold}) and the circuit stayed pinned`);
// A checkpoint into a fresh realm (route memory, no route cache) plays on as the realm that kept going.
const sv = checked(await S2.save(code, nid));
checked((await S2.load(code, [{ nid: nid2, env: { s: sv.txt, uidN: sv.uidN, rt: sv.rt }, lang: 'en', prefs: {} }]))[0]);
await realm(nid2, `__srvClock(${await realm(nid, 'return __srvClock()')});return 1;`);
await days(15, [nid, nid2], false);
const s1 = canon(await realm(nid, 'return JSON.stringify(S)')), s2 = canon(await realm(nid2, 'return JSON.stringify(S)'));
assert.ok(s1 === s2, `S after the checkpoint:\n${s1 === s2 ? '' : differs(s1, s2)}`);
assert.ok(canon(await realm(nid, `return ${RSIG}`)) === canon(await realm(nid2, `return ${RSIG}`)), 'R after the checkpoint');
assert.ok(JSON.parse(s1).stats.cmSold > sold, 'it went on selling');
assert.deepEqual(await realm(nid, 'return [__SRV_T.n,__SRV_T.at]'), [0, []], 'no timer');
assert.deepEqual(P.errors, []);
});
test(`timer audit and gate: ${LONG ? 365 : 60} days with everything on, then every sent button a crawl finds`, { timeout: LONG ? 1800e3 : 300e3 }, async (t) => {
const S2 = createEngine({ workers: 1, test: TEST, strict: true, timeouts: ROOMY });
t.after(() => S2.close());
const code = 'AVD1T5', nid = 'audt0001';
const SETUP = `S.lvl=Math.max(S.lvl,6);S.rules=makeRules('bgp');ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
ACT.salesHire({id:'shark'});ACT.salesAuto();closeModal();S.nextFail=S.day+2;S.nextEvent=S.day+3;compute();`;
checked((await S2.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
await S2.eval(code, nid, SETUP + 'return 1;');
const timers = async () => (await S2.eval(code, nid, 'return [__SRV_T.n,__SRV_T.at]')).value;
const N = LONG ? 365 : 60;
let fails = 0;
for (let d = 1; d <= N; d++) {
const D = checked(await S2.day(code, { d, speed: 8, last: 8, alone: [], nets: [nid] }));
assert.equal(D.nets[nid].err, undefined, `day ${d}: ${D.nets[nid].err}`);
if (D.nets[nid].lost) break;
if (d % 30 === 0) checked(await S2.pull(code, nid, { snap: d === 30 }));
}
const after = (await S2.eval(code, nid, 'return [S.inc.length+S.stats.incidents,S.ops.log.length,S.biz.length,S.day]')).value;
assert.ok(after[0] > 0 && after[1] > 0, `failures happened and the intern worked: ${after}`);
let [n, at] = await timers();
assert.equal(n, 0, `no timer on a day: ${(at || []).join('\n')}`);
// Every sent button of the same network, found by a page.
const P = page({ save: (await S2.eval(code, nid, 'return JSON.stringify(S)')).value });
t.after(() => P.close());
const btns = crawl(P.ev).filter(([act]) => A.SEND.includes(act));
assert.ok(btns.length > 150, `a real sweep: ${btns.length} buttons`);
for (const q of ['mktCfg', 'mktHold', 'pathPin']) assert.ok(btns.some(([a]) => a === q), `the crawl found ${q}`);
// By default the first three different buttons of each act (about 250); SIM_LONG every one (about 3,000).
const seen = new Set(), per = {}, outs = {}, caught = new Set();
for (const [act, args] of btns) {
const k = act + JSON.stringify(args);
if (seen.has(k) || (!LONG && (per[act] || 0) >= 3)) continue;
seen.add(k); per[act] = (per[act] || 0) + 1;
let body;
try { body = msg(act, args, { ...(A.CONFIRM[act] ? { confirmed: true } : {}), ctx: { sel: { type: 'city', id: 'fra' }, tab: 'cust', left: 'noc', modal: false, w: 1024, h: 768 } }); } catch (e) { continue; }
const r = checked(await S2.act(code, nid, body));
if (r.t === 'err') { fails++; continue; }
outs[r.outcome] = (outs[r.outcome] || 0) + 1;
const g = /^sanitize would repair (\w+): (.*)$/.exec(r.why || '');
if (g && PENDING[act] === g[2]) { caught.add(act); continue; }
assert.equal(g, null, `the gate rolled back ${act} ${JSON.stringify(args)}: ${r.why}`);
if (r.outcome === 'error') assert.fail(`${act} ${JSON.stringify(args)}: ${r.why}`);
}
if (caught.size) t.diagnostic(`the gate refused, rightly, until the game writes these keys as a reload does (T2 report): ${[...caught].map((a) => a + ' ' + PENDING[a]).join(', ')}`);
assert.equal(fails, 0, 'no action timed out or broke its pipeline');
assert.ok(outs.applied > 20, `actions applied: ${JSON.stringify(outs)}`);
[n, at] = await timers();
assert.equal(n, 0, `no timer in an action: ${(at || []).join('\n')}`);
// Nothing waits to run later: S stays as it is after the worker's next turns.
const s1 = (await S2.eval(code, nid, 'return JSON.stringify(S)')).value;
await new Promise((r) => setTimeout(r, 50));
assert.ok((await S2.eval(code, nid, 'return JSON.stringify(S)')).value === s1, 'S changed after the call was over');
// A day after all of it still passes the strict gate.
const D = checked(await S2.day(code, { d: N + 1, speed: 1, last: 1, alone: [], nets: [nid] }));
assert.equal(D.nets[nid].err, undefined);
});

308
tests/mp-sim-engine.test.js Normal file
View file

@ -0,0 +1,308 @@
// The server-run engine (scripts/lib/mp-sim-engine.js, -worker.js, -realm.js; the server-sim design, sections 4.1-4.3,
// 5.3-5.10, 9): networks load, play days, take actions and what-ifs, and answer pulls and saves, every reply in the
// contract's shapes (tests/lib/mp-sim-shape.js); the capture table turns each kind of effect into an fx; failures go back
// to the mark (a throw in place, a timeout into a fresh realm, an exiting worker rejects everything pending); asks put
// everything back; actions report only the UI they changed; a session's day holds back loads; unwatched networks stay
// bounded; and realms do not share their intrinsics.
const test = require('node:test');
const assert = require('node:assert/strict');
const { createEngine, snapWith } = require('../scripts/lib/mp-sim-engine');
const { checkEvent, checkFx, fixture } = require('./lib/mp-sim-shape');
const { MP, TEST, ROOMY, bigScenic, msg, begin, checked } = require('./lib/mp-sim-play');
const E = createEngine({ workers: 2, test: TEST, timeouts: ROOMY });
test.after(() => E.close());
const on = (X) => ({
day: (code, d, nets, o = {}) => X.day(code, { d, speed: 1, last: 1, alone: [], nets, ...o }).then(checked),
ev: async (code, nid, src) => { const r = await X.eval(code, nid, src); assert.equal(r.error, undefined, r.error); return r.value; },
});
const { day, ev } = on(E);
const updOf = (r) => JSON.parse(r.upd);
const HOST = { clock: fixture('clock'), roster: fixture('roster'), since: { days: 0, again: 0 } };
test('a new network: begin, a snapshot, its welcome, actions, days, a what-if, views, prefs, a save and a card', async () => {
const code = 'NEWN3T', nid = 'neww0001';
const [L] = await E.load(code, [begin(nid, { tut: true })]);
checked(L);
assert.equal(L.day, 0);
assert.equal(L.saved.nid, nid, 'a new network is checkpointed at once');
assert.equal(JSON.parse(L.saved.txt).mp.sim, 1);
assert.equal(JSON.parse(L.saved.txt).tut, 0, 'the tutorial starts on the server');
// A page's first snapshot: v 0, the realm's half, a stream event once the host adds its own.
const P0 = checked(await E.pull(code, nid, { snap: true }));
assert.deepEqual([P0.v, P0.upd], [0, undefined]);
assert.deepEqual(checkEvent(JSON.parse(snapWith(P0.snap, HOST))), []);
assert.equal(JSON.parse(P0.snap).S.log[0].k, 'goal', 'the welcome is in the log');
// The welcome comes to that page with the first update: here the one-shots a page says on opening (greet).
const G = checked(await E.greet(code, nid));
assert.equal(G.v, 1);
assert.ok(updOf(G).fx.some(([k, p]) => k === 'toast' && p.k === 'goal' && /AS201234/.test(p.h)), 'the welcome toast');
// Actions: the update with the result is version v; the tutorial moves on the server.
const a1 = checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
assert.deepEqual([a1.outcome, a1.v, a1.epoch], ['applied', 2, L.epoch]);
const u1 = updOf(a1);
assert.equal(u1.from, 1);
assert.deepEqual(u1.acts.map((x) => x.rid), [JSON.parse(JSON.stringify(a1.rid))]);
assert.equal(u1.s.tut, 1, 'the first coach step is done');
assert.ok('cash' in u1.s && 'pops' in u1.s, 'the keys it changed');
assert.ok(!('links' in u1.s), 'and only those');
const net = await ev(code, nid, "return NETS.filter(n=>sellsAt(n,'fra'))[0].id");
assert.equal(checked(await E.act(code, nid, msg('buyTransit', { city: 'fra', net, tier: 1 }))).outcome, 'applied');
assert.equal(checked(await E.act(code, nid, msg('buyTransit', { city: 'nowhere', net, tier: 1 }))).outcome, 'no_effect');
// Refused by the game with a toast (and its log line): rejected, and the page hears why.
const cash = await ev(code, nid, 'const c=S.cash;S.cash=10;return c;');
const poor = checked(await E.act(code, nid, msg('buildPop', { city: 'syd' })));
assert.equal(poor.outcome, 'rejected');
assert.ok(updOf(poor).fx.some(([k, p]) => k === 'toast' && p.k === 'bad'), 'the refusal toast');
await ev(code, nid, `S.cash=${cash};return 1;`);
assert.equal(checked(await E.act(code, nid, msg('buildPop', { city: 'ams' }))).outcome, 'applied');
const link = checked(await E.act(code, nid, msg('buildLink', { tier: 0 }, { ui: { pending: { a: 'fra', b: 'ams' }, route: '', via: '', cnPrem: false } })));
assert.equal(link.outcome, 'applied');
assert.equal(updOf(link).acts[0].ui.closed, 1, 'the link window closes on the page');
// A draft that names no place is refused before the act runs.
const bad = checked(await E.act(code, nid, msg('buildLink', { tier: 0 }, { ui: { pending: { a: 'fra', b: 'atlantis' } } })));
assert.deepEqual([bad.outcome, /pending/.test(bad.why)], ['rejected', true]);
for (let d = 1; d <= 6; d++) { const D = await day(code, d, [nid]); assert.equal(D.nets[nid].day, d); }
const P1 = checked(await E.pull(code, nid, {}));
const u = updOf(P1);
assert.deepEqual([u.from, u.day, u.s.day], [bad.v, 6, 6], 'the days come after the last action\'s update');
assert.ok(u.r && u.r.tTop8, 'a new R after days, slim');
assert.equal(checked(await E.pull(code, nid, {})).upd, undefined, 'nothing new, no version');
// A what-if: the window it opened, the network as it was.
const lid = await ev(code, nid, 'return S.links[0].id');
const s0 = await ev(code, nid, 'return JSON.stringify(S)');
const K = checked(await E.ask(code, nid, msg('linkCheck', { id: lid }, { ctx: { w: 390, h: 844, coarse: true } })));
assert.match(K.modal.h, /redundancy|backhoe/i);
assert.equal(K.modal.c, 'link-check');
assert.equal(await ev(code, nid, 'return JSON.stringify(S)'), s0);
// Views: the selected link's flows and a city's PNI flows, per view.
const V = checked(await E.pull(code, nid, { views: [{ link: lid }, { peer: 'fra' }] }));
assert.deepEqual(Object.keys(V.subs).sort(), ['link:' + lid, 'peer:fra']);
assert.ok(Object.keys(V.subs['link:' + lid].ef).length <= 1, 'at most the link\'s own flow record');
const SB = checked(await E.sub(code, nid, { views: [{ link: lid }] }));
assert.deepEqual(Object.keys(SB.subs), ['link:' + lid]);
assert.equal(await E.prefs(code, nid, { prefs: { warnUnhappy: false } }), undefined);
assert.equal(await ev(code, nid, 'return pref("warnUnhappy")'), false);
const SV = checked(await E.save(code, nid));
assert.deepEqual([SV.day, SV.lost, typeof SV.rt.load], [6, false, 'object']);
const C = checked(await E.card(code, nid));
assert.deepEqual([C.card.day, C.card.asn, C.card.pops.sort()], [6, MP.asn, ['ams', 'fra']]);
assert.deepEqual(E.stats().realms >= 1, true);
checked(await E.unload(code, nid));
await assert.rejects(E.act(code, nid, msg('launchBB', { city: 'ams' })), (e) => e.code === 'NO_REALM');
});
test('the capture table: every kind of effect comes out as an fx in its shape, at most 60 an update', async () => {
const code = 'CAPTVR', nid = 'capt0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.pull(code, nid, { snap: true }));
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
await ev(code, nid, `UI.speed=1;toast('<b>Hello</b> world','good',[{l:'Open',act:'leftTab',args:{t:'noc'}}]);sfx('coin');haptic(8);floater(1,2,'+$5','#16A866');
track('probe',true);autoPause();showWin();showLose();showBaronWin();mkStart('fra');mkEnd(true,true);
S.stats.loans=1;checkBadges();return 1;`);
const u = updOf(checked(await E.pull(code, nid, {})));
const kinds = new Set(u.fx.map((f) => f[0]));
for (const k of ['toast', 'sfx', 'haptic', 'floater', 'track', 'pause', 'modal', 'mk', 'badge']) assert.ok(kinds.has(k), `fx ${k}`);
for (const f of u.fx) assert.deepEqual(checkFx(f), [], JSON.stringify(f));
assert.deepEqual(u.fx.filter((f) => f[0] === 'modal').map((f) => f[1]), ['win', 'lose', 'baron'], 'windows are fx, not opened');
assert.equal(await ev(code, nid, "return $('modal').hidden"), true);
const t = u.fx.find((f) => f[0] === 'toast' && f[1].h.startsWith('<b>Hello'));
assert.deepEqual([t[1].k, t[1].a[0].act, t[1].tick], ['good', 'leftTab', false]);
assert.equal(await ev(code, nid, "return S.log.some(x=>x.h==='Hello')"), true, 'a toast is still a log line');
// Over 60: floaters go first; windows and badges stay.
await ev(code, nid, "for(let i=0;i<30;i++)floater(i,i,'x','#fff');for(let i=0;i<50;i++)sfx('click');showWin();return 1;");
const u2 = updOf(checked(await E.pull(code, nid, {})));
assert.equal(u2.fx.length, 60);
assert.deepEqual([u2.fx.filter((f) => f[0] === 'floater').length, u2.fx.filter((f) => f[0] === 'sfx').length], [9, 50], 'the 21 too many were the oldest floaters');
assert.deepEqual(u2.fx.filter((f) => f[0] === 'modal').map((f) => f[1]), ['win']);
await E.unload(code);
});
test('a timeout inside opsQuiet: the fresh realm has its toast and after, and the day is played', async (t) => {
// An engine with the server's own time limits: the injected endless loop is stopped by them.
const E = createEngine({ workers: 1, test: TEST });
t.after(() => E.close());
const { day, ev } = on(E);
const code = 'QV13T0', nid = 'quie0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
const ep0 = checked(await E.pull(code, nid, {})).epoch;
// The intern's way of working (opsQuiet mutes toast, after, sfx and floater), stuck for ever in the middle of a day.
await ev(code, nid, '{const f=ddosTick;ddosTick=function(){f();opsQuiet(()=>{for(;;){}});};}return 1;');
const D = await day(code, 1, [nid]);
assert.deepEqual([D.nets[nid].day, D.nets[nid].retried, D.nets[nid].err], [1, true, undefined]);
const P = checked(await E.pull(code, nid, {}));
assert.notEqual(P.epoch, ep0, 'a fresh realm');
assert.deepEqual(await ev(code, nid, "return [/srvFx/.test(String(toast)),/routeIfChanged/.test(String(after)),/srvFx/.test(String(sfx)),/srvFx/.test(String(floater))]"), [true, true, true, true]);
const a = checked(await E.act(code, nid, msg('buildPop', { city: 'ams' })));
assert.equal(a.outcome, 'applied');
assert.ok(updOf(a).fx.some((f) => f[0] === 'toast' || f[0] === 'sfx'), 'its toasts reach the page again');
// And a throw inside opsQuiet (its finally ran) leaves the same realm working, put back in place.
await ev(code, nid, "{const f=ddosTick;let once=true;ddosTick=function(){f();if(once){once=false;opsQuiet(()=>{throw new Error('inside')});}};}return 1;");
const D2 = await day(code, 2, [nid]);
assert.deepEqual([D2.nets[nid].day, D2.nets[nid].retried], [2, true]);
assert.equal(checked(await E.pull(code, nid, {})).epoch, P.epoch);
assert.equal(await ev(code, nid, 'return /srvFx/.test(String(toast))'), true);
await E.unload(code);
});
test('a throw in an action puts the network back in place; with an attack on, R\'s attacks point into the restored S', async () => {
const code = 'THR0WN', nid = 'thrw0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const ep = checked(await E.pull(code, nid, { snap: true })).epoch;
assert.ok(await ev(code, nid, 'const a=ddosAttack(true);a.until=S.day+5;return R.ddos.filter(m=>m.attack).length'), 'R holds the attack');
const s0 = await ev(code, nid, 'return JSON.stringify(S)');
await ev(code, nid, "{const f=ACT.buildPop;ACT.buildPop=a=>{f(a);throw new Error('after the change');};}return 1;");
const r = checked(await E.act(code, nid, msg('buildPop', { city: 'dus' })));
assert.deepEqual([r.outcome, /after the change/.test(r.why), r.epoch], ['error', true, ep]);
assert.equal(await ev(code, nid, 'return JSON.stringify(S)'), s0, 'S as it was');
assert.deepEqual(updOf(r).acts[0].ui, {}, 'the page is told, nothing else');
assert.equal(await ev(code, nid, 'return R.ddos.every(m=>!m.attack||m.attack===ddosFind(m.attack.id))&&R.ddos.some(m=>m.attack)'), true);
await E.unload(code);
});
test('an ask leaves S (the same object), R, the dice and uidN as they were, also during an attack', async () => {
const code = 'ASK3D0', nid = 'askd0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
await ev(code, nid, "const a=ddosAttack(true);a.until=S.day+5;S.te={on:true,day:S.day,script:''};compute();return 1;");
checked(await E.pull(code, nid, { snap: true })); checked(await E.pull(code, nid, {}));
const before = "window.__S0=S;window.__R0=R;window.__rng=S.rng;window.__u=uidN;window.__j=JSON.stringify(S);return 1;";
const same = 'return [S===__S0,R===__R0,S.rng===__rng,uidN===__u,JSON.stringify(S)===__j,R.ddos.some(m=>m.attack)&&R.ddos.every(m=>!m.attack||m.attack===ddosFind(m.attack.id))]';
const lid = await ev(code, nid, 'return S.links.find(l=>!linkDown(l)).id');
const script = await ev(code, nid, 'return TE_EXAMPLE');
for (const [act, args] of [['teSlop', {}], ['teCheck', { script }], ['linkCheck', { id: lid }], ['teSlop', {}]]) {
await ev(code, nid, before);
const r = checked(await E.ask(code, nid, msg(act, args)));
assert.ok(r.modal && r.modal.h.length > 20, `${act} answers with its window`);
if (act !== 'linkCheck') assert.equal(typeof r.ui.teDraft, 'string', `${act}: the draft`);
if (act === 'teSlop') assert.equal(r.ui.slop, r.ui.teDraft, 'the AI\'s script is the draft');
assert.deepEqual(await ev(code, nid, same), [true, true, true, true, true, true], act);
}
assert.equal(checked(await E.pull(code, nid, {})).upd, undefined, 'and nothing to send');
await E.unload(code);
});
test('ui.sel is reported only when the act changed it', async () => {
const code = 'SE1ECT', nid = 'selc0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const lid = await ev(code, nid, "return S.links.find(l=>l.kind==='wave').id");
const rm = checked(await E.act(code, nid, msg('rmLink', { id: lid }, { confirmed: true, ctx: { sel: { type: 'link', id: lid }, tab: 'cust', left: 'goals', modal: false } })));
assert.equal(rm.outcome, 'applied');
assert.equal(updOf(rm).acts[0].ui.sel, null, 'the selected link is gone: the selection with it');
const net = await ev(code, nid, "return NETS.filter(n=>sellsAt(n,'fra')&&!S.transit.some(t=>t.city==='fra'&&t.net===n.id))[0].id");
const bt = checked(await E.act(code, nid, msg('buyTransit', { city: 'fra', net, tier: 1 }, { ctx: { sel: { type: 'city', id: 'fra' }, tab: 'up', left: 'goals', modal: false } })));
assert.equal(bt.outcome, 'applied');
assert.equal('sel' in updOf(bt).acts[0].ui, false, 'a city still selected: nothing to say');
// A selection that names nothing is no selection.
const x = checked(await E.act(code, nid, msg('buildPop', { city: 'dus' }, { ctx: { sel: { type: 'link', id: 'nope' }, tab: 'cust', left: 'goals', modal: false } })));
assert.equal(x.outcome, 'applied');
// A busy link's view: its flow record, and the descriptions of the ways in it names.
const busy = await ev(code, nid, 'return S.links.find(l=>(R.load[l.id]||0)>1&&R.ef[edgeKey(l)]&&Object.keys(R.ef[edgeKey(l)].eg||{}).length).id');
const V = checked(await E.sub(code, nid, { views: [{ link: busy }, { peer: 'fra' }] }));
const rec = V.subs['link:' + busy];
assert.equal(Object.keys(rec.ef).length, 1);
assert.ok(Object.keys(rec.egd).length > 0, 'with its ways in');
assert.ok(Object.keys(V.subs['peer:fra'].pf.fra).length > 0, 'and Frankfurt\'s PNI flows');
await E.unload(code);
});
test('a begin sent during a session\'s day waits for its dayDone; actions of another session do not', async () => {
const code = 'M1DDAY', a = 'midd0001', b = 'midd0002', other = '0TH3R5', o = 'othr0001';
checked((await E.load(code, [{ nid: a, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
checked((await E.load(other, [begin(o)]))[0]);
const order = [];
const d = E.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [a] }).then((r) => { order.push('day'); return checked(r); });
const l = E.load(code, [begin(b)]).then((r) => { order.push('load'); return r; });
const D = await d, L = await l;
assert.deepEqual(order, ['day', 'load']);
assert.deepEqual(Object.keys(D.nets), [a], 'the day\'s networks were fixed when it started');
checked(L[0]);
assert.equal(L[0].day, 0);
await E.unload(code); await E.unload(other);
});
test('an unwatched network stays bounded: at most 200 fx, badges and windows kept (at most 32), a snapshot keeps them', async () => {
const code = 'VNWTCH', nid = 'unwt0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.pull(code, nid, { snap: true }));
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
for (let d = 1; d <= 60; d++) await day(code, d, [nid]);
await ev(code, nid, "for(let i=0;i<500;i++)toast('note '+i);for(let i=0;i<40;i++)srvFx(['badge',{id:'b'+i,v:'oncall'}]);showLose();for(let i=0;i<300;i++)sfx('click');return 1;");
const [n, keep, last] = await ev(code, nid, "return [SIMR.fx.length,SIMR.fx.filter(f=>f[0]==='badge'||f[0]==='modal').length,SIMR.fx.filter(f=>f[0]==='modal').length]");
assert.ok(n <= 200, `${n} fx held`);
assert.equal(keep, 32);
assert.equal(last, 1, 'the newest window is kept');
const P = checked(await E.pull(code, nid, { snap: true }));
const snap = JSON.parse(P.snap);
assert.equal(snap.keep.length, 32);
assert.deepEqual(snap.keep.at(-1), ['modal', 'lose']);
assert.ok(JSON.parse(P.upd).fx.length <= 60);
assert.deepEqual(checkEvent(JSON.parse(snapWith(P.snap, HOST))), []);
await E.unload(code);
});
test('a loaded network that played unwatched: its first snapshot keeps the badges and windows, and no stale fx follow', async (t) => {
const code = 'VNSEEN', nid = 'unsn0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
for (let d = 1; d <= 8; d++) await day(code, d, [nid]);
// The badges it earned on those days stay too (the big fixture predates the traffic badges: it earns some at once).
const won = await ev(code, nid, "return SIMR.fx.filter(f=>f[0]==='badge').map(f=>f[1].id)");
t.diagnostic(`badges earned unwatched: ${won.join(', ') || 'none'}`);
await ev(code, nid, "for(let i=0;i<300;i++)toast('old news '+i);srvFx(['badge',{id:'debt',v:'oncall'}]);showWin();return 1;");
const P = checked(await E.pull(code, nid, { snap: true }));
assert.deepEqual(JSON.parse(P.snap).keep.map((f) => (f[0] === 'badge' ? f[1].id : f[0] + ':' + f[1])), [...won, 'debt', 'modal:win']);
assert.equal(JSON.parse(P.snap).v, P.v, 'the snapshot is at the version after the update to the streams there were');
assert.equal(checked(await E.pull(code, nid, {})).upd, undefined, 'nothing stale comes after the snapshot');
await E.unload(code);
});
test('alone, an auto-pause stops the realm\'s clock as the page\'s does: a second one that day finds it paused', async () => {
const code = 'PAVSE2', nid = 'paus0001';
checked((await E.load(code, [begin(nid)]))[0]);
assert.deepEqual(await ev(code, nid, 'SIMR.alone=true;SIMR.last=4;UI.speed=4;const a=autoPause(),b=autoPause();return [a,b,UI.speed,UI.resumeSpeed]'), [true, false, 0, 4]);
assert.deepEqual(await ev(code, nid, 'SIMR.alone=false;UI.speed=4;return [autoPause(),autoPause(),UI.speed]'), [false, false, 4], 'with others the world goes on');
const D = await day(code, 1, [nid], { alone: [nid], speed: 2, last: 2 });
assert.equal(D.nets[nid].day, 1);
assert.equal(await ev(code, nid, 'return UI.speed'), 2, 'the next day runs at the session\'s speed');
await E.unload(code);
});
test('a network whose save does not load is broken; the others of the session load', async () => {
const code = 'BR0K3N', ok = 'okok0001', bad = 'badd0002';
const L = await E.load(code, [{ nid: ok, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'de', prefs: {} }, { nid: bad, env: { s: '{"v":1,"pops":', uidN: 1 }, lang: 'en', prefs: {} }]);
L.forEach(checked);
assert.deepEqual([L[0].err, typeof L[1].err], [undefined, 'string']);
assert.deepEqual(Object.keys(L[1]).sort(), ['err', 'nid', 't']);
// The network's language is the realm's: the log speaks German.
checked(await E.act(code, ok, msg('buildPop', { city: 'dus' })));
assert.match(await ev(code, ok, 'return LANG+":"+S.log[0].t'), /^de:/);
await assert.rejects(E.act(code, bad, msg('buildPop', { city: 'dus' })), (e) => e.code === 'NO_REALM');
await E.unload(code);
});
test('a polluted prototype stays in its own realm', async () => {
const code = 'P0WWVT', a = 'poll0001', b = 'poll0002';
(await E.load(code, [begin(a), begin(b)])).forEach(checked);
assert.equal(await ev(code, a, 'Object.prototype.polluted=1;Array.prototype.evil=()=>1;return ({}).polluted'), 1);
assert.deepEqual(await ev(code, b, 'return [({}).polluted===undefined,[].evil===undefined]'), [true, true]);
assert.equal(({}).polluted, undefined, 'nor the host');
const D = await day(code, 1, [a, b]);
assert.deepEqual([D.nets[a].day, D.nets[b].day], [1, 1]);
await E.unload(code);
});
test('a worker that exits rejects every call pending on it; the engine goes on with a new one', async () => {
const W = createEngine({ workers: 1, test: TEST, timeouts: ROOMY });
try {
const code = 'EX1T3D', nid = 'exit0001';
checked((await W.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const calls = [W.day(code, { d: 1, nets: [nid] }), W.act(code, nid, msg('buildPop', { city: 'dus' })), W.pull(code, nid, { snap: true }), W.save(code, nid)];
W.kill(0);
for (const p of calls) await assert.rejects(p, (e) => e.code === 'EXIT' && /worker exited/.test(e.message));
assert.deepEqual(W.stats(), { workers: 1, realms: 0, sessions: 0 }, 'its sessions are gone; a new worker took its place');
await assert.rejects(W.act(code, nid, msg('buildPop', { city: 'dus' })), (e) => e.code === 'NO_REALM');
// The host loads the session again (4.7).
checked((await W.load(code, [begin(nid)]))[0]);
assert.equal(W.stats().realms, 1);
} finally { await W.close(); }
});