seriesoftubes/tests/mp-sim-contract.test.js
jvanvik 065c922287 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.
2026-11-09 19:30:38 +01:00

296 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The contracts server-run play is built against (the server-sim design, sections 4.2, 5 and 10): the act tables and
// the envelope check (scripts/lib/mp-sim-acts.js), the canned stream (tests/fixtures/mp-sim/) and its shape checker
// (tests/lib/mp-sim-shape.js), the fake engine (tests/lib/mp-sim-fake-engine.js), and the harness's MP page with its
// fake streaming fetch. The engine, the host and the client each test their side against these.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load, fakeFetch, sse, flush } = require('./harness');
const { simId } = require('../scripts/lib/page');
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');
const SIM = simId();
const env = (act, args = {}, more = {}) => ({ rid: 'a1b2c3d4e5', dev: '9f8e7d6c', sim: SIM, act, args, ...more });
test('every ACT is classified once: SEND, ASK, VOTE, LOCAL or PUZZLE; SEND is the agent\'s game commands, adjusted', (t) => {
// The development page of a multiplayer build: every ACT there is, the server-play client's (98-server-play) too.
const { ev, errors, dom } = load({ agent: true, mp: true });
t.after(() => dom.window.close());
const acts = JSON.parse(ev('JSON.stringify(Object.keys(ACT))'));
const lists = { SEND: A.SEND, ASK: A.ASK, VOTE: A.VOTE, LOCAL: A.LOCAL, PUZZLE: A.PUZZLE };
const where = {};
for (const [name, list] of Object.entries(lists)) {
assert.deepEqual([...list].sort(), list, `${name} stays sorted, one per line`);
for (const a of list) { assert.equal(where[a], undefined, `ACT.${a} is in both ${where[a]} and ${name}`); where[a] = name; }
}
for (const a of acts) assert.ok(where[a], `ACT.${a} is not classified: add it to SEND, ASK, VOTE or LOCAL in scripts/lib/mp-sim-acts.js`);
for (const a of Object.keys(where)) assert.ok(acts.includes(a), `${a} is in scripts/lib/mp-sim-acts.js (${where[a]}) but ACT has no such act`);
for (const a of A.PUZZLE) assert.match(a, /^pz[A-Z]/);
// SEND, derived again: never counted by hand.
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, 'SEND = API_CMD − pz* − {teCheck, traceRun, closeModal} + {connCancel, pieRename, tutSkip}');
// The other tables only name sent acts (asks for ASK), and their own args.
for (const a of [...Object.keys(A.CONFIRM), ...Object.keys(A.DRAFTS), ...Object.keys(A.QUOTE)]) assert.ok(A.SEND.includes(a), `${a} is sent`);
for (const a of Object.keys(A.TEXT)) assert.ok(A.SEND.includes(a) || A.ASK.includes(a), `${a} is sent or asked`);
for (const ks of Object.values(A.DRAFTS)) for (const k of ks) assert.ok(A.DRAFT_TYPES[k], `draft ${k} has a type`);
assert.equal(A.armKey('connCancel', { k: 't', id: 'i9' }), 'cc:t:i9');
assert.equal(A.armKey('rmSite', { city: 'fra' }), 'sitefra');
assert.equal(A.armKey('cancelTransit', { id: 'x' }), null, "an 'arg' act arms with ok:1, not a key");
assert.deepEqual(errors, []);
});
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');
const { ev, errors, dom } = load({ seed: 77 });
t.after(() => dom.window.close());
ev(`Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.lvl=Math.max(S.lvl,6);
ACT.opsHire({id:'kevin'});closeModal();ACT.salesHire({id:'eng'});closeModal();S.popStd=bstdPut({...bstd(),rt:2});compute();renderAll();`);
const btns = crawl(ev);
const sent = btns.filter(([a]) => A.SEND.includes(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', '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',
seaterminal:false,seaengineering:false,decom:['fra'],slop:false,pieIns:false,pieLas:false})`)) : null;
const body = env(act, args, { ...(ui ? { ui: Object.fromEntries(A.DRAFTS[act].map((k) => [k, ui[k]])) } : {}), ...(A.CONFIRM[act] ? { confirmed: true } : {}),
ctx: { sel: { type: 'city', id: 'fra' }, tab: 'cust', left: 'noc', modal: false, w: 390, h: 844, coarse: true } });
const r = A.checkEnvelope('act', JSON.parse(JSON.stringify(body)), { sim: SIM });
assert.ok(r.ok, `${act} ${JSON.stringify(args)}: ${r.error}`);
}
assert.deepEqual(errors, []);
});
test('the envelope check refuses what section 10 refuses', () => {
const ok = (kind, b) => A.checkEnvelope(kind, b, { sim: SIM });
assert.equal(ok('act', env('buyTransit', { city: 'fra', net: 'cog', tier: 1 })).ok, true);
const no = (kind, b, why) => { const r = ok(kind, b); assert.equal(r.ok, false, `${why}: refused`); assert.equal(r.code, 400, why); };
const proto = JSON.parse('{"__proto__":{"polluted":1}}');
for (const [b, why] of [
[null, 'null'], [[], 'an array'], ['x', 'a string'], [{ ...env('buildPop', { city: 'fra' }), rid: 'AB' }, 'a bad rid'], [{ ...env('buildPop', { city: 'fra' }), dev: 'x'.repeat(17) }, 'a bad dev'],
[{ ...env('buildPop', { city: 'fra' }), sim: 'nothex' }, 'a bad sim'], [{ ...env('buildPop', { city: 'fra' }), extra: 1 }, 'an unknown field'],
[env('start', {}), 'a session act'], [env('pzStart', {}), 'a puzzle act'], [env('speed', { v: 8 }), 'a vote'], [env('teOpt', {}), 'a local act'],
[env('constructor', {}), 'constructor'], [env('__proto__', {}), '__proto__'], [env('toString', {}), 'toString'],
[env('buildPop', { city: { id: 'fra' } }), 'a nested object'], [env('buildPop', proto), '__proto__ in args'], [env('buildPop', { constructor: 1 }), 'constructor in args'],
[env('buildPop', Object.fromEntries(Array.from({ length: 13 }, (x, i) => ['k' + i, i]))), '13 args'], [env('buildPop', { city: 'x'.repeat(65) }), 'a 65-character string'],
[env('buildPop', { city: Array(65).fill('fra') }), 'an array of 65'], [env('buildPop', { city: [{}] }), 'an object in an array'], [env('buildPop', { city: NaN }), 'NaN'],
[env('buildPop', { 'bad-key': 1 }), 'a bad arg name'], [env('buildPop', [1, 2]), 'args as an array'],
[env('buildLink', { tier: 1 }, { ui: { pending: 'fra-ams' } }), 'a draft of the wrong type'], [env('buildLink', { tier: 1 }, { ui: { decom: ['fra'] } }), 'a draft the act does not read'],
[env('buildLink', { tier: 1 }, { ui: { pending: { a: 'fra', b: 'ams', c: 'x' } } }), 'a pair with more'], [env('buildLink', { tier: 1 }, { ui: { pending: { a: 'fra', b: 'fra' } } }), 'a link from a city to itself'], [env('buildPop', { city: 'fra' }, { ui: { pending: { a: 'fra', b: 'ams' } } }), 'drafts on an act without'],
[env('decomGo', {}, { ui: { decom: Array(201).fill('fra') } }), '201 cities'],
[env('buildPop', { city: 'fra' }, { confirmed: true }), 'confirmed on a one-click act'], [env('rmLink', { id: 'l1' }, { confirmed: false }), 'confirmed false'],
[env('buildPop', { city: 'fra' }, { ctx: { sel: { type: 'ix', id: 'fra' } } }), 'a selection of another type'], [env('buildPop', { city: 'fra' }, { ctx: { tab: 'Cust' } }), 'a tab with capitals'],
[env('buildPop', { city: 'fra' }, { ctx: { w: 0 } }), 'a viewport of nothing'], [env('buildPop', { city: 'fra' }, { ctx: { h: Infinity } }), 'an endless viewport'], [env('buildPop', { city: 'fra' }, { ctx: { w: '390' } }), 'a viewport as text'],
[env('buildPop', { city: 'fra' }, { ctx: { evil: 1 } }), 'an unknown ctx field'], [env('buildPop', { city: 'fra' }, { ctx: [] }), 'ctx as an array'],
[env('pniAll', { net: null, tier: 1 }), 'a quote act without its quote'], [env('utilityCaches', { city: 'fra', quote: 5 }), 'a key quote as a number'],
[env('bstdApply', { q: 5 }), 'the build standard without its plan'], [env('bstdApply', { quote: 5 }), 'a plan key as a number'],
[env('teDeploy', { script: 'x'.repeat(4001) }), 'a script over 4000'], [env('metricSet', { id: 'l1', v: '1'.repeat(17) }), 'a metric over 16'],
]) no('act', b, why);
assert.equal(ok('act', env('teDeploy', { script: 'x'.repeat(4000) })).ok, true, 'a long script within its cap');
// A viewport outside what the layout tells apart is clamped, not refused: a 5120-px monitor, a desktop zoomed out.
for (const [w, h, cw, ch] of [[5120, 1440, A.VIEW_MAX, 1440], [100, 50, A.VIEW_MIN, A.VIEW_MIN], [390, 844, 390, 844]]) {
const b = env('buildPop', { city: 'fra' }, { ctx: { w, h } });
assert.equal(ok('act', b).ok, true, `${w}×${h}`);
assert.deepEqual([b.ctx.w, b.ctx.h], [cw, ch], `${w}×${h} clamped into ${A.VIEW_MIN}–${A.VIEW_MAX}`);
}
assert.equal(ok('act', env('rmLink', { id: 'l1' }, { confirmed: true })).ok, true);
const old = ok('act', { ...env('buildPop', { city: 'fra' }), sim: 'ffffffffffff' });
assert.deepEqual([old.ok, old.code, old.old], [false, 409, true], 'a page of another build is told it is old');
// Asks: only the three what-ifs, without drafts or confirmations.
assert.equal(ok('ask', env('teCheck', { script: 'prefer cog at fra' })).ok, true);
assert.equal(ok('ask', env('linkCheck', { id: 'l1' })).ok, true);
no('ask', env('buildPop', { city: 'fra' }), 'a sent act as an ask');
no('ask', env('linkCheck', { id: 'l1' }, { confirmed: true }), 'an ask confirmed');
// Votes, presence, settings.
for (const s of [0, 0.5, 1, 2, 4, 8, null]) assert.equal(ok('vote', { speed: s, sim: SIM }).ok, true, `vote ${s}`);
no('vote', { speed: 3, sim: SIM }, 'a speed that is none'); no('vote', { speed: 1, sim: SIM, x: 1 }, 'a vote with more');
assert.equal(ok('vote', { speed: 1, sim: 'ffffffffffff' }).code, 409);
assert.equal(ok('here', { dev: '9f8e7d6c', hidden: false, hold: true, view: { link: 'l1' } }).ok, true);
no('here', { dev: '9f8e7d6c', view: { link: { x: 1 } } }, 'a view with an object'); no('here', { dev: '9f8e7d6c', hidden: 'yes' }, 'a flag that is no boolean');
assert.equal(ok('prefs', { prefs: { pauseFurious: true }, lang: 'de' }).ok, true);
no('prefs', { prefs: { muted: true } }, 'a preference that is not the network\'s'); no('prefs', { lang: '../x' }, 'a language that is no code');
no('nope', {}, 'an unknown kind');
});
test('the canned stream: every fixture passes the shape checker, and the shape checker catches broken ones', () => {
for (const n of FIXTURES) assert.deepEqual(checkEvent(fixture(n)), [], n);
const upd = fixture('upd-act');
assert.equal(upd.acts.length, 2, 'two actions in one update');
assert.equal(upd.v, upd.from + 1);
assert.equal(fixture('upd-day').from, fixture('snap').v, 'the day follows the snapshot');
assert.equal(upd.from, fixture('upd-day').v, 'the actions follow the day');
assert.ok('off' in fixture('clock'), 'the clock carries each network\'s calendar offset');
const broken = [
[{ ...upd, v: upd.from + 2 }, /from \+ 1/], [{ ...upd, r: { ...upd.r, ef: {} } }, /never carries/], [{ ...upd, fx: [['boom', 1]] }, /unknown effect/],
[{ ...upd, acts: [{ rid: 'x', dev: '9f8e7d6c', ui: {} }] }, /rid/], [{ ...fixture('clock'), speed: 3 }, /speed/], [{ ...fixture('roster'), on: ['NOPE'] }, /on/],
[{ ...fixture('snap'), S: { ...fixture('snap').S, mp: { ...fixture('snap').S.mp, sim: undefined } } }, /server network/], [{ t: 'bye', why: 'tired' }, /why/], [{ t: 'nope' }, /unknown event/],
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/],
];
for (const [e, re] of broken) assert.match(checkEvent(e).join('\n'), re);
assert.deepEqual(checkFx(['floater', [1, 2, 'x', '#fff']]), []);
assert.match(checkFx(['toast', { h: 1 }]).join(), /toast/);
// Over the wire: sse() writes what parseSse() reads.
const text = FIXTURES.map((n, i) => sse(fixture(n).t, fixture(n), i % 2 ? `k3f9.${i}` : undefined)).join(': hb\n\n');
const back = parseSse(text);
assert.deepEqual(back.map((e) => e.data), FIXTURES.map(fixture));
assert.equal(back[1].id, 'k3f9.1');
});
test('the canned state is the game\'s own: migrate() keeps the snapshot and every update applied to it as they are', (t) => {
const { ev, errors, dom } = load();
t.after(() => dom.window.close());
const same = (s) => ev(`(()=>{const a=${lit(JSON.stringify(s))},b=JSON.stringify(migrate(JSON.parse(a)));return a===b?'':b.slice(0,0)+'differs';})()`);
let S = fixture('snap').S;
assert.equal(same(S), '', 'the snapshot');
for (const n of ['upd-day', 'upd-act']) {
const u = fixture(n);
S = { ...S, ...u.s };
for (const k of u.del || []) delete S[k];
assert.equal(same(S), '', `after ${n}`);
}
assert.deepEqual(errors, []);
});
test('the fake engine answers every call in the shapes of section 4.2', async () => {
const e = createFakeEngine(), code = 'K7Q2XD', a = 'abcd1234', b = 'efgh5678';
const all = [];
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false }, lang: 'en', prefs: {} }, { nid: b, env: { day: 40 }, lang: 'de', prefs: {} }]);
assert.equal(L.length, 2); assert.ok(L[0].saved, 'a new network is checkpointed at once');
assert.ok(L[0].epoch && L[1].epoch && L[0].epoch !== L[1].epoch, 'each realm load has its own epoch');
all.push(...L);
const D = await e.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [b, a] });
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.equal(D.nets[b].day, 41);
all.push(D);
const P1 = await e.pull(code, a, {}), P2 = await e.pull(code, a, {});
assert.ok(P1.upd && !P2.upd, 'a pull sends what changed, once'); assert.equal(P2.v, P1.v, 'only a pull with something to send is a version');
const act = await e.act(code, a, env('buildPop', { city: 'par' }));
assert.equal(act.v, P1.v + 1); assert.equal(JSON.parse(act.upd).acts[0].rid, 'a1b2c3d4e5');
assert.deepEqual([P1.epoch, P2.epoch, act.epoch], [L[0].epoch, L[0].epoch, L[0].epoch], 'every versioned reply names the realm\'s epoch');
all.push(P1, P2, act, await e.ask(code, a, env('linkCheck', { id: 'l1' })), await e.pull(code, b, { snap: true, views: [{ link: 'l1' }, { peer: 'fra' }] }),
await e.sub(code, a, { views: [{ link: 'l1' }] }), await e.greet(code, a), await e.save(code, b), await e.card(code, a));
assert.equal(await e.prefs(code, a, { prefs: { pauseFurious: true } }), undefined);
e.lose(code, b);
const D2 = await e.day(code, { d: 2, nets: [a, b] });
assert.equal(D2.nets[b].lost, true);
const D3 = await e.day(code, { d: 3, nets: [a, b] });
assert.equal(D3.nets[b], undefined, 'a lost network has no more days');
assert.equal((await e.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
e.failNext('act', 'timeout');
const tmo = await e.act(code, a, env('buildPop', { city: 'par' }));
assert.deepEqual([tmo.t, tmo.what], ['err', 'timeout']);
// 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.
e.hold('day');
let done = false; const p = e.day(code, { d: 4, nets: [a] }).then(() => { done = true; });
await new Promise((r) => setImmediate(r));
assert.equal(done, false, 'held');
e.release('day'); await p; assert.equal(done, true);
e.hold('save');
const s1 = e.save(code, a), s2 = e.save(code, b);
e.exit();
await assert.rejects(s1, /worker exited/); await assert.rejects(s2, /worker exited/);
assert.equal(e.stats().realms, 0);
e.failNext('load', 'exit');
await assert.rejects(e.load(code, [{ nid: a, env: {}, lang: 'en', prefs: {} }]), /worker exited/);
assert.deepEqual(checkWorker({ t: 'unloaded', code }), []);
assert.ok(e.calls.length > 15);
});
test('the fake engine fails the way the engine does: a network that does not load, a day that fails twice or once', async () => {
const a = 'abcd1234', b = 'efgh5678', c = 'ijkl9012', net = (nid) => ({ nid, env: { day: 5 }, lang: 'en', prefs: {} });
// A save that does not load (4.7): that network is broken, the others load.
const e = createFakeEngine(), code = 'K7Q2XD';
e.breakNext(code, b);
const L = await e.load(code, [net(a), net(b)]);
assert.equal(Array.isArray(L), true);
assert.deepEqual([!!L[0].err, !!L[1].err], [false, true]);
assert.deepEqual(Object.keys(L[1]).sort(), ['err', 'nid', 't'], 'a broken load has no realm: no epoch, day or lost');
e.failNext('load', 'timeout', c);
const L2 = await e.load('Q9W8E7', [net(a), net(c)]);
assert.deepEqual([!!L2[0].err, !!L2[1].err], [false, true], 'a failed load call names the network it failed');
e.failNext('load', 'throw');
const L3 = await e.load('Z2X3C4', [net(a), net(b)]);
assert.deepEqual(L3.map((l) => !!l.err), [true, true], 'without a network, every network of the call');
// Days: one that fails once and passes on the retry, one that fails twice (broken at its pre-day state).
e.flaky(code, a);
const D1 = await e.day(code, { d: 1, nets: [a] });
assert.deepEqual([D1.nets[a].day, D1.nets[a].retried, D1.nets[a].err], [6, true, undefined]);
const E = createFakeEngine();
await E.load(code, [net(a), net(b)]);
E.failNext('day', 'throw', b);
const D2 = await E.day(code, { d: 1, nets: [a, b] });
assert.equal(D2.nets[a].day, 6);
assert.deepEqual([D2.nets[b].day, D2.nets[b].retried, typeof D2.nets[b].err], [5, true, 'string']);
const D3 = await E.day(code, { d: 2, nets: [a, b] });
assert.equal(D3.nets[b], undefined, 'a broken network has no more days');
assert.equal((await E.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
// A day that timed out twice leaves a fresh realm (a new epoch) as well.
const ep = (await E.pull(code, a, {})).epoch;
E.failNext('day', 'timeout');
const D4 = await E.day(code, { d: 3, nets: [a] });
assert.equal(typeof D4.nets[a].err, 'string');
assert.notEqual((await E.pull(code, a, {})).epoch, ep);
for (const m of [...L, ...L2, ...L3, D1, D2, D3, D4]) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
// The checker holds the host to it.
assert.match(checkWorker({ t: 'loaded', nid: a, day: 1, lost: false }).join(), /epoch: missing/);
assert.match(checkWorker({ t: 'pulled', nid: a, v: 1 }).join(), /epoch: missing/);
assert.match(checkWorker({ t: 'loaded', nid: a, err: 'x', saved: { t: 'saved' } }).join(), /nothing saved/);
assert.deepEqual(checkFx(['toast', { h: 'one argument', tick: false }]), [], 'toast(html): k and a may be left out');
});
test('the harness: load({mp:true}) is a stamped MP page, and fakeFetch streams events the page reads through fetch', async (t) => {
const f = fakeFetch([[/^POST \/api\/mp\/sessions\/K7Q2XD\/act$/, (c) => ({ status: 200, json: { rid: c.body.rid, outcome: 'applied', v: 414 } })]]);
const { ev, errors, dom } = load({ mp: true, fetch: f });
t.after(() => dom.window.close());
assert.equal(ev('MP_API'), '/api/mp');
assert.equal(ev('SIM_ID'), SIM);
// A stream, read the way a page reads one.
ev(`window.__got=[];window.__end='';window.__ac=new AbortController();
fetch(MP_API+'/sessions/K7Q2XD/stream?dev=9f8e7d6c&sim='+SIM_ID,{headers:{Authorization:'Bearer abcd1234.x'},signal:__ac.signal}).then(r=>{
if(!r.ok||!/event-stream/.test(r.headers.get('content-type')))return;const rd=r.body.getReader(),dc=new TextDecoder();let buf='';
const go=()=>rd.read().then(({done,value})=>{if(done){__end='done';return;}buf+=dc.decode(value,{stream:true});let i;
while((i=buf.indexOf('\\n\\n'))>=0){const blk=buf.slice(0,i);buf=buf.slice(i+2);const d=blk.split('\\n').filter(l=>l.startsWith('data: ')).map(l=>l.slice(6)).join('\\n');if(d)__got.push(JSON.parse(d).t);}go();},e=>{__end=e.name;});go();});`);
const s = await f.stream(0);
assert.equal(s.call.path, '/sessions/K7Q2XD/stream');
assert.deepEqual(s.call.query, { dev: '9f8e7d6c', sim: SIM });
assert.equal(s.call.headers.authorization, 'Bearer abcd1234.x');
s.send('snap', fixture('snap'), 'k3f9.412').comment().send('upd', fixture('upd-day'), 'k3f9.413');
await flush(5);
assert.deepEqual(JSON.parse(ev('JSON.stringify(__got)')), ['snap', 'upd']);
ev('__ac.abort()');
await flush(5);
assert.equal(s.aborted, true, 'the page aborted it');
assert.equal(ev('__end'), 'AbortError');
// A second stream that the server ends.
ev(`fetch(MP_API+'/sessions/K7Q2XD/stream?dev=9f8e7d6c&sim='+SIM_ID).then(r=>r.body.getReader().read()).then(x=>{window.__d2=x.done;})`);
(await f.stream(1)).close();
await flush(5);
assert.equal(ev('__d2'), true);
// A POST answered by a route; the call is recorded with its parsed body.
ev(`fetch(MP_API+'/sessions/K7Q2XD/act',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({rid:'a1b2c3d4e5'})}).then(r=>r.json()).then(j=>{window.__j=j;})`);
await flush(5);
assert.equal(ev('__j.outcome'), 'applied');
assert.equal(f.calls.at(-1).body.rid, 'a1b2c3d4e5');
ev(`fetch(MP_API+'/sessions/K7Q2XD/vote',{method:'POST',body:'{}'}).then(r=>{window.__st=r.status;})`);
await flush(5);
assert.equal(ev('__st'), 404, 'anything else is not here');
assert.deepEqual(errors, []);
});