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