Merge upstream: Lambda Bazaar, traffic badges, moving customers and faster routing (3.3.0)
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
CHANGELOG.md: upstream's released sections as they are; main's 11 Unreleased bullets kept under Unreleased. scripts/lib/route-fuzz.js: upstream's skip of dashboard tabs the base lacks, plus main's trimming of args the base's buttons lack. src/game/10-catalog/40-ports.js: upstream's one-pass portsAt(); an express still takes ports per channel at its ends. src/game/10-catalog/60-reach-and-subsea.js: upstream's dfLit/dfCap0/dfOn (managed waves carved out); capOf() keeps xp and sat. src/game/60-features/80-new-game.js: upstream's vol and cm in a new game, with main's ip4, rgen, mp and saved-shape fields. src/game/60-features/95-standing-orders.js: upstream's portsAt, cachePlan and promiseCheck, inside main's build-standard routers order, optup marks, opsDarkPre and decom gone list; opsPairs still leaves satellites out. src/game/80-simulation/30-compute.js: upstream's routing core; main's satellite edges (SATN) pass into it, express risks and sat/ip4 money stay. src/game/80-simulation/29-route-core.js: main's satellite latency note moved into the core, where upstream moved the flow loop. src/game/80-simulation/40-billing.js: main's linkCut() and xp/sat in linkDown(), with upstream's dfOn(). src/game/80-simulation/50-sanitize.js: upstream's cmClean listings and cmFix/volFix; main keeps the xp/sat kinds, mpSanitize, ip4Fix and satSanitize. src/game/80-simulation/60-requirements.js: upstream's shared diversity graph; an express link carries the list of trenches it rides. src/game/91-save.js: upstream's saves in the worker, except a multiplayer session network, whose text is made on the page (mpSave) so the server gets the very save the slot holds; bootNotes() kept. src/game/91-slots.js: upstream's slot text and day, with main's mp badge on a slot. src/game/93-ui/70-link-panels.js: a fiber says both its managed waves and the expresses it carries. src/game/94-dashboard/60-dashboard.js: upstream's carried tile, main's themed demand line. src/game/95-modals/70-link-modal.js: main's Express tab, then upstream's hint for a coast no cable lands on (#321). After the merge: - Moving a circuit: a path over an express shares the trenches of the fibers it rides, so it is never called fully diverse from a path along them (test in express-fiber). - The capacity market and moving customers leave the slots expresses hold (test in express-fiber; no code change needed). - The NOC log keeps only the kinds a reload keeps: the market's info/warn news is a plain line, live as after a reload. - New acts classified for server-run play: market and path moves sent, marketOpen and pathOpen local; pathPin's path may be longer than 64 characters. - Server-play fixtures written again (new cm and vol fields); the dark-mode test reads mapStill()'s three states. - A big multiplayer network that moved on still pushes its save to the server (test in multiplayer). - The full suite ran on jsdom 31.0.0 and playwright-core 1.65.0, the versions the merged lockfile pins.
This commit is contained in:
commit
61e31c53d3
105 changed files with 3281 additions and 664 deletions
149
tests/capacity-market.test.js
Normal file
149
tests/capacity-market.test.js
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
// The capacity market, Lambda Bazaar (37-fiber-market.js): products from spectrum to 1.6T waves and dark pairs, demand
|
||||
// that moves and grows, thresholds, managed waves carved out of your own capacity, customers moving up a size, the
|
||||
// Cable broker's fee and forecast, and saves.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e9;S.lvl=6;S.offers=[];S.biz=[];S.inc=[]");
|
||||
const fiber = (ev, id, a, b, ch = 'tp16', n = 8) => ev(`for(const c of ['${a}','${b}'])if(!S.pops[c])ACT.buildPop({city:c});closeModal();
|
||||
S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'cl',ch:Array(${n}).fill('${ch}'),km:Math.round(kmBetween('${a}','${b}')*1.05),ready:0,day:0,cut:0,mo:100,trench:'own:${id}',pairs:1});compute();`);
|
||||
const route = (k) => `cmRoutes().get('${k}')`;
|
||||
|
||||
test('demand moves all the time: its own cycle, noise, and news; a forecast sees the cycle and the news already out', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'f', 'fra', 'ams');
|
||||
const hs = JSON.parse(ev(`JSON.stringify(Array.from({length:24},(_, i)=>cmHeat(${route('ams|fra')},'w400',i*15)))`));
|
||||
assert.ok(Math.max(...hs) - Math.min(...hs) > 0.3, `heat over a year: ${Math.min(...hs).toFixed(2)} to ${Math.max(...hs).toFixed(2)}`);
|
||||
assert.ok(hs.every((h) => h >= 0.3 && h <= 2.5));
|
||||
assert.equal(ev(`cmFc(${route('ams|fra')},'w400',30)`), ev(`cmDem(${route('ams|fra')},'w400',S.day+30,true)`));
|
||||
// A cut on a fiber next door is news the next morning, and carriers want routes around it.
|
||||
const before = ev(`cmDem(${route('ams|fra')},'spec',S.day+10)`);
|
||||
// (No other news today: the daily roll for news of its own comes out high.)
|
||||
ev("S.inc.push({id:'cut1',type:'cut',ref:'own:f',until:S.day+5,msg:''});const r0=Math.random;Math.random=()=>0.99;cmShocks(S.day);Math.random=r0");
|
||||
assert.equal(ev('S.cm.news[0].why'), 'cut');
|
||||
assert.ok(ev(`cmDem(${route('ams|fra')},'spec',S.day+10)`) > before * 1.4, 'a cut makes the route around it hot');
|
||||
ev('const r0=Math.random;Math.random=()=>0.99;cmShocks(S.day);Math.random=r0');
|
||||
assert.equal(ev("S.cm.news.filter(n=>n.why==='cut').length"), 1, 'one incident is news once');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('demand grows every year, and buyers move from 100G to 400G, 800G and 1.6T', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'f', 'fra', 'ams');
|
||||
ev('S.cm.sh=[]');
|
||||
const gbps = (d) => ev(`CM_W.reduce((a,p)=>a+cmDem(${route('ams|fra')},p,${d},true)*CM_G[p],0)`);
|
||||
assert.ok(Math.abs(ev('cmGrowth(365*5)') - Math.pow(1.15, 5)) < 1e-9, 'about 15% more every year');
|
||||
assert.ok(gbps(365 * 5) > gbps(0) * 1.3, `five years on, carriers want ${Math.round(gbps(365 * 5))} G against ${Math.round(gbps(0))} G`);
|
||||
const sh = (p, d) => ev(`cmShare('${p}',${d})`);
|
||||
assert.ok(sh('w100', 0) > sh('w100', 365 * 4), '100G fades');
|
||||
assert.ok(sh('w1600', 0) < 0.05 && sh('w1600', 365 * 10) > 0.5, '1.6T is rare at first and common ten years on');
|
||||
assert.ok(Math.abs(['w100', 'w400', 'w800', 'w1600'].reduce((a, p) => a + sh(p, 900), 0) - 1) < 1e-9, 'the shares add up');
|
||||
assert.ok(ev('cmGrowth(365*40)') <= 8, 'growth has a ceiling');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('prices: a 400G wave is 2.7 times a 100G one on land and 3.8 on subsea, short straight routes earn more, and floors hold', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'f', 'fra', 'ams');
|
||||
const r = route('ams|fra');
|
||||
assert.ok(Math.abs(ev(`cmList(${r},'w400')/cmList(${r},'w100')`) - 2.7) < 1e-9);
|
||||
assert.ok(Math.abs(ev(`(()=>{const x={...${r},sub:true};return cmList(x,'w400')/cmList(x,'w100')})()`) - 3.8) < 1e-9);
|
||||
assert.ok(ev(`cmList(${r},'w1600')/16 < cmList(${r},'w100')`), 'a bit on a 1.6T wave is cheaper than on a 100G one');
|
||||
assert.ok(ev(`${r}.lp`) > ev(`({...${r},lp:0}, cmRoute('ams','fra',[{...S.links.find(l=>l.id==='f'),km:2000}]).lp)`), 'a long detour loses the latency premium');
|
||||
// Each unit sold makes the next cheaper, and the broker never sells below the floor.
|
||||
ev("for(const p of CM_P){S.cm.p[p].on=true;S.cm.p[p].floor=100;S.cm.p[p].min=1;}__reseed(5)");
|
||||
ev('for(let d=0;d<400;d++){S.day++;cmDay(S.day);}');
|
||||
const sales = JSON.parse(ev("JSON.stringify(S.biz.map(b=>({t:b.type,g:b.g||0})))"));
|
||||
assert.ok(sales.length > 0, 'something sold');
|
||||
assert.ok(ev(`(()=>{const rs=cmRoutes(),s=cmSold(rs).get('ams|fra');return CM_P.every(p=>!s[p]||cmIdx(rs.get('ams|fra'),p,s[p]-1,0,S.day)*100>=0)})()`));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('auto-listing follows the thresholds and the share kept back; managed waves come out of your own capacity', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'f', 'fra', 'ams', 'zr4', 8);
|
||||
ev("S.cm.hold=50;S.cm.p.w400.on=true;S.cm.p.w400.min=1;S.cm.p.w400.floor=60;S.cm.p.w800.on=true;S.cm.p.w800.min=1;S.cm.p.w800.floor=60;cmRelist()");
|
||||
const L = () => JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').list||{})"));
|
||||
assert.ok(L().m4 > 0 && L().m4 <= 4, `half of 3.2T kept back leaves at most four 400G waves (${L().m4})`);
|
||||
assert.equal(L().m8, undefined, 'no 800G wave on 400G optics');
|
||||
ev("S.cm.p.w400.min=16;cmRelist()");
|
||||
assert.equal(L().m4, undefined, 'below the minimum demand the broker takes it off');
|
||||
// A sold managed wave carves its capacity out of your own; when your optics cannot carry it, its customer suffers.
|
||||
ev("const l=S.links.find(x=>x.id==='f');cmSell(l,'w400',2,1000,0);compute()");
|
||||
assert.equal(ev("dfLit(S.links.find(l=>l.id==='f'))-dfCap(S.links.find(l=>l.id==='f'))"), 800);
|
||||
assert.equal(ev("fiberOk(S.biz.find(b=>b.type==='mwave'))"), true);
|
||||
ev("S.links.find(l=>l.id==='f').ch=['zr4']");
|
||||
assert.equal(ev("fiberOk(S.biz.find(b=>b.type==='mwave'))"), false, '400G lit cannot carry 800G sold');
|
||||
ev("ACT.mktCfg({p:'w400',k:'on',v:0})");
|
||||
assert.equal(ev("S.cm.p.w400.on"), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a carrier on your glass moves up a size once the next one is common, if there is room', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'f', 'fra', 'ams', 'tp16', 8);
|
||||
ev("S.day=365*4;S.cm.hold=0;const l=S.links.find(x=>x.id==='f');cmSell(l,'w400',2,2000,0);compute()");
|
||||
const b0 = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.type==='mwave'))"));
|
||||
ev("Math.random=()=>0;cmGrow(S.day)");
|
||||
const b1 = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.type==='mwave'))"));
|
||||
assert.equal(b1.g, 800);
|
||||
assert.ok(b1.rate > b0.rate, `pays more: ${b0.rate} to ${b1.rate}`);
|
||||
assert.equal(ev("dfLit(S.links.find(l=>l.id==='f'))-dfCap(S.links.find(l=>l.id==='f'))"), 1600);
|
||||
// No room: it asks, and does not ask again for half a year (1.6T is common by year 9).
|
||||
ev("S.links.find(l=>l.id==='f').ch=['tp16'];S.cm.hold=50;S.day=365*9;cmGrow(S.day)");
|
||||
const gw = ev('S.biz.find(b=>b.type===\'mwave\').gw');
|
||||
ev('S.day+=30;cmGrow(S.day)');
|
||||
const b2 = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.type==='mwave'))"));
|
||||
assert.equal(b2.g, 800);
|
||||
assert.equal(gw, 365 * 9);
|
||||
assert.equal(b2.gw, 365 * 9, 'not again a month later');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a Cable broker pays 3% instead of 10% and sees routes it could build with their forecast', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
assert.equal(ev('cmCut()'), 0.9);
|
||||
ev("ACT.charter({k:'broker'});closeModal();S.cash=1e9");
|
||||
assert.equal(ev('cmCut()'), 0.97);
|
||||
for (const c of ['fra', 'ams', 'par', 'bru']) ev(`if(!S.pops['${c}'])ACT.buildPop({city:'${c}'});closeModal()`);
|
||||
const sc = JSON.parse(ev('JSON.stringify(cmScout().map(r=>r.k))'));
|
||||
assert.ok(sc.length > 0 && sc.every((k) => k.includes('|')));
|
||||
ev("UI.dtab='market';$('dash').hidden=false;renderDash()");
|
||||
const html = ev("$('dashCard').textContent");
|
||||
assert.match(html, /Lambda Bazaar/);
|
||||
assert.match(html, /Routes you could build/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the market is kept in the save, checked, and old saves get the defaults', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
fiber(ev, 'f', 'fra', 'ams');
|
||||
ev("S.cm.hold=10;S.cm.p.w1600.on=true;S.cm.p.w1600.min=2;S.cm.off['ams|fra']=1;cmNews('glut',{k:'ams|fra',a:'ams',b:'fra'},S.day);cmSell(S.links[S.links.length-1],'w800',1,500,0)");
|
||||
ev('const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))');
|
||||
const cm = JSON.parse(ev('JSON.stringify(S.cm)'));
|
||||
assert.equal(cm.hold, 10);
|
||||
assert.deepEqual(cm.p.w1600, { on: true, min: 2, floor: 80 });
|
||||
assert.equal(cm.off['ams|fra'], 1);
|
||||
assert.equal(cm.sh[0].why, 'glut');
|
||||
assert.equal(ev("S.biz.find(b=>b.type==='mwave').g"), 800);
|
||||
ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.cm={hold:33,p:{w100:{on:'yes',min:999,floor:-1}},off:{'zzz|ams':1},sh:[{why:'nope'},{why:'dc',c:'atlantis'}],news:'x'};o.biz.find(b=>b.type==='mwave').g=999;o.links.find(l=>l.id==='f').list={m8:'lots',m16:3};S=migrate(o)");
|
||||
const c2 = JSON.parse(ev('JSON.stringify(S.cm)'));
|
||||
assert.equal(c2.hold, 25);
|
||||
assert.deepEqual(c2.p.w100, { on: true, min: 4, floor: 80 });
|
||||
assert.deepEqual(c2.off, {});
|
||||
assert.deepEqual(c2.sh, []);
|
||||
assert.deepEqual(c2.news, []);
|
||||
assert.equal(ev("S.biz.find(b=>b.type==='mwave').g"), 100);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').list)")), { w: 0, p: 0, m16: 3 });
|
||||
ev('const o=JSON.parse(JSON.stringify(packSave(S)));delete o.cm;S=migrate(o)');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.cm.p.spec)')), { on: false, min: 2, floor: 80 });
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
251
tests/customer-paths.test.js
Normal file
251
tests/customer-paths.test.js
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
// Moving a customer to another path between the same two POPs: fiber customers to another fiber, circuits by a pin.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
// New York and Ashburn, with Boston as the way round, for the test's sake. Fiber a is the direct one, on its own trench;
|
||||
// b runs beside it in the same trench; c is direct on another trench; d and e go through Boston on trenches of their own.
|
||||
const fib = (id, a, z, km, trench, n = 8) => `S.links.push({id:'${id}',a:'${a}',b:'${z}',kind:'df',own:true,sys:'roadm',pairs:1,ch:Array(${n}).fill('zr4'),km:${km},sub:false,cable:null,mo:1,trench:'${trench}',cut:0,day:0,ready:0,spares:false});`;
|
||||
const BASE = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
|
||||
"for(const c of ['nyc','ash','bos'])if(!S.pops[c])S.pops[c]={day:0,bb:null,boost:0,down:0,routers:4,gen:false,rgen:RG.length-3};S.links=[];" +
|
||||
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');
|
||||
const hasCities = (ev) => ev("['nyc','ash','bos'].every(isCity)");
|
||||
const wave = "S.biz.push({id:'w',type:'wwave',name:'Zay-No Fiber',city:'nyc',city2:'ash',link:'a',slots:2,bw:1,rate:9000,reqs:[],mood:80,since:0,day:0,route:'normal',what:'x'});";
|
||||
const pair = (type, id = 'p', link = 'a') => `S.biz.push({id:'${id}',type:'${type}',name:'A Customer ${id}',city:'nyc',city2:'ash',link:'${link}',slots:0,bw:1,rate:9000,reqs:[],mood:80,since:0,day:0,route:'normal',what:'x'});`;
|
||||
const circuit = (bw = 100) => `S.biz.push({id:'k',type:'l2vpn',name:'Big Circuit',city:'nyc',city2:'ash',bw:${bw},rate:10,reqs:[],mood:80,since:0,day:0,route:'normal'});`;
|
||||
function game(t, extra = '') { const h = load({ seed: 777 }); t.after(() => h.dom.window.close());
|
||||
h.ev(BASE); assert.equal(hasCities(h.ev), true); h.ev(extra + 'compute();'); return h; }
|
||||
const biz = (ev, id, k) => ev(`S.biz.find(b=>b.id===${lit(id)}).${k}`);
|
||||
const modal = (ev) => ev("document.getElementById('modal').textContent");
|
||||
|
||||
test('a wave moves to another fiber: free, its channels go with it, and the first choice is on another trench', (t) => {
|
||||
const { ev, errors } = game(t, wave);
|
||||
const cash = ev('S.cash');
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).map(x=>[x.l.id,x.diverse,x.no]))")), [['c', true, ''], ['b', false, '']]);
|
||||
assert.equal(ev("soldSlots(S.links.find(l=>l.id==='a'))"), 2);
|
||||
ev("ACT.pathOpen({id:'w'})");
|
||||
assert.match(modal(ev), /Fully diverse/); assert.match(modal(ev), /Same trench/);
|
||||
ev("ACT.pathMove({id:'w',link:'c'})");
|
||||
assert.equal(biz(ev, 'w', 'link'), 'c');
|
||||
assert.equal(ev("soldSlots(S.links.find(l=>l.id==='a'))"), 0);
|
||||
assert.equal(ev("soldSlots(S.links.find(l=>l.id==='c'))"), 2);
|
||||
assert.equal(ev('S.cash'), cash, 'free');
|
||||
assert.equal(biz(ev, 'w', 'rate'), 9000, 'the contract stands');
|
||||
assert.equal(ev("document.getElementById('modal').hidden"), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a wave needs room on the new fiber; a move is checked again when it is made', (t) => {
|
||||
const { ev, errors } = game(t, wave + "S.links.find(l=>l.id==='c').ch=Array(63).fill('zr4');");
|
||||
const c = JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).find(x=>x.l.id==='c'))"));
|
||||
assert.match(c.no, /1 free, needs 2/);
|
||||
ev("ACT.pathMove({id:'w',link:'c'})");
|
||||
assert.equal(biz(ev, 'w', 'link'), 'a', 'refused');
|
||||
for (const link of ['a', 'd', 'nope']) { ev(`ACT.pathMove({id:'w',link:${lit(link)}})`); assert.equal(biz(ev, 'w', 'link'), 'a', `${link}: not a fiber it can go to`); }
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a carrier already renting waves on the new fiber ends up with one contract', (t) => {
|
||||
const { ev, errors } = game(t, wave + "S.biz.push({id:'w2',type:'wwave',name:'Zay-No Fiber',city:'nyc',city2:'ash',link:'c',slots:3,bw:1,rate:1000,reqs:[],mood:90,since:5,day:0,route:'normal',what:'x'});");
|
||||
ev("ACT.pathMove({id:'w',link:'c'})");
|
||||
assert.equal(ev("S.biz.filter(b=>b.type==='wwave').length"), 1);
|
||||
assert.equal(biz(ev, 'w2', 'slots'), 5); assert.equal(biz(ev, 'w2', 'rate'), 10000); assert.equal(biz(ev, 'w2', 'mood'), 80, 'the unhappier of the two'); assert.equal(biz(ev, 'w2', 'since'), 0);
|
||||
assert.match(biz(ev, 'w2', 'what'), /5/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a wave leaves alone the channels kept back for your own traffic', (t) => {
|
||||
// 47 channels lit of 64: 17 free, but a quarter of the fiber is kept back, so 1 spare.
|
||||
const { ev, errors } = game(t, wave + "S.cm.hold=25;S.links.find(l=>l.id==='c').ch=Array(47).fill('zr4');");
|
||||
assert.match(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), /1 left after the 25% you keep back.*needs 2/);
|
||||
ev("ACT.pathMove({id:'w',link:'c'})");
|
||||
assert.equal(biz(ev, 'w', 'link'), 'a', 'refused');
|
||||
ev("S.cm.hold=0;ACT.pathMove({id:'w',link:'c'})");
|
||||
assert.equal(biz(ev, 'w', 'link'), 'c', 'nothing kept back: it fits');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Four managed 400G waves, 1.6T in all, carved out of fiber a's lit capacity.
|
||||
const mwave = (id = 'm', link = 'a', g = 400, slots = 4) => `S.biz.push({id:'${id}',type:'mwave',g:${g},name:'Photon Express',city:'nyc',city2:'ash',link:'${link}',slots:${slots},bw:1,rate:5000,reqs:[],mood:80,since:0,day:0,route:'normal',what:'x'});`;
|
||||
|
||||
test('managed waves need that much spare lit capacity on the new fiber, on leased fiber too, and their capacity moves with them', (t) => {
|
||||
// c has 1.6T lit, but a quarter is kept back: 1.2T spare, room for three of the four. b has 3.2T: 2.4T spare.
|
||||
const { ev, errors } = game(t, mwave() + "S.cm.hold=25;S.links.find(l=>l.id==='c').ch=Array(4).fill('zr4');");
|
||||
const no = () => JSON.parse(ev("JSON.stringify(Object.fromEntries(fiberTargets(S.biz[0]).map(x=>[x.l.id,x.no])))"));
|
||||
assert.match(no().c, /Not enough spare capacity/);
|
||||
assert.equal(no().b, '');
|
||||
ev("ACT.pathMove({id:'m',link:'c'})");
|
||||
assert.equal(biz(ev, 'm', 'link'), 'a', '1.6T does not fit in 1.2T');
|
||||
// A leased fiber is lit capacity like any other: the reason is the room, not whose glass it is.
|
||||
ev("S.links.find(l=>l.id==='b').own=false;S.links.find(l=>l.id==='c').own=false;");
|
||||
assert.equal(no().b, '');
|
||||
assert.doesNotMatch(no().c, /own fiber/);
|
||||
assert.match(no().c, /spare capacity/);
|
||||
// What the fiber gives your own traffic follows the waves, at once.
|
||||
assert.equal(ev("mwG(S.links.find(l=>l.id==='a'))"), 1600);
|
||||
ev("ACT.pathMove({id:'m',link:'b'})");
|
||||
assert.equal(biz(ev, 'm', 'link'), 'b');
|
||||
assert.equal(ev("mwG(S.links.find(l=>l.id==='a'))"), 0);
|
||||
assert.equal(ev("mwG(S.links.find(l=>l.id==='b'))"), 1600);
|
||||
assert.equal(ev("dfCap0(S.links.find(l=>l.id==='a'))"), 3200);
|
||||
assert.equal(ev("dfCap0(S.links.find(l=>l.id==='b'))"), 1600);
|
||||
assert.match(biz(ev, 'm', 'what'), /4/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a managed wave needs a channel as big as it is; a carrier renting the same size there gets one contract, another size does not', (t) => {
|
||||
{ const { ev, errors } = game(t, mwave('m', 'a', 800, 1) + "S.cm.hold=0;");
|
||||
assert.match(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), /Needs a channel lit at/, '400G optics only');
|
||||
ev("S.links.find(l=>l.id==='c').ch=Array(8).fill('zr8');");
|
||||
assert.equal(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), '');
|
||||
assert.deepEqual(errors, []); }
|
||||
{ const { ev, errors } = game(t, mwave() + mwave('m2', 'b', 100, 2) + "S.cm.hold=0;");
|
||||
ev("ACT.pathMove({id:'m',link:'b'})");
|
||||
assert.equal(ev("S.biz.filter(b=>b.type==='mwave'&&b.link==='b').length"), 2, '400G and 100G waves stay apart');
|
||||
assert.equal(biz(ev, 'm2', 'slots'), 2);
|
||||
assert.equal(ev("mwG(S.links.find(l=>l.id==='b'))"), 1800);
|
||||
assert.deepEqual(errors, []); }
|
||||
{ const { ev, errors } = game(t, mwave() + mwave('m2', 'b', 400, 2) + "S.cm.hold=0;");
|
||||
ev("ACT.pathMove({id:'m',link:'b'})");
|
||||
assert.equal(ev("S.biz.filter(b=>b.type==='mwave').length"), 1);
|
||||
assert.equal(biz(ev, 'm2', 'slots'), 6); assert.equal(biz(ev, 'm2', 'rate'), 10000); assert.equal(biz(ev, 'm2', 'g'), 400);
|
||||
assert.match(biz(ev, 'm2', 'what'), /6/);
|
||||
assert.equal(ev("mwG(S.links.find(l=>l.id==='b'))"), 2400);
|
||||
assert.deepEqual(errors, []); }
|
||||
});
|
||||
|
||||
test('fiber pairs follow the same rules as signing them: your own fiber, and pairs still free', (t) => {
|
||||
for (const type of ['dfpair', 'pairs', 'capfib']) {
|
||||
const { ev, errors } = game(t, pair(type) + pair('pairs', 'q', 'b') + "S.links.find(l=>l.id==='e').x=1;");
|
||||
const T = JSON.parse(ev("JSON.stringify(Object.fromEntries(fiberTargets(S.biz[0]).map(x=>[x.l.id,x.no])))"));
|
||||
assert.equal(T.c, '', `${type} can go to the free fiber`);
|
||||
assert.match(T.b, /already rented/, `${type} cannot join a fiber whose pairs are sold`);
|
||||
ev("ACT.pathMove({id:'p',link:'b'})"); assert.equal(biz(ev, 'p', 'link'), 'a');
|
||||
ev("ACT.pathMove({id:'p',link:'c'})"); assert.equal(biz(ev, 'p', 'link'), 'c');
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
const { ev } = game(t, pair('dfpair') + "S.links.find(l=>l.id==='c').own=false;");
|
||||
assert.match(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), /your own fiber/);
|
||||
});
|
||||
|
||||
test('only working fibers are offered, and a customer on a cut fiber can be moved off it', (t) => {
|
||||
const { ev, errors } = game(t, wave + "S.links.find(l=>l.id==='a').cut=S.day+9;S.links.find(l=>l.id==='b').eqDown=S.day+9;" + fib('f', 'nyc', 'ash', 300, 'tf') + "S.links.at(-1).ready=S.day+5;");
|
||||
assert.equal(ev("fiberOk(S.biz[0])"), false);
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).map(x=>x.l.id))")), ['c']);
|
||||
ev("ACT.pathMove({id:'w',link:'c'})");
|
||||
assert.equal(ev("fiberOk(S.biz[0])"), true);
|
||||
ev("S.links.find(l=>l.id==='c').ready=S.day+5;");
|
||||
assert.deepEqual(JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).map(x=>x.l.id))")), [], 'nothing left');
|
||||
ev("ACT.pathOpen({id:'w'})");
|
||||
assert.match(modal(ev), /no other working fiber/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a pinned circuit rides its path, and takes the load off the direct fibers', (t) => {
|
||||
const { ev, errors } = game(t, circuit(100));
|
||||
const cash = ev('S.cash');
|
||||
const load = () => JSON.parse(ev("JSON.stringify(Object.fromEntries(['a','b','c','d','e'].map(i=>[i,R.load[i]||0])))"));
|
||||
const direct = load();
|
||||
assert.equal(Math.round(direct.a + direct.b + direct.c), 100, 'by default it takes the direct edge');
|
||||
assert.equal(Math.round(direct.d), 0);
|
||||
const T = JSON.parse(ev("JSON.stringify(circuitTargets(S.biz[0]))"));
|
||||
assert.deepEqual(T.now, ['nyc', 'ash']);
|
||||
assert.deepEqual(T.alts.map((x) => x.p), [['nyc', 'bos', 'ash']]);
|
||||
assert.equal(T.alts[0].shared, 0, 'nothing in common with the direct fibers');
|
||||
ev("ACT.pathOpen({id:'k'})");
|
||||
assert.match(modal(ev), /Fully diverse/);
|
||||
ev("ACT.pathPin({id:'k',via:'nyc,bos,ash'})");
|
||||
const on = load();
|
||||
assert.equal(Math.round(on.a + on.b + on.c), 0);
|
||||
assert.equal(Math.round(on.d), 100); assert.equal(Math.round(on.e), 100);
|
||||
assert.equal(ev("R.l2.k"), 100);
|
||||
assert.ok(ev('R.l2lat.k') > 0);
|
||||
assert.equal(ev('S.cash'), cash, 'free');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a pin falls back to routing while a link on it is down, comes back by itself, and can be undone', (t) => {
|
||||
const { ev, errors } = game(t, circuit(100) + "S.biz[0].pin=['nyc','bos','ash'];");
|
||||
assert.equal(ev('Math.round(R.load.d)'), 100);
|
||||
ev("S.links.find(l=>l.id==='e').cut=S.day+9;compute();");
|
||||
assert.equal(ev('Math.round(R.load.d||0)'), 0, 'off the broken path');
|
||||
assert.equal(ev('R.l2.k'), 100, 'and the customer keeps its service');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz[0].pin)')), ['nyc', 'bos', 'ash'], 'the pin is kept');
|
||||
assert.equal(ev('pinUp(S.biz[0])'), false);
|
||||
assert.match(ev('pathCtl(S.biz[0])'), /That path is down/);
|
||||
ev("S.links.find(l=>l.id==='e').cut=0;compute();");
|
||||
assert.equal(ev('Math.round(R.load.d)'), 100, 'back by itself');
|
||||
assert.doesNotMatch(ev('pathCtl(S.biz[0])'), /That path is down/);
|
||||
ev("ACT.pathOpen({id:'k'})");
|
||||
assert.match(modal(ev), /Let routing choose again/);
|
||||
ev("ACT.pathAuto({id:'k'})");
|
||||
assert.equal(ev("S.biz[0].pin===undefined"), true);
|
||||
assert.equal(ev('Math.round(R.load.d||0)'), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('choosing a route mode unpins; a bad path is refused; SD-WANs, pending deals and puzzles have no move', (t) => {
|
||||
const { ev, errors } = game(t, circuit(100));
|
||||
for (const via of ['nyc,ash,bos', 'bos,nyc,ash', 'nyc', 'nyc,nowhere,ash', 'nyc,bos,nyc,ash', 'nyc,ash,ash']) {
|
||||
ev(`ACT.pathPin({id:'k',via:${lit(via)}})`);
|
||||
assert.equal(ev('S.biz[0].pin===undefined'), true, via);
|
||||
}
|
||||
ev("ACT.pathPin({id:'k',via:null})"); ev("ACT.pathPin({id:'k',via:7})"); ev("ACT.pathPin({id:'nope',via:'nyc,ash'})");
|
||||
assert.equal(ev('S.biz[0].pin===undefined'), true);
|
||||
ev("S.links=S.links.filter(l=>l.id!=='e');compute();ACT.pathPin({id:'k',via:'nyc,bos,ash'})");
|
||||
assert.equal(ev('S.biz[0].pin===undefined'), true, 'a hop with no link');
|
||||
ev("ACT.pathPin({id:'k',via:'nyc,ash'})");
|
||||
assert.equal(ev('S.biz[0].pin.length'), 2);
|
||||
ev("ACT.setRoute({id:'k',m:'fast'})");
|
||||
assert.equal(ev('S.biz[0].pin===undefined'), true);
|
||||
assert.equal(ev("pathKind({type:'mtrain',city:'nyc',city2:'ash',sites:['nyc','ash']})"), '');
|
||||
assert.equal(ev("pathKind({type:'capw',city:'nyc',city2:'ash',due:9,live:false})"), '', 'not delivered yet');
|
||||
assert.equal(ev("pathKind({type:'capw',city:'nyc',city2:'ash',due:9,live:true})"), 'circuit');
|
||||
assert.equal(ev("pathKind({type:'l2vpn',city:'nyc'})"), '', 'no second city');
|
||||
assert.equal(ev("pathKind({type:'wwave',city:'nyc',link:'a'})"), '', 'no second city');
|
||||
assert.equal(ev("pathKind({type:'wwave',city:'nyc',city2:'ash'})"), '', 'no fiber yet');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('with no way round, the most diverse path shares what it must and says so', (t) => {
|
||||
// Boston reaches Ashburn only over the direct fibers' trench.
|
||||
const { ev, errors } = game(t, circuit(100) + "S.links.find(l=>l.id==='e').trench='ta';S.links=S.links.filter(l=>l.id!=='c');");
|
||||
const T = JSON.parse(ev('JSON.stringify(circuitTargets(S.biz[0]))'));
|
||||
assert.deepEqual(T.alts.map((x) => [x.p, x.shared]), [[['nyc', 'bos', 'ash'], 1]]);
|
||||
ev("ACT.pathOpen({id:'k'})");
|
||||
assert.match(modal(ev), /Shares 1 span/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the window warns when a path is too small or too slow for the customer', (t) => {
|
||||
const { ev, errors } = game(t, circuit(1e6) + "S.biz[0].latMax=0.1;");
|
||||
ev("ACT.pathOpen({id:'k'})");
|
||||
assert.match(modal(ev), /Fits only/);
|
||||
assert.match(modal(ev), /Over the 0.1 ms budget/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves: a pin survives a reload, and a bad one is dropped, leaving old saves alone', (t) => {
|
||||
const { ev, errors } = game(t, circuit(100) + "S.biz[0].pin=['nyc','bos','ash'];");
|
||||
const again = (pin) => ev(`(()=>{const s=JSON.parse(JSON.stringify(packSave(S)));s.biz[0].pin=${lit(pin)};return JSON.stringify(migrate(s).biz[0].pin);})()`);
|
||||
assert.deepEqual(JSON.parse(again(['nyc', 'bos', 'ash'])), ['nyc', 'bos', 'ash']);
|
||||
for (const bad of ['nyc', [], ['nyc'], ['nyc', 'nowhere', 'ash'], ['bos', 'ash'], ['nyc', 'bos'], ['nyc', 'bos', 'nyc', 'ash'], [1, 2], { a: 1 }])
|
||||
assert.equal(again(bad), undefined, JSON.stringify(bad));
|
||||
assert.equal(ev("(()=>{const s=JSON.parse(JSON.stringify(packSave(S)));delete s.biz[0].pin;return migrate(s).biz[0].pin===undefined;})()"), true);
|
||||
// Not a circuit: no pin.
|
||||
assert.equal(ev("(()=>{const s=JSON.parse(JSON.stringify(packSave(S)));s.biz[0].type='wwave';s.biz[0].pin=['nyc','ash'];return migrate(s).biz[0].pin===undefined;})()"), true);
|
||||
// A stale pin (a POP on it was closed) does no harm: routing carries the circuit.
|
||||
ev("delete S.pops.bos;S.links=S.links.filter(l=>l.a!=='bos'&&l.b!=='bos');compute();");
|
||||
assert.equal(ev('R.l2.k'), 100);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the buttons are in the panels: under a customer in its city, and on the fiber it rents', (t) => {
|
||||
const { ev, errors } = game(t, wave + circuit(100));
|
||||
ev("UI.tab='cust';UI.sel={type:'city',id:'nyc'};selectCity('nyc');UI.tab='cust';renderPanel();");
|
||||
assert.equal(ev("document.querySelectorAll('#panel [data-act=pathOpen]').length"), 2);
|
||||
ev("selectLink('a');renderPanel();");
|
||||
assert.equal(ev("[...document.querySelectorAll('#panel [data-act=pathOpen]')].length"), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -180,9 +180,10 @@ test('the map paints sea, land, clouds and labels in the theme\'s colours, in 2D
|
|||
assert.equal(frame(1016).paints, 0, 'and not on the next frame');
|
||||
// Paused and unmoved, the map is drawn again for the theme (mapStill() would otherwise keep the old frame).
|
||||
ev("FRAME.length=0;mapStill(0,performance.now());UI.drawnAt=performance.now();");
|
||||
assert.equal(ev('mapStill(0,performance.now())'), true, 'an unchanged frame is skipped');
|
||||
// mapStill() says how the map stands (MAP_MOVING, MAP_AMBIENT, MAP_STILL; 99-loop.js), not just whether it is still.
|
||||
assert.equal(ev('mapStill(0,performance.now())'), ev('MAP_STILL'), 'an unchanged frame is skipped');
|
||||
ev("ACT.themeSet({v:'light'})");
|
||||
assert.equal(ev('mapStill(0,performance.now())'), false, 'a theme change draws the map again');
|
||||
assert.equal(ev('mapStill(0,performance.now())'), ev('MAP_MOVING'), 'a theme change draws the map again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
35
tests/day-pace.test.js
Normal file
35
tests/day-pace.test.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// How fast days really come with the route worker (src/game/88-days/15-day-pace.js), for Settings › Diagnostic info:
|
||||
// the speed asked, the speed held from the starts of the last days, how long a day takes and the slowest. Measured
|
||||
// only: the clock starts days as it always did.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
test('Diagnostic info says the speed asked, the speed held and how long a day takes', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=8;");
|
||||
assert.equal(ev('diagPace()'), 'days: x8 asked · measuring');
|
||||
// A day every 400 ms (x8 asks one every 312.5), each taking 300 ms, one of them 700.
|
||||
ev('for(let i=0;i<14;i++){const t=1000+i*400;paceStart(t);paceEnd(t+(i===10?700:300));}');
|
||||
assert.equal(ev('diagPace()'), 'days: x8 asked · x6.3 held (one every 400 ms) · a day takes 333 ms, slowest 700');
|
||||
// Another speed: the measure starts again.
|
||||
ev('UI.speed=4;');
|
||||
assert.equal(ev('diagPace()'), 'days: x4 asked · measuring');
|
||||
ev('paceStart(9000);paceStart(9625);paceStart(10250);');
|
||||
assert.match(ev('diagPace()'), /^days: x4 asked · x4\.0 held \(one every 625 ms\)/);
|
||||
ev('UI.speed=0;');
|
||||
assert.equal(ev('diagPace()'), 'days: paused');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the clock with the worker feeds the measure and starts days as it always did', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();autoPause=()=>false;UI.speed=8;");
|
||||
// A stand-in worker day that ends at once: one day per 312.5 ms of clock, as before.
|
||||
ev(`window.__n=0;rwOn=()=>true;RW.w={postMessage(){},terminate(){}};rwDay=()=>{__n++;S.day++;rwDayDone();};
|
||||
for(let i=0;i<600;i++)runClock(1000/60);`);
|
||||
assert.equal(ev('__n'), Math.floor(600 * 1000 / 60 / 312.5), 'one day per 312.5 ms of clock');
|
||||
assert.equal(ev('PACE.st.length'), 13, 'the last days are measured');
|
||||
assert.match(ev('diagPace()'), /^days: x8 asked · x\d+\.\d held/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -1,19 +1,23 @@
|
|||
// 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.
|
||||
// way must be the day dayTick() plays, move for move, R.egDesc left out of the answers that repeat it and R.efg out of
|
||||
// the posts that would only send the worker its own, and a frame let through in the middle of each day. Also: the standing
|
||||
// orders' cache planner, now linear, plans the same boxes as the old formula.
|
||||
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 { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
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(),
|
||||
// The big network with an intern running every order, a failure and an event due soon, its circuits on scenic
|
||||
// routes, which read yesterday's R.efg, and renewal haggles the sales desk answers (slRenRun() routes after them). 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;
|
||||
const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(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.slAuto.ren=true;window.__ren=0;{const f=slRenOne;slRenOne=function(){__ren++;return f.apply(this,arguments);};}
|
||||
for(const b of S.biz.filter(b=>clOn(b)&&!BIZ_T[b.type].fiber).slice(0,20)){b.te=S.day+28;b.hag={rate:Math.round(b.rate*0.7),until:S.day+28};}
|
||||
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; };
|
||||
|
|
@ -25,18 +29,22 @@ function played(t) {
|
|||
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;
|
||||
// kept: answers that left R.egDesc out, the page keeping the one it has; lean: posts that left R.efg out, the worker
|
||||
// keeping its own.
|
||||
let kept = 0, lean = 0, rests = 0, delta = 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].efg===0')) lean++;
|
||||
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; };
|
||||
if (wk.ev('!!__out.R&&__out.R.egDesc===0')) kept++;
|
||||
if (wk.ev('!!(__out.R&&__out.R.egDesc&&__out.R.egDesc.dK!==undefined)')) delta++; page.ev('rwMsg(__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 };
|
||||
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('rwMsg(__a)'); };
|
||||
return { ...page, pump, pump1, kept: () => kept, lean: () => lean, rests: () => rests, delta: () => delta, trials: () => trials };
|
||||
}
|
||||
// R.egDesc too, key for key and in order.
|
||||
// R.egDesc too, key for key and in order: the worker sends only what changed in it.
|
||||
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 = [];
|
||||
|
|
@ -46,8 +54,8 @@ const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B =
|
|||
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.
|
||||
// The page itself never routes, the failure on day 3 (failureRun()), the sales desk's trials (offerTrial()) and its
|
||||
// renewal answers 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++) {
|
||||
|
|
@ -63,7 +71,11 @@ test('a day whose routings the worker answers is the day dayTick() plays', (t) =
|
|||
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('__ren') > 0 && p.ev('__ren') === ref.ev('__ren'), `renewal haggles the desk answered: ${p.ev('__ren')}`);
|
||||
assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes');
|
||||
assert.ok(p.kept() > 0 && p.kept() < served, `answers without R.egDesc: ${p.kept()} of ${served}`);
|
||||
assert.ok(p.delta() > 0, `answers with only what changed in R.egDesc: ${p.delta()}`);
|
||||
assert.ok(p.lean() > 0 && p.lean() < served, `posts without R.efg: ${p.lean()} of ${served}`);
|
||||
// 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');
|
||||
|
|
@ -99,7 +111,7 @@ test('an action while the worker routes stands; another network loaded mid-day g
|
|||
// 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();`);
|
||||
p.ev(`window.__old=S;S=migrate(JSON.parse(${lit(BIG)}));compute();`);
|
||||
const fresh = p.ev('JSON.stringify(S.hist)');
|
||||
p.pump();
|
||||
assert.equal(p.ev('JSON.stringify(S.hist)'), fresh);
|
||||
|
|
@ -200,7 +212,7 @@ test('a customer dropped while a sales trial routes: the trial runs again on the
|
|||
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);
|
||||
const pb=pniBatchRun;pniBatchRun=function*(...a){const b=yield* pb(...a);window.__b=b;return b;};
|
||||
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;`;
|
||||
|
|
@ -239,3 +251,61 @@ test('an incident repaired while its routing runs: the failure and the monkey st
|
|||
assert.equal(p.ev('typeof __c.impact'), 'number');
|
||||
assert.deepEqual(p.errors, []);
|
||||
});
|
||||
|
||||
test('the cache planner plans what the old formula planned, city by city', (t) => {
|
||||
const h = open(t, 777);
|
||||
h.ev(SETUP);
|
||||
// The formula as it was: the total share summed again for every network, the boxes filtered again for each.
|
||||
h.ev(`window.oldDem=(c,id)=>{const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;};
|
||||
window.oldPlan=city=>{const p=S.pops[city],sites=p.site2?['a','b']:['a'],add=[],have={};
|
||||
for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;}
|
||||
for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&oldDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0);
|
||||
sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}});
|
||||
const dem=oldDem(city,n.id),nb=cacheBox(city);
|
||||
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
|
||||
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
|
||||
return add;};`);
|
||||
// Some boxes gone, so there is something to plan; Russia, China and Korea's exit rule have tables of their own.
|
||||
h.ev("S.caches=S.caches.filter((c,i)=>i%3);S.krExit=true;for(const c of ['mos','pek','icn'])if(!S.pops[c])S.pops[c]={day:0,bb:{d:1},boost:0,down:0,routers:2,gen:true,rgen:0,site2:true};compute();");
|
||||
const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))'));
|
||||
let boxes = 0;
|
||||
for (const c of cities) {
|
||||
const got = h.ev(`JSON.stringify(utilityCaches('${c}').add)`);
|
||||
assert.equal(got, h.ev(`JSON.stringify(oldPlan('${c}'))`), c);
|
||||
boxes += JSON.parse(got).length;
|
||||
for (const id of JSON.parse(h.ev('JSON.stringify(NETS.map(n=>n.id))'))) if (h.ev(`cacheDem('${c}','${id}')!==oldDem('${c}','${id}')`)) assert.fail(`cacheDem ${c} ${id}`);
|
||||
}
|
||||
assert.ok(boxes > 50, `boxes planned: ${boxes}`);
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
||||
test('ports counted for every POP at once, and flows summed from the columns, are what each POP counted alone', (t) => {
|
||||
const h = open(t, 777);
|
||||
h.ev(SETUP);
|
||||
// The old ways: one pass over the whole network per POP, and the flows as objects (R.fl).
|
||||
h.ev(`window.oldPorts=(c,g)=>{let u=0;
|
||||
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);}
|
||||
for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1);
|
||||
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
|
||||
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
|
||||
if(S.myIx[c])u+=1;
|
||||
u+=cachePorts(c,[],g)+(S.nni||[]).filter(x=>x.city===c).length;return u;};
|
||||
window.oldFlows=c=>{const m={};for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
|
||||
o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;}return m;};`);
|
||||
const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))'));
|
||||
for (const g of ['undefined', '0', 'RG.length-1']) {
|
||||
const all = JSON.parse(h.ev(`JSON.stringify([...portsAt(Object.keys(S.pops),${g})])`));
|
||||
assert.deepEqual(all, cities.map((c) => [c, h.ev(`oldPorts('${c}',${g})`)]), `ports, router model ${g}`);
|
||||
}
|
||||
assert.ok(h.ev('Object.keys(S.pops).some(c=>portsUsed(c)>10)'));
|
||||
for (const c of cities) assert.equal(h.ev(`JSON.stringify(pniFlows('${c}'))`), h.ev(`JSON.stringify(oldFlows('${c}'))`), `flows from ${c}`);
|
||||
assert.ok(h.ev('Object.keys(S.pops).some(c=>Object.keys(pniFlows(c)).length>5)'));
|
||||
// The intern's weekly PNI round reads only pniVal()'s want, from typed columns (pniWant()): the very same numbers, for
|
||||
// every network at every POP (and 0 where no flow goes).
|
||||
const odd = h.ev(`(()=>{const bad=[];let n=0;for(const c in S.pops)for(const id of NET_IDS){const v=pniVal(id,c).want,w=pniWant(c,id);if(v>0)n++;
|
||||
if(!Object.is(v,w))bad.push(c+'/'+id+' '+v+' '+w);}return JSON.stringify({n,bad:bad.slice(0,5)});})()`);
|
||||
const r = JSON.parse(odd);
|
||||
assert.deepEqual(r.bad, [], 'pniWant() is pniVal().want');
|
||||
assert.ok(r.n > 50, `pairs with traffic: ${r.n}`);
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -103,7 +103,8 @@ test('on a 360 px phone the readout wraps inside the screen instead of running o
|
|||
try {
|
||||
ev('diagOn(true)');
|
||||
const st = ev('document.getElementById("diag").style.cssText');
|
||||
assert.match(st, /max-width: calc\(100vw - 32px\)/);
|
||||
// jsdom 31 serializes calc() with its terms sorted (calc(-32px + 100vw)); a browser keeps them as written.
|
||||
assert.match(st, /max-width: calc\((100vw - 32px|-32px \+ 100vw)\)/);
|
||||
assert.match(st, /white-space: pre-wrap/);
|
||||
assert.match(st, /pointer-events: none/, 'it never takes a tap meant for the map');
|
||||
} finally { h.done(); }
|
||||
|
|
|
|||
|
|
@ -175,6 +175,31 @@ test('slots: lit channels, sold alien waves and express channels share every lin
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the capacity market and moving customers leave the slots expresses hold; a path over an express shares its fibers\' trenches', (t) => {
|
||||
const { ev, errors } = game(t);
|
||||
ev("L(s1).ch=Array(61).fill('zr4');for(const c of ['fra','bru','par'])S.pops[c].routers=4;compute()");
|
||||
ev(BUILD);
|
||||
assert.equal(ev('xpSlots(L(s1))'), 1);
|
||||
assert.equal(ev('freeCh(L(s1))'), 2, '64 slots: 61 lit, 1 express');
|
||||
// Spectrum the broker can sell (Lambda Bazaar) is what is free after the express, never the express's own slot.
|
||||
assert.equal(ev("cmCan(L(s1),'spec')"), 2);
|
||||
assert.equal(ev("cmSpare(L(s1),'spec',0)"), 2);
|
||||
ev("ACT.listFiber({id:s1,w:3})");
|
||||
assert.equal(ev('(L(s1).list||{}).w||0'), 2, 'a listing stops at the free slots');
|
||||
// A carrier with three alien waves on a parallel fiber cannot move onto s1: the express holds the slot it would need.
|
||||
ev("window.s3=df('fra','bru');S.biz.push({id:'aw',city:'fra',city2:'bru',link:s3,slots:3,type:'wwave',name:'Alien Co',bw:1,rate:1000,reqs:[],mood:100,since:S.day,day:S.day,route:'normal',what:'x'});compute()");
|
||||
assert.match(ev("(fiberTargets(S.biz.find(b=>b.id==='aw')).find(o=>o.l.id===s1)||{}).no||''"), /2/, 'only 2 free channels there');
|
||||
ev("ACT.pathMove({id:'aw',link:s1})");
|
||||
assert.equal(ev("S.biz.find(b=>b.id==='aw').link"), ev('s3'), 'refused');
|
||||
// A circuit pinned through Brussels' router rides s1 and s2; the express to Paris runs in those very trenches.
|
||||
ev("L(s2).ch=['zr4'];compute();S.biz.push({id:'k',type:'l2vpn',name:'Big Circuit',city:'fra',city2:'par',bw:1,rate:10,reqs:[],mood:80,since:0,day:0,route:'normal',pin:['fra','bru','par']});compute()");
|
||||
const alts = JSON.parse(ev("JSON.stringify(circuitTargets(S.biz.find(b=>b.id==='k')).alts.map(a=>[a.p.join('>'),a.shared]))"));
|
||||
assert.deepEqual(alts, [['fra>par', 1]], 'the express is offered, sharing its one span with the path through Brussels');
|
||||
ev("ACT.pathOpen({id:'k'})");
|
||||
assert.doesNotMatch(ev("document.getElementById('modal').textContent"), /Fully diverse/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves: an express survives a round trip; one whose fibers are gone is dropped and its optics go on the shelf', (t) => {
|
||||
const { ev, errors } = game(t);
|
||||
// A save from before expresses existed loads as it always did.
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ test('a route\'s market follows the eyeballs at both ends, and a landing town co
|
|||
assert.ok(ev("brMarket('nyc','bde')") > ev("brMarket('nyc','gdx')"));
|
||||
});
|
||||
|
||||
// The market moves (37-fiber-market.js): demand has its own cycle and grows, so days pass here; at its hottest a route
|
||||
// wants CM_HMAX times its usual spectrum.
|
||||
test('a listing sells over time, never past the market, and rent from a road to nowhere stays small', () => {
|
||||
const { ev, errors } = load();
|
||||
start(ev);
|
||||
|
|
@ -23,11 +25,11 @@ test('a listing sells over time, never past the market, and rent from a road to
|
|||
fiber(ev, 'far', 'jed', 'gdx', 9089);
|
||||
ev("__reseed(7);ACT.listFiber({id:'big',w:60});ACT.listFiber({id:'far',w:60})");
|
||||
assert.equal(ev("S.biz.length"), 0, 'nothing sells the moment it is listed');
|
||||
ev('for(let d=0;d<720;d++)brTick()');
|
||||
ev('for(let d=0;d<720;d++){S.day++;brTick();}');
|
||||
const sold = (id) => ev(`S.biz.filter(b=>b.link==='${id}').reduce((a,b)=>a+(b.slots||0),0)`);
|
||||
assert.ok(sold('big') >= 3, `Frankfurt–Amsterdam sold ${sold('big')}`);
|
||||
assert.ok(sold('big') <= ev("brMarket('fra','ams')"), 'never more than the route wants');
|
||||
assert.equal(sold('far'), 1, 'Jeddah–Magadan: one wave, then the market is full');
|
||||
assert.ok(sold('big') <= ev("brMarket('fra','ams')*0.5*CM_HMAX*Math.pow(cmGrowth(S.day),0.7)"), 'never more than the route wants at its hottest');
|
||||
assert.ok(sold('far') >= 1 && sold('far') <= 2, `Jeddah–Magadan: a wave or two, then the market is full (${sold('far')})`);
|
||||
assert.equal(ev("brFree(S.links.find(l=>l.id==='far'))"), 0);
|
||||
// random alien-wave offers respect the market too
|
||||
ev("S.offers=[];for(let i=0;i<400;i++)spawnOffer()");
|
||||
|
|
|
|||
69
tests/fiber-lit-and-latency.test.js
Normal file
69
tests/fiber-lit-and-latency.test.js
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
// A fiber's capacity added up per run of identical optics, "is this fiber lit?" answered without adding it up
|
||||
// (dfOn(), linkDown()), and latency searches over one list of each city's links (latGraph(), latRun(), latPairs():
|
||||
// bestLat(), the boutique's routes, latency offers). Same answers as before: the old ways are written out here.
|
||||
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 { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
// The fixture's links as the player's own dark fiber (it has none), lit with 2 to 40 channels of one or two optics.
|
||||
const GLASS = "S.links.forEach((l,i)=>{l.kind='df';l.own=true;l.sys='roadm';l.ready=0;l.regen=3;const o=['zr4','zr8','tp16','tp32'][i%4];l.ch=Array.from({length:2+i%39},(_,j)=>i%5===0&&j%3===0?'zr4':o);delete l.tier;})";
|
||||
// Before: every channel's optG() added up, and the search that walked every link for every city it reached.
|
||||
const OLD = `window.oldCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,Math.max(0,g)-mwG(l));};
|
||||
window.oldLat=(a,b,f)=>{const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;};`;
|
||||
// Seeded trouble on the fibers: cuts, a failed optic (named or not, over or not, maybe the only one), equipment down, still building,
|
||||
// channels taken out or mixed, a subsea upgrade in service, managed waves sold on it (sometimes more than it carries).
|
||||
const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day;
|
||||
for(const l of S.links){const r=rnd();if(r<.06)l.cut=D+5;else if(r<.14){if(rnd()<.4)l.ch=l.ch.slice(0,1);l.chFail={o:rnd()<.5&&l.ch.length?l.ch[l.ch.length-1]:rnd()<.5?'tp32':null,until:rnd()<.8?D+3:D-1};}
|
||||
else if(r<.18)l.eqDown=D+2;else if(r<.22)l.ready=D+4;else if(r<.28)l.ch=l.ch.slice(0,Math.floor(rnd()*3));else if(r<.32)l.ch=l.ch.map((c,i)=>i%2?c:'zr8');
|
||||
else if(r<.36){l.sub=true;l.km=2000+Math.floor(rnd()*9000);if(rnd()<.5)l.subterminal=D-1;if(rnd()<.5)l.subengineering=D-1;}
|
||||
if(rnd()<.15)S.biz.push({type:'mwave',link:l.id,slots:1+Math.floor(rnd()*30),g:rnd()<.5?100:400});}})()`;
|
||||
|
||||
test('a fiber is lit, and carries, what adding up every channel said', () => {
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${GLASS};${OLD}`);
|
||||
let lit0 = 0, dark = 0;
|
||||
for (let v = 0; v < 6; v++) {
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(v)};S.day+=${v}`);
|
||||
const r = JSON.parse(ev(`JSON.stringify(S.links.map(l=>[oldCap(l),dfCap(l),dfOn(l),linkDown(l),l.cut>S.day]))`));
|
||||
for (const [want, cap, on, down, cut] of r) {
|
||||
assert.equal(cap, want);
|
||||
assert.equal(on, want > 0);
|
||||
assert.equal(down, cut || !(want > 0));
|
||||
if (on) lit0++; else dark++;
|
||||
}
|
||||
}
|
||||
assert.ok(lit0 > 600 && dark > 30, `lit ${lit0}, dark ${dark}`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('latency searches give what walking every link gave: bestLat, every pair at once, the boutique\'s routes', () => {
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
|
||||
const P = "Object.keys(S.pops).slice(0,25).concat(FIN.filter(c=>S.pops[c]))";
|
||||
const check = (f) => JSON.parse(ev(`(()=>{const P=${P},f=${f},bad=[];let n=0;
|
||||
for(let i=0;i<P.length;i++)for(let j=i+1;j<P.length;j++){const w=oldLat(P[i],P[j],f);if(bestLat(P[i],P[j],f)!==w)bad.push(P[i]+'-'+P[j]);if(isFinite(w))n++;}
|
||||
for(const [a,b,ms] of latPairs(P,f))if(ms!==oldLat(a,b,f))bad.push('pairs '+a+'-'+b);return JSON.stringify({n,bad:bad.slice(0,5)});})()`));
|
||||
// Leased waves, then some cut, then the player's own glass in trouble.
|
||||
let r = check('null');
|
||||
assert.deepEqual(r.bad, []);
|
||||
assert.ok(r.n > 150, `pairs with a path: ${r.n}`);
|
||||
ev("S.links.forEach((l,i)=>{if(i%4===0)l.cut=S.day+3;})");
|
||||
r = check("l=>l.kind!=='vxc'");
|
||||
assert.deepEqual(r.bad, []);
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(2)};S.mode='normal';delete S.scn;S.charter='boutique'`);
|
||||
r = check('ownGlass');
|
||||
assert.deepEqual(r.bad, []);
|
||||
assert.ok(r.n > 50, `pairs over own glass: ${r.n}`);
|
||||
// The boutique's routes: each financial pair, its own glass against the best leased latency. In trouble, then not.
|
||||
const SOL = `(()=>{const f=FIN.filter(c=>S.pops[c]),v=[];for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],o=oldLat(a,b,ownGlass),l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}return JSON.stringify(v);})()`;
|
||||
assert.equal(ev('SOLC=null;JSON.stringify(solRoutes())'), ev(SOL));
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};S.mode='normal';delete S.scn;S.charter='boutique'`);
|
||||
const want = ev(SOL);
|
||||
assert.equal(ev('SOLC=null;JSON.stringify(solRoutes())'), want);
|
||||
assert.ok(JSON.parse(want).length >= 1, `routes that beat leased: ${want}`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
2
tests/fixtures/mp-sim/snap.json
vendored
2
tests/fixtures/mp-sim/snap.json
vendored
File diff suppressed because one or more lines are too long
2
tests/fixtures/mp-sim/upd-act.json
vendored
2
tests/fixtures/mp-sim/upd-act.json
vendored
File diff suppressed because one or more lines are too long
2
tests/fixtures/mp-sim/upd-day.json
vendored
2
tests/fixtures/mp-sim/upd-day.json
vendored
File diff suppressed because one or more lines are too long
|
|
@ -1,8 +1,33 @@
|
|||
// 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.
|
||||
// The map's frame pacing (src/game/99-loop.js, mapStill()): while only the animation clock moves, the map is drawn at
|
||||
// most 30 times a second; anything else that moves gets every frame; paused, it is drawn about once a second.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A second of frames at 60 Hz (each() runs before every frame), and how many of them drew the map.
|
||||
const second = (ev, each = '') => ev(`(()=>{let n=0;const d=draw;draw=t=>{n++;return d(t);};
|
||||
try{for(let i=0;i<60;i++){window.__now=(window.__now||1000)+1000/60;${each};frame(__now);}}finally{draw=d;}return n;})()`);
|
||||
|
||||
test('ambient frames are drawn at most 30 times a second, the camera moving gets them all, paused about one', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;ACT.launchBB({city:'fra'});closeModal();UI.anim='on';UI.speed=1;autoPause=()=>false;");
|
||||
second(ev); // the land picture and the first frames settle
|
||||
const ambient = second(ev);
|
||||
assert.ok(ambient >= 28 && ambient <= 31, `ambient: ${ambient} draws`);
|
||||
assert.equal(second(ev, 'cam.x+=0.5'), 60, 'the camera moving');
|
||||
assert.equal(second(ev, "UI.hover=UI.hover==='fra'?null:'fra'"), 60, 'the pointer over a city and off it');
|
||||
ev('UI.speed=0');
|
||||
second(ev);
|
||||
const paused = second(ev);
|
||||
assert.ok(paused <= 2, `paused: ${paused} draws`);
|
||||
ev("UI.anim='off';UI.speed=1");
|
||||
second(ev);
|
||||
assert.ok(second(ev) <= 2, 'animations off: nothing moves, nothing to draw');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A day's steps on the page take half a frame at most before letting one through (RW.budget, rwGo()): 8 ms on a 60 Hz
|
||||
// screen, 3 ms on a 240 Hz one. One long frame (a big save, a tab switch) does not move it much.
|
||||
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;");
|
||||
|
|
@ -29,3 +54,41 @@ test("a device that cannot hold 50 frames a second gives a day half its frame, 3
|
|||
});
|
||||
|
||||
// The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one
|
||||
// asks: the very map one go would build. One that asks halfway finishes it at once.
|
||||
test('idle frames build the diverse-paths map in slices, the same map as in one go', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;");
|
||||
const sig = "JSON.stringify([diversityMap.key,diversityMap.links,diversityMap.adj])";
|
||||
ev('diversityMap=null;DIVW=null;diversityPossible("fra","ams");');
|
||||
const once = ev(sig);
|
||||
ev('diversityMap=null;DIVW=null;');
|
||||
let frames = 0;
|
||||
for (; frames < 2000 && ev('!diversityMap'); frames++) ev('window.__now=(window.__now||1000)+4;diversityWarm(0.05);');
|
||||
assert.ok(frames > 3, `built over several frames: ${frames}`);
|
||||
assert.equal(ev(sig), once, 'the same map');
|
||||
// Halfway, an offer asks: the rest is built at once, and it is still the same map.
|
||||
ev('diversityMap=null;DIVW=null;diversityWarm(0.05);');
|
||||
assert.equal(ev('!diversityMap&&!!DIVW'), true, 'half built');
|
||||
assert.equal(ev('typeof diversityPossible("fra","ams")'), 'boolean');
|
||||
assert.equal(ev(sig), once, 'finished at once, the same map');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// The latency floors latency customers are offered against (80-geography-and-latency.js) are worked out ahead too, a
|
||||
// few cities a frame, your POPs first: the same numbers as working one out when asked, even halfway through one.
|
||||
test('idle frames work the latency floors out ahead, the same numbers as when asked', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;ACT.buildPop({city:'ams'});");
|
||||
const ref = ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(latFloor0(c))))");
|
||||
ev('LATF.clear();LATW=null;');
|
||||
let n = 0;
|
||||
for (; n < 5000 && !(ev("LATF.has('fra')&&LATF.has('ams')&&LATF.has('nyc')")); n++) ev('latWarm(0.05)');
|
||||
assert.ok(n > 3, `over several frames: ${n}`);
|
||||
assert.equal(ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(LATF.get(c))))"), ref, 'the same floors');
|
||||
// Halfway through a city, an offer asks about it: finished at once, the same numbers.
|
||||
ev("LATF.clear();LATW=null;latWarm(0.01);");
|
||||
const a = ev('LATW&&LATW.a');
|
||||
assert.ok(a, 'a city half done');
|
||||
assert.equal(ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor('${a}',b)))`), ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor0('${a}')[CIDX[b]]))`));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -453,8 +453,11 @@ test('F5: rented capacity never outgrows the route\'s market (#203)', () => {
|
|||
const g = load();
|
||||
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.biz=[];S.offers=[];for(const c of ['jed','gdx'])ACT.buildPop({city:c})");
|
||||
g.ev("S.links.push({id:'f',a:'jed',b:'gdx',kind:'df',own:true,sys:'roadm',ch:[],km:9089,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});compute();__reseed(5);ACT.listFiber({id:'f',w:120,p:1})");
|
||||
g.ev('for(let d=0;d<1500;d++){brTick();if(d%7===0)spawnOffer();}for(const o of S.offers.filter(o=>o.link===\'f\'))ACT.accept({id:o.id})');
|
||||
assert.ok(g.ev("brSold('jed','gdx')") <= g.ev("brMarket('jed','gdx')"), 'F5: no more than the route wants');
|
||||
g.ev('for(let d=0;d<1500;d++){S.day++;brTick();if(d%7===0)spawnOffer();}for(const o of S.offers.filter(o=>o.link===\'f\'))ACT.accept({id:o.id})');
|
||||
// The market moves and grows (37-fiber-market.js): never more than the route wants at its hottest, today.
|
||||
const most = g.ev("Math.max(brMarket('jed','gdx'),Math.round(brMarket('jed','gdx')*0.5*CM_HMAX*Math.pow(cmGrowth(S.day),0.7)))");
|
||||
assert.ok(g.ev("brSold('jed','gdx')") <= most, `F5: no more than the route wants (${g.ev("brSold('jed','gdx')")} of ${most})`);
|
||||
assert.ok(g.ev("brSold('jed','gdx')") <= 3, 'a road to nowhere still sells only a little');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
|
|
@ -483,6 +486,26 @@ test('F7: extra crews cut a build on land to half its planned time at most (#203
|
|||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
test('F8: a managed wave costs your own capacity, rides one optic, and is priced against its fiber', () => {
|
||||
const g = load();
|
||||
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[];for(const c of ['fra','ams'])if(!S.pops[c])ACT.buildPop({city:c})");
|
||||
g.ev("S.links.push({id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'cl',ch:['zr4','zr4'],km:400,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});compute()");
|
||||
const r = "cmRoutes().get('ams|fra')";
|
||||
for (const [p, land, sea] of [['w400', 2.7, 3.8], ['w800', 4.6, 6.6], ['w1600', 7.8, 11]]) {
|
||||
assert.ok(Math.abs(g.ev(`cmList(${r},'${p}')/cmList(${r},'w100')`) - land) < 1e-9, `F8: ${p} on land`);
|
||||
assert.ok(Math.abs(g.ev(`(()=>{const x={...${r},sub:true};return cmList(x,'${p}')/cmList(x,'w100')})()`) - sea) < 1e-9, `F8: ${p} on subsea`);
|
||||
}
|
||||
for (let i = 1; i < 4; i++) assert.ok(g.ev(`cmList(${r},CM_W[${i}])/CM_G[CM_W[${i}]]<cmList(${r},CM_W[${i - 1}])/CM_G[CM_W[${i - 1}]]`), 'F8: cheaper per bit');
|
||||
assert.ok(Math.abs(g.ev(`cmList(${r},'spec')/(dfLeaseMo(400)+ampCount(400)*AMP_MO)`) - 0.3) < 1e-9, 'F8: spectrum lists at 30%');
|
||||
for (let d = 0; d < 720; d += 9) { const x = g.ev(`cmIdx(${r},'spec',0,0,${d})`); assert.ok(x >= 0.7 - 1e-9 && x <= 1.35 + 1e-9, `F8: heat moves a price by ${x}`); }
|
||||
assert.equal(g.ev("cmSpare(S.links[S.links.length-1],'w800',0)"), 0, 'F8: no 800G wave on 400G optics');
|
||||
g.ev("cmSell(S.links[S.links.length-1],'w400',1,100,0);compute()");
|
||||
assert.equal(g.ev("dfLit(S.links[S.links.length-1])-dfCap(S.links[S.links.length-1])"), 400, 'F8: it comes out of your own capacity');
|
||||
g.ev("S.links[S.links.length-1].ch=[]");
|
||||
assert.equal(g.ev("fiberOk(S.biz.find(b=>b.type==='mwave'))"), false, 'F8: unlit, its customer is down');
|
||||
assert.deepEqual(g.errors, []);
|
||||
});
|
||||
|
||||
// D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail.
|
||||
const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()");
|
||||
const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`);
|
||||
|
|
@ -652,7 +675,7 @@ test('O7: a fresh Tier 1 cannot afford a full Shortcrust in its first year', ()
|
|||
// most the Ex-Im Pie Bank lends a rocket company on top.
|
||||
const g = load();
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`);
|
||||
g.ev(`S=migrate(JSON.parse(${lit(save)}));compute()`);
|
||||
const rev = g.ev('R.revMo'), loan = g.ev('Math.max(...Object.values(BANKS).map(b=>b.amt[1]))') * rev + g.ev('pieEximCap()'), cash = Math.max(0, g.ev('S.cash'));
|
||||
const year = 12 * rev + loan + Math.min(cash, 12 * rev);
|
||||
const full = g.ev("pieFullCost('short')");
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ function split(html) {
|
|||
let s = SPLIT.get(html);
|
||||
if (s) return s;
|
||||
const code = [];
|
||||
const shell = html.replace(/<script>([\s\S]*?)<\/script>/g, (m, src) => {
|
||||
const shell = html.replace(/<script>([\s\S]*?)<\/script\b[^>]*>/gi, (m, src) => {
|
||||
code.push(new vm.Script(src, { filename: `page-script-${code.length}.js` }));
|
||||
return '<script></script>';
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
// Deliberately scan all exits for every flow, without byRank, local-city
|
||||
// shortcuts or first-group selection. Stable sorting preserves E order on ties.
|
||||
// Without Auto-TE, an exit whose shortest path from this POP is already full fits nothing, so it counts as
|
||||
// unusable, like a full exit (#210).
|
||||
// unusable, like a full exit (#210). It runs inside the routing core (29-route-core.js), which reads what exits have
|
||||
// used from its columns (USED, CAPX) and sends to exits by number (xi).
|
||||
module.exports = `
|
||||
// A carrier's own port (dr) is also a plain transit exit. A POP with a Prefer-marked transit port keeps what Prefer
|
||||
// says, and a port not set to carry only takes its own POP's traffic.
|
||||
|
|
@ -13,14 +14,14 @@ module.exports = `
|
|||
for(F=0;F<NF;F++){fci=FCI[F];fnj=FNJ[F];const n=NET_IDS[fnj];
|
||||
if(FREM[F]<=1e-6||(rank===0&&!FCA[F])||(pass===1&&!FBZ[F])||(pass===2&&FBZ[F]))continue;
|
||||
Dv=SDi[fci];Pv=SPi[fci];PP=walked[fci]||(walked[fci]=[]);vis++;
|
||||
const candidates=E.filter(e=>e.used<e.cap&&e.ok(n)&&
|
||||
const candidates=E.filter(e=>USED[e.xi]<CAPX[e.xi]&&e.ok(n)&&
|
||||
((TR?eff(e,n):base(e,n))===rank||(dr(e,fci,n)||-1)===rank)&&
|
||||
(rank!==DIRECT_RANK[1][1]&&rank!==DIRECT_RANK[2][1]||CIDX[e.city]===fci)&&Dv[CIDX[e.city]]<Infinity&&!gone(e))
|
||||
(rank!==DIRECT_RANK[1][1]&&rank!==DIRECT_RANK[2][1]||CIDX[e.city]===fci)&&Dv[CIDX[e.city]]<Infinity&&!gone(e.xi))
|
||||
.sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]+(tie(a)-tie(b)));
|
||||
for(let i=0;i<candidates.length&&FREM[F]>1e-6;){
|
||||
let j=i+1;while(j<candidates.length&&(candidates[j].pref==='high')===(candidates[i].pref==='high')&&
|
||||
Math.abs(Dv[CIDX[candidates[j].city]]-Dv[CIDX[candidates[i].city]]+(tie(candidates[j])-tie(candidates[i])))<1e-6)j++;
|
||||
sendGroup(candidates.slice(i,j));i=j;
|
||||
sendGroup(candidates.slice(i,j).map(e=>e.xi));i=j;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
64
tests/intern-dark-fiber-worker.test.js
Normal file
64
tests/intern-dark-fiber-worker.test.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
// The intern's line system swap asks first whether a day without the fiber still serves everything (opsDark(),
|
||||
// 95-standing-orders.js). That test routes the whole network: in play the route worker answers it, like a sales trial,
|
||||
// so the shift never routes on the page. jsdom has no Worker: a second page plays it (rwServe()), messages cloned both
|
||||
// ways. The shift played that way is the shift opsDay() plays; an action while the worker routes makes the page test again.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// tests/intern-optical-upgrade.test.js's network: a full, hot fiber Frankfurt–Amsterdam and the long way round through
|
||||
// Paris on two waves, big enough (tier 4) to carry the day without the fiber, or not (tier 0).
|
||||
const base = tier => "Date.now=()=>1.7e12;ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
|
||||
"for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}ACT.launchBB({city:'ams'});" +
|
||||
"S.transit=[];ACT.buyTransit({city:'fra',net:'cog',tier:2});" +
|
||||
"S.links=[{id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(16).fill('zr4'),km:450,trench:'t1',ready:0,cut:0,mo:1,pairs:1}," +
|
||||
`{id:'w1',a:'fra',b:'par',kind:'wave',tier:${tier},km:480,cut:0,mo:1},{id:'w2',a:'par',b:'ams',kind:'wave',tier:${tier},km:430,cut:0,mo:1}];compute();` +
|
||||
"ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap.optup=0;closeModal();S.ops.on.optup=true;S.ops.p.optup={at:80};R.load.f=dfCap(S.links[0])*0.9";
|
||||
const open = (t) => { const h = load(); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; };
|
||||
// The page with a stand-in worker (tests/day-steps.test.js): what it posts waits until pump() hands it to the other page.
|
||||
function played(t, tier) {
|
||||
const page = open(t), wk = open(t);
|
||||
page.ev(base(tier));
|
||||
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;}});');
|
||||
page.ev('window.__pc=0;{const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};}');
|
||||
wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};');
|
||||
let dark = 0;
|
||||
const one = () => { if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) dark++; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); };
|
||||
const pump = () => { for (;;) { if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; } if (!page.ev('__q.length')) break; one(); } };
|
||||
return { ...page, pump, one, dark: () => dark };
|
||||
}
|
||||
const STATE = "JSON.stringify({links:S.links,cash:S.cash,log:S.ops.log,spent:S.ops.spent,no:OPTUP_NO.get('f')??null,served:R.served})";
|
||||
|
||||
for (const [tier, sys] of [[4, 'roadm'], [0, 'lite']]) {
|
||||
test(`the dark fiber test goes to the worker and plays as on the page (waves of tier ${tier}: ${sys})`, (t) => {
|
||||
const ref = open(t), p = played(t, tier);
|
||||
ref.ev(base(tier));
|
||||
ref.ev('opsDay(S.day)');
|
||||
p.ev('rwGo(opsRun(S.day))');
|
||||
assert.equal(p.ev('!!(__q.length||__later.length)'), true, 'the shift waits for the worker');
|
||||
p.pump();
|
||||
assert.equal(p.ev('!!RW.job'), false, 'the shift is over');
|
||||
assert.equal(p.ev(STATE), ref.ev(STATE));
|
||||
assert.equal(p.ev('S.links[0].sys'), sys);
|
||||
assert.equal(p.dark(), 1, 'the worker tested the fiber dark');
|
||||
assert.equal(p.ev('__pc'), 0, 'no routing on the page');
|
||||
assert.equal(p.ev("S.links[0].eqDown===undefined||S.links[0].eqDown>S.day"), true);
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
}
|
||||
|
||||
test('an action while the worker tests the fiber: the page tests it again on the game as it is', (t) => {
|
||||
const ref = open(t), p = played(t, 4);
|
||||
ref.ev(base(4));
|
||||
ref.ev('opsDay(S.day)');
|
||||
p.ev('rwGo(opsRun(S.day))');
|
||||
// Up to the dark fiber's trial, then an action (it routes on the page, as always), then the worker's stale answer.
|
||||
for (let i = 0; i < 50 && !p.ev('!!(__q[0]&&__q[0].trial&&__q[0].trial.dark)'); i++) { if (p.ev('__later.length')) p.ev('__later.shift()()'); else if (p.ev('__q.length')) p.one(); else break; }
|
||||
assert.equal(p.ev('!!(__q[0].trial&&__q[0].trial.dark)'), true, 'the trial is in flight');
|
||||
p.ev('__pc=0;after()');
|
||||
p.pump();
|
||||
assert.equal(p.ev('__pc'), 2, "the action's routing, and the test made again here");
|
||||
assert.equal(p.ev(STATE), ref.ev(STATE));
|
||||
assert.equal(p.ev('S.links[0].sys'), 'roadm');
|
||||
assert.deepEqual([...ref.errors, ...p.errors], []);
|
||||
});
|
||||
|
|
@ -37,7 +37,7 @@ test('Annie peers every day and orders PNIs twice a week; the others weekly', t
|
|||
ev("S.ops.on.ix=true;S.day=15;opsDay(S.day)");
|
||||
assert.equal(ev('Object.keys(S.rs).length>0'), want, `${id} on a Tuesday`);
|
||||
// How often the PNI order looks for networks to order from, over one week.
|
||||
ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
|
||||
ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};if(typeof pniBatchRun==='function')pniBatchRun=function*(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
|
||||
assert.equal(ev('__pb'), want ? 2 : 1, `${id}: PNI rounds a week`);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1274,7 +1274,10 @@ test('#51 a dark fiber shows what is rented out, and spare capacity can be liste
|
|||
ev("for(let i=0;i<120&&!S.biz.some(b=>b.link==='df1');i++)brTick();renderPanel()");
|
||||
const b = JSON.parse(ev("JSON.stringify(S.biz.find(x=>x.link==='df1'))"));
|
||||
assert.equal(b.type, 'wwave');
|
||||
assert.equal(b.rate, ev(`(()=>{const F=dfLeaseMo(450)+ampCount(450)*AMP_MO,M=brMarket('fra','ams');let r=0;for(let i=0;i<${b.slots};i++)r+=F*WW_SHARE*(1-WW_FALL*Math.min(1,i/M));return Math.round(r*0.9)})()`), 'the alien-wave price, priced against the fiber, minus the broker');
|
||||
// The capacity market prices it (37-fiber-market.js): 30% of the fiber's cost a month, moved by how hot the route is
|
||||
// and how full, minus the broker.
|
||||
assert.equal(b.rate, ev(`(()=>{const r=cmRoutes().get('ams|fra');let x=0;for(let i=0;i<${b.slots};i++)x+=cmList(r,'spec')*cmIdx(r,'spec',0,i,S.day);return Math.round(x*0.9*mkt())})()`), 'the alien-wave price, priced against the fiber, minus the broker');
|
||||
assert.ok(Math.abs(ev("cmList(cmRoutes().get('ams|fra'),'spec')/(dfLeaseMo(450)+ampCount(450)*AMP_MO)") - 0.3) < 1e-9);
|
||||
assert.ok(txt().includes(b.name), 'the customer is listed on the fiber');
|
||||
assert.match(txt(), new RegExp(`Free channels\\s*${62 - b.slots} / 64`));
|
||||
assert.equal(ev("S.links[0].list?S.links[0].list.w:0"), 4 - b.slots, 'the listing shrinks by what sold');
|
||||
|
|
|
|||
|
|
@ -6,12 +6,13 @@ const assert = require('node:assert/strict');
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
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();`);
|
||||
ev(`S=migrate(JSON.parse(${lit(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)});})()`));
|
||||
|
|
|
|||
75
tests/lay-ship-delay.test.js
Normal file
75
tests/lay-ship-delay.test.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// #322: a construction delay that hits your own subsea cable while the lay ship is at sea holds the ship where it is.
|
||||
// It used to move the whole laying stretch later: the ship vanished, the laid km went back to zero and the survey and
|
||||
// factory could be hurried (and paid for) all over again.
|
||||
const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.day=200;S.nextFail=S.nextEvent=1e8;for(const g of GOALS)S.done[g.id]=0;";
|
||||
const own = "S.links=[{id:'own',a:'cpt',b:'bue',kind:'df',own:true,sub:true,sys:'roadm',km:6000,ch:[],day:200,ready:800,cut:0,mo:1}];";
|
||||
|
||||
test('#322 a delay while laying holds the lay ship; it does not start over', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev(start + own);
|
||||
assert.equal(ev('layStart(S.links[0])'), 760);
|
||||
ev("S.day=770");
|
||||
const laid = ev('layDone(S.links[0],S.day)');
|
||||
assert.equal(laid, 0.25);
|
||||
// A storm: 20 days late, as the daily construction delay does it.
|
||||
ev("setCableReady(S.links[0],S.links[0].ready+20)");
|
||||
assert.equal(ev('S.links[0].ready'), 820);
|
||||
assert.ok(ev('S.day>=layStart(S.links[0])'), 'still laying: the ship stays on the map');
|
||||
assert.equal(ev('layDone(S.links[0],S.day)'), laid, 'nothing laid is lost');
|
||||
assert.equal(ev('prepSteps(S.links[0])'), 0, 'no paying for the survey and factory again');
|
||||
assert.equal(ev('layQuote(S.links[0])'), null);
|
||||
ev("UI.sel={type:'link',id:'own'};renderPanel()");
|
||||
const panel = () => dom.window.document.querySelector('#panelBody').textContent;
|
||||
assert.match(panel(), /at sea, laying/);
|
||||
assert.match(panel(), /1,500 of 6,000 km/);
|
||||
assert.doesNotMatch(panel(), /Survey, permits and the cable factory|Hurry/);
|
||||
// The ship waits out the delay, then lays the other 30 days' worth, never going backwards.
|
||||
let prev = laid;
|
||||
for (let d = 770; d < 820; d++) {
|
||||
ev('S.day=' + d);
|
||||
const q = ev('layDone(S.links[0],S.day)');
|
||||
assert.ok(q >= prev, `day ${d}: ${q} < ${prev}`);
|
||||
assert.ok(ev('S.day>=layStart(S.links[0])'), `day ${d}: the ship is at sea`);
|
||||
if (d <= 790) assert.equal(q, laid, `day ${d}: waiting out the storm`);
|
||||
prev = q;
|
||||
}
|
||||
assert.equal(ev('layDone(S.links[0],819.5)') < 1, true);
|
||||
assert.equal(ev('layDone(S.links[0],820)'), 1);
|
||||
// A second delay during the wait adds to it.
|
||||
ev(start + own + "S.day=770;setCableReady(S.links[0],810);S.day=780;setCableReady(S.links[0],820)");
|
||||
assert.equal(ev('S.links[0].lay.t'), 790, 'held until 780, then 10 days more');
|
||||
assert.equal(ev('layDone(S.links[0],790)'), 0.25);
|
||||
assert.ok(ev('layDone(S.links[0],791)') > 0.25);
|
||||
assert.equal(ev('layDone(S.links[0],820)'), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#322 a held lay ship survives a save, and bad saved values are repaired', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start + own + "S.day=770;setCableReady(S.links[0],820)");
|
||||
const q = ev('layDone(S.links[0],795)');
|
||||
ev('S=migrate(JSON.parse(JSON.stringify(S)))');
|
||||
assert.equal(ev('layDone(S.links[0],795)'), q);
|
||||
assert.equal(ev('layDone(S.links[0],770)'), 0.25);
|
||||
// Junk from an edited save, or on a cable that is not your own subsea build, goes away.
|
||||
ev("S.links[0].lay={s:'x',q:7,t:-5};S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
const l = JSON.parse(ev('JSON.stringify(S.links[0].lay)'));
|
||||
assert.ok(l.q >= 0 && l.q <= 1 && l.s <= 770 && l.t <= 820, JSON.stringify(l));
|
||||
ev("S.links[0].lay=[1];S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.links[0].lay'), undefined);
|
||||
ev("S.links[0].sub=false;S.links[0].lay={s:760,q:.5,t:790};S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('S.links[0].lay'), undefined);
|
||||
// A finished cable drops it.
|
||||
ev(start + own + "S.day=770;setCableReady(S.links[0],820);S.day=819;dayTick()");
|
||||
assert.equal(ev('S.links[0].ready<=S.day'), true);
|
||||
assert.equal(ev('S.links[0].lay'), undefined);
|
||||
// Old saves (no lay field) lay as before.
|
||||
ev(start + own + "S=migrate(JSON.parse(JSON.stringify(S)))");
|
||||
assert.equal(ev('layStart(S.links[0])'), 760);
|
||||
assert.equal(ev('layDone(S.links[0],780)'), 0.5);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
39
tests/link-modal-no-cable.test.js
Normal file
39
tests/link-modal-no-cable.test.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// #321: a subsea link to or from a coast where no cable lands yet (Iqaluit, Adamstown, Murmansk) said
|
||||
// "Cables from Iqaluit reach . Hop through one of those." It now says what can actually reach that city.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const card = (ev, a, b) => ev(`UI.lmode='wave';openLinkModal('${a}','${b}');const t=$('modalCard').textContent;closeModal();t`);
|
||||
|
||||
test('#321 no cable lands in Iqaluit: no empty list, the only way in is your own cable', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const g of GOALS)S.done[g.id]=0");
|
||||
assert.ok(!ev("cabOpen()"));
|
||||
for (const [a, b] of [['yfb', 'nuk'], ['nuk', 'yfb'], ['nyc', 'pcn']]) {
|
||||
const t = card(ev, a, b), city = ev(`CITY['${b === 'nuk' ? a : b}'].name`);
|
||||
assert.doesNotMatch(t, /reach \.|Hop through/, `${a}→${b}: ${t}`);
|
||||
assert.ok(t.includes(ev(`tr('link_modal.no_subsea_cable_lands_in_city_own',{city:'${city}'})`)), `${a}→${b}: ${t}`);
|
||||
assert.match(t, /level 9 or Tier 1/, `${a}→${b} points at the level that unlocks your own cable`);
|
||||
}
|
||||
// once you can lay one, the button to do it is right there
|
||||
ev("S.lvl=9");
|
||||
assert.ok(ev("cabOpen()"));
|
||||
assert.match(card(ev, 'yfb', 'nuk'), /Lay your own subsea cable|Surveying/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('#321 a coast with no cable but a road in: reach it overland, never "hop through" cables that miss it', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const g of GOALS)S.done[g.id]=0");
|
||||
for (const [a, b, c] of [['nyc', 'mmk', 'mmk'], ['dks', 'nyc', 'dks']]) {
|
||||
const t = card(ev, a, b);
|
||||
assert.doesNotMatch(t, /Hop through/, `${a}→${b}: ${t}`);
|
||||
assert.ok(t.includes(ev(`tr('link_modal.no_subsea_cable_lands_in_city_land',{city:CITY.${c}.name})`)), `${a}→${b}: ${t}`);
|
||||
}
|
||||
// two cities that both have cables, just not a shared one, still get the cities to hop through
|
||||
const t = card(ev, 'nuk', 'syd');
|
||||
assert.match(t, /Hop through one of those/);
|
||||
assert.doesNotMatch(t, /reach \./);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -254,6 +254,34 @@ test('multiplayer: saves go to the server on a new day, at most every 15 s, neve
|
|||
dom.window.close();
|
||||
});
|
||||
|
||||
// A big network that moved on is saved by the route worker in a plain build (tests/save-size.test.js). A session
|
||||
// network is not: its text is made on the page (mpSave()), so the server gets the very save the slot holds.
|
||||
test('multiplayer: a big session network that moved on saves on the page, never in the route worker, and the server gets it', async () => {
|
||||
const srv = store(), f = fake(srv.routes);
|
||||
const { dom, ev, errors } = await started({ fetch: f, load: { gzip: true } });
|
||||
dom.window.structuredClone = globalThis.structuredClone;
|
||||
// Big enough for the worker (GZ_BG), small enough to be written plain at once when forced (GZ_MIN).
|
||||
ev("for(let i=0;i<5000;i++)S.log.push({d:S.day,h:'A long line in the log to make a big save '+i,k:''});save(true)");
|
||||
const len = ev('JSON.stringify(packSave(S)).length');
|
||||
assert.ok(len >= ev('GZ_BG') && len < ev('GZ_MIN'), `between the two thresholds: ${len}`);
|
||||
assert.equal(ev('SLOT.day[UI.slot]===S.day'), true, 'the slot knows its day');
|
||||
// A route worker that compresses, and keeps whatever else it is sent.
|
||||
ev("window.__q=[];rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>{if(m.gz!==undefined)gzB64(m.txt).then(data=>rwMsg({gz:m.gz,data}));else __q.push(m);},terminate(){}});");
|
||||
await until(() => ev('!MP.busy'));
|
||||
const n = f.saves().length;
|
||||
ev('S.day++;MP.last-=16000;save()');
|
||||
assert.equal(ev('__q.filter(m=>m.sv!==undefined).length'), 0, 'the whole save never went to the worker');
|
||||
assert.ok(await until(() => f.saves().length === n + 1), 'the new day went to the server');
|
||||
await until(() => ev('!MP.busy&&!UI.gzBusy'));
|
||||
ev(`window.__t=null;Promise.all([gunzip(slotRaw(UI.slot)),gunzip(${lit(srv.st.save.data)})]).then(t=>{window.__t=t;})`);
|
||||
assert.ok(await until(() => ev('!!window.__t')), 'the slot was written, both compressed');
|
||||
const here = JSON.parse(ev('__t[0]')), there = JSON.parse(ev('__t[1]'));
|
||||
assert.deepEqual([here.day, here.mp.seq], [there.day, there.mp.seq], 'the same day and number here and on the server');
|
||||
assert.equal(here.day, ev('S.day'));
|
||||
assert.deepEqual(errors, []);
|
||||
dom.window.close();
|
||||
});
|
||||
|
||||
test('multiplayer: when another device moved on, the player hears it once and chooses', async () => {
|
||||
const f = fake([okStart, okSave]);
|
||||
const { dom, ev, errors } = await started({ fetch: f });
|
||||
|
|
|
|||
|
|
@ -47,9 +47,11 @@ test('a save too big for the browser is not retried every few seconds, but leavi
|
|||
assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over');
|
||||
assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day'));
|
||||
assert.equal(a.ev('UI.saveFail'), null);
|
||||
a.ev('save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time');
|
||||
a.ev('__full=true;save();S=migrate(JSON.parse(JSON.stringify(S)));save()');
|
||||
a.ev('S.cash++;save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time the network changes');
|
||||
a.ev('save();save()');
|
||||
assert.equal(a.ev('__tries'), 4, 'and writes nothing while nothing changes');
|
||||
a.ev('__full=true;S.cash++;save();S=migrate(JSON.parse(JSON.stringify(S)));S.cash++;save()');
|
||||
assert.equal(a.ev('__tries'), 6, 'another game (a new state) tries at once');
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ const assert = require('node:assert/strict');
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
// A backbone London – New York – Auckland with transit in London and New York, full dishes with landing rights there, a
|
||||
// full lasered Shortcrust, and Pitcairn (Adamstown): a POP of its own with broadband, no cable, and a dish.
|
||||
|
|
@ -230,7 +231,7 @@ test('the traceroute to and from a cut-off POP shows the orbit hops', () => {
|
|||
test('saves without pies, and pie saves whose POPs are all connected, route as before', () => {
|
||||
const { ev, errors } = load();
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`);
|
||||
ev(`S=migrate(JSON.parse(${lit(save)}));compute()`);
|
||||
assert.equal(ev('S.pie'), null);
|
||||
const out = () => ev("JSON.stringify([R.served,R.demand,R.egT,R.load,R.l2,R.l2lat,R.citySrv])");
|
||||
const a = out();
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ const assert = require('node:assert/strict');
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
const YEARS = +(process.env.PIE_BALANCE_YEARS || 0);
|
||||
|
||||
|
|
@ -28,7 +29,7 @@ const YEARS = +(process.env.PIE_BALANCE_YEARS || 0);
|
|||
function sim(days, stop = false, seed = 7, gov = false) {
|
||||
const g = load({ seed });
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));S.pieV=1;UI.started=true;UI.pitched=true;UI.speed=0;S.nextFail=1e9;S.nextEvent=1e9;
|
||||
g.ev(`S=migrate(JSON.parse(${lit(save)}));S.pieV=1;UI.started=true;UI.pitched=true;UI.speed=0;S.nextFail=1e9;S.nextEvent=1e9;
|
||||
isTier1=()=>true;after=()=>{};pieModal=()=>{};compute();pieInit();UI.pieLas=true;ACT.pieFound();ACT.pieFactory();ACT.pieRd({k:'reuse'});
|
||||
for(const c of Object.keys(S.pops).filter(c=>pieCoast(c)&&piePadOk(c,'short')).sort((a,b)=>Math.abs(CITY[a].lat)-Math.abs(CITY[b].lat)).slice(0,2))ACT.piePad({city:c});
|
||||
window.__site=()=>{const ds=S.pie.dishes,lic=c=>pieLicOk(CITY[c].cc)?0:pieLicPrice(CITY[c].cc);
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ const assert = require('node:assert/strict');
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
// A sandbox with London and New York joined by a transatlantic wave, Frankfurt 640 km from London, a company, and a
|
||||
// 16-antenna dish with landing rights at each POP.
|
||||
|
|
@ -159,7 +160,7 @@ test('spats: data stays home, and not over my airspace', () => {
|
|||
test('saves without pies route identically, and pay nothing for orbit', () => {
|
||||
const { ev, errors } = load();
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`);
|
||||
ev(`S=migrate(JSON.parse(${lit(save)}));compute()`);
|
||||
assert.equal(ev('S.pie'), null);
|
||||
const out = () => ev("JSON.stringify([R.served,R.demand,R.revMo,R.egT,R.load,R.l2,R.l2lat,R.rev])");
|
||||
const a = out();
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ const assert = require('node:assert/strict');
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('./harness');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
// London, New York and Frankfurt on one backbone, a company, 16-antenna dishes with landing rights at each.
|
||||
const world = (ev, opt = {}) => {
|
||||
|
|
@ -195,7 +196,7 @@ test('the traceroute shows a circuit through orbit hop by hop', () => {
|
|||
test('saves without pies: no traffic data, the same routing, and an untouched map', () => {
|
||||
const { ev, errors } = load();
|
||||
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`);
|
||||
ev(`S=migrate(JSON.parse(${lit(save)}));compute()`);
|
||||
assert.equal(ev('R.pie===undefined'), true);
|
||||
assert.equal(ev("trSkyList().length"), 0);
|
||||
assert.equal(ev("pieFiberMs({k:'c',id:'x'})"), Infinity);
|
||||
|
|
|
|||
|
|
@ -66,7 +66,8 @@ test('a link’s card: sizes first, then what it carries, then its routing', ()
|
|||
test('nothing on a phone scrolls by design: the bar and the card’s body have no scroll of their own', () => {
|
||||
const { ev, errors } = load();
|
||||
const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText))
|
||||
.flatMap(m=>[...m.cssRules]).map(r=>({sel:r.selectorText||'',ov:r.style.getPropertyValue('overflow')+r.style.getPropertyValue('overflow-y'),mh:r.style.getPropertyValue('max-height')})))`));
|
||||
.flatMap(m=>[...m.cssRules]).map(r=>({sel:r.selectorText||'',ov:r.style.getPropertyValue('overflow-y')||r.style.getPropertyValue('overflow'),mh:r.style.getPropertyValue('max-height')})))`));
|
||||
// (jsdom 31 expands the overflow shorthand into overflow-y too; jsdom 30 kept only the shorthand.)
|
||||
const dock = rules.find((r) => r.sel === '#pzBox.dock');
|
||||
assert.ok(dock && dock.ov === 'visible' && dock.mh === 'none', 'the bar is as tall as it needs, never a scroll box');
|
||||
assert.ok(!rules.some((r) => /pzd-/.test(r.sel) && /auto|scroll/.test(r.ov)), 'no part of the bar or the cards scrolls');
|
||||
|
|
|
|||
|
|
@ -86,3 +86,61 @@ test('days in a row reuse the kept tables and route like a fresh start every day
|
|||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('with Auto-TE, kept orders and the no-detour marks route like a fresh start every day', () => {
|
||||
// The routing core (29-route-core.js) keeps each list's order for each city with the tables, and Auto-TE marks the
|
||||
// pairs with no detour: both have to give exactly what scanning and searching afresh give. The network is made busy
|
||||
// (half its link capacity) so that flows spill, detours are searched and many fail.
|
||||
const { ev, errors } = open();
|
||||
ev("S.core.run=2;S.te={on:true,day:S.day,script:'spill at 85%'};for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';for(const l of S.links)if(l.kind==='wave')l.cap=(l.cap||0)/2;compute();compute();");
|
||||
assert.equal(ev('!!(S.te.on&&coreTE())'), true);
|
||||
let tried = 0;
|
||||
for (let d = 0; d < 4; d++) {
|
||||
ev('dayTick()');
|
||||
const r = step(ev, '');
|
||||
assert.ok(r.same, `day ${d}: the same routing with and without the kept tables`);
|
||||
assert.ok(!r.g && !r.x, `day ${d}: a day of demand only keeps the tables`);
|
||||
tried = Math.max(tried, ev('R.teMoved'));
|
||||
}
|
||||
assert.ok(tried > 0, 'Auto-TE moved traffic onto detours');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// When the exits change but the graph does not (a network leaves an exchange because its PNI came up), the lists that
|
||||
// did not change keep the orders routing worked out for them (the same arrays, used the same day), the ones that did
|
||||
// start again, and routing is still exactly routing without the kept tables, day after day.
|
||||
test('lists an exit change leaves alone keep their orders; routing stays the same as without the kept tables', () => {
|
||||
const { ev, errors } = open();
|
||||
// Two days on the kept build: the lists get their orders.
|
||||
ev('compute();compute();');
|
||||
ev('window.__ords=new Set(RC.x.lists.flatMap(d=>d.cs?d.ord.filter(Boolean):[d.ord]).filter(o=>Object.keys(o).length));');
|
||||
assert.ok(ev('__ords.size') > 5, `orders worked out: ${ev('__ords.size')}`);
|
||||
// One network leaves one exchange: the exits key moves, the graph does not.
|
||||
const r = step(ev, `(()=>{const ix=Object.keys(S.ixp).find(x=>ixSessions(x).size>3),n=[...ixSessions(ix)][0];window.__left=n+'@'+ix;
|
||||
S.peers[n+'@'+ix]=false;delete S.peers[n+'@'+ix];S.rs[ix]=false;S.pni.push({id:'pk1',net:n,city:ixCity(ix),tier:1,n:1});})()`);
|
||||
assert.equal(r.g, false, 'same graph');
|
||||
assert.equal(r.x, true, 'the exits changed');
|
||||
assert.equal(r.same, true, 'the same routing as without the kept tables');
|
||||
const kept = ev('RC.x.lists.flatMap(d=>d.cs?d.ord.filter(Boolean):[d.ord]).filter(o=>__ords.has(o)).length');
|
||||
const all = ev('RC.x.lists.length');
|
||||
assert.ok(kept > 0 && kept < ev('__ords.size') + 1, `lists that kept their orders: ${kept} of ${all}`);
|
||||
// And a few more days, with the next change between them.
|
||||
for (let d = 0; d < 3; d++) assert.equal(step(ev, 'for(const c in S.pops)if(S.pops[c].bb)S.pops[c].bb.d*=1.03').same, true, `day ${d + 1} after`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('an exit that turns from an exchange into a PNI at the same place in the list does not keep its old order', () => {
|
||||
const { ev, errors } = open();
|
||||
// The last exchange with a few networks on it, its city A, and a network m there that also gets a PNI at A.
|
||||
ev(`(()=>{const ixs=Object.keys(S.ixp).filter(c=>S.pops[ixCity(c)]);let p=null;
|
||||
for(let k=ixs.length-1;k>=0&&!p;k--){const c=ixs[k],ss=[...ixSessions(c)];if(ss.length>2)p={c,A:ixCity(c),m:ss[0]};}
|
||||
window.__P=p;for(const c of Object.keys(S.ixp).slice(Object.keys(S.ixp).indexOf(p.c)+1))delete S.ixp[c];
|
||||
S.pni.push({id:'pz0',net:p.m,city:p.A,tier:1,n:1,pref:'normal'});})();compute();compute();compute();`);
|
||||
assert.ok(ev('!!__P'), 'an exchange to drop');
|
||||
// The exchange goes and a PNI with m at A comes first: an exit of the same city and preference, but now a PNI.
|
||||
const r = step(ev, `delete S.ixp[__P.c];S.pni.unshift({id:'pz1',net:__P.m,city:__P.A,tier:1,n:1,pref:'normal'})`);
|
||||
assert.equal(r.g, false, 'same graph');
|
||||
assert.equal(r.x, true, 'the exits changed');
|
||||
assert.equal(r.same, true, 'the same routing as without the kept tables');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -15,11 +15,17 @@ const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.c
|
|||
// R with its lazy parts (R.ef, R.fl) read out, attacks by id.
|
||||
const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()";
|
||||
|
||||
// R.efg, which the next day's routing reads: every link's sums, Map order included (they cross as typed arrays).
|
||||
const EFG = "JSON.stringify(Object.entries(R.efg).map(([k,e])=>[k,[...e.t.g],e.t.v,e.t.n,e.t.d]))";
|
||||
|
||||
test('R packed, cloned and unpacked is the same R, lazy parts and key order included', (t) => {
|
||||
const { ev, errors } = big(t);
|
||||
const want = ev(SIG);
|
||||
const want = ev(SIG), efg = ev(EFG);
|
||||
ev("{const {o,p,tr}=rwPack(R);const c=structuredClone({o,p},{transfer:tr});R=rwUnpack(c.o,c.p);UI.hotMap=hotByCity();}");
|
||||
assert.equal(ev(EFG), efg);
|
||||
assert.equal(ev(SIG), want);
|
||||
// Sent back to the worker after an action, a link's sums still clone whole.
|
||||
assert.equal(ev("JSON.stringify(Object.entries(structuredClone(rwEfgOut(R.efg))).map(([k,t])=>[k,[...t.g],t.v,t.n,t.d]))"), efg);
|
||||
assert.equal(ev('pniFlows(Object.keys(S.pops)[0])!==null'), true, 'the PNI list reads the unpacked flows');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -30,10 +36,13 @@ test('the worker side routes what it is sent: same R as routing on the page', (t
|
|||
ev("window.__got=null;window.postMessage=(m)=>{window.__got=m;};");
|
||||
ev("{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}");
|
||||
ev("R=rwUnpack(structuredClone(__got.R),__got.ef)");
|
||||
const fromWorker = ev(SIG);
|
||||
const fromWorker = ev(SIG), hot = ev('JSON.stringify(structuredClone(__got.hot))');
|
||||
ev('R=__R0;S=JSON.parse(__S0);compute()');
|
||||
assert.equal(ev('JSON.stringify(S)'), ev('__S0'), 'routing does not change S');
|
||||
assert.equal(ev(SIG), fromWorker);
|
||||
// The full ports it found come along (the page no longer works them out again), key order included.
|
||||
assert.equal(hot, ev('JSON.stringify(UI.hotMap)'));
|
||||
assert.ok(Object.keys(JSON.parse(hot)).length > 5, 'some ports are full on the big network');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -22,15 +22,16 @@ function network(ev) {
|
|||
}
|
||||
compute();`);
|
||||
// Share the model and path sender, but replace indexed exit selection with
|
||||
// the original full scan and stable sort for every flow.
|
||||
const source = ev('compute.toString()');
|
||||
const start = source.indexOf(' for(const pass of PASSES)for(const rank of RANKS){');
|
||||
const end = source.indexOf(' for(const i of NORD)', start);
|
||||
// the original full scan and stable sort for every flow: in the routing core (29-route-core.js), the passes of run().
|
||||
const core = ev('routeCore.toString()'), source = ev('compute.toString()');
|
||||
const start = core.indexOf(' for(const pass of PASSES)for(const rank of RANKS){');
|
||||
const end = core.indexOf(' for(let x=0;x<NX;x++)E[x].used=USED[x];', start);
|
||||
assert.ok(start >= 0 && end > start, 'allocation loop boundaries must exist');
|
||||
// The reference also builds every table afresh, so the comparison covers what routing keeps between calls.
|
||||
assert.ok(source.includes('RCON=RC.on'), 'compute() can be told not to keep its tables');
|
||||
const ref = (source.slice(0,start)+referenceAllocation+source.slice(end)).replace('RCON=RC.on', 'RCON=false');
|
||||
ev(`window.referenceCompute=eval('('+${lit(ref)}+')')`);
|
||||
const refCore = (core.slice(0, start) + referenceAllocation + core.slice(end)).replace(/^function routeCore/, 'function');
|
||||
ev(`window.referenceCore=(${refCore})();window.referenceRaw=(0,eval)('('+${lit(source.replace('RCON=RC.on', 'RCON=false').replace(/^function compute/, 'function'))}+')');
|
||||
window.referenceCompute=function(){const r=ROUTE;ROUTE=referenceCore;try{referenceRaw();}finally{ROUTE=r;}};`);
|
||||
}
|
||||
|
||||
test('indexed routing matches the simple allocation loop across network changes', () => {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ const refuse = name => `window.__err=${lit(name)};{const P=Object.getPrototypeOf
|
|||
test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});UI.saveFail=null;" + refuse('QuotaExceededError'));
|
||||
ev('save()');
|
||||
ev('S.cash++;save()');
|
||||
const toasts = () => [...dom.window.document.querySelectorAll('.toast')].filter(t => /not being saved/.test(t.textContent));
|
||||
assert.equal(toasts().length, 1, 'one warning');
|
||||
assert.match(toasts()[0].textContent, /too big for this browser/);
|
||||
|
|
@ -31,7 +31,8 @@ test('#176 a save that does not fit tells the player once, with Export, and the
|
|||
|
||||
test('#176 storage that is blocked altogether gets its own advice', () => {
|
||||
const { ev, dom, errors } = load();
|
||||
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';save()');
|
||||
// The game moves on first: a save of the very text the slot already holds writes nothing.
|
||||
ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';S.cash+=1;save()');
|
||||
assert.match(dom.window.document.body.textContent, /private window/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -126,3 +127,95 @@ test('#176 a damaged compressed save is kept, marked damaged, and the player is
|
|||
assert.equal(ev('!!UI.started'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A big network's autosave is compressed in the route worker (rwGzip()), not on the page: deflating it there held the
|
||||
// page about as long as writing it plain. jsdom has no Worker: a second page answers as the worker, messages cloned
|
||||
// both ways. A save as the page closes stays plain, and a worker lost mid-job leaves its job to the page.
|
||||
test('a big autosave is compressed in the route worker and loads back; a closing save stays plain', async () => {
|
||||
const a = load({ gzip: true }), w = load({ gzip: true });
|
||||
for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone;
|
||||
a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()");
|
||||
const len = a.ev('JSON.stringify(packSave(S)).length');
|
||||
assert.ok(len >= a.ev('GZ_BG') && len < a.ev('GZ_MIN'), `between the two thresholds: ${len}`);
|
||||
a.ev("window.__q=[];window.__pz=0;const gp=gzPipe;gzPipe=(...x)=>{__pz++;return gp(...x);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});");
|
||||
w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};');
|
||||
const pump = async () => { for (let k = 0; k < 200; k++) {
|
||||
while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); }
|
||||
while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); }
|
||||
if (a.ev("(slotRaw(UI.slot)||'').startsWith(GZ)&&!UI.gzBusy")) return; await new Promise((r) => setTimeout(r, 5)); } };
|
||||
// Closing: plain text, at once.
|
||||
a.ev('save(true)');
|
||||
assert.equal(a.ev('slotRaw(UI.slot)[0]'), '{', 'a save as the page closes is written plain');
|
||||
// The autosave: compressed by the worker.
|
||||
a.ev("S.name='Worker Zip';save()");
|
||||
assert.equal(a.ev('__q.length'), 1, 'the text went to the worker');
|
||||
await pump();
|
||||
assert.ok(a.ev("slotRaw(UI.slot).startsWith(GZ)"), 'stored compressed');
|
||||
assert.equal(a.ev('__pz'), 0, 'nothing was deflated on the page');
|
||||
a.ev("gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length].join('|');})");
|
||||
await settle(a.ev, '!!window.__t');
|
||||
assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length].join('|')"));
|
||||
// The worker lost while it compresses: the page compresses that save itself.
|
||||
a.ev("__pz=0;S.name='Page Zip';save();rwKill()");
|
||||
await settle(a.ev, "!UI.gzBusy&&__pz>0", 'compressed on the page');
|
||||
a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>window.__t=JSON.parse(t).name)");
|
||||
await settle(a.ev, '!!window.__t');
|
||||
assert.equal(a.ev('__t'), 'Page Zip');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(w.errors, []);
|
||||
});
|
||||
|
||||
// A big network that moved on since its last save is packed, turned into text and compressed by the route worker
|
||||
// (rwSave()): the page copies the game over and writes what comes back. A paused game (same day) is still compared on
|
||||
// the page, so an unchanged one is not written again. The worker lost mid-save: the next frame saves again, here.
|
||||
test('a big game that moved on is saved by the route worker, a paused one is still compared on the page', async () => {
|
||||
const a = load({ gzip: true }), w = load({ gzip: true });
|
||||
for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone;
|
||||
a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()");
|
||||
a.ev("window.__q=[];window.__pk=0;const pk=packBiz;packBiz=b=>{__pk++;return pk(b);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});");
|
||||
w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};');
|
||||
const pump = async (cond) => { for (let k = 0; k < 300; k++) {
|
||||
while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); }
|
||||
while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); }
|
||||
if (a.ev(cond)) return; await new Promise((r) => setTimeout(r, 5)); } assert.fail('never: ' + cond); };
|
||||
// The first save of the session is made here, and tells the slot which day it holds.
|
||||
a.ev('save()'); await pump("!UI.gzBusy&&(slotRaw(UI.slot)||'').startsWith(GZ)");
|
||||
// A day later: the whole save goes to the worker.
|
||||
a.ev("__pk=0;S.day++;S.name='Moved On';save()");
|
||||
assert.equal(a.ev('__q.length&&!!__q[0].sv&&!!__q[0].S'), true, 'the game went to the worker');
|
||||
await pump("!UI.gzBusy&&SLOT.day[UI.slot]===S.day");
|
||||
assert.equal(a.ev('__pk'), 0, 'nothing was packed on the page');
|
||||
a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length,!!j.sv].join('|');})");
|
||||
await settle(a.ev, '!!window.__t');
|
||||
assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length,true].join('|')"), 'the slot holds the game, stamped');
|
||||
assert.equal(a.ev('SLOT.txt[UI.slot]===JSON.stringify(packSave(S))'), true, 'the slot knows its text');
|
||||
a.ev('__pk=0');
|
||||
// Paused, nothing changed: compared on the page and not written again.
|
||||
a.ev("__pk=0;window.__w=0;const sp=slotPut;slotPut=(...x)=>{__w++;return sp(...x);};save()");
|
||||
assert.equal(a.ev('__q.length'), 0, 'nothing went to the worker');
|
||||
assert.ok(a.ev('__pk') > 0, 'packed here, to compare');
|
||||
assert.equal(a.ev('__w'), 0, 'the same game is not written again');
|
||||
// The worker lost while it saves: the next frame saves again.
|
||||
a.ev("S.day++;save();rwKill()");
|
||||
await settle(a.ev, '!UI.gzBusy');
|
||||
assert.equal(a.ev('UI.lastSave'), 0, 'the next frame saves again');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(w.errors, []);
|
||||
});
|
||||
|
||||
// Loaded from a big slot, the game's first save once it moves on already goes to the worker: the slot knows its day.
|
||||
test('the first save after loading a big slot goes to the route worker once the game moves on', async () => {
|
||||
const a = load({ gzip: true });
|
||||
a.ev(bigBiz + ';' + huge);
|
||||
a.ev('save(true)');
|
||||
await settle(a.ev, "(slotRaw(UI.slot)||'').startsWith(GZ)");
|
||||
const b = load({ gzip: true, storage: { 'sot-save-v1': a.ev('slotRaw(UI.slot)') } });
|
||||
await settle(b.ev, 'UI.started===true');
|
||||
b.dom.window.structuredClone = globalThis.structuredClone;
|
||||
b.ev("window.__q=[];rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){}});");
|
||||
assert.equal(b.ev('SLOT.big[UI.slot]===true&&SLOT.day[UI.slot]===S.day'), true, 'the slot knows its day and size');
|
||||
b.ev('S.day++;save()');
|
||||
assert.equal(b.ev('__q.length===1&&!!__q[0].sv'), true, 'the whole save went to the worker');
|
||||
assert.deepEqual(a.errors, []);
|
||||
assert.deepEqual(b.errors, []);
|
||||
});
|
||||
|
|
|
|||
88
tests/shared-promise-checks.test.js
Normal file
88
tests/shared-promise-checks.test.js
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
// Diverse paths, a land path and a latency budget asked for many pairs on one network: the offers spotted for
|
||||
// sovereign clouds (spots0()) and the intern's check before taking a wave out (opsDecomSafe()) build one graph per
|
||||
// network and ask it for every pair (divGraph()/divOn(), promiseCheck()). Same answers as before: the old ways are
|
||||
// written out here.
|
||||
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 { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
// Before: each question filtered the links again and built both searches' graphs from lists.
|
||||
const OLD = `window.oldDiv=(a,b)=>{const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));
|
||||
const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
|
||||
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
|
||||
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
|
||||
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
|
||||
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));};
|
||||
window.oldLand=(a,b)=>{const adj={};for(const l of S.links.filter(l=>!l.sub&&!linkDown(l))){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
|
||||
const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;};
|
||||
window.oldLat=(a,b)=>{const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}
|
||||
if(u===null)break;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;};
|
||||
window.oldSafe=l=>{const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
|
||||
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true);
|
||||
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}};`;
|
||||
// Seeded trouble: cuts, POPs down, trenches shared by several links, a VXC to a city with no POP.
|
||||
const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day;
|
||||
for(const l of S.links)if(rnd()<.1)l.cut=D+3;for(const c in S.pops)if(rnd()<.06)S.pops[c].down=D+2;
|
||||
const ls=S.links.filter(l=>!l.sub);for(let i=${v};i<ls.length;i+=6)ls[i].trench='shared'+(i%3);
|
||||
const p=FABS.find(f=>f.cities.some(c=>S.pops[c])&&f.cities.some(c=>!S.pops[c]));if(p&&${v}%2){const a=p.cities.find(c=>S.pops[c]),b=p.cities.find(c=>!S.pops[c]);
|
||||
S.links.push({id:'vx'+${v},a,b,kind:'vxc',prov:p.id,vt:'1g',km:kmBetween(a,b),sub:isSub(a,b),mo:1,cut:0,day:0});}})()`;
|
||||
|
||||
test('diverse paths: one graph for every pair answers like a search per pair, and spots the same sovereign clouds', () => {
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
|
||||
let yes = 0, no = 0;
|
||||
for (let v = 0; v < 6; v++) {
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''}`);
|
||||
const r = JSON.parse(ev(`(()=>{const C=Object.keys(S.pops).filter((c,i)=>i%3===0).concat(S.links.filter(l=>l.kind==='vxc').map(l=>l.b),['nowhere']),g=divGraph(),bad=[];let y=0,n=0;
|
||||
for(const a of C)for(const b of C){const w=oldDiv(a,b);if(diversePaths(a,b)!==w||divOn(g,a,b)!==w)bad.push(a+'-'+b);w?y++:n++;}
|
||||
const by={};for(const c of Object.keys(S.pops).filter(bizCity))(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c);const sov=[];
|
||||
for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(oldDiv(cs[i],cs[j]))sov.push(cs[i]+'-'+cs[j]);
|
||||
const got=spots0(0).filter(s=>s.t==='sov').map(s=>s.a+'-'+s.b);return JSON.stringify({y,n,bad:bad.slice(0,5),sov,got});})()`));
|
||||
assert.deepEqual(r.bad, [], `state ${v}`);
|
||||
assert.deepEqual(r.got, r.sov, `sovereign clouds, state ${v}`);
|
||||
yes += r.y; no += r.n;
|
||||
}
|
||||
assert.ok(yes > 300 && no > 1000, `diverse ${yes}, not ${no}`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('taking a wave out: the shared check refuses what asking customer by customer refused, for each promise', () => {
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
|
||||
// Customers between linked POPs: diverse paths, afraid of sharks, a latency budget just above today's best.
|
||||
const BIZ = `(()=>{const ls=S.links.filter(l=>S.pops[l.a]&&S.pops[l.b]);let n=0;for(let i=0;i<ls.length;i+=2){const l=ls[i],k=['diverse','sharks','lat'][n%3],b={id:'pc'+n++,city:l.a,city2:l.b,type:'l2',bw:1,reqs:[k]};
|
||||
if(k==='lat')b.latMax=+(bestLat(l.a,l.b)+0.02).toFixed(2);if(k!=='lat'||isFinite(b.latMax))S.biz.push(b);}})()`;
|
||||
const refused = { diverse: 0, sharks: 0, lat: 0 };
|
||||
for (let v = 0; v < 4; v++) {
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''};${BIZ}`);
|
||||
// From a few hubs to every POP: several customers of one city, some served and some not.
|
||||
const hub = JSON.parse(ev(`(()=>{const P=Object.keys(S.pops),H=P.filter((c,i)=>i%25===0);let n=0;for(const a of H)for(const b of P)if(a!==b)for(const k of ['diverse','sharks','lat']){const o={id:'hb'+n++,city:a,city2:b,type:'l2',bw:1,reqs:[k]};
|
||||
if(k==='lat')o.latMax=n%2?oldLat(a,b):oldLat(a,b)*0.995;S.biz.push(o);}
|
||||
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true);
|
||||
const pc=promiseCheck(),bz=S.biz.filter(b=>/^hb/.test(b.id)),w=bz.map(chk);S.biz=S.biz.filter(b=>!/^hb/.test(b.id));
|
||||
return JSON.stringify({bad:bz.filter((b,i)=>pc(b)!==w[i]).map(b=>b.id).slice(0,5),yes:w.filter(Boolean).length,n:w.length});})()`));
|
||||
assert.deepEqual(hub.bad, [], `hubs, state ${v}`);
|
||||
assert.ok(hub.yes > 50 && hub.n - hub.yes > 50, JSON.stringify(hub));
|
||||
const r = JSON.parse(ev(`(()=>{const bad=[],why=[],all=S.biz;for(const l of S.links.slice(0,60)){const w=oldSafe(l);if(opsDecomSafe(l)!==w)bad.push(l.id);
|
||||
if(!w)for(const k of ['diverse','sharks','lat']){S.biz=all.filter(b=>/^pc/.test(b.id)&&b.reqs[0]===k);if(!oldSafe(l))why.push(k);S.biz=all;}}
|
||||
return JSON.stringify({bad,why});})()`));
|
||||
assert.deepEqual(r.bad, [], `state ${v}`);
|
||||
for (const k of r.why) refused[k]++;
|
||||
}
|
||||
for (const k in refused) assert.ok(refused[k] >= 2, `refused for ${k}: ${JSON.stringify(refused)}`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('latency searches at the edges: a city with no link, the same city twice, a city nobody reaches', () => {
|
||||
const { ev, errors } = load({ seed: 3 });
|
||||
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();`);
|
||||
const r = JSON.parse(ev(`(()=>{const lone=CITIES.find(c=>!S.links.some(l=>l.a===c.id||l.b===c.id)).id,p=S.links[0].a,g=latGraph(),d=latRun(g,p);
|
||||
return JSON.stringify([bestLat(lone,lone),bestLat(p,p),bestLat(lone,p),bestLat(p,lone),latRun(g,lone),latAt(g,d,p,p),latAt(g,d,p,lone),latAt(g,null,lone,p),
|
||||
latPairs([lone,p,lone]).map(x=>x[2])]);})()`));
|
||||
assert.deepEqual(r, [0, 0, null, null, null, 0, null, null, [null, 0, null]]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -195,7 +195,9 @@ test('the map is only redrawn when something on it can have changed', () => {
|
|||
assert.ok(frame('', 1100) > 0, 'and once a second anyway');
|
||||
assert.ok(frame('WL.key=null') > 0, 'the land picture catching up after a zoom or resize redraws');
|
||||
ev('UI.speed=1');
|
||||
assert.ok(frame() > 0 && frame() > 0, 'with the clock running every frame moves');
|
||||
// Only the animation clock moves: ambient, drawn at most 30 times a second (tests/frame-pacing.test.js).
|
||||
const run = [frame(), frame(), frame(), frame()].filter((n) => n > 0).length;
|
||||
assert.ok(run >= 2 && run < 4, `with the clock running the map moves, every other frame at 60 Hz (${run} of 4)`);
|
||||
ev("ACT.animSet({v:'off'})");
|
||||
frame(); frame();
|
||||
assert.equal(frame(), 0, 'with animations off the running map stands still between days');
|
||||
|
|
@ -287,28 +289,41 @@ test('the map is not drawn while the dashboard covers the whole screen', () => {
|
|||
// compare the two on a busy network (Auto-TE, then a RouteScript that keeps headroom on every link) and on a small one
|
||||
// where Auto-TE has to route around a full link, so it keeps holding when the game's numbers change.
|
||||
function plainCompute(ev) {
|
||||
const src = ev('compute.toString()');
|
||||
let plain = src
|
||||
const src = ev('compute.toString()'), csrc = ev('routeCore.toString()');
|
||||
const plain = src
|
||||
.replace('const ns=e.nets||NET_IDS;', 'const ns=NET_IDS;')
|
||||
// ...and without what routing keeps between calls (29-route-cache.js): the plain path builds everything afresh,
|
||||
// which also leaves the lists without kept orders, so the first group and the rest are scanned and sorted.
|
||||
.replace('RCON=RC.on', 'RCON=false');
|
||||
// The routing core (29-route-core.js) with its shortcuts off: Auto-TE's no-detour marks and its searches picked up
|
||||
// where the last one stopped back to the cache lookup and a fresh dijkstra() for every detour.
|
||||
let core = csrc
|
||||
.replace('if(!lst.hi&&!lst.mx&&ALONE[fci])', 'if(false)')
|
||||
.replace('if(!GN){\n // One scan', 'if(false){\n // One scan')
|
||||
.replace('const ns=e.nets||NET_IDS;', 'const ns=NET_IDS;')
|
||||
.replace('if(P.dead)return 0;', '').replaceAll('if(r<=1e-6){P.dead=1;return 0;}', '')
|
||||
.replace('if(!P.dead)room-=push(', 'room-=push(').replace(/const gone=e=>\{[^\n]*\};/, 'const gone=e=>false;')
|
||||
// ...and without what routing keeps between calls (29-route-cache.js): the plain path builds everything afresh.
|
||||
.replace('RCON=RC.on', 'RCON=false');
|
||||
.replace('if(!P.dead)room-=push(', 'room-=push(').replace(/const gone=x=>\{[^\n]*\};/, 'const gone=x=>false;')
|
||||
// ...and every exit is called, even one whose path is full with no detour (dud()).
|
||||
.replace(/const dud=x=>\{[^\n]*\};/, 'const dud=x=>false;')
|
||||
.replace('if(TEF[key]===1)return null;const c0=teCache.get(key);', 'const c0=teCache.get(key);if(c0===false)return null;')
|
||||
.replace('const d=teSearch(src,dst);', 'const d=dijkstraTo(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3)||(CORE&&OUT[v]&&v!==dst),dst);')
|
||||
.replace('const d=dijkstraTo(adj,src,wW,', 'const {D:D0,P:P0}=dijkstra(adj,src,wW,').replace(',dst);\n if(d===Infinity', ',dst),d=D0[dst];\n if(d===Infinity')
|
||||
.replace('walkP(DJ.P,src,dst)', 'walkP(P0,src,dst)');
|
||||
// ...and the group split and sorting written the plain way, with array copies, as before they were made allocation-free
|
||||
const sg = plain.indexOf('const ROOM=[],sendGroup='), sd = plain.indexOf('const sortD=');
|
||||
const sg = core.indexOf('const ROOM=[],sendGroup='), sd = core.indexOf('const sortD=');
|
||||
assert.ok(sg > 0 && sd > sg, 'found the group sender and the sort');
|
||||
plain = plain.slice(0, sg) + `const ROOM=[],sendGroup=(g0,i0=0,i1=g0.length)=>{const g=g0.slice(i0,i1);for(const e of g)e.vis=vis;
|
||||
if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=FREM[F];if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));}
|
||||
for(const e of g){if(FREM[F]<=1e-6)break;send(e,FREM[F]);}};\n ` + plain.slice(sd).replace(/^const sortD=\(a,n=a\.length\)=>\{[^\n]*\};/, 'const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);for(let i=0;i<n;i++)a[i]=t[i];};');
|
||||
for (const [a, b] of [[src, plain]]) assert.notEqual(a, b);
|
||||
assert.equal((plain.match(/if\(false\)/g) || []).length, 2, 'both shortcuts were found and switched off');
|
||||
core = core.slice(0, sg) + `const ROOM=[],sendGroup=(g0,i0=0,i1=g0.length)=>{const g=g0.slice(i0,i1);for(const x of g)VISX[x]=vis;
|
||||
if(g.length>1){const room=g.map(x=>Math.max(0,CAPX[x]-USED[x])),tot=room.reduce((a,b)=>a+b,0),want=FREM[F];if(tot>1e-6)g.forEach((x,k)=>send(x,want*room[k]/tot));}
|
||||
for(const x of g){if(FREM[F]<=1e-6)break;send(x,FREM[F]);}};\n ` + core.slice(sd).replace(/^const sortD=\(a,n=a\.length\)=>\{[^\n]*\};/, 'const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);for(let i=0;i<n;i++)a[i]=t[i];};');
|
||||
assert.notEqual(src, plain); assert.notEqual(csrc, core);
|
||||
assert.equal((core.match(/if\(false\)/g) || []).length, 2, 'both shortcuts were found and switched off');
|
||||
assert.ok(!plain.includes('e.nets||NET_IDS'), 'the exit index was switched off');
|
||||
assert.ok(!plain.includes('P.dead'), 'the full-path mark was switched off');
|
||||
assert.ok(!core.includes('P.dead'), 'the full-path mark was switched off');
|
||||
assert.ok(core.includes('const dud=x=>false;'), 'every exit of a group is called');
|
||||
assert.ok(plain.includes('RCON=false') && !plain.includes('RC.on'), 'the kept routing tables were switched off');
|
||||
assert.ok(plain.includes('const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);') && plain.includes('g.forEach('), 'the plain group split and sort are in');
|
||||
ev('window.__plain=' + plain.replace(/^function compute/, 'function'));
|
||||
assert.ok(!core.includes('TEF[key]===1') && !core.includes('dijkstraTo(') && !core.includes('const d=teSearch(') && core.includes('if(c0===false)return null;'), "Auto-TE's shortcuts were switched off");
|
||||
assert.ok(core.includes('const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);') && core.includes('g.forEach('), 'the plain group split and sort are in');
|
||||
ev('window.__plainC=' + plain.replace(/^function compute/, 'function') + ';window.__plainR=(' + core.replace(/^function routeCore/, 'function') + ')();');
|
||||
ev('window.__plain=function(){const r=ROUTE;ROUTE=__plainR;try{__plainC();}finally{ROUTE=r;}};');
|
||||
}
|
||||
|
||||
test('fast routing gives exactly the same result as the plain path it replaces', () => {
|
||||
|
|
@ -363,6 +378,51 @@ test('Auto-TE routes around a full link exactly like the plain path', () => {
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Auto-TE's searches for a detour, on meshes of thin and thick links where POPs fill up and some sit outside the core
|
||||
// (TE never steers through them, but may end there): a search from a city picks up where the last one from there
|
||||
// stopped until a link or router runs out of room, and an exit whose full path has no detour is not called. Several
|
||||
// seeded networks, from light to heavy load, must route exactly as the plain path that searches every time.
|
||||
test('Auto-TE detours route like the plain path on crowded meshes with POPs outside the core', () => {
|
||||
const { ev, errors } = load();
|
||||
plainCompute(ev);
|
||||
// The fast core, counting the searches that were picked up: answered at once, or gone on from where the last stopped.
|
||||
const csrc = ev('routeCore.toString()'), counted = csrc.replace('if(go){g=LRg;if(DJ.done[dst]===g)return DJ.D[dst];', 'if(go){g=LRg;if(DJ.done[dst]===g){__TE.had++;return DJ.D[dst];}__TE.went++;');
|
||||
assert.notEqual(counted, csrc, 'found the picked-up search');
|
||||
ev('window.__TE={had:0,went:0};ROUTE=(' + counted.replace(/^function routeCore/, 'function') + ')();');
|
||||
const CS = ['fra', 'ams', 'bru', 'par', 'lon', 'zrh', 'mil', 'vie', 'prg', 'ber', 'muc', 'mad', 'cph', 'waw', 'mrs', 'ham', 'dus'];
|
||||
let moved = 0, outs = 0;
|
||||
for (let seed = 1; seed <= 6; seed++) {
|
||||
let a = seed * 7919;
|
||||
const rnd = () => { a = (a * 16807) % 2147483647; return a / 2147483647; }, int = (n) => Math.floor(rnd() * n);
|
||||
const cs = CS.filter(() => rnd() < 0.75), links = [];
|
||||
for (let i = 1; i < cs.length; i++) links.push([cs[int(i)], cs[i], int(4)]);
|
||||
for (let k = 0; k < cs.length; k++) { const x = cs[int(cs.length)], y = cs[int(cs.length)]; if (x !== y) links.push([x, y, int(4)]); }
|
||||
const out = cs.filter(() => rnd() < 0.3), up = cs.filter((c) => out.includes(c) || rnd() < 0.3).concat(cs[0]);
|
||||
ev(`ACT.start({});S.cash=1e12;S.lvl=13;for(const g of GOALS)S.done[g.id]=0;S.pops={};S.links=[];S.transit=[];
|
||||
const cs=${JSON.stringify(cs)},out=${JSON.stringify(out)},IN=RG.findIndex(g=>g.cr>=3&&!g.noMpls),OUT=RG.findIndex(g=>g.cr<2);
|
||||
for(const c of cs){ACT.buildPop({city:c});const p=S.pops[c];p.rgen=RG_TOP;p.routers=RMAX;if(!p.bb)ACT.launchBB({city:c});}
|
||||
const L=(a,b,t)=>{UI.via=null;UI.lmode='wave';UI.route='main';try{openLinkModal(a,b);ACT.buildLink({tier:t});}catch(e){}closeModal();};
|
||||
for(const [a,b,t] of ${JSON.stringify(links)})L(a,b,t);
|
||||
for(const c of ${JSON.stringify(up)}){const t=NETS.find(n=>n.price&&n.pops.includes(c)&&(n.type==='t1'||n.type==='t2'));if(t)ACT.buyTransit({city:c,net:t.id,tier:3});}
|
||||
// Then the routers: some too old for the core, and few enough that POPs fill up too.
|
||||
for(const c of cs){const p=S.pops[c];p.rgen=out.includes(c)?OUT:IN;p.routers=1+${int(3)};}
|
||||
S.ixp={};S.pni=[];S.caches=[];S.biz=[];S.te={on:true,day:0};S.core={lv:3,run:2};S.nextFail=1e9;S.nextEvent=1e9;`);
|
||||
assert.ok(ev('coreOn()&&coreTE()'), 'the core rules apply and Auto-TE runs');
|
||||
outs += ev('Object.keys(S.pops).filter(c=>!inCore(c)).length');
|
||||
const sig = () => ev('JSON.stringify({served:R.served,teMoved:R.teMoved,egT:R.egT,load:S.links.map(l=>R.load[l.id]||0),node:R.nodeLoad,t:R.useT,f:R.fl.map(f=>[f.got,f.via])})');
|
||||
for (const load of [0.3, 0.8, 1.6, 3]) {
|
||||
ev(`for(const c in S.pops)S.pops[c].bb.d=CITY[c].P*${load}`);
|
||||
ev('compute()'); const fast = sig(); moved += ev('R.teMoved');
|
||||
ev('__plain()'); const ref = sig();
|
||||
assert.equal(fast, ref, `network ${seed} at load ${load}: the fast and the plain path route the same`);
|
||||
}
|
||||
}
|
||||
assert.ok(moved > 100, 'Auto-TE found detours');
|
||||
assert.ok(outs > 0, 'some POPs are outside the core');
|
||||
assert.ok(ev('__TE.had') > 0 && ev('__TE.went') > 0, 'searches were picked up: some answered at once, some gone on');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('fiber customers are checked by link id the same way with or without the lookup tables', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'})");
|
||||
|
|
|
|||
62
tests/traffic-badges.test.js
Normal file
62
tests/traffic-badges.test.js
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
// Traffic badges: the rate ladder (1 Tbps, 10 Tbps, then the old 100 Tbps and 1 Pbps) and the odometer, S.vol, the
|
||||
// petabytes carried in a game, with badges at 1 PB, 100 PB, 1 EB and 1 ZB.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()";
|
||||
|
||||
test('every day adds a day of what was served: 1 Gbps for a day is 10.8 TB', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
assert.equal(ev('S.vol'), 0, 'a new game starts at zero');
|
||||
// What a day adds, from the day's own served traffic, whatever it is.
|
||||
const r = JSON.parse(ev('(()=>{const out=[];for(let i=0;i<20;i++){const v0=S.vol;dayTick();out.push({add:S.vol-v0,srv:R.served});}return JSON.stringify(out);})()'));
|
||||
for (const x of r) assert.ok(Math.abs(x.add - x.srv * 0.0108) < 1e-9, `${x.add} PB for ${x.srv} Gbps`);
|
||||
assert.ok(r.some((x) => x.srv > 0), 'some traffic flowed');
|
||||
assert.equal(ev('fmtVol(0.0108)'), '11 TB');
|
||||
assert.equal(ev('fmtVol(1)'), '1.0 PB');
|
||||
assert.equal(ev('fmtVol(1500)'), '1.50 EB');
|
||||
assert.equal(ev('fmtVol(2e6)'), '2.00 ZB');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the ladders: each badge at its line, not before', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
const got = () => JSON.parse(ev("JSON.stringify(['tera','tera10','peta','petabit','vol_pb','vol_100pb','vol_eb','vol_zb'].filter(k=>S.ach&&S.ach[k]!==undefined))"));
|
||||
const at = (served, vol) => { ev(`R.served=${served};S.vol=${vol};checkBadges()`); return got(); };
|
||||
assert.deepEqual(at(999, 0.99), []);
|
||||
assert.deepEqual(at(1000, 1), ['tera', 'vol_pb']);
|
||||
assert.deepEqual(at(9999, 99.9), ['tera', 'vol_pb']);
|
||||
assert.deepEqual(at(10000, 100), ['tera', 'tera10', 'vol_pb', 'vol_100pb']);
|
||||
assert.deepEqual(at(10000, 1000), ['tera', 'tera10', 'vol_pb', 'vol_100pb', 'vol_eb']);
|
||||
assert.deepEqual(at(1e6, 1e6), ['tera', 'tera10', 'peta', 'petabit', 'vol_pb', 'vol_100pb', 'vol_eb', 'vol_zb']);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the dashboard shows what was carried', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev('S.vol=1234.5');
|
||||
ev('renderDash()');
|
||||
const h = ev("document.getElementById('dash').innerHTML");
|
||||
assert.match(h, /Carried/);
|
||||
assert.match(h, /1\.23 EB/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('saves: kept, repaired, and an old save starts from the history it still holds', () => {
|
||||
const { ev, errors } = load();
|
||||
ev(start);
|
||||
ev('S.vol=42;S.hist=[{d:1,srv:1000},{d:2,srv:2000}]');
|
||||
const s = JSON.parse(ev('JSON.stringify(packSave(S))'));
|
||||
const fix = (x) => JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(x))})).vol)`));
|
||||
assert.equal(fix(s), 42);
|
||||
for (const bad of [-5, 'lots', null, Infinity]) assert.ok(Math.abs(fix({ ...s, vol: bad }) - 3000 * 0.0108) < 1e-9, `${bad} is rebuilt from the history`);
|
||||
delete s.vol;
|
||||
assert.ok(Math.abs(fix(s) - 3000 * 0.0108) < 1e-9, 'a save from before the odometer: 3,000 Gbps-days of history');
|
||||
s.hist = [{ d: 1, srv: 'x' }, { d: 2, srv: -1 }, null];
|
||||
assert.equal(fix(s), 0, 'junk history counts for nothing');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -68,14 +68,15 @@ test('a still map is drawn again when the zoom comes to rest, so the stretched p
|
|||
const { ev, errors } = open();
|
||||
ev(STUB);
|
||||
// Animations off: the loop skips frames while nothing changes.
|
||||
// mapStill() says how the map stands (MAP_MOVING, MAP_AMBIENT, MAP_STILL; 99-loop.js), not just whether it is still.
|
||||
ev(`cam.z=1;draw(__T);mapStill(0,__T);UI.drawnAt=__T;cam.z=1.3;__T+=16;mapStill(0,__T);draw(__T);UI.drawnAt=__T;`);
|
||||
ev(`__T+=16`);
|
||||
assert.equal(ev('mapStill(0,__T)'), true, 'nothing moved since the last frame');
|
||||
assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'nothing moved since the last frame');
|
||||
ev(`__T+=300`);
|
||||
assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame');
|
||||
assert.equal(ev('mapStill(0,__T)'), ev('MAP_MOVING'), 'the zoom has rested: one more frame');
|
||||
ev(`draw(__T);UI.drawnAt=__T;__T+=16`);
|
||||
assert.equal(ev('ZH.f'), 1);
|
||||
assert.equal(ev('mapStill(0,__T)'), true, 'and then the map stays still again');
|
||||
assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'and then the map stays still again');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue