// 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.
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 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]);
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('Hello 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('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', 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(); }
});