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

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

626 lines
43 KiB
JavaScript

// 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; realms do not share their intrinsics; every call is answered, whatever a load holds; and a session whose load
// takes its worker down gets a worker of its own, then is given up, while the others keep their places.
// Review fixes: an arg that names a built-in is refused, and a realm whose built-ins changed is replaced; a mark that
// runs out of time undoes nothing; a fresh realm takes over the fx waiting for a page; a network whose realm cannot be
// built again is dropped and the host told; a day with bad lists is refused, never the worker's end; an exit blames the
// session that was running; a worker that cannot start backs off, then SIM_DOWN; the game is read once (a src/ that
// does not compile fails at start, a respawned worker runs the same game); a damaged route memory still loads, a save
// that is no server network does not; and the fake engine answers the same edge calls with the same codes.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
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 wait = (ms) => new Promise((ok) => setTimeout(ok, ms));
// A call's answer within ms, or a failure that says it never came (a hung call would hang the test instead).
const within = (p, ms = 3000) => { let t; return Promise.race([p, new Promise((ok, no) => { t = setTimeout(() => no(new Error(`no answer within ${ms} ms`)), ms); })]).finally(() => clearTimeout(t)); };
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]);
assert.ok(a1.ms > 0 && G.ms >= 0, 'the worker time of a call, for the rate limit');
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);window.__hot=UI.hotMap;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)),UI.hotMap===__hot]';
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, 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', zz = 'zzzz0003';
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: {} }, { ...begin(zz), lang: 'zz' }]);
L.forEach(checked);
assert.deepEqual([L[0].err, typeof L[1].err, L[2].err], [undefined, 'string', undefined]);
assert.deepEqual(Object.keys(L[1]).sort(), ['err', 'nid', 't']);
assert.equal(await ev(code, zz, 'return LANG'), 'en', 'a language without a dictionary here plays in English');
// 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 load call with a malformed network changes nothing, one without a save is broken, and every call still answers', async () => {
const code = 'MA1F0R', a = 'mala0001', b = 'malb0002';
const [A] = await E.load(code, [begin(a)]);
checked(A);
const env = { s: A.saved.txt, uidN: A.saved.uidN, rt: A.saved.rt };
// A network without a nid, or one twice: the call is refused whole, and a keeps the realm it had.
await assert.rejects(within(E.load(code, [{ nid: a, env, lang: 'en', prefs: {} }, { env, lang: 'en', prefs: {} }])), (e) => e.code === 'ERR');
assert.equal(checked(await within(E.pull(code, a, {}))).epoch, A.epoch, 'a as it was');
await assert.rejects(within(E.load(code, [begin(b), begin(b)])), (e) => e.code === 'ERR' && /twice/.test(e.message));
assert.equal(checked(await within(E.act(code, a, msg('launchBB', { city: 'ams' })))).epoch, A.epoch);
// a again with b, whose checkpoint the host could not read: b is broken, a loads (a new epoch).
const L = await within(E.load(code, [{ nid: a, env, lang: 'en', prefs: {} }, { nid: b, env: null, lang: 'en', prefs: {} }]));
L.forEach(checked);
assert.deepEqual([L[0].err, L[1].err], [undefined, 'no save to load']);
assert.notEqual(L[0].epoch, A.epoch);
// Every call of the session answers at once: a plays, b has no realm, unloads and loads go through.
assert.equal(checked(await within(E.act(code, a, msg('launchBB', { city: 'fra' })))).outcome, 'applied');
assert.equal(checked(await within(E.day(code, { d: 1, nets: [a, b] }))).nets[a].day, 1);
await assert.rejects(within(E.pull(code, b, {})), (e) => e.code === 'NO_REALM');
checked(await within(E.unload(code, a)));
checked((await within(E.load(code, [begin(a)])))[0]);
checked(await within(E.unload(code)));
// Nothing is left waiting, so the workers are idle (a job that can never run once kept one at 100% of a core).
await wait(100);
const c0 = process.cpuUsage();
await wait(1000);
const c = process.cpuUsage(c0), ms = (c.user + c.system) / 1000;
assert.ok(ms < 400, `${ms.toFixed(0)} ms of CPU over 1 s of quiet`);
});
test('an unload and a load sent back to back (a language change) keep the session on its worker', async () => {
const code = 'GERM4N', nid = 'lang0001';
checked((await E.load(code, [begin(nid)]))[0]);
const w = E.workerOf(code);
const u = E.unload(code), l = E.load(code, [{ ...begin(nid), lang: 'de' }]);
checked(await within(u));
checked((await within(l))[0]);
assert.equal(E.workerOf(code), w);
assert.equal(checked(await within(E.pull(code, nid, {}))).nid, nid, 'the network answers where it is');
checked((await E.load(code, [begin('lang0002')]))[0]);
assert.equal(E.workerOf(code), w, 'and the session\'s next network goes there too');
checked(await within(E.pull(code, nid, {})));
await E.unload(code);
});
test('a session whose load takes its worker down: twice, a worker of its own; once more, given up; the others keep their places', async () => {
const W = createEngine({ workers: 2, test: TEST, timeouts: ROOMY });
try {
const code = 'P01S0N', nid = 'pois0001', by = { BYST01: 'byst0001', BYST02: 'byst0002' };
for (const [c, n] of Object.entries(by)) checked((await W.load(c, [begin(n)]))[0]);
assert.deepEqual([W.workerOf('BYST01'), W.workerOf('BYST02')], [0, 1]);
// Its load crashes the worker (as a save that overflows the heap would): the worker it shares with BYST01.
const lost = [];
for (let i = 0; i < 2; i++) {
const p = W.load(code, [begin(nid)]);
assert.deepEqual([W.workerOf(code), W.dedicated(code)], [0, false], `attempt ${i + 1}: in the pool`);
W.killOf(code);
await assert.rejects(p, (e) => e.code === 'EXIT');
for (const [c, n] of Object.entries(by)) {
if (!(await W.pull(c, n, {}).then(() => false, (e) => e.code === 'NO_REALM'))) continue;
lost.push(c);
checked((await W.load(c, [begin(n)]))[0]);
assert.equal(W.dedicated(c), false, `${c} is not blamed: it goes back to the pool`);
}
}
assert.deepEqual(lost, ['BYST01', 'BYST01'], 'the bystander on that worker lost its realm each time, the other never');
// Twice within the hour: a worker of its own. An unload and a load back to back stay there, and answer.
checked((await W.load(code, [begin(nid)]))[0]);
assert.deepEqual([W.dedicated(code), W.stats().workers], [true, 3]);
const u = W.unload(code), l = W.load(code, [begin(nid)]);
checked(await within(u));
checked((await within(l))[0]);
checked(await within(W.pull(code, nid, {})));
assert.equal(W.dedicated(code), true);
// Once more, on its own worker: given up until a restart; its worker is not replaced, and the others play on.
const p = W.load(code, [begin('pois0002')]);
W.killOf(code);
await assert.rejects(p, (e) => e.code === 'EXIT');
await assert.rejects(W.load(code, [begin(nid)]), (e) => e.code === 'GAVE_UP');
for (const [c, n] of Object.entries(by)) checked(await within(W.pull(c, n, {})));
assert.deepEqual([W.stats().workers, W.dedicated('BYST01')], [2, false]);
} finally { await W.close(); }
});
test('a polluted prototype stays in its own realm, and that realm is replaced at its next call', async () => {
const code = 'P0WWVT', a = 'poll0001', b = 'poll0002';
(await E.load(code, [begin(a), begin(b)])).forEach(checked);
const ep = checked(await E.pull(code, a, {})).epoch;
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[a].retried, D.nets[b].day, D.nets[b].retried], [1, true, 1, undefined]);
assert.notEqual(checked(await E.pull(code, a, {})).epoch, ep, 'a fresh realm');
assert.deepEqual(await ev(code, a, 'return [({}).polluted===undefined,[].evil===undefined]'), [true, true]);
await E.unload(code);
});
test('an arg that names a built-in is refused; an act that changes the built-ins all the same leaves a fresh realm and the network as before', async () => {
const code = 'PR0T0S', nid = 'prot0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
const ep = checked(await E.pull(code, nid, {})).epoch;
// The envelope refuses it (tests/mp-sim-contract.test.js); a body that got past it, the realm refuses too.
const r0 = checked(await E.act(code, nid, { ...msg('launchBB', { city: 'ams' }), args: { city: '__proto__' } }));
assert.deepEqual([r0.outcome, r0.why], ['rejected', 'an arg names a built-in']);
assert.equal(await ev(code, nid, 'for(const k in {})return k;return null;'), null);
// An act that writes through a prototype all the same (by hand here): the reply says so, the realm that saw it is
// never used again, and the network is as it was before the act.
const s0 = await ev(code, nid, 'return JSON.stringify(S)');
await ev(code, nid, '{const f=ACT.buildPop;ACT.buildPop=a=>{f(a);Object.prototype.bb={d:null};};}return 1;');
const r1 = checked(await E.act(code, nid, msg('buildPop', { city: 'ams' })));
assert.deepEqual([r1.t, r1.what, /built-ins of the realm changed: Object\.prototype\.bb/.test(r1.msg)], ['err', 'throw', true]);
const P = checked(await E.pull(code, nid, { snap: true }));
assert.notEqual(P.epoch, ep, 'a fresh realm');
assert.equal(await ev(code, nid, 'return JSON.stringify(S)'), s0, 'the act undone');
assert.equal(await ev(code, nid, "for(const k in {})return k;return ACT.buildPop.toString().includes('prototype')"), false, 'clean, with the game\'s own act');
assert.equal(checked(await E.act(code, nid, msg('buildPop', { city: 'ams' }))).outcome, 'applied', 'and it plays on');
// One that also throws (its finally blocks ran: S went back in place, the prototype did not): the same.
await ev(code, nid, "{const f=ACT.buildPop;ACT.buildPop=a=>{f(a);Array.prototype.evil=1;throw new Error('and threw');};}return 1;");
const r2 = checked(await E.act(code, nid, msg('buildPop', { city: 'dus' })));
assert.deepEqual([r2.t, /Array\.prototype\.evil/.test(r2.msg)], ['err', true]);
assert.deepEqual(await ev(code, nid, "for(const k in [])return k;return [!!S.pops.ams,!!S.pops.dus]"), [true, false]);
await E.unload(code);
});
test('a mark that runs out of time changes nothing: no applied action or day is undone, and the reply names the mark', async (t) => {
const W = createEngine({ workers: 1, test: TEST, timeouts: { ...ROOMY, mark: 300 } });
t.after(() => W.close());
const { ev } = on(W);
const code = 'MARKT0', nid = 'mark0001';
checked((await W.load(code, [begin(nid)]))[0]);
assert.equal(checked(await W.act(code, nid, msg('buildPop', { city: 'ams' }))).outcome, 'applied');
checked(await W.day(code, { d: 1, nets: [nid] }));
const ep = checked(await W.pull(code, nid, {})).epoch;
await ev(code, nid, 'srvMark=function(){for(;;){}};return 1;');
const r = checked(await W.act(code, nid, msg('buildPop', { city: 'dus' })));
assert.deepEqual([r.t, r.what, r.msg], ['err', 'timeout', 'marking the network took longer than 300 ms']);
assert.deepEqual(await ev(code, nid, 'return [S.day,!!S.pops.ams,!!S.pops.dus]'), [1, true, false], 'what was applied stays');
assert.notEqual(checked(await W.pull(code, nid, {})).epoch, ep, 'built again from its own save');
// A day whose mark runs out of time: built again from its own save, and the day plays in the fresh realm.
await ev(code, nid, 'srvMark=function(){for(;;){}};return 1;');
const D = checked(await W.day(code, { d: 2, nets: [nid] }));
assert.deepEqual([D.nets[nid].day, D.nets[nid].retried, D.nets[nid].err], [2, true, undefined]);
assert.deepEqual(await ev(code, nid, 'return [S.day,!!S.pops.ams]'), [2, true]);
});
test('a fresh realm after a timeout takes over the fx waiting for a page: badges, windows and toasts', async (t) => {
const W = createEngine({ workers: 1, test: TEST, timeouts: { ...ROOMY, day: 600, act: 400 } });
t.after(() => W.close());
const { ev } = on(W);
const code = 'FXKEEP', nid = 'fxkp0001';
checked((await W.load(code, [begin(nid)]))[0]);
checked(await W.pull(code, nid, { snap: true }));
const ep = checked(await W.pull(code, nid, {})).epoch;
const waiting = (id) => `srvFx(['badge',{id:'${id}',v:'oncall'}]);showWin();toast('still waiting');`;
const kept = (P) => { const k = JSON.parse(P.snap).keep.map((f) => (f[0] === 'badge' ? 'badge:' + f[1].id : f[0] + ':' + f[1])); return k; };
// A day that runs out of time once (the fx were waiting before it), then plays in a fresh realm.
await ev(code, nid, waiting('probe') + '{const f=ddosTick;let once=true;ddosTick=function(){f();if(once){once=false;for(;;){}}};}return 1;');
const D = checked(await W.day(code, { d: 1, nets: [nid] }));
assert.deepEqual([D.nets[nid].day, D.nets[nid].retried], [1, true]);
const P = checked(await W.pull(code, nid, { snap: true }));
assert.notEqual(P.epoch, ep);
assert.ok(kept(P).includes('badge:probe') && kept(P).includes('modal:win'), `kept: ${kept(P)}`);
assert.ok(JSON.parse(P.upd).fx.some(([k, p]) => k === 'toast' && p.h === 'still waiting'), 'and the toast');
// An action that runs out of time: the same, and its own fx are not among them.
await ev(code, nid, waiting('probe2') + "ACT.buildPop=()=>{toast('mine');for(;;){}};return 1;");
const r = checked(await W.act(code, nid, msg('buildPop', { city: 'ams' })));
assert.deepEqual([r.t, r.what], ['err', 'timeout']);
const P2 = checked(await W.pull(code, nid, { snap: true }));
assert.notEqual(P2.epoch, P.epoch);
assert.deepEqual(kept(P2), ['badge:probe2', 'modal:win']);
const fx2 = JSON.parse(P2.upd).fx;
assert.ok(fx2.some(([k, p]) => k === 'toast' && p.h === 'still waiting') && !fx2.some(([k, p]) => k === 'toast' && p.h === 'mine'));
});
test('a network whose realm cannot be built again is dropped: the host is told, its calls answer NO_REALM, the others play on', async (t) => {
const lost = [];
const W = createEngine({ workers: 1, test: TEST, timeouts: { ...ROOMY, act: 400 }, onLost: (c, nids, why) => lost.push([c, nids, why]) });
t.after(() => W.close());
const { ev } = on(W);
const code = 'DR0PPD', a = 'lost0001', b = 'lost0002';
(await W.load(code, [begin(a), begin(b)])).forEach(checked);
// Its marks are no saves that load (as a corrupt state would be), and an act runs for ever inside opsQuiet.
await ev(code, a, "{const m0=srvMark;srvMark=function(i){const r=m0(i);return r.slice(0,r.indexOf('\\n'))+'\\n{\"cash\":';};}ACT.buildPop=()=>opsQuiet(()=>{for(;;){}});return 1;");
const r = checked(await W.act(code, a, msg('buildPop', { city: 'ams' })));
assert.deepEqual([r.t, r.what, /the network was dropped/.test(r.msg)], ['err', 'timeout', true]);
assert.deepEqual(lost.map(([c, nids]) => [c, nids]), [[code, [a]]]);
assert.match(lost[0][2], /rebuilding the realm failed/);
assert.deepEqual([W.has(code, a), W.has(code, b)], [false, true]);
await assert.rejects(W.pull(code, a, {}), (e) => e.code === 'NO_REALM');
await assert.rejects(W.act(code, a, msg('buildPop', { city: 'ams' })), (e) => e.code === 'NO_REALM');
assert.deepEqual(Object.keys(checked(await W.day(code, { d: 1, nets: [a, b] })).nets), [b], 'stopped, not playing; the other plays on');
// The host loads it again from its checkpoint.
checked((await W.load(code, [begin(a)]))[0]);
assert.equal(W.has(code, a), true);
});
test('a day with lists that are not lists is refused whole; the worker and its other sessions go on', async () => {
const code = 'B4DDAY', nid = 'alon0001', other = 'BYSTD1', o = 'byst0009';
checked((await E.load(code, [begin(nid)]))[0]);
checked((await E.load(other, [begin(o)]))[0]);
const w = E.stats().workers;
for (const bad of [{ alone: {} }, { alone: 5 }, { nets: 'x' }]) await assert.rejects(within(E.day(code, { d: 1, nets: [nid], ...bad })), (e) => e.code === 'ERR', JSON.stringify(bad));
assert.equal(checked(await within(E.day(code, { d: 1, nets: [nid], alone: [nid, 7] }))).nets[nid].day, 1);
checked(await within(E.pull(other, o, {})));
assert.deepEqual([E.stats().workers, E.has(other, o)], [w, true]);
await E.unload(code); await E.unload(other);
});
test('an exit counts against the session the worker was running, not one whose load waited behind it; own workers are capped', async (t) => {
const W = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, maxOwn: 1 });
t.after(() => W.close());
// Twice: the hog's call runs for ever while another session's load waits behind it, and the worker dies.
const hog = async (code, nid) => {
for (let i = 0; i < 2; i++) {
checked((await W.load(code, [begin(nid)]))[0]);
const p = W.eval(code, nid, 'for(;;){}', 60000), q = W.load('J01NER', [begin('join0001')]);
for (let k = 0; k < 300 && W.running(0) !== code; k++) await wait(10);
assert.equal(W.running(0), code, 'the worker runs the hog');
W.kill(0);
await assert.rejects(p, (e) => e.code === 'EXIT');
await assert.rejects(q, (e) => e.code === 'EXIT');
}
};
await hog('H0G001', 'hogg0001');
checked((await W.load('H0G001', [begin('hogg0001')]))[0]);
checked((await W.load('J01NER', [begin('join0001')]))[0]);
assert.deepEqual([W.dedicated('H0G001'), W.dedicated('J01NER')], [true, false], 'the hog has a worker of its own, the joiner none');
// Another like it: no third worker (maxOwn 1), given up.
await hog('H0G002', 'hogg0002');
await assert.rejects(W.load('H0G002', [begin('hogg0002')]), (e) => e.code === 'GAVE_UP');
assert.equal(W.stats().workers, 2);
checked(await within(W.pull('J01NER', 'join0001', {}).catch(() => W.load('J01NER', [begin('join0001')]).then((r) => r[0]))));
});
test('a worker that cannot start is not started again at once: after a few tries every call answers SIM_DOWN', async (t) => {
const logs = [];
const W = createEngine({ workers: 1, test: { ...TEST, startFail: true }, startBackoffMs: 10, log: (l, x) => logs.push(String(x)) });
t.after(() => W.close());
await assert.rejects(W.load('D0WN00', [begin('down0001')]), (e) => e.code === 'EXIT' || e.code === 'SIM_DOWN');
for (let k = 0; k < 200 && !logs.some((x) => /server-run play is down/.test(x)); k++) await wait(50);
await assert.rejects(W.load('D0WN00', [begin('down0001')]), (e) => e.code === 'SIM_DOWN');
await assert.rejects(W.pull('D0WN00', 'down0001', {}), (e) => e.code === 'SIM_DOWN');
await assert.rejects(W.day('D0WN00', { d: 1, nets: [] }), (e) => e.code === 'SIM_DOWN');
await wait(300);
assert.deepEqual([logs.filter((x) => /could not start/.test(x)).length, logs.filter((x) => /is down/.test(x)).length], [4, 1], 'five starts, then said once');
});
test('the game is read once: a src/ that does not compile fails at start, and a worker started later runs the same game', async (t) => {
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-sim-src-'));
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
fs.cpSync(path.join(__dirname, '..', 'src'), path.join(tmp, 'src'), { recursive: true });
const W = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, root: tmp });
t.after(() => W.close());
assert.equal(W.simId, E.simId, 'the same src/, the same build id');
checked((await W.load('SAMEG4', [begin('same0001')]))[0]);
// The checkout changes under a running engine (a pull before the restart), and its worker dies.
fs.appendFileSync(path.join(tmp, 'src', 'game', '99-loop.js'), '\n;globalThis.__pulled=1;\n');
W.kill(0);
for (let k = 0; k < 200 && W.stats().realms; k++) await wait(10);
checked((await W.load('SAMEG4', [begin('same0001')]))[0]);
assert.equal((await W.eval('SAMEG4', 'same0001', 'return typeof globalThis.__pulled')).value, 'undefined', 'the game the engine names, not the one on disk');
fs.appendFileSync(path.join(tmp, 'src', 'game', '99-loop.js'), '\n}}}(\n');
assert.throws(() => createEngine({ workers: 1, root: tmp }), /does not compile/);
});
test('a checkpoint whose route memory is damaged still loads; a save that is no server network does not', async () => {
const code = 'RTDAMG', a = 'rtdm0001';
const [L] = await E.load(code, [begin(a)]);
checked(L);
const s = L.saved.txt, net = (nid, env) => ({ nid, env: { uidN: L.saved.uidN, ...env }, lang: 'en', prefs: {} });
const R = await E.load(code, [
net('rtdm0002', { s, rt: { efg: { x: { g: [1, 2], v: [1] } } } }),
net('rtdm0003', { s: JSON.stringify({ ...JSON.parse(s), mp: null }), rt: null }),
net('rtdm0004', { s: JSON.stringify({ ...JSON.parse(s), mode: 'sandbox' }), rt: null }),
]);
R.forEach(checked);
assert.equal(R[0].err, undefined, R[0].err);
assert.match(R[1].err, /not a server network/);
assert.match(R[2].err, /server networks are Normal games/);
assert.equal(checked(await E.day(code, { d: 1, nets: ['rtdm0002'] })).nets.rtdm0002.day, 1);
await E.unload(code);
});
test('the fake engine fails as the engine does: the same edge calls, the same codes', async (t) => {
const { createFakeEngine } = require('./lib/mp-sim-fake-engine');
const lostR = [], lostF = [];
const R = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, onLost: (c, n, w) => lostR.push([c, n, w]) });
const F = createFakeEngine({ onLost: (c, n, w) => lostF.push([c, n, w]) });
t.after(() => R.close());
const code = 'PAR1TY', a = 'pari0001', b = 'pari0002';
const out = (p) => p.then((r) => (Array.isArray(r) ? r.map((x) => x.err || 'ok') : r && r.t === 'dayDone' ? Object.keys(r.nets) : 'ok'), (e) => 'rejected ' + e.code);
const same = async (what, f) => { const x = await out(f(R)), y = await out(f(F)); assert.deepEqual(y, x, what); return x; };
assert.equal(await same('an act with no realm', (X) => X.act(code, a, msg('buildPop', { city: 'ams' }))), 'rejected NO_REALM');
await same('a load of nothing', (X) => X.load(code, []));
await same('a network twice', (X) => X.load(code, [begin(a), begin(a)]));
await same('neither a save nor a begin', (X) => X.load(code, [{ nid: a, env: { day: 5 }, lang: 'en', prefs: {} }]));
await same('a day of a session that is not here', (X) => X.day('N0SVCH', { d: 1, nets: [a] }));
await same('a load', (X) => X.load(code, [begin(a)]));
await same('a day naming a network that is not loaded', (X) => X.day(code, { d: 1, nets: [a, b] }));
await same('nets that is no list', (X) => X.day(code, { d: 2, nets: 'x' }));
assert.deepEqual([R.has(code, a), F.has(code, a)], [true, true]);
// A worker that dies: a session with nothing pending loses its realms all the same; its next call answers NO_REALM.
R.kill(0); F.exit();
for (let k = 0; k < 200 && !lostR.length; k++) await wait(10);
assert.deepEqual(lostR, lostF);
assert.deepEqual(lostR, [[code, [a], 'exit']]);
assert.equal(await same('a call after the worker died', (X) => X.pull(code, a, {})), 'rejected NO_REALM');
await R.close(); await F.close();
await same('a load after close', (X) => X.load(code, [begin(a)]));
assert.equal(await same('a pull after close', (X) => X.pull(code, a, {})), 'rejected CLOSED');
});
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(); }
});