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.
85 lines
5.4 KiB
JavaScript
85 lines
5.4 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) 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 };
|