Merge pull request #313: every routing a day needs runs in the route worker, and a long day lets frames through
Conflicts with main resolved: the intern's chosen router model, optical upgrades and personas are generators like the
other orders, with a rest after each job. The optical upgrade's fiber test is a step the day answers, in the route
worker in play (opsDark(), {dark}), like the sales desk's trial; the renewal desk's reroute is a step too (slRenRun()).
This commit is contained in:
commit
410eb81544
28 changed files with 612 additions and 141 deletions
241
tests/day-steps.test.js
Normal file
241
tests/day-steps.test.js
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
// The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the
|
||||
// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so
|
||||
// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that
|
||||
// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
// The big network with an intern running every order, a failure and an event due soon, and its circuits on scenic
|
||||
// routes, which read yesterday's R.efg. Ids come from Date.now(),
|
||||
// so the clock stands still in every page.
|
||||
const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;
|
||||
S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;
|
||||
S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;
|
||||
S.nextFail=S.day+3;S.nextEvent=S.day+5;for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';compute();__reseed(4242);`;
|
||||
const open = (t, seed) => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
|
||||
// The page, with a stand-in worker: what it posts waits in a queue until pump() hands it to the other page.
|
||||
function played(t) {
|
||||
const page = open(t, 777), wk = open(t, 1);
|
||||
page.ev(SETUP);
|
||||
// No time to spare: every DAY_REST waits for the next "frame", which pump() gives it.
|
||||
page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});');
|
||||
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
|
||||
// Answers what is waiting, one message at a time; returns how many routings it served.
|
||||
let rests = 0, trials = 0;
|
||||
const pump = () => { let n = 0; for (;;) {
|
||||
if (page.ev('__later.length')) { rests++; page.ev('__later.shift()()'); continue; }
|
||||
if (!page.ev('__q.length')) break;
|
||||
if (page.ev('!!__q[0].trial')) trials++;
|
||||
wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out');
|
||||
page.ev('rwDone(__a)'); n++; } return n; };
|
||||
// One message to the worker and its answer back (the trial test steps through a day with it).
|
||||
const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); };
|
||||
return { ...page, pump, pump1, rests: () => rests, trials: () => trials };
|
||||
}
|
||||
// R.egDesc too, key for key and in order.
|
||||
const STATE = "JSON.stringify({S,R:{served:R.served,demand:R.demand,rev:R.revMo,cost:R.costMo,load:R.load,useT:R.useT,usePni:R.usePni,egDesc:R.egDesc}})";
|
||||
// Equal states, or which of their fields differ.
|
||||
const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = JSON.parse(b), d = [];
|
||||
for (const o of ['S', 'R']) for (const k of new Set([...Object.keys(A[o]), ...Object.keys(B[o])])) if (JSON.stringify(A[o][k]) !== JSON.stringify(B[o][k])) d.push(`${o}.${k}`);
|
||||
assert.fail(`${msg}: ${d.join(', ')} differ`); };
|
||||
|
||||
test('a day whose routings the worker answers is the day dayTick() plays', (t) => {
|
||||
const ref = open(t, 777), p = played(t);
|
||||
ref.ev(SETUP);
|
||||
// The page itself never routes, the failure on day 3 (failureRun()) and the sales desk's trials (offerTrial())
|
||||
// included: they are steps like the others, routed by the worker.
|
||||
p.ev('window.__pc=0;window.__tr=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};');
|
||||
let served = 0, extra = 0;
|
||||
for (let i = 0; i < 12; i++) {
|
||||
ref.ev('dayTick()');
|
||||
p.ev('rwDay()');
|
||||
assert.equal(p.ev('!!RW.job'), true, 'the day waits for the worker');
|
||||
const n = p.pump(); served += n; if (n > 1) extra++;
|
||||
assert.equal(p.ev('!!RW.job'), false);
|
||||
same(p.ev(STATE), ref.ev(STATE), `day ${i + 1}`);
|
||||
}
|
||||
// Each day routes once, and some days again after a failure, an event or the intern's jobs: all in the worker.
|
||||
assert.ok(served > 12 && extra > 0, `routings served: ${served}, days with more than one: ${extra}`);
|
||||
assert.ok(ref.ev('S.inc.length') > 0 || ref.ev('S.stats.incidents') > 0, 'a failure happened');
|
||||
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
|
||||
assert.ok(p.trials() > 0, `sales trials the worker ran: ${p.trials()}`);
|
||||
assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes');
|
||||
// A frame through before the intern's shift, after each of the orders on duty (decommissioning aside), and after
|
||||
// each job of an order (a generator's yields).
|
||||
const orders = p.ev('OPS_ORDER.slice(0,-1).filter(k=>S.ops.on[k]).length');
|
||||
assert.ok(orders > 3, `orders on duty: ${orders}`);
|
||||
assert.ok(p.rests() > 12 * (1 + orders), `each day let a frame through before the shift, between its orders and its jobs: ${p.rests()}`);
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
|
||||
test('a half day is never saved, and a worker lost mid-day finishes it on the page', (t) => {
|
||||
const ref = open(t, 777), p = played(t);
|
||||
ref.ev(SETUP);
|
||||
ref.ev('dayTick()');
|
||||
p.ev("window.__saves=0;const s0=save;save=(...a)=>{if(!RW.job)__saves++;return s0(...a);};rwDay()");
|
||||
p.ev('save()');
|
||||
assert.equal(p.ev('UI.saveDue'), true, 'saving waits for the end of the day');
|
||||
p.ev('rwKill()');
|
||||
assert.equal(p.ev('RW.job&&RW.job.rest'), true, 'the day goes on on the page, up to its rest');
|
||||
assert.equal(p.pump(), 0, 'with no worker left');
|
||||
assert.equal(p.ev('!!RW.job'), false, 'the day is over');
|
||||
assert.equal(p.ev('UI.saveDue'), false, 'and saved');
|
||||
same(p.ev(STATE), ref.ev(STATE), 'the day');
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
|
||||
test('an action while the worker routes stands; another network loaded mid-day gets none of that day', (t) => {
|
||||
const p = played(t);
|
||||
p.ev('rwDay()');
|
||||
// The action routes on the page as always: the worker's answer is stale, and the day goes on with the action's R.
|
||||
p.ev('after()');
|
||||
assert.equal(p.pump() >= 1, true);
|
||||
assert.equal(p.ev('!!RW.job'), false);
|
||||
assert.equal(p.ev('S.day'), p.ev('S.hist[S.hist.length-1].d'), 'the day was finished');
|
||||
// A new game while a day is in flight: the old day's steps never touch it.
|
||||
p.ev('rwDay()');
|
||||
const day = p.ev('S.day');
|
||||
p.ev(`window.__old=S;S=migrate(JSON.parse(${JSON.stringify(BIG)}));compute();`);
|
||||
const fresh = p.ev('JSON.stringify(S.hist)');
|
||||
p.pump();
|
||||
assert.equal(p.ev('JSON.stringify(S.hist)'), fresh);
|
||||
assert.equal(p.ev('__old.day'), day);
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
// A sales trial the worker is routing when the player acts (an action routes on the page): its answer was for the game
|
||||
// as it was, so the trial runs again on the page, on the game as it is now.
|
||||
test("a sales trial overtaken by the player's action runs again on the page", (t) => {
|
||||
const p = played(t);
|
||||
p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};");
|
||||
let found = false;
|
||||
for (let d = 0; d < 20 && !found; d++) {
|
||||
p.ev('rwDay()');
|
||||
// Hand the worker one message at a time until a trial is the one waiting.
|
||||
for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {
|
||||
if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; }
|
||||
if (!found && p.ev('__q.length&&!!__q[0].trial')) { found = true; p.ev('compute()'); }
|
||||
p.pump1();
|
||||
}
|
||||
}
|
||||
assert.ok(found, 'the sales desk trialled an offer');
|
||||
assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran on the page');
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
// The rest of what used to route on the page in a day: a DDoS that a failure starts (and Auto-RTBH pulling a plug), an
|
||||
// event that cuts cables or power, and the chaos monkey's snip. Each is a step the worker routes, and the day is still
|
||||
// the day dayTick() plays.
|
||||
test('DDoS, cable and power events and the chaos monkey route in the worker too, and the day stays the same', (t) => {
|
||||
// A visiting monkey does the breaking instead of the failures: failures first, then the monkey.
|
||||
const MONKEY = 'S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day+1,n:0,hurt:0,c:S.home,next:S.day};';
|
||||
const FORCE = `S.ddosAuto={rtbh:true};mkElig=()=>true;S.monkey={on:0,next:S.day+999};S.nextFail=S.day+1;S.nextEvent=S.day+2;
|
||||
failureRun=eval('('+failureRun.toString().replace('if(only)type=only;',"type=S.day%2?'ddos':'cut';")+')');
|
||||
fireEvent=eval('('+fireEvent.toString().replace('const e=pick(opts);',"const e=['redsea','typhoon','baltic','runet'].find(x=>opts.includes(x))||'redsea';")+')');__reseed(99);`;
|
||||
const ref = open(t, 777), p = played(t);
|
||||
ref.ev(SETUP); ref.ev(FORCE); p.ev(FORCE);
|
||||
// The reference routes an event on the spot, the way it always did (no deferred routing).
|
||||
ref.ev('eventRun=function*(){fireEvent();};');
|
||||
ref.ev("window.__dd=0;const da=ddosAttack;ddosAttack=(...a)=>{const r=da(...a);if(r)__dd++;return r;};window.__ev=0;const fe=fireEvent;fireEvent=(...a)=>{__ev++;return fe(...a);};");
|
||||
p.ev('window.__pc=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};');
|
||||
for (let i = 0; i < 12; i++) {
|
||||
if (i === 6) for (const h of [ref, p]) h.ev(MONKEY);
|
||||
for (const h of [ref, p]) h.ev('S.nextFail=S.day+1;S.nextEvent=S.day+1;');
|
||||
ref.ev('dayTick()');
|
||||
p.ev('rwDay()'); p.pump();
|
||||
same(p.ev(STATE), ref.ev(STATE), `day ${i + 1}`);
|
||||
}
|
||||
assert.ok(ref.ev('__dd') > 0, `DDoS attacks started: ${ref.ev('__dd')}`);
|
||||
assert.ok(ref.ev('S.monkey.n') > 0, `the monkey snipped: ${ref.ev('S.monkey.n')}`);
|
||||
assert.ok(ref.ev('__ev') > 2, `events: ${ref.ev('__ev')}`);
|
||||
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
|
||||
// Quiet notifications keep the day's own news to the NOC log (UI.tick, 95-modals/10-toasts.js). Play goes through the
|
||||
// worker's steps, not dayTick(): every step of the day is announced as the day's, on both sides of each routing.
|
||||
test('quiet notifications hold while the worker plays the day', (t) => {
|
||||
const p = played(t);
|
||||
p.ev("window.__tc=[];const t0=toast;toast=function(m,k){__tc.push(!!UI.tick);return t0.apply(this,arguments);};");
|
||||
for (let i = 0; i < 12; i++) { p.ev('rwDay()'); p.pump(); }
|
||||
const calls = JSON.parse(p.ev('JSON.stringify(__tc)'));
|
||||
assert.ok(calls.length > 0, 'the days had news');
|
||||
assert.deepEqual(calls.filter((x) => !x), [], 'every toast of the day came with UI.tick set');
|
||||
assert.equal(p.ev('UI.tick'), false, 'and it is off between days');
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
// What the player does while a step waits for the worker: the step goes on with the game as it is by then.
|
||||
const TICK_ERR = "window.__te=[];tickErr=e=>__te.push(String(e&&e.stack||e));";
|
||||
|
||||
test('a customer dropped while a sales trial routes: the trial runs again on the customers left', (t) => {
|
||||
const p = played(t);
|
||||
p.ev(TICK_ERR);
|
||||
p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};");
|
||||
let found = false;
|
||||
for (let d = 0; d < 20 && !found; d++) {
|
||||
p.ev('rwDay()');
|
||||
for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {
|
||||
if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; }
|
||||
// A trial the offer passes, the last customer among the happy ones: that customer goes, and the trial's list of
|
||||
// who was happy (indices in S.biz) now points one past the end.
|
||||
if (!found && p.ev('__q.length&&!!__q[0].trial&&!!__q[0].trial.hx&&__q[0].trial.hx.includes(S.biz.length-1)&&!!offerTrial(__q[0].trial.b,__q[0].trial.hx)')) {
|
||||
found = true; p.ev('__ot=0;const b=S.biz[S.biz.length-1];UI.confirm=b.id;ACT.dropBiz({id:b.id});');
|
||||
}
|
||||
p.pump1();
|
||||
}
|
||||
}
|
||||
assert.ok(found, 'the desk trialled an offer');
|
||||
assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran again on the page');
|
||||
assert.equal(p.ev('JSON.stringify(__te)'), '[]');
|
||||
assert.equal(p.ev('!!RW.job'), false);
|
||||
assert.equal(p.ev('S.day'), p.ev('S.hist[S.hist.length-1].d'), 'the day was finished');
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
test("the intern's PNI round never orders again what the player ordered while it waited", (t) => {
|
||||
// The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile.
|
||||
const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true;
|
||||
const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a);
|
||||
window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0;
|
||||
for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;}
|
||||
window.__n=S.pni.length-n0;`;
|
||||
const key = "S.pni.map(p=>p.city+'|'+p.net)";
|
||||
const ref = open(t, 777), p = open(t, 777);
|
||||
ref.ev(SETUP); p.ev(SETUP);
|
||||
ref.ev(ROUND(false));
|
||||
assert.ok(ref.ev('__b.orders.length') > 0 && ref.ev('__n') > 0, `the intern orders PNIs: ${ref.ev('__n')} of ${ref.ev('__b.orders.length')}`);
|
||||
p.ev(ROUND(true));
|
||||
assert.ok(p.ev('__h') > p.ev('S.pni.length') - p.ev('__n'), 'the player ordered some by hand');
|
||||
assert.equal(p.ev('S.pni.length'), p.ev('__h'), 'the intern ordered nothing more');
|
||||
const keys = p.ev(key);
|
||||
assert.equal(new Set(keys).size, keys.length, 'one PNI per city and network');
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
|
||||
test('an incident repaired while its routing runs: the failure and the monkey still tell its own story', (t) => {
|
||||
const p = open(t, 777);
|
||||
p.ev(SETUP);
|
||||
// On land: a repair clears the incident (at sea it would charter a ship).
|
||||
p.ev("S.rules.sea='timer';S.inc=[];");
|
||||
// Repaired before the answer, the only incident there was: nothing left to read as "the last one".
|
||||
p.ev(`const g=failureRun('cut');g.next();window.__i=S.inc[S.inc.length-1];ACT.fixInc({id:__i.id});g.next();`);
|
||||
assert.equal(p.ev('S.inc.length'), 0);
|
||||
assert.equal(p.ev('typeof __i.impact'), 'number', 'its impact is its own');
|
||||
// An older incident stands: the new one's impact is not pinned on it.
|
||||
p.ev(`runNow(failureRun('cut'));window.__a=S.inc[S.inc.length-1];__a.impact=-7;
|
||||
const g2=failureRun('cut');g2.next();window.__b=S.inc[S.inc.length-1];ACT.fixInc({id:__b.id});g2.next();`);
|
||||
assert.equal(p.ev('__a!==__b&&S.inc.includes(__a)&&!S.inc.includes(__b)'), true);
|
||||
assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
|
||||
assert.equal(p.ev('typeof __b.impact'), 'number');
|
||||
// The monkey's snip, the same way.
|
||||
p.ev(`S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day,n:0,hurt:0,c:S.home,next:S.day};
|
||||
const g3=mkSnipRun();g3.next();window.__c=S.inc[S.inc.length-1];ACT.fixInc({id:__c.id});g3.next();`);
|
||||
assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
|
||||
assert.equal(p.ev('typeof __c.impact'), 'number');
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
18
tests/frame-pacing.test.js
Normal file
18
tests/frame-pacing.test.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// How long a day may run on the page between two frames (src/game/99-loop.js, rwGo()): half a frame, from 3 to 8 ms.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test("a day's steps follow the screen: half a frame between two, from 3 to 8 ms", () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
|
||||
const run = (hz, n, extra = '') => ev(`(()=>{for(let i=0;i<${n};i++){window.__now=(window.__now||1000)+1000/${hz};${extra};frame(__now);}return RW.budget;})()`);
|
||||
assert.equal(run(240, 300), 3, 'a 240 Hz screen');
|
||||
const b = run(240, 1, '__now+=250');
|
||||
assert.ok(b < 6, `one long frame barely moves it: ${b}`);
|
||||
assert.equal(run(60, 300), 8, 'a 60 Hz screen');
|
||||
assert.ok(Math.abs(run(120, 300) - 1000 / 120 / 2) < 0.1, 'a 120 Hz screen: half its frame');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one
|
||||
|
|
@ -47,17 +47,17 @@ test('every incident and event type fires and clears cleanly', () => {
|
|||
ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.via='grace';openLinkModal('nyc','lon');ACT.buildLink({tier:1});closeModal()");
|
||||
ev("UI.pending={a:'fra',b:'ams'};UI.lmode='df';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.pops.fra.rgen=2;S.pops.ams.rgen=2");
|
||||
ev("const df=S.links.find(l=>l.kind==='df');ACT.addCh({id:df.id,o:'zr4'});df.ready=S.day");
|
||||
const failSrc = ev('fireFailure.toString()');
|
||||
const failSrc = ev('failureRun.toString()');
|
||||
const types = ['harmless','fatwave','label','mtu','oops','cleaner','maxpfx','prepend','rpki','amp','roadmff','optic','ac','cut','crash','power','transit','ixloop','leak','ddos'];
|
||||
for (const t of types) {
|
||||
const funny = ['harmless','fatwave','label','mtu','oops','cleaner','maxpfx','prepend','rpki','roadmff','ac'].includes(t);
|
||||
const patched = failSrc
|
||||
.replace(/^function fireFailure/, 'function')
|
||||
.replace(/^function\* failureRun/, 'function*')
|
||||
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${funny ? 'funny' : t}'))return;opts.splice(0,opts.length,['${funny ? 'funny' : t}',1]);let tot=opts.reduce`)
|
||||
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
|
||||
ev('window.__ff=' + patched);
|
||||
ev('S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute()');
|
||||
ev('__ff()');
|
||||
ev('runNow(__ff())');
|
||||
ev('dayTick()');
|
||||
}
|
||||
const evSrc = ev('fireEvent.toString()');
|
||||
|
|
|
|||
|
|
@ -255,7 +255,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => {
|
|||
// [function, what it must read]
|
||||
const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
|
||||
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
|
||||
['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'],
|
||||
['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'],
|
||||
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']];
|
||||
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');
|
||||
// and in play: no chaos and no market means a quiet year
|
||||
|
|
|
|||
|
|
@ -20,9 +20,10 @@ function open(cfg = {}) {
|
|||
}
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
// A day in flight in the worker when the trial ends: rwDone() would run its dayPost() whenever the answer comes.
|
||||
const IN_FLIGHT = `window.__old=S;RW.seq=41;RW.job={seq:41,d:201,gen:RW.gen-1,t:0};window.__posts=[];
|
||||
dayPost=function(d){__posts.push({d,old:S===__old});};`;
|
||||
// A day in flight in the worker when the trial ends: rwDone() would go on with its steps (the rest of the day, a
|
||||
// generator, 10-day-tick.js) whenever the answer comes. This one only notes on which save it ends.
|
||||
const IN_FLIGHT = `window.__old=S;window.__posts=[];const g=(function*(){yield;__posts.push({d:201,old:S===__old});})();g.next();
|
||||
RW.seq=41;RW.job={seq:41,g,gen:RW.gen-1,t:0,state:S};`;
|
||||
|
||||
test('a late answer from the route worker lands on the trial it belongs to, not the next one', async () => {
|
||||
const { ev, errors } = open();
|
||||
|
|
|
|||
|
|
@ -36,14 +36,14 @@ function tour(ev) {
|
|||
['route script', 'S.lvl=Math.max(S.lvl,3);S.cash+=1e6;ACT.coreUp();ACT.coreUp();ACT.buyTE();ACT.teEdit();ACT.teExample();ACT.teCheck();closeModal()'],
|
||||
['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"],
|
||||
['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src);
|
||||
const failSrc = ev('fireFailure.toString()');
|
||||
const failSrc = ev('failureRun.toString()');
|
||||
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
|
||||
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
|
||||
const patched = failSrc.replace(/^function fireFailure/, 'function')
|
||||
const patched = failSrc.replace(/^function\* failureRun/, 'function*')
|
||||
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`)
|
||||
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
|
||||
assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'fireFailure still has the hooks this tour forces');
|
||||
step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();__ff();dayTick();ACT.leftTab({t:'noc'})`);
|
||||
assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'failureRun() still has the hooks this tour forces');
|
||||
step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();runNow(__ff());dayTick();ACT.leftTab({t:'noc'})`);
|
||||
}
|
||||
// A cable the Baltic event can hit, so the anchor badge does not depend on what the random days built.
|
||||
step('baltic cable', "if(!S.pops.hel)ACT.buildPop({city:'hel'});UI.via='clion';openLinkModal('fra','hel');ACT.buildLink({tier:0});closeModal();UI.via=null");
|
||||
|
|
|
|||
|
|
@ -256,8 +256,8 @@ test('LACP trouble, partial packet loss and PMTUD black holes fire, hurt and cle
|
|||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev("ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.lagT({id:S.transit[0].id,d:1});ACT.buyIx({city:'ams',tier:1});ACT.lagIx({city:'ams',d:1});S.day=100;compute()");
|
||||
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function').replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce");
|
||||
const fire = (t) => { ev('window.__ff=' + src.replace('type=pick(f);}', `type='${t}';}`)); ev('__ff();compute()'); };
|
||||
const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*').replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce");
|
||||
const fire = (t) => { ev('window.__ff=' + src.replace('type=pick(f);}', `type='${t}';}`)); ev('runNow(__ff());compute()'); };
|
||||
for (let i = 0; i < 12; i++) { fire('lacp'); }
|
||||
assert.ok(ev("S.inc.some(i=>i.type==='lacp')"), 'LACP incidents fire');
|
||||
assert.ok(ev("S.transit[0].lacp||S.ev.ixlacp"), 'a LAG is degraded');
|
||||
|
|
@ -1316,7 +1316,7 @@ test('#134 an exchange named after its city does not repeat the city in messages
|
|||
const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))"));
|
||||
assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | '));
|
||||
assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | '));
|
||||
ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()");
|
||||
ev("S.inc=[];runNow(eval('('+failureRun.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')())");
|
||||
const msg = ev("S.inc.map(i=>i.msg).join(' ')");
|
||||
assert.match(msg, /IX\.brrr Campinas/);
|
||||
assert.doesNotMatch(msg, /in Campinas/);
|
||||
|
|
|
|||
35
tests/land-islands.test.js
Normal file
35
tests/land-islands.test.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// "Afraid of sharks" (a path that never goes under the sea, 60-requirements.js) asked for every customer in the daily
|
||||
// mood check: the land islands are worked out once for the check (TERR), and two cities have a land path exactly when
|
||||
// they are on one island. Same answers as walking the links each time, with links cut, subsea or not, and cities alone.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
|
||||
test('land islands answer "a path without subsea" as walking the links does', () => {
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;closeModal();compute();`);
|
||||
const cmp = () => JSON.parse(ev(`(()=>{const cs=Object.keys(S.pops).concat(['sin','nyc','lon',null,undefined]);let n=0,yes=0;const bad=[];
|
||||
for(const a of cs.slice(0,60))for(const b of cs){if(!a)continue;TERR=null;const w=terrestrialPath(a,b);TERR={S,gen:RW.gen,m:null};const i=terrestrialPath(a,b);TERR=null;
|
||||
n++;if(w)yes++;if(w!==i)bad.push(a+'-'+b);}return JSON.stringify({n,yes,bad:bad.slice(0,5)});})()`));
|
||||
let r = cmp();
|
||||
assert.deepEqual(r.bad, []);
|
||||
assert.ok(r.yes > 20 && r.yes < r.n, `pairs with a land path: ${r.yes} of ${r.n}`);
|
||||
// Cut a third of the land links (an island splits) and the answers still agree.
|
||||
ev("S.links.forEach((l,i)=>{if(!l.sub&&i%3===0)l.cut=S.day+5;})");
|
||||
const r2 = cmp();
|
||||
assert.deepEqual(r2.bad, []);
|
||||
assert.ok(r2.yes < r.yes, `fewer land paths once links are cut: ${r2.yes} < ${r.yes}`);
|
||||
// Kept for the day, the islands follow an action that routes (RW.gen), and are never used for another game.
|
||||
ev("TERR={S,gen:RW.gen,m:null};terrestrialPath('fra','ams');window.__m=TERR.m;S.links.forEach(l=>{if(!l.sub)l.cut=0;});compute();");
|
||||
assert.equal(ev("terrestrialPath('fra','ams')===(()=>{const t=TERR;TERR=null;const w=terrestrialPath('fra','ams');TERR=t;return w;})()&&TERR.m!==__m"), true, 'made again after routing');
|
||||
ev("const S0=S;S={...S,links:[]};window.__r=terrestrialPath('fra','ams');S=S0;TERR=null;");
|
||||
assert.equal(ev('__r'), false, 'another game walks its own links');
|
||||
// The daily check leaves no islands behind (a later question walks the links of the moment).
|
||||
ev('S.nextFail=S.nextEvent=S.day+99;dayTick()');
|
||||
assert.equal(ev('TERR'), null);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -109,9 +109,9 @@ test('old saves with inbox, max-prefix and Large Peering Model state load and pl
|
|||
test('max-prefix incidents can no longer fire', () => {
|
||||
const { ev, errors } = load();
|
||||
setup(ev);
|
||||
assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false);
|
||||
ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
|
||||
ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
|
||||
assert.equal(ev("failureRun.toString().includes('maxpfx')"), false);
|
||||
ev("S.day=100;const src=failureRun.toString().replace(/^function\* failureRun/,'function*').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
|
||||
ev("__reseed(7);for(let i=0;i<200;i++){runNow(__ff());S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
|
||||
assert.equal(ev('!!window.__mp'), false);
|
||||
assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined');
|
||||
assert.deepEqual(errors, []);
|
||||
|
|
|
|||
|
|
@ -204,10 +204,10 @@ test('a peer at a rival exchange can de-peer you without stopping the game', ()
|
|||
test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100");
|
||||
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function')
|
||||
const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*')
|
||||
.replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce");
|
||||
ev('window.__ff=' + src);
|
||||
ev('__ff()');
|
||||
ev('runNow(__ff())');
|
||||
assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))"));
|
||||
// a tick that throws is caught, reported once, and the loop keeps going
|
||||
ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0");
|
||||
|
|
|
|||
|
|
@ -458,9 +458,9 @@ test('#76 Kansas City, Calgary, Vancouver and Ottawa, with two more Canadian gia
|
|||
assert.equal(ev("NET.tlu.up.every(id=>NET[id].type==='t1')&&NET.rgc.up.every(id=>NET[id].type==='t1')"), true);
|
||||
// a cut on a Canadian link is often a beaver
|
||||
ev("ACT.buildPop({city:'van'});ACT.buildPop({city:'cal'});S.links=[];UI.via=null;openLinkModal('van','cal');ACT.buildLink({tier:1});closeModal()");
|
||||
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function');
|
||||
const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*');
|
||||
ev('window.__ff=' + src.replace('type=pick(f);}', "type='cut';}"));
|
||||
ev("for(let i=0;i<40&&!(S.stats.f&&S.stats.f.beaver);i++){for(const l of S.links)l.cut=0;S.inc=[];__ff();}");
|
||||
ev("for(let i=0;i<40&&!(S.stats.f&&S.stats.f.beaver);i++){for(const l of S.links)l.cut=0;S.inc=[];runNow(__ff());}");
|
||||
assert.ok(ev("!!(S.stats.f&&S.stats.f.beaver)"), 'a beaver chewed through it');
|
||||
ev('checkBadges()');
|
||||
assert.ok(ev("(S.badges||[]).includes('beaver')||!!(S.badge&&S.badge.beaver)||BADGES.find(b=>b.id==='beaver').ok()"), 'Dam It');
|
||||
|
|
@ -504,13 +504,13 @@ test('#79 Benelux: Brussels red tape, the Flanders duopoly, Oostkamp trawlers an
|
|||
assert.ok(ev("cablesFor('lon','oos').some(c=>c.cid==='clementine')"));
|
||||
ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'oos'});S.links=[];UI.lmode='wave';UI.via='clementine';openLinkModal('lon','oos');ACT.buildLink({tier:1});closeModal()");
|
||||
assert.equal(ev("S.links.length&&S.links[0].sub"), true);
|
||||
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function');
|
||||
const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*');
|
||||
ev('window.__ff=' + src.replace('type=pick(f);}', "type='cut';}"));
|
||||
ev("for(let i=0;i<30&&!S.log.some(e=>/trawler|wind-farm/.test(e.t));i++){for(const l of S.links)l.cut=0;S.inc=[];__ff();}");
|
||||
ev("for(let i=0;i<30&&!S.log.some(e=>/trawler|wind-farm/.test(e.t));i++){for(const l of S.links)l.cut=0;S.inc=[];runNow(__ff());}");
|
||||
assert.ok(ev("S.log.some(e=>/trawler|wind-farm/.test(e.t))"), 'a North Sea boat found the cable');
|
||||
// Bettembourg's chillers run on steam from burning waste wood
|
||||
ev("S.pops={bet:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}};window.__ac=" + src.replace('type=pick(f);}', "type='ac';}"));
|
||||
ev("for(let i=0;i<20&&!S.log.some(e=>/waste-wood/.test(e.t));i++){S.pops.bet.hot=0;S.inc=[];__ac();}");
|
||||
ev("for(let i=0;i<20&&!S.log.some(e=>/waste-wood/.test(e.t));i++){S.pops.bet.hot=0;S.inc=[];runNow(__ac());}");
|
||||
assert.ok(ev("S.log.some(e=>/waste-wood/.test(e.t))"), 'the forestry strike');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -692,18 +692,18 @@ test('Australian failures: cockatoos, kangaroos and emus cut land fiber, and rou
|
|||
ev("ACT.pickStart({city:'syd'});ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0");
|
||||
ev("ACT.buildPop({city:'mel'});S.links=[];UI.via=null;UI.lmode='wave';openLinkModal('syd','mel');ACT.buildLink({tier:1});closeModal()");
|
||||
assert.equal(ev('S.links.length'), 1);
|
||||
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function');
|
||||
const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*');
|
||||
const AU = /cockatoo|kangaroo|backhoe|emus|Bushfire|copper/;
|
||||
ev('window.__cut=' + src.replace('type=pick(f);}', "type='cut';}"));
|
||||
let seen = false;
|
||||
for (let i = 0; i < 30 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];__cut()'); seen = AU.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
|
||||
for (let i = 0; i < 30 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];runNow(__cut())'); seen = AU.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
|
||||
assert.ok(seen, 'an Australian wildlife cut');
|
||||
seen = false;
|
||||
for (let i = 0; i < 80 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];__cut()'); seen = /copper/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
|
||||
for (let i = 0; i < 80 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];runNow(__cut())'); seen = /copper/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
|
||||
assert.ok(seen, 'copper thieves who find fiber');
|
||||
ev('window.__crash=' + src.replace('type=pick(f);}', "type='crash';}"));
|
||||
seen = false;
|
||||
for (let i = 0; i < 40 && !seen; i++) { ev('for(const c in S.pops){S.pops[c].down=0;S.pops[c].routers=1;}S.inc=[];__crash()'); seen = /Floptus|huntsman/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
|
||||
for (let i = 0; i < 40 && !seen; i++) { ev('for(const c in S.pops){S.pops[c].down=0;S.pops[c].routers=1;}S.inc=[];runNow(__crash())'); seen = /Floptus|huntsman/.test(ev("S.inc.map(x=>x.msg).join(' ')")); }
|
||||
assert.ok(seen, 'an Australian router crash');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -41,7 +41,8 @@ test('a day split around its routing is the same day; tests never use the worker
|
|||
const a = big(t), b = big(t);
|
||||
for (const h of [a, b]) h.ev('S.nextFail=S.nextEvent=S.day+99;__reseed(4242)');
|
||||
a.ev('for(let i=0;i<3;i++)dayTick()');
|
||||
b.ev('for(let i=0;i<3;i++){const d=dayPre();compute();dayPost(d);}');
|
||||
// Every routing it asks for done by hand (a DAY_REST is only a place to let a frame through, not a routing).
|
||||
b.ev("for(let i=0;i<3;i++){const g=dayRun();for(let s=g.next();!s.done;s=g.next())if(s.value!==DAY_REST)compute();}");
|
||||
const st = "JSON.stringify({day:S.day,cash:S.cash,moods:S.biz.map(b=>b.mood),offers:S.offers.length,served:R.served})";
|
||||
assert.equal(b.ev(st), a.ev(st));
|
||||
assert.equal(a.ev('rwOn()'), false);
|
||||
|
|
|
|||
|
|
@ -114,7 +114,7 @@ test('#173 a consortium seat: offer, pay, build, light, cut, save', () => {
|
|||
ev(`ACT.subUpgrade({id:'${l.id}',k:'terminal'})`);
|
||||
assert.equal(ev(`S.links.find(l=>l.id==='${l.id}').subterminal`), undefined, 'the consortium owns the terminals');
|
||||
// A cut on the cable cuts your share.
|
||||
ev(`S.links=S.links.filter(l=>l.id==='${l.id}');eval('('+fireFailure.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')()`);
|
||||
ev(`S.links=S.links.filter(l=>l.id==='${l.id}');runNow(eval('('+failureRun.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')())`);
|
||||
assert.ok(ev(`linkDown(S.links.find(l=>l.id==='${l.id}'))`), 'the cut takes your pairs down too');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue