Merge v2 into architect

This commit is contained in:
Frederic Jung 2026-10-30 08:01:42 +01:00
commit 235ff2f9b5
No known key found for this signature in database
83 changed files with 1847 additions and 1121 deletions

View file

@ -47,7 +47,7 @@ test('Coax gets Spectre-um’d a year in, and Final Frontear joins Very-Zone a y
start(ev2);
ev2("ACT.buildPop({city:'chi'});S.pni.push({id:'a',net:'cxc',city:'chi',tier:1,ready:0},{id:'b',net:'spc',city:'chi',tier:1,ready:0});S.day=400;dayTick()");
assert.equal(ev2("S.pni.filter(p=>p.city==='chi').map(p=>p.net).join()"), 'spc');
// the inbox never brings requests from a brand that no longer exists, and saves keep the record
// saves keep the record of who merged
ev("const o=JSON.parse(JSON.stringify(S));S=migrate(o)");
assert.equal(ev("merged('cxc')&&merged('ftr')"), true);
ev("S.merged={cxc:'x',zzz:3};S=migrate(JSON.parse(JSON.stringify(S)))");

View file

@ -469,10 +469,6 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens
const os = JSON.parse(ev("JSON.stringify(S.log.map(e=>e.o))"));
assert.deepEqual(os, [null, { a: 'city', v: 'lon' }, { a: 'link', v: linkId }, { a: 'city', v: 'fra' }]);
assert.equal(ev("S.log[0].h"), 'Raffle'); assert.equal(ev("S.log[0].t"), 'Raffle You won a T-shirt.');
// the peering inbox's own button opens the peering inbox
ev("toast('<b>Peering request</b><br>From a small network.','',[{l:'Inbox',act:'inbox',args:{}}])");
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'inbox' });
ev('ACT.logOpen({id:S.log[0].id})'); assert.equal(ev("$('modal').hidden"), false, 'the inbox opens');ev('closeModal();S.log.shift()');
// an incident points at what broke
assert.deepEqual(JSON.parse(ev(`JSON.stringify(incOpen({ref:'${linkId}'}))`)), { a: 'link', v: linkId });
assert.deepEqual(JSON.parse(ev("JSON.stringify(incOpen({ref:S.links[0].trench||S.links[0].id}))")), { a: 'link', v: ev('S.links[0].id') });
@ -483,14 +479,13 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens
assert.equal(ev("S.log.length"), 6, 'a minute later it starts a new line');
// the NOC shows them right after the incidents, with Open where there is something to open
assert.equal(ev("logUnread()"), 6);
ev("renderHUD()"); assert.equal(doc.getElementById('hNocNew').hidden, false); assert.equal(doc.getElementById('hNocNew').textContent, '6');
ev("renderHUD()"); assert.equal(doc.getElementById('hNocNew').hidden, true, 'no unread count on the NOC button (2.0)');
ev("UI.left='noc';UI.leftOpen=true;UI.sel=null;renderLeft();renderHUD()");
const body = doc.getElementById('leftBody').textContent;
assert.match(body, /Notifications\s*last 10 minutes/);
assert.ok(body.indexOf('Notifications') < body.indexOf('DDoS scrubbing'), 'near the top, not at the bottom');
assert.match(body, /×5/); assert.match(body, /just now/);
assert.equal(doc.querySelectorAll('#leftBody [data-act=logOpen]').length, 2, 'Open only where it leads somewhere (2 of the 5 shown)');
assert.equal(doc.getElementById('hNocNew').hidden, true, 'read once the NOC is open');
assert.equal(ev("logUnread()"), 0);
ev("ACT.logAll()"); assert.equal(doc.querySelectorAll('#leftBody .note').length, 6); assert.equal(doc.querySelectorAll('#leftBody [data-act=logOpen]').length, 3);
// Open goes there
@ -506,12 +501,15 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens
ev("S.log.push({t:'old',k:'weird',o:{a:'city',v:'atlantis'},n:'many'},{t:5},{t:'x',o:{a:'tab',v:'evil'}},{t:'y',o:{a:'link',v:'l1'},at:'soon'});S=sanitize(S)");
const tail = JSON.parse(ev("JSON.stringify(S.log.slice(-3))"));
assert.deepEqual(tail.map(e => [e.t, e.k, e.o, e.n, e.at]), [['old', '', null, 1, 0], ['x', '', null, 1, 0], ['y', '', { a: 'link', v: 'l1' }, 1, 0]]);
// phones: the NOC tab carries the count
// phones: the NOC tab shows no numbers, only a red dot while something is broken
ev("__tick(1000);toast('<b>Router crashed</b><br>Your router in London is rebooting.','bad');UI.left='goals';UI.leftOpen=false");
dom.window.innerWidth = 360; ev("renderAll&&renderAll()");
const nocTab = [...doc.querySelectorAll('#tabbar [data-act=phoneTab]')].find(b => JSON.parse(b.dataset.args).t === 'noc');
assert.equal(nocTab.querySelector('.cnt').textContent, '1', 'one unread notification on the NOC tab');
assert.equal(nocTab.querySelector('.cnt').classList.contains('red'), false, 'not red: red is for incidents');
assert.equal(nocTab.querySelector('.cnt'), null, 'no number for unread notifications on the NOC tab');
ev("S.inc.push({id:'x1',type:'crash',city:'lon',msg:'',until:S.day+3});renderAll()");
const nocTab2 = [...doc.querySelectorAll('#tabbar [data-act=phoneTab]')].find(b => JSON.parse(b.dataset.args).t === 'noc');
assert.ok(nocTab2.querySelector('.cnt.dot.red'), 'a live incident shows a red dot');
assert.equal(nocTab2.querySelector('.cnt').textContent, '', 'and no number');
assert.deepEqual(errors, []);
});

View file

@ -163,7 +163,7 @@ test('N2: names are puns: no network, cable, exchange, data center, router or op
const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim();
const real = new Set(REAL_NAMES.map(norm));
const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]),
...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n])].filter(x=>x[1])`);
...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]])].filter(x=>x[1])`);
fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun');
fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word');
});
@ -215,8 +215,8 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at
const P = J('PRESETS'), C = J('CHAOS'), lead = { quick: 0, real: 1 };
assert.ok(C[P.freeze.chaos].m <= C[P.oncall.chaos].m && C[P.oncall.chaos].m <= C[P.bgp.chaos].m, 'M2: chaos');
assert.ok(lead[P.freeze.lead] <= lead[P.oncall.lead] && lead[P.oncall.lead] <= lead[P.bgp.lead], 'M2: lead times');
for (const k of ['market', 'inbox']) assert.ok(!P.freeze[k] || P.oncall[k], `M2: ${k}`);
assert.ok(P.bgp.market && P.bgp.inbox && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship');
assert.ok(!P.freeze.market || P.oncall.market, 'M2: market');
assert.ok(P.bgp.market && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship');
// seeded: the same network for a year under each preset
const n = {};
for (const p of ['freeze', 'oncall', 'bgp']) {
@ -230,15 +230,14 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at
test('M3: every subsystem that can annoy the player reads a rule', () => {
// [function, what it must read]
const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['inboxDay', "rule('inbox')"],
const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]];
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');
// and in play: no chaos, no market, no inbox means a quiet year
// and in play: no chaos and no market means a quiet year
const g = load();
g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false,inbox:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()");
g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()");
assert.equal(g.ev('S.inc.length+(S.stats.incidents||0)'), 0, 'M3: nothing breaks without chaos');
assert.equal(g.ev('S.inbox.items.length+S.inbox.seq'), 0, 'M3: no mail without the inbox');
assert.equal(g.ev("hwMul('rt')"), 1, 'M3: no hardware inflation without the market');
assert.equal(g.ev("CITIES.slice(0,40).some(c=>soldOut('fra',c.id,1))"), false, 'M3: no sold-out routes without the market');
assert.deepEqual(g.errors, []);
@ -343,6 +342,25 @@ test('F2: a simple build in a start city makes money within three months on On-c
fail('F2', bad, 'a balance change made the start too hard; fix the balance, or argue for a new N in the gameplay-rules skill');
});
test('F3: a specialist path only brings customers you can already serve', () => {
const g = load();
g.ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const c of ['nyc','chi','ash'])S.pops[c]=S.pops[c]||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}");
g.ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0},{id:'d',a:'chi',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4','zr4','zr4','zr4'],km:kmBetween('chi','ash'),sub:false,cable:null,mo:0,trench:'d',cut:0,day:0,ready:0,spares:false},{id:'e',a:'nyc',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4'],km:kmBetween('nyc','ash'),sub:false,cable:null,mo:0,trench:'e',cut:0,day:0,ready:0,spares:false});compute()");
const Jg = (x) => JSON.parse(g.ev(`JSON.stringify(${x})`));
const sp = Jg('spots()');
assert.ok(sp.length > 0, 'F3: the reference network is spotted');
const bad = [];
for (const s of sp) {
const T = Jg(`BIZ_T.${s.t}`);
if (!(T.lv > 1)) bad.push(`${s.t} needs no spotting at level 1`);
if (![s.a, s.b].filter(Boolean).every((c) => g.ev(`!!S.pops['${c}']`))) bad.push(`${s.t} names a city without a POP`);
if (s.k === 'lat' && !(g.ev(`bestLat('${s.a}','${s.b}')<=latMaxOf('${s.a}','${s.b}')`))) bad.push(`${s.t} ${s.a}–${s.b} is too slow`);
if (s.k === 'df' && !(s.n >= T.opts[0] * 0.75)) bad.push(`${s.t} ${s.a}–${s.b} asks for far more than the fiber carries`);
}
fail('F3', bad, 'spots0() must only name what the network can serve, or nearly');
assert.deepEqual(g.errors, []);
});
test('no page errors while checking the rules', () => {
assert.deepEqual(errors, []);
});

54
tests/gangnam.test.js Normal file
View file

@ -0,0 +1,54 @@
// Gangnam Style Peering: sender pays, turned up by the scenario rule `sender` (and only there).
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const start = (ev) => ev(`beginGame('T','icn',{scn:SCN.find(x=>x.id==='gangnam')});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e8`);
const seoul = "ACT.launchBB({city:'icn'});ACT.buyTransit({city:'icn',net:'cog',tier:1});compute();for(let i=0;i<20;i++)dayTick();compute()";
test('sender pays: fee on Seoul transit, incumbents only over a paid PNI, cheap broadband', () => {
const { ev, errors } = load();
start(ev);
ev(seoul);
assert.ok(ev("scnRule('sender')"));
assert.equal(ev("R.reachable.ktt||R.reachable.skb||R.reachable.lgu"), false, 'transit does not carry the incumbents');
assert.ok(ev('R.reach') < 0.99);
const t = JSON.parse(ev("(()=>{const t=S.transit[0],q=R.p95[t.id];return JSON.stringify({fee:krFee(t,q),q,mo:transitMo(t,q)})})()"));
assert.ok(t.q > 0 && t.fee === Math.round(t.q * ev('KR_FEE')), 'a sender-pays fee per Gbps of transit');
assert.ok(ev("Math.abs(R.rev.eyeballs-R.cityEye.icn*sfOf(R,'icn')*EYE_RATE*KR_ARPU)<1"));
ev("ACT.pni({city:'icn',net:'ktt',tier:0});closeModal();for(let i=0;i<90&&!S.pni.every(pniOn);i++)dayTick();compute()");
assert.ok(ev('R.reachable.ktt') && ev('R.reach') >= 0.99, 'a paid PNI with Kay-Tea brings the reach');
assert.match(ev('scnCard()'), /Seoul served well/);
assert.match(ev('scnCard()'), /Monthly profit/);
assert.deepEqual(errors, []);
});
test('sender pays: Korean users mind a haul to Tokyo even over peering', () => {
const { ev, errors } = load();
start(ev);
ev("ACT.launchBB({city:'icn'});UI.via=null;UI.route=null;openLinkModal('icn','tok');ACT.buildLink({tier:1});closeModal();for(const x of ixIdsIn('tok')){ACT.buyIx({city:x,tier:1,signed:true});ACT.rs({city:x});}compute()");
assert.ok(ev('R.egT.ix') > 0 && !ev('R.egT.t'), 'only peering in Tokyo');
assert.ok(ev('R.latF.icn') < 0.95, 'the haul costs service');
assert.match(ev("latNote('icn')"), /Korean users notice/);
assert.deepEqual(errors, []);
});
test('Korea outside the scenario keeps its usual prices', () => {
const { ev, errors } = load();
ev("UI.startCity='icn';ACT.start({});closeModal();S.cash=1e8");
ev(seoul);
assert.ok(!ev("scnRule('sender')"));
assert.ok(ev('R.reachable.ktt'), 'transit reaches the incumbents');
assert.equal(ev("krFee(S.transit[0],100)"), 0);
assert.ok(ev("Math.abs(R.rev.eyeballs-R.cityEye.icn*sfOf(R,'icn')*EYE_RATE)<1"));
assert.deepEqual(errors, []);
});
test('an older Gangnam save picks up the sender-pays rule', () => {
const { ev, errors } = load();
start(ev);
const s = ev("(()=>{const o=JSON.parse(JSON.stringify(S));o.scn.rules={};return JSON.stringify(o);})()");
ev(`S=migrate(JSON.parse(${JSON.stringify(s)}))`);
assert.ok(ev("S.scn.rules.sender===true"));
assert.deepEqual(errors, []);
});

View file

@ -36,8 +36,8 @@ function tour(ev) {
['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"],
['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src);
const failSrc = ev('fireFailure.toString()');
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
const patched = failSrc.replace(/^function fireFailure/, 'function')
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`)
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
@ -82,8 +82,8 @@ test('missing translations fall back to the English, with placeholders filled',
assert.equal(ev("tr('test.no_such_label {n}',{n:3})"), 'test.no_such_label 3', 'an unknown label comes back as it is');
assert.equal(ev("trn('test.cats',1)"), '1 cat');
assert.equal(ev("trn('test.cats',2)"), '2 cats');
assert.equal(ev("trn('peering_inbox.n_day_ago',1)"), '1 giorno fa');
assert.equal(ev("trn('peering_inbox.n_day_ago',3)"), '3 giorni fa');
assert.equal(ev("trn('slots.n_day_ago',1)"), '1 giorno fa');
assert.equal(ev("trn('slots.n_day_ago',3)"), '3 giorni fa');
});
test('text that old saves stored in English is still translated', () => {

View file

@ -1,252 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev) {
ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()");
}
test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => {
const { ev, errors } = load();
setup(ev);
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})");
assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill');
assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/);
// one order in seven gets lost in provisioning for months
ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})");
const p = JSON.parse(ev('JSON.stringify(S.pni[0])'));
assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`);
ev('compute()');
assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery');
assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed');
ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()');
assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day');
// an upgrade is an augment on order: the old port keeps working meanwhile
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})");
assert.equal(ev('S.pni[0].tier'), 1);
assert.equal(ev('S.pni[0].up.tier'), 2);
ev('ACT.lagP({id:S.pni[0].id,d:1})');
assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time');
ev('S.day=S.pni[0].up.ready-1;dayTick()');
assert.equal(ev('S.pni[0].tier'), 2);
assert.equal(ev('S.pni[0].up'), undefined);
// chasing it does nothing, mostly
ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]");
const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)'));
assert.equal(r0, r1);
// most orders arrive in about a month
ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})");
assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30);
ev("S.pni=S.pni.filter(p=>p.net!=='ggl')");
// a beer at a conference halves the wait
ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}");
assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved');
ev('Math.random=()=>0.1');
assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved');
ev('Math.random=()=>0.99');
ev('S.conf=null');
// a small network: a few weeks
const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id");
ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`);
const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`);
assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`);
assert.deepEqual(errors, []);
});
test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => {
const { ev, errors } = load();
setup(ev);
ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})");
assert.equal(ev('S.pni.length'), 0);
assert.equal(ev("peerOk('dtk','pni','fra').ok"), true);
ev("ACT.pni({city:'fra',net:'dtk',tier:-1})");
assert.equal(ev('S.pni[0].g1'), true);
ev('S.pni[0].ready=S.day;compute()');
assert.equal(ev('pniG(S.pni[0])'), 1);
assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1);
assert.equal(ev('pniPN(S.pni[0])'), '1G');
// and 1G grows into 10G
ev("ACT.pni({city:'fra',net:'dtk',tier:0})");
assert.equal(ev('S.pni[0].up.tier'), 0);
ev('S.day=S.pni[0].up.ready-1;dayTick()');
assert.equal(ev('S.pni[0].g1'), undefined);
assert.equal(ev('pniG(S.pni[0])'), 10);
ev("selectCity('fra');ACT.tab({t:'peer'})");
assert.deepEqual(errors, []);
});
test('Microsnoft has no capacity on the US east coast, at any price', () => {
const { ev, errors } = load();
setup(ev);
ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5");
for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) {
assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c);
assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c);
}
assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i);
assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine');
ev("ACT.pni({city:'ash',net:'msf',tier:1})");
assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0);
assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni*repMul())"), 'other networks are not affected');
assert.deepEqual(errors, []);
});
test('the peering inbox fills up, wants answers, and max-prefix alerts are growth or a leak', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});S.inbox.pol='selective';compute()");
ev('for(let i=0;i<60;i++)dayTick()');
assert.ok(ev('S.inbox.items.length') >= 2, 'mail arrives with an exchange port');
assert.ok(ev('S.inbox.rep') < 0, 'and ignoring it has a price');
// accept a real network's request: a bilateral session
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006&&!ixSessions('ams').has(id);})");
assert.ok(net);
ev(`S.inbox.items=[{id:901,k:'req',ix:'ams',net:'${net}',day:S.day,stale:false,yrs:1,say:0},{id:902,k:'req',ix:'ams',nm:'Bob’s Bits',asn:212345,day:S.day,stale:true,yrs:7,say:3}];ACT.inbox()`);
assert.match(ev("document.getElementById('modalCard').textContent"), /Bob’s Bits/);
ev("ACT.inboxAct({id:901,a:'accept'});ACT.inboxAct({id:902,a:'accept'})");
assert.equal(ev(`!!S.peers['${net}@ams']`), true);
assert.equal(ev('S.inbox.tiny[212345].nm'), 'Bob’s Bits');
ev('compute()');
assert.equal(ev(`ixSessions('ams').has('${net}')`), true);
// growth: raising the limit brings the session back
ev(`S.inbox.items.push({id:903,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4});S.inbox.down['${net}@ams']=1e9`);
assert.equal(ev(`ixSessions('ams').has('${net}')`), false, 'down on max-prefix');
ev("ACT.inboxAct({id:903,a:'raise'})");
assert.equal(ev(`ixSessions('ams').has('${net}')`), true);
// a leak: raising the limit is a route leak, keeping it down is right
ev(`S.inbox.items.push({id:904,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:904,a:'raise'})`);
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'a route leak');
assert.ok(ev("S.inc.some(i=>i.type==='leak')"));
ev(`S.inbox.items.push({id:905,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:905,a:'keep'})`);
const back = ev(`S.inbox.down['${net}@ams']`);
assert.ok(back > ev('S.day') && back < ev('S.day') + 12, 'back on its own in a few days');
// unanswered requests expire, and the reputation makes selective networks pickier
ev("S.inbox.items=[{id:906,k:'req',ix:'ams',net:'" + net + "',day:S.day-31,stale:false,yrs:1,say:0}];S.inbox.rep=0;inboxDay(S.day)");
assert.equal(ev('S.inbox.items.some(x=>x.id===906)'), false);
assert.ok(ev('S.inbox.rep') < 0);
ev('S.inbox.rep=-10');
assert.ok(ev('repMul()') > 1.05 && ev('repMul()') <= 1.1, 'pickier, but never a wall');
// an alert nobody answers clears itself once the other side notices
ev(`S.inbox.items=[{id:910,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4}];S.inbox.down['${net}@ams']=S.day+1;inboxDay(S.day+1)`);
assert.equal(ev('S.inbox.items.some(x=>x.id===910)'), false);
// bulk answers
ev("S.inbox.items=[{id:907,k:'req',ix:'ams',nm:'A',asn:1,day:S.day,say:0,yrs:1},{id:908,k:'req',ix:'ams',nm:'B',asn:2,day:S.day,say:0,yrs:1}];ACT.inboxAll({a:'decline'})");
assert.equal(ev('S.inbox.items.length'), 0);
// the Networks tab says how much mail is waiting
ev("S.inbox.items=[{id:909,k:'req',ix:'ams',nm:'C',asn:3,day:S.day,say:1,yrs:1}];closeModal();UI.left='nets';UI.leftOpen=true;renderLeft()");
assert.match(ev("document.getElementById('left').textContent"), /Peering inbox/);
assert.deepEqual(errors, []);
});
test('the AI agent answers everything, costs $20M a year and gets it wrong a lot', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()");
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})");
const cash = ev('S.cash');
ev("ACT.inboxBot({on:1});compute()");
assert.equal(ev('S.inbox.bot'), true);
assert.ok(cash - ev('S.cash') >= ev('AI_MO'));
assert.ok(ev('R.cost.extras') >= ev('AI_MO'), 'billed every month');
assert.ok(Math.abs(ev('AI_MO*12') - 20e6) < 12);
// it always gets a leak wrong when the dice say so
ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}];S.inbox.down['${net}@ams']=1e9`);
ev('Math.random=()=>0.1;inboxBot()');
assert.equal(ev('S.inbox.items.length'), 0, 'inbox zero');
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'and a route leak');
assert.ok(ev("S.inbox.log.some(e=>/They seemed nice/.test(tr(e.m,e.a)))"), 'the log keeps a label, read in the language of the player');
ev('ACT.inbox()');
assert.match(ev("document.getElementById('modalCard').textContent"), /They seemed nice/);
// and sometimes it gets it right
ev(`S.inbox.items=[{id:3,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3}];S.ev.leak=null;Math.random=()=>0.9;inboxBot()`);
assert.ok(!ev('S.ev.leak'));
ev('ACT.inboxBot({on:0});compute()');
assert.equal(ev('S.inbox.bot'), false);
assert.ok(ev('R.cost.extras') < ev('AI_MO'));
assert.deepEqual(errors, []);
});
test('saves: the inbox and PNIs on order survive, and garbage is repaired', () => {
const { ev, errors } = load();
setup(ev);
ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})");
ev("S.inbox={items:[{id:1,k:'req',ix:'ams',nm:'Ok',asn:5,day:1,say:99},{k:'evil',ix:'ams'},{id:2,k:'mp',ix:'nowhere',key:'a'},'x'],down:{'a@b':'7'},tiny:{'12':{nm:'T',ix:'ams'},'no':{ix:'ams'}},rep:99,bot:'yes',log:[{d:1,m:'hi',a:{who:{x:1}}},5],seq:'z'}");
ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o');
assert.equal(ev('__o.inbox.items.length'), 1);
assert.equal(ev('__o.inbox.items[0].say'), ev('REQ_SAY.length-1'));
assert.equal(ev('__o.inbox.rep'), 5);
assert.equal(ev('__o.inbox.bot'), true);
assert.equal(ev("__o.inbox.down['a@b']"), 7);
assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(__o.inbox.tiny))')), ['12']);
assert.equal(ev('typeof __o.inbox.log[0].a.who'), 'string');
assert.equal(ev('__o.inbox.seq'), 1);
assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX'));
assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true);
assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G');
// an old save without an inbox loads with an empty one
ev('const p=JSON.parse(JSON.stringify(S));delete p.inbox;sanitize(p);window.__p=p');
assert.equal(ev('__p.inbox.items.length'), 0);
assert.equal(ev('__p.inbox.bot'), false);
assert.deepEqual(errors, []);
});
test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3");
assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days');
// find a day when 400G is sold out between Frankfurt and Amsterdam
const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()");
assert.ok(day > 0, 'it happens');
ev(`S.day=${day}`);
const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))"));
assert.ok(so.until > day && so.until - day <= 90);
assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window');
ev(`S.day=${day}`);
const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()");
assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`);
ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`);
assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/);
const n = ev('S.links.length');
ev('ACT.buildLink({tier:2})');
assert.equal(ev('S.links.length'), n, 'no 400G today');
assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/);
assert.deepEqual(errors, []);
});
test('peering policy: open accepts everyone, selective is quieter but manual, closed scares customers; raise all limits at once', () => {
const { ev, errors } = load();
setup(ev);
ev("S.nextFail=S.nextEvent=1e9;ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams'});compute()");
assert.equal(ev("ppol()"), 'open', 'open by default, as before');
const rsOpen = ev("ixSessions('ams').size");
assert.ok(rsOpen > 0, 'the route server works');
// open: requests are accepted as they come in
ev("Math.random=()=>0.01;inboxDay(S.day+1)");
assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0);
assert.ok(ev("Object.keys(S.inbox.tiny).length+Object.keys(S.peers).length") > 0, 'and they become sessions');
// selective: the route server stops counting, you ask yourself, and requests wait for you
ev("ACT.inboxPol({p:'selective'});compute()");
assert.ok(ev("ixSessions('ams').size") < rsOpen, 'no route server sessions');
ev("selectCity('ams');ACT.tab({t:'peer'})");
assert.match(ev("document.getElementById('panelBody').textContent"), /Off while your peering policy is Selective/);
ev("closeModal();S.inbox.items=[];inboxDay(S.day+1)");
assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 1, 'it waits for an answer');
// closed: no requests, a sinking reputation, fewer customers calling
ev("ACT.inboxPol({p:'closed'});S.inbox.items=[];S.inbox.rep=0;for(let i=0;i<10;i++)inboxDay(S.day+1)");
assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0);
assert.ok(ev('S.inbox.rep') < 0);
// raise all: every alert at once, leaks included
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})");
ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:71,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:80,leak:false,yrs:2},{id:72,k:'mp',key:'t9',nm:'X',asn:9,ix:'ams',day:S.day,lim:50,got:990000,leak:true,yrs:2}];S.inbox.down['${net}@ams']=1e9;ACT.inbox()`);
assert.match(ev("document.getElementById('modalCard').textContent"), /Raise all max-prefix limits/);
ev('ACT.inboxRaiseAll()');
assert.equal(ev("S.inbox.items.length"), 0);
assert.equal(ev(`!!S.inbox.down['${net}@ams']`), false);
assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'one was a leak');
assert.match(ev("document.getElementById('toasts').textContent"), /One of them was a route leak/);
// saves keep the policy
ev("const o=JSON.parse(JSON.stringify(S));o.inbox.pol='weird';sanitize(o);window.__o=o");
assert.equal(ev('__o.inbox.pol'), 'open');
assert.deepEqual(errors, []);
});

View file

@ -571,7 +571,8 @@ test('buttons behind an open modal stay quiet, and a declined PNI clears its sta
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'mrs'});ACT.buyTransit({city:'mrs',net:'cog',tier:1});compute()");
// the PNI button was drawn while Tangerine still wanted our traffic; by the click it doesn't
ev("R.demTo.tng=50;UI.sel={type:'city',id:'mrs'};UI.tab='peer';renderAll();R.demTo.tng=0;window.__n=0;const o=toast;toast=function(h){if(/declined/.test(h))window.__n++;return o.apply(this,arguments);}");
// Tier 2 is folded when nothing there is worth a PNI (#175): open it, as a player would.
ev("UI.pniOpen={t2:true};R.demTo.tng=50;UI.sel={type:'city',id:'mrs'};UI.tab='peer';renderAll();R.demTo.tng=0;window.__n=0;const o=toast;toast=function(h){if(/declined/.test(h))window.__n++;return o.apply(this,arguments);}");
const btn = "document.querySelector('#panel [data-act=pni][data-args*=tng]')";
assert.ok(ev(`!!${btn}`), 'a stale button to start with');
ev(`${btn}.focus();${btn}.click()`);
@ -1310,7 +1311,7 @@ test('#134 an exchange named after its city does not repeat the city in messages
const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))"));
assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | '));
assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | '));
ev("S.inc=[];eval('('+fireFailure.toString().replace('type=pick(f);}',\"type='maxpfx';}\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()");
ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()");
const msg = ev("S.inc.map(i=>i.msg).join(' ')");
assert.match(msg, /IX\.brrr Campinas/);
assert.doesNotMatch(msg, /in Campinas/);

View file

@ -299,12 +299,12 @@ test('#34 scenario goal, progress and customer level are always in view', () =>
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderAll()");
const left = () => dom.window.document.getElementById('leftBody').textContent;
assert.match(left(), /Mind the Gap/);
assert.match(left(), /POP in Bogotá/);
assert.match(left(), /Bogotá on your network/);
assert.match(left(), /days left/);
assert.match(left(), /Customer level 1 of 13/);
assert.equal(ev("$('hScn').hidden"), false, 'scenario chip in the top bar');
const f0 = ev('scnProg().f');
ev("S.cash=1e8;ACT.buildPop({city:'bog'});ACT.buildPop({city:'lim'});compute();renderAll()");
ev("S.cash=1e8;UI.via='pccs';openLinkModal('pan','bog');ACT.buildLink({tier:1});closeModal();compute();renderAll()");
assert.ok(ev('scnProg().f') > f0, 'progress moves when a goal step is reached');
assert.match(ev("$('hScnVal').textContent"), /%/);
assert.match(ev("$('hTier').textContent"), /Lv 1/);
@ -361,8 +361,10 @@ test('Flood Season: attacks keep coming, grow, and only count when service held'
for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; }
assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`);
assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored');
// scoring: held only if service stayed at 97%+
ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})");
// scoring: held only if service stayed at 97%+, and a terabit one only with scrubbing or Flowspec
ev("S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,vec:'http',worst:0.99})");
assert.equal(ev('S.stats.ddosOk+S.stats.ddosOkBig'), 1, 'held, but no terabit credit without mitigation');
ev("S.scrubs.push({city:'ams',tier:1});S.stats.ddosOk=0;S.stats.ddosOkBig=0;S.stats.ddosLost=0;ddosDone({city:'ams',gbps:1500,worst:0.99});ddosDone({city:'ams',gbps:20,worst:0.5});ddosDone({city:'xyz',gbps:30,worst:1})");
assert.equal(ev('S.stats.ddosOk'), 2);
assert.equal(ev('S.stats.ddosOkBig'), 1);
assert.equal(ev('S.stats.ddosLost'), 1);

32
tests/own-asn.test.js Normal file
View file

@ -0,0 +1,32 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('pick your own AS number next to the name, or leave it empty for a random one (#135)', () => {
const { ev, errors } = load();
assert.ok(ev("!!document.querySelector('.network-name .nmwrap #nmIn')&&!!document.querySelector('.nmwrap .reroll[data-act=randomName]')"), 'round reroll button inside the name box');
const sug = ev("+document.getElementById('asnIn').placeholder");
assert.ok(ev(`asnOk(${sug})`), 'the suggestion is usable');
const set = v => ev(`(()=>{const i=document.getElementById('asnIn');i.value=${JSON.stringify(v)};i.dispatchEvent(new Event('input'));return i.value})()`);
assert.equal(set('AS 2-0-1-9-1-7'), '201917', 'only digits stay');
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
assert.equal(ev('S.asn'), 201917);
assert.match(ev("document.getElementById('hAsn').textContent"), /AS201917/);
assert.deepEqual(errors, []);
});
test('an AS number that would not route is refused before the game starts', () => {
const { ev, errors } = load();
for (const bad of ['0', '23456', '64512', '4200000001', String(ev('NETS[0].asn'))]) {
assert.equal(ev(`asnOk(${bad})`), false, bad);
}
ev("(()=>{const i=document.getElementById('asnIn');i.value='64512';i.dispatchEvent(new Event('input'))})()");
assert.ok(ev("document.getElementById('asnIn').classList.contains('bad')"));
ev('ACT.start({})');
assert.equal(ev('S'), null, 'no game');
assert.match(ev("document.getElementById('toasts').textContent"), /won't route/);
ev("(()=>{const i=document.getElementById('asnIn');i.value='';i.dispatchEvent(new Event('input'))})()");
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()");
assert.ok(ev('asnOk(S.asn)&&S.asn>=200000'), 'empty: a random one');
assert.deepEqual(errors, []);
});

117
tests/peering-desk.test.js Normal file
View file

@ -0,0 +1,117 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev) {
ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()");
}
// Math.random returns these, then 0.5: [ask?, which IX, a real network?, (which one), fresh PeeringDB?]
const seq = (ev, a) => ev(`(()=>{const q=${JSON.stringify(a)};Math.random=()=>q.length?q.shift():0.5;})()`);
const REAL = [0.01, 0.01, 0.01, 0.01, 0.01], STALE = [0.01, 0.01, 0.9, 0.1], FRESH = [0.01, 0.01, 0.9, 0.9];
test('peering requests are answered by policy: Open accepts all, Selective the worthwhile ones, Closed none', () => {
const { ev, errors } = load();
setup(ev);
assert.equal(ev('ppol()'), 'open', 'open by default, as before');
const day = () => ev('peeringDeskDay(S.day)');
const peers = () => ev("Object.keys(S.peers).filter(k=>k.endsWith('@ams')).length");
let n = peers();
seq(ev, REAL); day();
assert.equal(peers(), n + 1, 'Open: a real network on the exchange gets its session at once');
assert.ok(ev("ixSessions('ams').size") > 0);
seq(ev, STALE); day();
assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [2, 0], 'Open even takes the stale newcomer');
ev("ACT.peerPol({p:'selective'})");
assert.equal(ev('ppol()'), 'selective');
n = peers(); seq(ev, REAL); day();
assert.equal(peers(), n + 1, 'Selective: a real small network is worth it');
seq(ev, STALE); day();
seq(ev, FRESH); day();
assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [4, 1], 'stale PeeringDB declined, up-to-date one accepted');
ev("ACT.peerPol({p:'closed'})");
n = peers(); seq(ev, REAL); day(); seq(ev, FRESH); day();
assert.equal(peers(), n, 'Closed: nobody gets a session');
assert.equal(ev('S.pdesk.d'), 3);
ev("ACT.peerPol({p:'nope'})");
assert.equal(ev('ppol()'), 'closed', 'junk is ignored');
assert.deepEqual(errors, []);
});
test('once a week the NOC log gets one folded peering desk line', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.buyIx({city:'fra',tier:1,signed:true});ACT.peerPol({p:'selective'})");
seq(ev, [0.99]); ev('S.day=Math.ceil(S.day/7)*7+7;S.pdesk=null;peeringDeskDay(S.day)');
const w = ev('Math.floor(S.day/7)');
for (let i = 0; i < 6; i++) { seq(ev, i % 3 === 2 ? STALE : [0.01, i % 2 ? 0.01 : 0.99, 0.9, 0.9]); ev(`peeringDeskDay(S.day+${i})`); }
assert.equal(ev('S.pdesk.w'), w);
const logs = ev('S.log.length');
seq(ev, [0.99]); ev('peeringDeskDay(S.day+7)');
assert.equal(ev('S.log.length'), logs + 1, 'one line for the week');
const line = ev('S.log[0].t');
assert.match(line, /^Peering desk: 4 new sessions at .+ and .+, 2 declined \(Selective\)\.$/);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'tab', v: 'nets' });
assert.equal(ev('S.pdesk.w'), w + 1);
// a quiet week says nothing
ev('peeringDeskDay(S.day+14)');
assert.equal(ev('S.log.length'), logs + 1);
// the Networks tab has the policy picker, what it does, and last week's line; it fits a phone
ev("window.innerWidth=360;UI.left='nets';UI.leftOpen=true;S.pdeskRep.w=Math.floor(S.day/7)-1;renderLeft()");
const left = ev("document.getElementById('left').textContent");
assert.match(left, /Peering policy: Selective/);
assert.match(left, /newcomers with an up-to-date PeeringDB/);
assert.match(left, /Peering desk: 4 new sessions/);
assert.doesNotMatch(left, /inbox/i);
ev("document.querySelector('#left [data-act=peerPol][data-args*=closed]').click()");
assert.equal(ev('ppol()'), 'closed');
assert.match(ev("document.getElementById('left').textContent"), /Every peering request is declined/);
// more than four exchanges fold into "and N more"
ev("S.pdeskRep={w:0,a:9,d:0,p:'open',ix:['ams','fra','lon','par','nyc']}");
assert.match(ev('pdeskLine(S.pdeskRep)'), /9 new sessions at .+, .+, .+ and 2 more exchanges \(Open to all\)/);
assert.match(ev("pdeskLine({a:0,d:1,p:'closed',ix:[]})"), /^Peering desk: 1 request declined \(Closed\)\.$/);
assert.deepEqual(errors, []);
});
test('old saves with inbox, max-prefix and Large Peering Model state load and play', () => {
const { ev, errors } = load();
setup(ev);
const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})");
ev(`S.peers['${net}@ams']=true;delete S.ppol;delete S.pdesk;delete S.pdeskRep;
S.inbox={items:[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}],
down:{'${net}@ams':S.day+30},tiny:{'4':{nm:'D',ix:'ams'}},rep:-8,bot:true,pol:'selective',log:[{d:1,m:'peering_inbox.fire_the_ai',a:{}}],seq:2};
S.rules={...S.rules,inbox:true};S.ev.ixdown={ams:S.day+2};
S.inc.push({id:'m1',type:'maxpfx',ref:'ams',until:S.day+2,msg:'A member leaked the table.',cost:0,start:S.day});
S.log.unshift({id:'l1',t:'Peering request',h:'Peering request',k:'',o:{a:'inbox'},ts:Date.now()})`);
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev('S.inbox'), undefined, 'the inbox is gone');
assert.equal(ev('ppol()'), 'selective', 'the policy is kept');
assert.equal(ev("'inbox' in S.rules"), false);
assert.equal(ev("S.inc.find(i=>i.id==='m1').type"), 'ixloop', 'a max-prefix outage in flight becomes an ordinary IX outage');
assert.equal(ev("S.inc.some(i=>i.type==='maxpfx')"), false);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.log.find(e=>e.id==='l1').o)")), { a: 'tab', v: 'nets' });
assert.equal(ev(`ixSessions('ams').has('${net}')`), true, 'no session stays down on an old max-prefix limit');
const extras = ev('R.cost.extras');
assert.ok(extras < 20e6 / 12, 'the Large Peering Model no longer bills');
ev("ACT.logOpen({id:'l1'})");
assert.equal(ev('UI.left'), 'nets');
ev('for(let i=0;i<40;i++)dayTick()');
assert.ok(ev('S.inc.every(i=>i.type!=="maxpfx")'));
assert.ok(ev('S.pdesk&&S.pdesk.w>=0'));
// garbage in the new fields is repaired
ev("const o=JSON.parse(JSON.stringify(S));o.ppol='weird';o.pdesk={w:'x',a:-5,d:1e9,ix:['ams','ams','nowhere',3]};o.pdeskRep=[1];sanitize(o);window.__o=o");
assert.equal(ev('__o.ppol'), 'open');
assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.pdesk)')), { w: 0, a: 0, d: 1e5, ix: ['ams'] });
assert.equal(ev('__o.pdeskRep'), null);
assert.deepEqual(errors, []);
});
test('max-prefix incidents can no longer fire', () => {
const { ev, errors } = load();
setup(ev);
assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false);
ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')");
ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}");
assert.equal(ev('!!window.__mp'), false);
assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined');
assert.deepEqual(errors, []);
});

View file

@ -200,15 +200,14 @@ test('a peer at a rival exchange can de-peer you without stopping the game', ()
assert.deepEqual(errors, []);
});
test('an IX meltdown at a rival exchange names the city, and a failing day tick does not stop the game', () => {
test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100");
const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function')
.replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce")
.replace('type=pick(f);}', "type='maxpfx';}");
.replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce");
ev('window.__ff=' + src);
ev('__ff()');
assert.match(ev("S.inc.find(i=>i.type==='maxpfx').msg"), /in Amsterdam, is down/);
assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))"));
// a tick that throws is caught, reported once, and the loop keeps going
ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0");
assert.equal(ev('UI.tickErr'), true);

135
tests/pni-list.test.js Normal file
View file

@ -0,0 +1,135 @@
// The PNI list (#175, #172): how you reach each network, whether a PNI here is worth it, sorted, filtered and grouped.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Frankfurt with 100G of Cogentle transit and 50G of eyeballs: nothing dropped, everything over transit.
const fra = (ev, d = 50) => {
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev(`S.pops.fra.bb.d=${d};S.grace=null;ACT.buyTransit({city:'fra',net:'cog',tier:1});for(const t of S.transit)t.ready=0;compute()`);
};
const chip = (ev, id, c = 'fra') => ev(`(()=>{const d=document.createElement('div');d.innerHTML=pniChip('${id}',${c ? `'${c}'` : 'null'});return d.textContent})()`);
test('one status chip per network, most direct first', () => {
const { ev, errors } = load();
fra(ev);
assert.equal(chip(ev, 'ggl'), '💸 Via transit');
// PNI here, with its size and load
ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()");
const load_ = ev("pct(R.usePni[S.pni[0].id]/100)");
assert.equal(chip(ev, 'ggl'), `🔗 PNI here · 100G · ${load_}`);
// On order shows as such
ev("S.pni[0].ready=S.day+20;compute()");
assert.equal(chip(ev, 'ggl'), '🔗 PNI here · on order');
ev("S.pni[0].ready=0;compute()");
// Elsewhere: the city names, and in the Networks tab (no POP) "PNI at"
ev("for(const c of ['ams','lon','par'])S.pni.push({id:'x'+c,net:'nfx',city:c,tier:1});compute()");
assert.equal(chip(ev, 'nfx'), '🔗 PNI elsewhere: Amsterdam, London +1');
assert.equal(chip(ev, 'ggl', null), '🔗 PNI at Frankfurt');
// IX session
ev("ACT.buyIx({city:'fra',tier:1,signed:true});S.peers['akm@fra']=true;compute()");
assert.equal(chip(ev, 'akm'), `🤝 Peers at ${ev("ixName('fra')")}`);
// Through a peer's customer cone: named after the peer that carries it (R.cone)
ev("S.pni.push({id:'pntt',net:'ntt',city:'fra',tier:1});compute()");
assert.equal(ev("R.cone.voc"), 'ntt');
assert.equal(chip(ev, 'voc'), `🧺 Via ${ev("NET.ntt.name")}'s cone`);
// Not reached once transit goes
ev("S.transit=[];compute()");
assert.equal(ev("R.reachable.lvl"), false);
assert.equal(chip(ev, 'lvl'), '🚫 Not reached');
assert.deepEqual(errors, []);
});
test('the value line matches the transit bill by hand, and the worth-it rule', () => {
const { ev, errors } = load();
fra(ev);
const v = ev("pniVal('ggl','fra')");
const t = ev("(()=>{const t=S.transit[0];return {q:R.p95[t.id],per:transitPerG(NET[t.net],t.city,premOn(t))*S.priceMul,floor:PORT[t.tier].g*0.2}})()");
assert.ok(v.t > 1 && v.ix === 0 && v.p === 0 && v.u < 1e-6, 'all of it over transit');
assert.ok(t.q - v.t > t.floor, 'above the commit, so each Gbps saved is the per-Gbps price');
assert.ok(Math.abs(v.saved - v.t * t.per) < 1e-6, 'saved = Gbps × transit price');
assert.equal(v.cost, ev("PORT[1].pni"), 'a 100G PNI with Goggle (no fee, no per-G)');
assert.equal(v.tier, 1, 'the smallest port Goggle accepts');
assert.equal(v.val, v.saved - v.cost);
assert.equal(v.worth, v.val > 0);
// Below the commit floor nothing is saved: a tiny network has little to gain.
const small = ev("pniVal('pst','fra')");
assert.ok(small.g < 1 && !small.worth);
// A full transit port drops traffic: a PNI that carries it is worth it even if it saves no transit.
ev("S.pops.fra.bb.d=400;compute()");
const big = ev("pniVal('nfx','fra')");
assert.ok(big.u >= 1 && big.drop >= 1 && big.worth, 'dropped traffic makes it worth it');
// Information only: routing is the same with or without the list reading it.
const before = ev("JSON.stringify(R.usePni)+R.served");
ev("renderAll();UI.sel={type:'city',id:'fra'};UI.tab='peer';renderPanel();compute()");
assert.equal(ev("JSON.stringify(R.usePni)+R.served"), before);
assert.deepEqual(errors, []);
});
test('the PNI list: worth it first, filters, groups by type folded when idle, phones', () => {
const { ev, errors, dom } = load();
dom.window.innerWidth = 360;
fra(ev, 400);
ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()");
const panel = () => { ev("UI.sel={type:'city',id:'fra'};UI.tab='peer';UI._ph=null;renderPanel()"); return dom.window.document.getElementById('panelBody'); };
let p = panel();
const heads = [...p.querySelectorAll('.pgrp')].map(x => x.textContent);
assert.ok(heads.length >= 4, 'grouped by type');
assert.match(heads[0], /Tier 1/);
assert.ok(heads.some(h => /Paid peering/.test(h)), 'paid networks get their own group');
// A group with nothing worth it and no PNI stays folded; one with a worth-it network is open, best first.
const rows = ev("(()=>{const r=NETS.filter(n=>n.pops.includes('fra')&&n.type==='cdn'&&n.pol!=='paid').map(n=>({id:n.id,v:pniVal(n.id,'fra')})).filter(x=>!S.pni.some(p=>p.net===x.id));return r})()");
const w = rows.filter(r => r.v.worth).sort((a, b) => b.v.val - a.v.val);
assert.ok(w.length, 'some content network is worth it at 400G of demand');
const names = [...p.querySelectorAll('.prow .nm')].map(x => x.textContent);
const first = ev(`NET.${w[0].id}.name`);
assert.ok(names.some(n => n.startsWith(first) && /Worth it/.test(n)), 'best candidate is tagged');
assert.equal(p.querySelectorAll('.prow .pchip').length, names.length, 'every row has a status chip');
assert.ok(p.querySelector('.pval'), 'value line');
// Filters
ev("ACT.pniFilter({f:'pni'})");p = panel();
assert.deepEqual([...p.querySelectorAll('.prow .nm')].map(x => x.textContent.split(' ')[0]), [ev("NET.ggl.name").split(' ')[0]]);
ev("ACT.pniFilter({f:'worth'})");p = panel();
assert.ok([...p.querySelectorAll('.prow .nm')].every(x => /Worth it/.test(x.textContent)));
ev("ACT.pniFilter({f:'t'})");p = panel();
assert.ok([...p.querySelectorAll('.pchip')].every(x => /Via transit|Not reached/.test(x.textContent)));
// Folding and unfolding by hand, A-Z sort
ev("ACT.pniFilter({f:'all'})");
ev("ACT.pniGrp({g:'t1',o:0})");p = panel();
assert.match(p.querySelector('.pgrp').textContent, /▸/);
ev("ACT.pniGrp({g:'t1',o:1});ACT.pniSort()");p = panel();
assert.match(p.textContent, /Sort: A–Z/);
// Phone: chips wrap, value text stays on one line
const css = ev("[...document.querySelectorAll('style')].map(s=>s.textContent).join('')");
assert.match(css, /\.pchips\{display:flex;flex-wrap:wrap/);
assert.match(css, /\.pval\{white-space:nowrap;overflow:hidden;text-overflow:ellipsis/);
assert.equal(ev("isPhone()"), true);
assert.deepEqual(errors, []);
});
test('the same chip in the Networks tab and the bulk PNI preview', () => {
const { ev, errors, dom } = load();
fra(ev);
ev("S.pni.push({id:'pg',net:'ggl',city:'fra',tier:1});compute()");
ev("UI.sel=null;UI.left='nets';UI.leftOpen=true;UI._lh=null;renderLeft()");
const left = dom.window.document.getElementById('leftBody');
assert.ok(left.querySelectorAll('.pchip').length >= 10);
assert.ok(/PNI at Frankfurt/.test(left.textContent), 'Goggle shows its PNI');
ev("ACT.pniAllOpen({net:null})");
const m = dom.window.document.getElementById('modal');
assert.ok(m.querySelectorAll('.pchip').length > 0);
assert.ok(/Via transit/.test(m.textContent), 'bulk preview chips');
assert.deepEqual(errors, []);
});
test('every language renders the PNI list without raw labels', () => {
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
const { ev, errors, dom } = load({ lang });
fra(ev, 400);
ev("UI.sel={type:'city',id:'fra'};UI.tab='peer';renderPanel();UI.left='nets';UI.leftOpen=true;renderLeft()");
const txt = dom.window.document.getElementById('panelBody').textContent + dom.window.document.getElementById('leftBody').textContent;
assert.doesNotMatch(txt, /pni_list\./, lang);
assert.ok(dom.window.document.querySelector('#panelBody .pchip'), lang);
assert.deepEqual(errors, [], lang);
}
});

View file

@ -0,0 +1,127 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev) {
ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()");
}
test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => {
const { ev, errors } = load();
setup(ev);
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})");
assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill');
assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/);
// one order in seven gets lost in provisioning for months
ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})");
const p = JSON.parse(ev('JSON.stringify(S.pni[0])'));
assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`);
ev('compute()');
assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery');
assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed');
ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()');
assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day');
// an upgrade is an augment on order: the old port keeps working meanwhile
ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})");
assert.equal(ev('S.pni[0].tier'), 1);
assert.equal(ev('S.pni[0].up.tier'), 2);
ev('ACT.lagP({id:S.pni[0].id,d:1})');
assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time');
ev('S.day=S.pni[0].up.ready-1;dayTick()');
assert.equal(ev('S.pni[0].tier'), 2);
assert.equal(ev('S.pni[0].up'), undefined);
// chasing it does nothing, mostly
ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]");
const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)'));
assert.equal(r0, r1);
// most orders arrive in about a month
ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})");
assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30);
ev("S.pni=S.pni.filter(p=>p.net!=='ggl')");
// a beer at a conference halves the wait
ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}");
assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved');
ev('Math.random=()=>0.1');
assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved');
ev('Math.random=()=>0.99');
ev('S.conf=null');
// a small network: a few weeks
const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id");
ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`);
const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`);
assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`);
assert.deepEqual(errors, []);
});
test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => {
const { ev, errors } = load();
setup(ev);
ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})");
assert.equal(ev('S.pni.length'), 0);
assert.equal(ev("peerOk('dtk','pni','fra').ok"), true);
ev("ACT.pni({city:'fra',net:'dtk',tier:-1})");
assert.equal(ev('S.pni[0].g1'), true);
ev('S.pni[0].ready=S.day;compute()');
assert.equal(ev('pniG(S.pni[0])'), 1);
assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1);
assert.equal(ev('pniPN(S.pni[0])'), '1G');
// and 1G grows into 10G
ev("ACT.pni({city:'fra',net:'dtk',tier:0})");
assert.equal(ev('S.pni[0].up.tier'), 0);
ev('S.day=S.pni[0].up.ready-1;dayTick()');
assert.equal(ev('S.pni[0].g1'), undefined);
assert.equal(ev('pniG(S.pni[0])'), 10);
ev("selectCity('fra');ACT.tab({t:'peer'})");
assert.deepEqual(errors, []);
});
test('Microsnoft has no capacity on the US east coast, at any price', () => {
const { ev, errors } = load();
setup(ev);
ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5");
for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) {
assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c);
assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c);
}
assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i);
assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine');
ev("ACT.pni({city:'ash',net:'msf',tier:1})");
assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0);
assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni)"), 'other networks are not affected');
assert.deepEqual(errors, []);
});
test('saves: PNIs on order survive, and garbage is repaired', () => {
const { ev, errors } = load();
setup(ev);
ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})");
ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o');
assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX'));
assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true);
assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G');
assert.deepEqual(errors, []);
});
test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3");
assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days');
// find a day when 400G is sold out between Frankfurt and Amsterdam
const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()");
assert.ok(day > 0, 'it happens');
ev(`S.day=${day}`);
const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))"));
assert.ok(so.until > day && so.until - day <= 90);
assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window');
ev(`S.day=${day}`);
const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()");
assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`);
ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`);
assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/);
const n = ev('S.links.length');
ev('ACT.buildLink({tier:2})');
assert.equal(ev('S.links.length'), n, 'no 400G today');
assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/);
assert.deepEqual(errors, []);
});

View file

@ -18,7 +18,7 @@ const REF = {
downunder: { one: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1]], three: [['syd', 'mel', 'land', 1], ['syd', 'bne', 'land', 1], ['mel', 'adl', 'land', 1], ['bne', 'adl', 'land', 1]] },
edgelord: { one: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]], three: [['@rt', 'ams', 5, 1], ['@rt', 'lon', 5, 1], ['ams', 'lon', 'concerto', 2], ['ams', 'lon', 'nshuttle', 2], ['ams', 'lon', 'circe', 1]] },
hubcap: { one: [['@rt', 'lon', 5, 1], ['lon', 'par', 'pasdc', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1]], three: [['@rt', 'lon', 5, 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'concerto', 1], ['lon', 'ams', 'circe', 1], ['lon', 'ams', 'nshuttle', 1], ['lon', 'par', 'chn', 1], ['lon', 'par', 'pasdc', 1], ['ams', 'fra', 'land', 1], ['ams', 'fra', 'land', 1], ['lon', 'ams', 'uly', 1]] },
flash: { one: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] },
flash: { one: [['nyc', 'lon', 'hibx', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'lon', 'hibx', 0]] },
baltic: { one: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['@route', 1, 'fast']], three: [['fra', 'hel', 'clion', 1], ['tll', 'hel', 'land', 1], ['fra', 'tll', 'land', 1], ['@route', 1, 'fast']] },
fjord: { one: [['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']], three: [['par', 'svg', 'land', 1], ['par', 'lon', 'pasdc', 1], ['svg', 'lon', 'tampn', 1], ['@route', 1, 'fast']] },
braces: { one: [['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]], three: [['nyc', 'lon', 'grace', 1], ['nyc', 'dub', 'havf', 1], ['lon', 'dub', 'celtix', 1]] },
@ -488,7 +488,7 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
ev("ACT.pzPop({city:'lon'})");
const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})");
const s0 = st();
for (const a of ["opsOpen({})", "inbox({})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})",
for (const a of ["opsOpen({})", "peerPol({p:'closed'})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})",
"exportSave({})", "launchBB({city:'lon'})", "ad({city:'lon'})", "addRouter({city:'lon'})", "upRouter({city:'lon'})", "addSite({city:'lon'})", "buyTE({})",
"buildScrub({city:'lon',tier:0})", "buildPop({city:'par'})", "buyTransit({city:'lon',net:'cog',tier:1})", "scenarios({})", "share({})", "importGo({})", "cont({})", "start({})", "newgame({})"]) {
ev('ACT.' + a);
@ -530,3 +530,18 @@ test('a POP in a thin market costs its higher monthly rent too, and the panel sa
assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo'));
assert.deepEqual(errors, []);
});
test('each pack\'s idea is needed: three stars without it fail, and the one-star builds are not secretly three', () => {
const { ev, errors } = load();
const stars = (id, steps) => { ev(`pzBegin(pzDef('${id}'))`); build(ev, steps); return evalP(ev).stars; };
const packs = JSON.parse(ev('JSON.stringify(Object.fromEntries(PZ.map(p=>[p.id,p.pack])))'));
for (const id of Object.keys(REF)) {
// A ring puzzle's cheapest delivering build is a ring, which is already N-1.
if (id !== 'fire') assert.ok(stars(id, REF[id].one) < 3, `${id}: the one-star reference earns three stars`);
if (packs[id] === 'rodeo') assert.ok(stars(id, REF[id].three.filter((s) => s[0] !== '@rt')) < 3, `${id}: three stars on the starter routers`);
if (REF[id].three.some((s) => s[0] === '@route')) assert.ok(stars(id, REF[id].three.filter((s) => s[0] !== '@route')) < 3, `${id}: three stars without the routing choice`);
// N-1 Club: the brute-force answer (every one-star link doubled) is over budget or not N-1.
if (packs[id] === 'n1') assert.ok(stars(id, [...REF[id].one, ...links(REF[id].one)]) < 3, `${id}: doubling every link earns three stars`);
}
assert.deepEqual(errors, []);
});

View file

@ -563,8 +563,10 @@ test('the Amazon doubles overland fiber, and there is a national-operator scenar
assert.equal(ev('S.scn.id'), 'ixbr');
assert.equal(ev('brIxN()'), 0);
ev("S.cash=1e9;for(const c of ['sao','rio','mao'])ACT.buildPop({city:c});S.ixp.sao=1;S.ixp.mao=1;compute()");
assert.equal(ev('brIxN()'), 2);
assert.equal(ev('brIxN()'), 1, 'a Manaus port on a POP the backbone does not reach does not count');
assert.equal(ev("scnProg().items[1].v"), 1, 'Manaus step done');
ev("S.links.push({id:'y1',a:'sao',b:'mao',km:2700,sub:false,kind:'wave',tier:0,mo:1});compute()");
assert.equal(ev('brIxN()'), 2, 'joined up, it counts');
assert.deepEqual(errors, []);
});
@ -670,8 +672,10 @@ test('Fibre to the Basement: own fibre skips the wholesale cut but pays the levy
assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), false, 'still needs cables overseas');
ev("S.links.push({id:'x1',a:'syd',b:'tok',km:8000,sub:true,cable:'sushi',kind:'wave',tier:1,mo:1},{id:'x2',a:'per',b:'sin',km:4000,sub:true,cable:'avo',kind:'wave',tier:1,mo:1},{id:'x3',a:'mel',b:'hba',km:600,sub:true,cable:'ferry',kind:'wave',tier:1,mo:1})");
assert.equal(ev('auExits()'), 2, 'Bass Strait does not count as overseas');
assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), false, 'still needs the traffic');
ev('R.served=FTTB_G');
assert.equal(ev("SCN.find(s=>s.id==='fttb').ok()"), true);
assert.equal(ev("SCN_PROG.fttb().length"), 6);
assert.equal(ev("SCN_PROG.fttb().length"), 7);
assert.deepEqual(errors, []);
});

View file

@ -20,10 +20,11 @@ test('bugs and ideas point to GitHub from the menu and How to play, and the chat
}
});
test('the GitHub card fits a phone', () => {
test('the GitHub link fits a phone: a small link next to the chat link in the menu', () => {
const { ev, errors } = load();
ev("ACT.start({});window.innerWidth=360;ACT.menu()");
assert.ok(ev('isPhone()'));
assert.ok(ev(`!!document.querySelector('#modal a.plug[href="${ISSUES}"] .go')`), 'same card layout as the chat card');
assert.ok(ev(`!!document.querySelector('#modal .menu-plugs a.mplug[href="${ISSUES}"]')`), 'bug link in the menu');
assert.ok(ev(`!!document.querySelector('#modal .menu-plugs a.mplug[href="'+SIGNAL+'"]')`), 'chat link beside it');
assert.deepEqual(errors, []);
});

View file

@ -159,11 +159,10 @@ test('quick lead times: PNIs, dark fiber and own builds arrive in days (#151)',
assert.deepEqual(errors, []);
});
test('Change Freeze: no peering inbox, no hardware market, no sold-out routes', () => {
test('Change Freeze: no hardware market, no sold-out routes', () => {
const { ev, errors } = load();
start(ev, { mode: 'normal', preset: 'freeze' });
ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<60;i++)inboxDay(S.day+i)");
assert.equal(ev('S.inbox.items.length+S.inbox.seq'), 0, 'no mail');
ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true})");
ev('S.day=2000');
assert.equal(ev("hwMul('rt')"), 1, 'no inflation');
assert.equal(ev("hwCard()"), '');

View file

@ -0,0 +1,81 @@
// Rule C1, played (gameplay-rules): every handmade scenario has a reference strategy (scripts/lib/scenario-ref.js,
// the player's own actions, a plan a sensible human would follow) that wins within its days, and the obvious shortcut
// does not. The win days below were recorded in the 2.0.0 playtest; a balance change that moves them far is a change
// in how the scenario plays, so look before you re-record.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const { play } = require('../scripts/lib/scenario-ref');
const HIRE = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix']];
const home = (c) => [['bb', c], ['tr', c, 1], ['ix', c]];
const GN_H = ['hire', ['transit', 'routers', 'repair', 'sales', 'ix', 'caches', 'pni']];
const GN_REF = [['bb', 'icn'], ['ix', 'icn'], ['tr', 'icn', 1], ['pni', 'icn', 'ktt', 0], GN_H, ['served', 120], ['link', 'icn', 'tok', 1], ['tr', 'tok', 1], ['ix', 'tok'], ['last', 'icn'], ['pop', 'hkg']];
// ref: the reference plan; win: [earliest, latest] day it may win on; cheese: the shortcut, and `by`, the day before
// which it must not win (null: never within the scenario's days).
const PLAY = {
stg: { ref: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['link', 'fra', 'ams', 1], ['ix', 'ams'], ['bb', 'ams'], ['link', 'ams', 'lon', 1], ['ix', 'lon'], ['bb', 'lon'], ['link', 'fra', 'par', 1], ['ix', 'par'], ['bb', 'par'], ['hire', ['routers', 'repair', 'caches', 'pni', 'ix', 'sales'], { pni: { paid: true } }], ['link', 'stg', 'muc', 1], ['ix', 'muc'], ['bb', 'muc'], ['wait', 120], ['pnis'], ['link', 'lon', 'nyc', 2], ['ix', 'nyc'], ['bb', 'nyc'], ['wait', 200], ['pnis']],
win: [120, 240], cheese: [['bb', 'stg'], ['ix', 'stg'], ['link', 'stg', 'fra', 1], ['ix', 'fra'], ['bb', 'fra'], ['loans'], ['hire', ['routers', 'repair']]], by: null },
// The other way round the planet: Paris, New York, Los Angeles, Tokyo, Hong Kong, Singapore.
redsea: { ref: [...home('mrs'), ['link', 'mrs', 'par', 1], ['bb', 'par'], ['ix', 'par'], ['link', 'par', 'nyc', 1, 'amitie'], ['tr', 'nyc', 1], ['ix', 'nyc'], ['link', 'nyc', 'lax', 1], ['ix', 'lax'], ['tr', 'lax', 1], ['link', 'lax', 'tok', 1, 'jup'], ['bb', 'tok'], ['tr', 'tok', 1], ['ix', 'tok'], ['link', 'tok', 'hkg', 1, 'apg'], ['bb', 'hkg'], ['tr', 'hkg', 1], ['ix', 'hkg'], ['link', 'hkg', 'sin', 1], ['bb', 'sin'], ['tr', 'sin', 1], ['ix', 'sin'], HIRE],
// 2.0.0: no more max-prefix outages to break the 30-day streak, so the reference can finish in under 100 days.
win: [80, 250], cheese: [...home('mrs'), ['loans'], ['link', 'mrs', 'sin', 1], ['bb', 'sin']], by: null },
spat: { ref: [...home('nyc'), HIRE], avoid: ['cog'], win: [50, 140], cheese: [...home('nyc'), ['hire', ['routers', 'repair']]], by: 160 },
carnaval: { ref: [...home('rio'), ['hire'], ['wait', 69], ['prep', 'rio', 400], ['wait', 76], ['prep', 'rio', 400], ['wait', 83], ['prep', 'rio', 400]], win: [95, 95], cheese: [...home('rio'), ['loans']], by: null },
darien: { ref: [...home('pan'), ['link', 'pan', 'bog', 1, 'pccs'], ['bb', 'bog'], ['ix', 'bog'], ['link', 'bog', 'lim', 1], ['bb', 'lim'], ['ix', 'lim'], ['link', 'lim', 'scl', 1], ['bb', 'scl'], ['ix', 'scl'], ['link', 'scl', 'sao', 1], ['bb', 'sao'], ['tr', 'sao', 1], ['ix', 'sao'], HIRE],
win: [30, 90], cheese: [...['pan', 'bog', 'lim', 'scl', 'sao'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['hire']], by: null },
c2c: { ref: [...home('cpt'), ['link', 'cpt', 'jnb', 1], ['bb', 'jnb'], ['tr', 'jnb', 1], ['ix', 'jnb'], ['link', 'jnb', 'nbo', 1], ['bb', 'nbo'], ['ix', 'nbo'], ['link', 'nbo', 'cai', 1], ['bb', 'cai'], ['ix', 'cai'], ['link', 'jnb', 'lag', 1], ['bb', 'lag'], ['ix', 'lag'], HIRE],
win: [70, 200], cheese: [...home('cpt'), ['link', 'cpt', 'cai', 0], ['pop', 'lag'], ['pop', 'nbo'], ['hire']], by: null },
ixbr: { ref: [...home('sao'), ...[['sao', 'rio', 1], ['sao', 'cpq', 0], ['sao', 'cwb', 0], ['cwb', 'poa', 0], ['rio', 'bhz', 0], ['bhz', 'bsb', 0], ['bsb', 'gyn', 0], ['rio', 'ssa', 0], ['ssa', 'rec', 0], ['rec', 'for', 0], ['rec', 'nat', 0], ['for', 'bel', 0], ['bel', 'mao', 0], ['bsb', 'cgb', 0], ['sao', 'vix', 0]].flatMap(([a, b, t]) => [['link', a, b, t], ['ix', b, 0]]), ['bb', 'rio'], ['tr', 'rio', 1], ['bb', 'bsb'], ['tr', 'bsb', 1], ['bb', 'for'], ['tr', 'for', 1], HIRE],
win: [40, 120], cheese: [['bb', 'sao'], ['tr', 'sao', 1], ...['sao', 'rio', 'bsb', 'bhz', 'cwb', 'poa', 'for', 'rec', 'ssa', 'cpq', 'gyn', 'bel', 'mao', 'nat', 'vix', 'cgb'].flatMap((c) => [['pop', c], ['ix', c, 0]]), ['hire']], by: null },
// Sender pays: Seoul transit to start (dear, but fast), one paid PNI with Kay-Tea for reach, then haul the bulk from
// Tokyo and keep Seoul transit as the last resort. Seoul alone loses money on the sender-pays fee and never wins.
gangnam: { ref: GN_REF, win: [130, 190], cheese: [...home('icn'), ['loans']], by: null },
// Bigger routers bring Flowspec, which also takes floods: without a scrubbing center it takes twice as long.
flood: { ref: [...home('ams'), ['scrub', 'ams', 1], ['tr', 'ams', 1], HIRE], win: [80, 200], cheese: [...home('ams'), ['tr', 'ams', 1], ['loans']], by: 180 },
fttb: { ref: [...home('syd'), ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ...['mel', 'bne', 'adl', 'per'].flatMap((c) => [['bb', c], ['tr', c, 1]]), ['link', 'syd', 'mel', 1], ['link', 'syd', 'bne', 1], ['link', 'mel', 'adl', 1], ['link', 'adl', 'per', 0], HIRE],
win: [80, 200], cheese: [...['syd', 'mel', 'bne', 'adl', 'per'].map((c) => ['bb', c]), ['tr', 'syd', 1], ['link', 'syd', 'akl', 0, 'tasman'], ['link', 'syd', 'nou', 0, 'gond'], ['loans']], by: 60 },
// Tallinn has no transit: over the water to Helsinki and Stockholm on two cables each way, and round by land to Riga.
baltic: { ref: [['bb', 'tll'], ['ix', 'tll'], ['link', 'tll', 'hel', 1, 'balt'], ['tr', 'hel', 1], ['link', 'tll', 'sto', 1, 'balt'], ['tr', 'sto', 1], ['link', 'tll', 'hel', 1, 'elisa'], ['link', 'tll', 'rix', 1], ['tr', 'rix', 1], ['hire', ['transit', 'routers', 'repair', 'ix']]],
win: [90, 200], cheese: [['bb', 'tll'], ['ix', 'tll'], ['loans']], by: null },
// The 1.6T chains: grow the traffic first, then light every hop at once (a day-0 build also gets there, just).
pac: { ref: [...home('hnl'), ...home('lax'), ...home('syd'), ['link', 'lax', 'tok', 1, 'jup'], HIRE, ['served', 145], ['link', 'lax', 'hnl', 4, 'seaus'], ['link', 'hnl', 'suv', 4, 'scx'], ['link', 'suv', 'syd', 4, 'scx']],
win: [50, 120], cheese: [...home('hnl'), ...home('lax'), ...home('syd'), ['link', 'lax', 'tok', 1, 'jup'], ['link', 'lax', 'syd', 3, 'hwk'], ['loans']], by: null },
atl: { ref: [['bb', 'pdl'], ['tr', 'pdl', 1], ...home('mia'), ...home('mad'), ...home('lis'), HIRE, ['link', 'mia', 'bda', 4, 'sol'], ['link', 'bda', 'pdl', 4, 'sol'], ['link', 'pdl', 'mad', 4, 'sol'], ['served', 90], ['link', 'lis', 'tci', 4, 'ace'], ['link', 'tci', 'lag', 4, 'twoaf'], ['bb', 'lag']],
win: [40, 120], cheese: [['bb', 'pdl'], ['tr', 'pdl', 1], ...home('mia'), ...home('mad'), ...home('lis'), ['link', 'mia', 'mad', 3, 'col3'], ['link', 'lis', 'lag', 3, 'equi'], ['loans']], by: null },
};
test('C1 played: every scenario has a reference strategy and a shortcut that fails', () => {
const g = load();
const ids = JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'));
assert.deepEqual(Object.keys(PLAY).sort(), ids.slice().sort(), 'C1: every scenario has a reference strategy here');
});
for (const [id, P] of Object.entries(PLAY)) {
test(`${id}: the reference wins in its days, the shortcut does not`, () => {
const g = load();
const r = play(g.ev, id, P.ref, { avoid: P.avoid });
assert.ok(r.won !== null, `${id}: the reference does not win (${JSON.stringify(r)})`);
assert.ok(r.won >= P.win[0] && r.won <= P.win[1] && (id === 'carnaval' || r.won <= r.limit * 0.75), `${id}: won on day ${r.won}, want ${P.win.join('-')} of ${r.limit}`);
const c = play(g.ev, id, P.cheese, { days: P.by || undefined });
assert.ok(c.won === null, `${id}: the shortcut wins on day ${c.won}${P.by ? ` (before day ${P.by})` : ''}`);
assert.deepEqual(g.errors, []);
});
}
// Gangnam Style Peering bites every way (2.0.0 playtest): paying the sender-pays fee on everything loses money, hauling
// everything from Tokyo is too slow for Korean users, and the old plan (transit everywhere, no Kay-Tea) has neither
// the reach nor the profit. The reference's Seoul transit as first choice, not last resort, also stays in the red.
for (const [name, plan] of Object.entries({
'Seoul transit and Kay-Tea': [['bb', 'icn'], ['ix', 'icn'], ['tr', 'icn', 1], ['pni', 'icn', 'ktt', 0], GN_H],
'everything from Tokyo': [['bb', 'icn'], ['link', 'icn', 'tok', 1], ['tr', 'tok', 1], ['ix', 'tok'], ['pni', 'tok', 'ktt', 0], ['pop', 'hkg'], GN_H],
'the 1.x reference': [...home('icn'), ['link', 'icn', 'tok', 1], ['ix', 'tok'], ['tr', 'tok', 1], ['link', 'icn', 'hkg', 1], ['ix', 'hkg'], ['tr', 'hkg', 1], HIRE],
'Tokyo haul, Seoul transit first': GN_REF.filter((s) => s[0] !== 'last'),
})) {
test(`gangnam: ${name} does not win`, () => {
const g = load();
const r = play(g.ev, 'gangnam', plan);
assert.equal(r.won, null, `${name} won on day ${r.won}`);
assert.deepEqual(g.errors, []);
});
}

170
tests/specialist.test.js Normal file
View file

@ -0,0 +1,170 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// Specialist play (#187, #173): capability offers, vendor demo units, pioneer fiber, consortium seats, charters.
const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})";
const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};`;
const df = (id, a, b, ch, own = true) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:${own},sys:'roadm',ch:${JSON.stringify(ch)},km:kmBetween('${a}','${b}'),sub:false,cable:null,mo:0,trench:'${id}',cut:0,day:0,ready:0,spares:false});`;
// Spawn offers until one of a type shows up (or give up), with everything else cleared out of the way.
const spawnUntil = (ev, type, n = 400) => ev(`(()=>{for(let i=0;i<${n};i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='${type}');if(o)return JSON.stringify(o);}return 'null';})()`);
test('#187 a capability brings its customers before the level does, only when you can serve them', () => {
const { ev, dom, errors } = load();
ev(start);
ev(`S.lvl=1;${pop('nyc')}${pop('chi')}compute()`);
assert.equal(ev("spots().filter(s=>s.t==='hft').length"), 0, 'no low-latency path, no trading firm');
assert.equal(JSON.parse(spawnUntil(ev, 'hft')), null, 'level 1 alone never brings HFT');
ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0});compute()");
const s = JSON.parse(ev("JSON.stringify(spots().find(s=>s.t==='hft'))"));
assert.deepEqual([s.a, s.b].sort(), ['chi', 'nyc']);
const o = JSON.parse(spawnUntil(ev, 'hft'));
assert.ok(o, 'the trading firm calls');
assert.equal(o.bw, ev("BIZ_T.hft.opts[0]"), 'at the smallest size');
assert.deepEqual(o.reqs, ['lat']);
assert.ok(o.latMax >= s.n, 'and the path you have already meets it');
assert.equal(o.spot.k, 'lat');
ev("ACT.leftTab({t:'deals'});renderAll()");
assert.match(dom.window.document.body.innerHTML, /They spotted your [\d.]+ ms (New York|Chicago)–(New York|Chicago) path/);
// Lit dark fiber with enough capacity brings AI interconnects (level 4) to a level 3 network; not the bigger DCI.
ev(`S.lvl=3;${df('d', 'nyc', 'chi', ['zr4', 'zr4'])}compute()`);
const t = JSON.parse(ev("JSON.stringify([...new Set(spots().map(s=>s.t))])"));
assert.ok(t.includes('ai'), 'AI training interconnect');
assert.ok(!t.includes('hyper'), 'not a hyperscaler DCI three times its size');
assert.ok(!t.includes('hft'), 'level 3 gets HFT anyway: no spotting needed');
ev("S.lvl=5");
assert.ok(!ev("spots().some(s=>s.t==='ai')"), 'once the level brings them, they are ordinary offers');
assert.equal(ev("(()=>{S.rules.gates='open';const n=spots().length;S.rules.gates='ladder';return n;})()"), 0, 'open gates need no spotting');
assert.deepEqual(errors, []);
});
test('#187 vendor demo units: one level ahead, a wait and a markup', () => {
const { ev, errors } = load();
ev(start);
ev('S.lvl=1');
assert.equal(ev("RG[1].lvl"), 2);
assert.equal(ev("techOk('rg',1,2)"), false);
ev("ACT.demoAsk({k:'rg',id:2})");
assert.equal(ev("demoAt('rg',2)"), null, 'never two levels ahead');
ev("ACT.demoAsk({k:'rg',id:1})");
const at = ev("demoAt('rg',1)");
assert.equal(at - ev('S.day'), ev('leadDays(DEMO_DAYS)'), 'a short wait');
ev("ACT.upRouter({city:'fra',g:1})");
assert.equal(ev("S.pops.fra.rgen||0"), 0, 'not before it ships');
ev(`S.day=${at}`);
assert.equal(ev("techOk('rg',1,2)"), true);
assert.equal(ev("swapCost('fra',1)"), ev("Math.round(RG[1].cost*hwMul('rt')*1.6)-tradeIn(0,1)"), '+60%');
const cash = ev('S.cash');
ev("ACT.upRouter({city:'fra',g:1})");
assert.equal(ev("S.pops.fra.rgen"), 1);
assert.ok(cash - ev('S.cash') > 0);
// Optics and line systems the same way.
ev("S.lvl=2;ACT.demoAsk({k:'opt',id:'zr8'});ACT.demoAsk({k:'sys',id:'roadm'})");
assert.ok(ev("demoAt('opt','zr8')!==null&&demoAt('sys','roadm')!==null"));
ev("S.day+=30");
assert.equal(ev("optCost('zr8')"), ev("Math.round(OPT.zr8.cost*1.6*hwMul('opt'))"));
assert.equal(ev("sysCost('roadm')"), ev("Math.round(DF_SYS.roadm.cost*1.6)"));
ev('S.lvl=3');
assert.equal(ev("optCost('zr8')"), ev("Math.round(OPT.zr8.cost*hwMul('opt'))"), 'list price once your level catches up');
assert.equal(ev("demoCan(5)"), false);
assert.deepEqual(errors, []);
});
test('#187 pioneer fiber: dig your own before level 3, at a markup', () => {
const { ev, errors } = load();
ev(start);
ev(`S.lvl=2;${pop('ams')}UI.dfSrc='build';UI.dfSys='lite';UI.pending={a:'fra',b:'ams'};`);
const km = ev("kmBetween('fra','ams')");
assert.equal(ev(`digCost(${km})`), ev(`Math.round(dfBuildCost(${km})*1.6)`));
const cash = ev('S.cash');
ev('ACT.orderDf()');
const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.kind==='df'))"));
assert.ok(l && l.own, 'your own trench');
assert.equal(cash - ev('S.cash'), ev(`digCost(${km})+DF_SYS.lite.cost+ampCount(${km})*AMP_COST`));
ev('S.lvl=3');
assert.equal(ev(`digCost(${km})`), ev(`dfBuildCost(${km})`), 'no markup at level 3');
assert.deepEqual(errors, []);
});
test('#173 a consortium seat: offer, pay, build, light, cut, save', () => {
const { ev, dom, errors } = load();
ev(start);
ev("S.lvl=3;S.capDeal={at:S.day,c:'lon'};capDealTick(S.day)");
const off = JSON.parse(ev('JSON.stringify(S.seatOff)'));
assert.ok(off && ev(`SEAT_ROUTES.lon.some(r=>r[2]===${JSON.stringify(off.name)})`), 'a capacity conference offers a seat on one of its routes');
ev("ACT.leftTab({t:'deals'});renderAll()");
assert.match(dom.window.document.body.innerHTML, /Consortium seat: /);
// A seat short enough to light with level 2 optics.
ev("S.lvl=2;S.seatOff={a:'syd',b:'akl',name:'Tasman Devil',km:seatKm('syd','akl'),exp:S.day+30}");
const km = ev('S.seatOff.km');
const cash = ev('S.cash'), popC = ev("popCost('syd')+popCost('akl')");
ev('ACT.seatBuy({n:2})');
assert.equal(cash - ev('S.cash'), ev(`seatCost(${km},2)`) + popC, 'your share of the build, and the landing POPs');
const l = JSON.parse(ev("JSON.stringify(S.links.find(l=>l.seat))"));
assert.ok(l.own && l.sub && l.pairs === 2 && l.ready > ev('S.day'), 'your own subsea glass, being laid');
assert.equal(ev('S.seatOff'), null);
assert.equal(ev("pairsMax(S.links.find(l=>l.seat))"), 2, 'only the pairs you bought');
// Save and load keep it.
ev('const s=migrate(JSON.parse(JSON.stringify(S)));window.__s=s');
assert.equal(ev("__s.links.find(l=>l.seat).pairs"), 2);
// It lands and lights with your own optics.
ev(`S.day=${l.ready};S.pops.syd.rgen=S.pops.akl.rgen=1;ACT.addCh({id:'${l.id}',o:'zr4'});compute()`);
assert.ok(ev(`dfCap(S.links.find(l=>l.id==='${l.id}'))`) > 0, 'lit');
ev(`ACT.subUpgrade({id:'${l.id}',k:'terminal'})`);
assert.equal(ev(`S.links.find(l=>l.id==='${l.id}').subterminal`), undefined, 'the consortium owns the terminals');
// A cut on the cable cuts your share.
ev(`S.links=S.links.filter(l=>l.id==='${l.id}');eval('('+fireFailure.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')()`);
assert.ok(ev(`linkDown(S.links.find(l=>l.id==='${l.id}'))`), 'the cut takes your pairs down too');
assert.deepEqual(errors, []);
});
test('#187 the Low-latency boutique: pick it on day 0, traders weigh more and pay more, Speed of Light wins', () => {
const { ev, dom, errors } = load();
ev(start);
ev("ACT.leftTab({t:'goals'});renderAll()");
assert.match(dom.window.document.body.innerHTML, /Pick a charter/);
ev("window.innerWidth=360;renderAll()");
assert.match(dom.window.document.body.innerHTML, /Low-latency boutique/, 'on a phone too');
ev("window.innerWidth=1280");
assert.equal(ev('charter()'), 'global', 'Global backbone until you pick');
ev("ACT.charter({k:'boutique'})");
assert.equal(ev('charter()'), 'boutique');
ev("ACT.charter({k:'global'})");
assert.equal(ev('charter()'), 'boutique', 'picked once');
// More and better-paid trading firms than a global backbone with the same network.
const count = (k) => {
const g = load();
g.ev(start);
g.ev(`S.lvl=2;S.charter='${k}';${pop('nyc')}${pop('chi')}compute()`);
return JSON.parse(g.ev("(()=>{let n=0,r=0;for(let i=0;i<300;i++){S.offers=[];spawnOffer();const o=S.offers.find(o=>o.type==='hft');if(o){n++;if(o.reqs.length===1)r=o.rate/(150+kmBetween(o.city,o.city2)*0.08)/BIZ_T.hft.km;}}return JSON.stringify({n,r});})()"));
};
const gl = count('global'), bq = count('boutique');
assert.ok(bq.n > gl.n * 1.5, `boutique traders call more (${bq.n} vs ${gl.n})`);
assert.ok(Math.abs(bq.r - 1.4) < 0.02 && Math.abs(gl.r - 1) < 0.02, 'and pay 40% more');
// Speed of Light: three finance routes faster on your own glass than any lease, and two paying latency customers.
ev(`S.lvl=2;${pop('nyc')}${pop('chi')}${pop('ash')}${df('a', 'nyc', 'chi', ['zr4'])}${df('b', 'chi', 'ash', ['zr4'])}${df('c', 'nyc', 'ash', ['zr4'])}compute()`);
assert.equal(ev('solRoutes().length'), 3);
ev('specDay(S.day)');
assert.equal(ev('S.solWon'), 0, 'not without paying customers');
ev("for(const [a,b] of [['nyc','chi'],['chi','ash']])S.biz.push({id:uid(),city:a,city2:b,name:'T',type:'hft',bw:1,rate:1000,reqs:['lat'],latMax:latMaxOf(a,b),mood:100,since:0});compute();specDay(S.day)");
assert.equal(ev('S.solWon'), Math.max(1, ev('S.day')), 'Speed of Light');
ev('checkBadges()');
assert.notEqual(ev("S.ach.sol"), undefined, 'and its badge');
ev("renderAll()");
assert.match(dom.window.document.body.innerHTML, /Won on /);
assert.deepEqual(errors, []);
});
test('#187 old saves load as Global backbone; scenarios ignore charters', () => {
const { ev, errors } = load();
ev(start);
ev("const o=JSON.parse(JSON.stringify(S));for(const k of ['charter','chartSet','demo','seatOff','solWon'])delete o[k];o.links.push({id:'q',a:'fra',b:'ams',kind:'df',own:false,sub:false,seat:true,sys:'lite',ch:[],km:400,ready:0});window.__o=migrate(o)");
assert.equal(ev('__o.charter'), 'global');
assert.equal(ev('__o.chartSet'), true, 'no charter card for an old save');
assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.demo)')), {});
assert.equal(ev('__o.seatOff'), null);
assert.equal(ev("__o.links.find(l=>l.id==='q').seat"), undefined, 'a forged seat is dropped');
ev("S.charter='boutique';S.scn={id:'x'}");
assert.equal(ev('charter()'), 'global');
assert.deepEqual(errors, []);
});

View file

@ -127,7 +127,7 @@ test('route-server batch leaves peering policy and player-owned exchanges alone'
const { ev, errors } = setup(t);
ev('ACT.utilityRouteServers()');
assert.equal(ev('Object.keys(S.rs).length'), 0, 'does not join an IX without a port');
ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.inboxPol({p:'closed'});ACT.utilityRouteServers()");
ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.peerPol({p:'closed'});ACT.utilityRouteServers()");
assert.equal(ev('ppol()'), 'closed');
assert.equal(ev('S.rs.fra'), true);
assert.equal(ev("ixSessions('fra').has('drz')"), false, 'does not bypass closed policy');