Merge v2 into v2-saves

This commit is contained in:
Frederic Jung 2026-10-29 07:32:19 +01:00
commit 5f412f72d8
No known key found for this signature in database
96 changed files with 6237 additions and 321 deletions

220
tests/automation.test.js Normal file
View file

@ -0,0 +1,220 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// #185's sales and repair engines now run as the NOC intern's standing orders, once per game day.
function setup(ev) {
ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.lvl=2;S.ops.intern='kevin';S.ops.floor=0;S.rules=makeRules('freeze');compute()");
}
const orders = (ev, on) => ev(`for(const k of ${JSON.stringify(on)})S.ops.on[k]=true`);
const shift = ev => ev('opsDay(S.day)');
function offer(ev, id, extra = {}) {
ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`);
}
test('the sales order signs ready offers once per shift, and pausing it stops it', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'first');
shift(ev);
assert.equal(ev('S.biz.length'), 0, 'off by default');
orders(ev, ['sales']);
shift(ev);
assert.equal(ev('S.biz[0].id'), 'first');
ev("ACT.opsToggle({k:'sales'})");
offer(ev, 'off');
ev('dayTick()');
assert.equal(ev('S.biz.length'), 1, 'a paused order signs nothing');
assert.ok(ev("S.offers.some(o=>o.id==='off')"));
assert.deepEqual(errors, []);
dom.window.close();
});
test('the trial includes new bandwidth and later offers cannot overbook earlier accepted sales', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'one', { bw: 60 });
offer(ev, 'two', { bw: 60 });
const state = ev('JSON.stringify(S)');
ev('window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap');
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
assert.equal(ev('JSON.stringify(S)'), state);
assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true);
ev('S.ops.on.sales=true;opsDay(S.day)');
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.offers[0].id'), 'two');
assert.ok(ev('bizSf(S.biz[0])') >= 0.95);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the sales order checks actual circuits, latency and NNI capacity', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()");
offer(ev, 'circuit', { type: 'hft', city2: 'ams', bw: 10, latMax: 50, reqs: ['lat'] });
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'POPs alone are not a circuit');
ev("S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});compute()");
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
ev('S.offers[0].latMax=0.1');
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'latency budget must pass');
ev("S.offers=[];window.fabric=FABS.find(f=>f.cities.includes('fra')).id;ACT.buyNni({city:'fra',prov:fabric,tier:0})");
const prov = ev('fabric');
const bandwidth = ev('NNI[0].g * 0.75');
offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] });
offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] });
// Transit has enough headroom, so the second rejection is the shared NNI port.
ev("S.transit[0].tier=4;compute();S.ops.on.sales=true;opsDay(S.day)");
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.offers[0].id'), 'fabric-two');
assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g"));
assert.deepEqual(errors, []);
dom.window.close();
});
test('new circuits do not take service away from healthy signed customers', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});S.transit[0].city='ams';compute()");
offer(ev, 'existing', { bw: 80 });
ev("ACT.accept({id:'existing'})");
offer(ev, 'new-circuit', { type: 'l2vpn', city2: 'ams', bw: 50 });
assert.equal(ev('bizWhy(S.biz[0]).length'), 0);
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
assert.ok(ev('bizSf(S.biz[0])') >= 0.95, 'failed preview leaves the old routing result intact');
assert.deepEqual(errors, []);
dom.window.close();
});
test('fiber sales check live equipment and free spectrum, and repeated carrier orders still merge', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(14).fill('zr4'),km:450,sub:false,ready:0,cut:0,mo:1}];S.biz=[{id:'old',name:'Same Carrier',type:'wwave',city:'fra',city2:'ams',link:'fiber',bw:1,rate:1000,slots:1,reqs:[],mood:100,since:0}];compute()");
offer(ev, 'full', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 2 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()");
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale');
ev('S.links[0].eqDown=0;compute();S.ops.on.sales=true;opsDay(S.day)');
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.biz[0].slots'), 2);
assert.equal(ev('S.biz[0].rate'), 1600);
assert.equal(ev('freeCh(S.links[0])'), 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('capacity pair sales need completed infrastructure and reserve it for the accepted contract', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()");
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
ev('S.ops.on.sales=true;opsDay(S.day)');
assert.equal(ev('S.biz[0].link'), 'own');
assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day');
offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'the same trench cannot be promised twice');
assert.deepEqual(errors, []);
dom.window.close();
});
test('future event demand is tested before signing, with booked events reserving headroom', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 });
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
ev('S.ops.on.sales=true;opsDay(S.day)');
assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date');
assert.equal(ev('R.cityDem.fra'), 0);
offer(ev, 'too-large', { bw: 30 });
assert.equal(ev('!!autoOffer(S.offers[0])'), false);
ev('S.offers[0].bw=10');
assert.equal(ev('!!autoOffer(S.offers[0])'), true);
assert.equal(ev('S.biz[0].start'), 10);
assert.equal(ev('R.cityDem.fra'), 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('failed capacity trials restore game, routing and map state even when compute throws', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
ev("window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap;window.originalCompute=compute;window.compute=()=>{throw new Error('trial failed')}");
assert.throws(() => ev('autoOffer(S.offers[0])'), /trial failed/);
assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true);
ev('window.compute=originalCompute');
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('S.offers.length'), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the repair order rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its pause', () => {
const { ev, dom, errors } = load();
setup(ev);
ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}];
S.pops.fra.down=8;S.inc=[
{id:'amp',type:'amp',ref:'fiber',until:10,cost:30000,msg:'Broken amp'},
{id:'optic',type:'optic',ref:'fiber',until:10,cost:5000,msg:'Broken optic'},
{id:'slow',type:'crash',ref:'fra',until:8,cost:2000,slow:true,msg:'Slow boot'},
{id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'},
{id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'},
{id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}];
S.ops.on.repair=true;opsDay(S.day)`);
assert.equal(ev('S.cash'), 3000);
assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false);
assert.equal(ev('S.links[0].chFail'), null);
assert.equal(ev("S.inc.find(i=>i.id==='slow').rushed"), true);
assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1);
assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0);
assert.equal(ev('S.pops.fra.down'), 1);
ev('opsDay(S.day)');
assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment');
ev('S.cash=40000;opsDay(S.day)');
assert.equal(ev('S.cash'), 10000);
assert.equal(ev('S.links[0].eqDown'), 0);
assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false);
ev("ACT.opsToggle({k:'repair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});opsDay(S.day)");
assert.equal(ev('S.cash'), 10000);
assert.equal(ev("S.inc.some(i=>i.id==='new')"), true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the sales order leaves unready and expired offers alone without failure notifications', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'generator', { reqs: ['gen'] });
offer(ev, 'missing-pop', { city: 'ams' });
offer(ev, 'scrub', { type: 'scrub' });
offer(ev, 'expired', { exp: 0 });
offer(ev, 'ipv6', { reqs: ['ipv6'] });
const log = ev('S.log.length');
ev('S.ops.on.sales=true;opsDay(S.day)');
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('S.offers.length'), 5);
assert.equal(ev('S.log.length'), log, 'no failed manual-action toasts and no shift line when nothing got done');
ev('S.pops.fra.gen=true;compute();opsDay(S.day)');
assert.equal(ev('S.biz.length'), 1);
assert.equal(ev('S.biz[0].id'), 'generator');
// Manual acceptance keeps its existing sign-now, provision-later behavior.
ev("ACT.accept({id:'scrub'})");
assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the #185 toggles in old saves become the sales and repair orders, malformed ones stay off', () => {
const { ev, dom, errors } = load();
setup(ev);
ev("delete S.ops;S.autoSales=true;S.autoRepair=true;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.ops.on.sales&&S.ops.on.repair'), true);
assert.equal(ev("'autoSales' in S||'autoRepair' in S"), false);
assert.equal(ev('S.ops.intern'), null, 'no intern until you hire one, so nothing runs yet');
ev("delete S.ops;S.autoSales='true';S.autoRepair=1;S=migrate(S)");
assert.equal(ev('S.ops.on.sales||S.ops.on.repair'), false);
assert.deepEqual(errors, []);
dom.window.close();
});

View file

@ -135,3 +135,37 @@ test('the share card rings the variant badges', () => {
assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`);
assert.deepEqual(errors, []);
});
test('a variant named after an Object prototype key is not a variant', () => {
const { ev, errors } = load();
start(ev);
for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${JSON.stringify(k)}};S=migrate(o)`);
assert.equal(ev('S.achP.hello'), 'oncall', k);
assert.equal(ev(`bvar(${JSON.stringify(k)}).k`), 'oncall', `bvar(${k})`);
ev(`S.rules={preset:${JSON.stringify(k)}}`);
assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`);
}
ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()");
assert.deepEqual(errors, []);
});
test('"Badge upgraded" means the collection on this device got a better variant', () => {
const { ev, errors } = load();
const spy = () => ev("window.__t=[];if(!window.__sp){window.__sp=1;const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);};}");
// a new game, but this device already holds the frosted badge: the standard one upgrades it
start(ev, 'oncall');
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{freeze:'2026-01-01'}}}))");
spy(); earnHello(ev);
assert.match(ev("window.__t.join(' ')"), /Badge upgraded/);
assert.equal(hof(ev).hello.v, 'oncall');
// another new game, the device already holds the fiery one: earning the frosted one is a plain unlock
start(ev, 'freeze');
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{bgp:'2026-01-01'}}}))");
spy(); earnHello(ev);
const t = ev("window.__t.join(' ')");
assert.match(t, /Badge unlocked/);
assert.doesNotMatch(t, /Badge upgraded/);
assert.equal(hof(ev).hello.v, 'bgp', 'the best variant stays on the shelf');
assert.deepEqual(errors, []);
});

View file

@ -2,6 +2,16 @@ const test = require('node:test');
const assert = require('node:assert/strict');
const { load, seed } = require('./harness');
test('daily DDoS spawns share one routing calculation and score their first active day', () => {
const { ev, errors } = load();
// The busier DDoS schedule needs spicy chaos (BGP at 3 a.m.) or gaming customers.
ev("ACT.start({});S.rules=makeRules('bgp');S.cash=1e9;S.day=50;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();window.__compute=compute;window.__random=Math.random;window.__computes=0;compute=()=>{window.__computes++;window.__compute()};Math.random=()=>0;dayTick();compute=window.__compute;Math.random=window.__random");
assert.equal(ev('ddosAll().length'), 2, 'both daily spawn opportunities were used');
assert.equal(ev('window.__computes'), 1, 'daily spawns do not reroute the whole network individually');
assert.ok(ev('ddosAll().every(a=>a.worst===ddosSf(a))'), 'first-day service is recorded after routing');
assert.deepEqual(errors, []);
});
test('page boots to the title screen without errors', () => {
const { ev, errors } = load();
assert.equal(ev("document.getElementById('modal').hidden"), false);
@ -197,6 +207,52 @@ test('Flowspec is a router-model capability, and each tool answers a flood', ()
assert.deepEqual(errors, []);
});
test('a distributed SYN flood reports actual Flowspec drops and sends only the remainder to scrubbing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'edge',city:'fra',share:1}]};compute()");
assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0);
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2);
assert.match(ev('ddosPanel()'), /— No Flowspec filtering: ingress routers have no TCAM/);
assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 30\.2 Gbps \/ 100G/);
assert.doesNotMatch(ev('ddosPanel()'), /✓ Flowspec|After upstream scrubbing|Reaching your network/);
for (const [router, dropped, scrubbed] of [[1,18.12,12.08], [3,25.67,4.53]]) {
ev(`S.pops.fra.rgen=${router};compute()`);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-dropped)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-scrubbed)<1e-9);
assert.match(ev('ddosPanel()'), new RegExp('✓ Flowspec dropping: '+dropped.toFixed(1).replace('.', '\\.')+' Gbps'));
assert.match(ev('ddosPanel()'), new RegExp('Scrubbing in Frankfurt: '+scrubbed.toFixed(1).replace('.', '\\.')+' Gbps / 100G'));
assert.doesNotMatch(ev('ddosPanel()'), /no TCAM|Edge filters dropping/);
}
ev("S.ev.ddos.vec='ack';compute()");
assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0);
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2);
assert.match(ev('ddosPanel()'), /— Flowspec cannot catch ACK flood/);
assert.deepEqual(errors, []);
});
test('Flowspec accounts for each ingress router, upstream cleaning and other edge filters separately', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.pops.nyc.rgen=3;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0},{city:'nyc',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.5},{k:'t',id:'tn',city:'nyc',share:0.5}]};compute()");
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-12.835)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)')-17.365)<1e-9);
assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 12\.8 Gbps; some ingress routers have no TCAM/);
assert.match(ev('ddosPanel()'), /Scrubbing in Frankfurt: 15\.1 Gbps \/ 100G/);
assert.match(ev('ddosPanel()'), /Scrubbing in New York: 2\.3 Gbps \/ 100G/);
assert.equal(ev('ddosMitigation(S.ev.ddos).flowspec'), ev('ddosReport(S.ev.ddos).flowspec'), 'uncached reports also filter at the ingress instead of the target');
ev('S.transit[1].clean=true;compute()');
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-16.61)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.2835)<1e-9);
assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 16\.6 Gbps/);
assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 1\.3 Gbps/);
ev("S.pops.fra.rgen=3;S.ixp={fra:1,nyc:1};S.ev.ddos.ixbh=true;compute()");
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-14.1185)<1e-9);
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-1.24575)<1e-9);
assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 14\.1 Gbps/);
assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 1\.2 Gbps/);
assert.ok(ev('Math.abs(ddosReport(S.ev.ddos).reaching-ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)-ddosReport(S.ev.ddos).leak)<1e-9'));
assert.deepEqual(errors, []);
});
test('RTBH blackholes the victim, and HackBack 3000 is a gamble', () => {
const { ev } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=120;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()");
@ -478,3 +534,615 @@ test('the broadband panel shows what homes in that city really pay, not the base
assert.ok(ev("cityPanel('del')").includes(rev + '/mo'), `revenue line matches what the month pays (${rev})`);
assert.deepEqual(errors, []);
});
// Custom routing metrics: a fra–ams–par triangle where the direct fra–par link is normally shortest.
const triangle = (ev) => {
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("for(const c of ['ams','par'])ACT.buildPop({city:c});const L=(a,b)=>{UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();};L('fra','ams');L('ams','par');L('fra','par');compute()");
ev("window.FP=S.links.find(l=>(l.a==='fra'&&l.b==='par')||(l.a==='par'&&l.b==='fra')).id;window.FK=edgeKey(S.links.find(l=>l.id===FP));window.pmOf=()=>S.pairMet[FK];window.hops=()=>JSON.stringify(trPaths('fra').path('par').map(h=>h.l.id))");
};
test('a custom multiplier routes exactly like the matching preset', () => {
const { ev, errors } = load();
triangle(ev);
assert.equal(ev("hops()"), JSON.stringify([ev("FP")]), 'direct link wins by default');
ev("ACT.setMetric({id:FP,v:'avoid'})");
const avoid = ev("JSON.stringify({h:hops(),load:R.load,served:R.served})");
ev("ACT.setMetric({id:FP,v:'custom'})");
assert.equal(ev("pairMet(FK)"), 'custom');
const m = ev("pmOf()");
assert.equal(m.k, 'f');
assert.equal(m.v, 4, 'custom starts from the preset it replaces');
assert.equal(ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"), avoid);
ev("ACT.setMetric({id:FP,v:'normal'})");
assert.equal(ev("FK in S.pairMet"), false, 'presets drop the custom metric');
assert.deepEqual(errors, []);
});
test('an absolute custom cost steers the path, and switching modes keeps the cost', () => {
const { ev, errors } = load();
triangle(ev);
ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'})");
const l = ev("S.links.find(l=>l.id===FP)");
assert.equal(ev("pmOf().k"), 'w');
assert.equal(ev("pmOf().v"), Math.round(l.km + 60), 'switching to cost keeps the effective metric');
ev("ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})");
assert.equal(ev("pmOf().v"), 65535);
assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'a huge cost sends traffic round via Amsterdam');
ev("renderAll();$('metIn').value='1';ACT.metricSet({id:FP})");
assert.equal(ev("hops()"), JSON.stringify([ev("FP")]));
ev("ACT.metricMode({id:FP,k:'f'})");
assert.equal(ev("pmOf().v"), 0.1, 'converted back to a multiplier, clamped to the minimum');
assert.deepEqual(errors, []);
});
test('custom metric input is validated and clamped', () => {
const { ev, errors } = load();
triangle(ev);
ev("ACT.setMetric({id:FP,v:'custom'});ACT.selLink({id:FP});renderAll()");
ev("$('metIn').value='';ACT.metricSet({id:FP})");
assert.equal(ev("pmOf().v"), 1, 'empty input changes nothing');
ev("renderAll();$('metIn').value='9999';ACT.metricSet({id:FP})");
assert.equal(ev("pmOf().v"), 100);
ev("renderAll();$('metIn').value='0';ACT.metricSet({id:FP})");
assert.equal(ev("pmOf().v"), 0.1);
ev("ACT.metricMode({id:FP,k:'x'});ACT.setMetric({id:FP,v:'bogus'})");
assert.equal(ev("pairMet(FK)"), 'custom');
assert.deepEqual(errors, []);
});
test('custom metrics survive a save, and broken ones are repaired', () => {
const { ev, errors } = load();
triangle(ev);
ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});pmOf().v=777;S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.deepEqual(JSON.parse(ev("JSON.stringify(pmOf())")), { k: 'w', v: 777 });
ev("S.pairMet[FK]={k:'zz',v:'lots'};S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.deepEqual(JSON.parse(ev("JSON.stringify(pmOf())")), { k: 'f', v: 1 });
ev("S.pairMet[FK]={k:'w',v:1e9};S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev("pmOf().v"), 65535);
// An old save: a preset metric on the link itself, from before metrics moved to the city pair.
ev("delete S.pairMet[FK];S.links.find(l=>l.id===FP).metric='avoid';S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.equal(ev("pmOf()"), 'avoid');
assert.equal(ev("'metric' in S.links.find(l=>l.id===FP)"), false);
assert.equal(JSON.parse(ev("hops()")).length, 2, 'the old save still routes, avoiding the direct link');
assert.deepEqual(errors, []);
});
test('preset buttons stay plain, and Custom explains the numbers, also on phones', () => {
const { ev, dom, errors } = load();
triangle(ev);
for (const w of [1280, 390]) {
ev(`window.innerWidth=${w};ACT.setMetric({id:FP,v:'normal'});ACT.selLink({id:FP});renderAll()`);
const doc = dom.window.document;
const btns = [...doc.querySelectorAll('#panel [data-act="setMetric"]')];
assert.equal(btns.length, 5);
const km = ev("S.links.find(l=>l.id===FP).km");
assert.deepEqual(btns.map(b => b.textContent), ['Prefer', 'Normal', 'Avoid', 'Backup only', 'Custom']);
assert.equal(doc.getElementById('metIn'), null);
assert.doesNotMatch(doc.getElementById('panel').textContent, /times a multiplier/);
ev("ACT.setMetric({id:FP,v:'custom'})");
assert.ok(doc.getElementById('metIn'), `custom editor at ${w}px`);
assert.ok(doc.querySelector('#panel [data-act="metricMode"]'));
const txt = doc.getElementById('panel').textContent;
assert.match(txt, /times a multiplier/);
assert.match(txt, new RegExp(`Normal ×1 = ${Math.round(km + 60)}, Avoid ×4 = ${Math.round((km + 60) * 4)}`));
assert.match(txt, /Multiplier: scales the distance cost/);
assert.match(txt, /Cost on this link/);
ev("ACT.metricMode({id:FP,k:'w'})");
assert.match(doc.getElementById('panel').textContent, /Cost: the exact number/);
}
assert.deepEqual(errors, []);
});
test('a custom metric belongs to the city pair, like the presets, and a standby link keeps it', () => {
const { ev, errors } = load();
triangle(ev);
ev("UI.via=null;openLinkModal('fra','par');ACT.buildLink({tier:1});closeModal();compute()");
ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})");
const other = ev("S.links.find(l=>l.id!==FP&&edgeKey(l)===FK).id");
assert.equal(ev(`pairMet(edgeKey(S.links.find(l=>l.id==='${other}')))`), 'custom', 'the second link between the cities shares it');
ev(`ACT.setStandby({id:'${other}',on:1})`);
assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'the pair is still avoided');
assert.equal(ev("pmOf().v"), 65535);
// Removing every link of the pair drops the metric with it.
ev("S.links=S.links.filter(l=>edgeKey(l)!==FK);prunePairMet()");
assert.equal(ev("FK in S.pairMet"), false);
assert.deepEqual(errors, []);
});
test('Memcached amplification and ACK flood are available without gaming customers and respect Flowspec', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});RG[0].fs=2");
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('DDOS_VEC.memcached.fs'), true);
assert.equal(ev('DDOS_VEC.ack.fs'), false);
ev("S.ev.ddos={city:'fra',vec:'ack',gbps:300,until:S.day+3,start:S.day};compute()");
const ack = ev('R.served');
assert.match(ev('ddosPanel()'), /ACK flood/);
assert.doesNotMatch(ev('ddosPanel()'), /application layer/);
ev("S.ev.ddos.vec='memcached';compute()");
assert.ok(ev('R.served') > ack, 'Flowspec filters Memcached but cannot filter ACK');
for (const vec of ['memcached', 'ack']) {
ev(`const old=Math.random;Math.random=()=>(${['dns','ntp','memcached','ack'].indexOf(vec)}+0.1)/ddosVectors().length;ddosAttack();Math.random=old`);
assert.equal(ev('ddosAll().at(-1).vec'), vec, 'the generator can select each new vector');
}
assert.deepEqual(errors, []);
});
test('DDoS accounting conserves attack bandwidth through upstream, edge and local scrubbing', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.bb.d=100;S.scrubs=[{city:'fra',tier:1}];S.transit[0].clean=true;S.ev.ddos={city:'fra',vec:'http',gbps:1842,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute()");
assert.ok(Math.abs(ev('R.ddos[0].reaching') - 184.2) < 1e-9);
assert.equal(ev('R.ddos[0].sp.parts[0].cleaned'), ev('R.ddos[0].reaching'));
assert.equal(ev('R.ddos[0].leak'), 0, 'the 1T center cleans the upstream remainder');
assert.doesNotMatch(ev('ddosPanel()'), /842 Gbps of attack traffic leaks/);
ev('S.transit[0].clean=false;compute()');
assert.equal(ev('R.ddos[0].reaching'), 1842);
assert.equal(ev('R.ddos[0].leak'), 842);
for (const setup of ["S.transit[0].clean=true", "RG[0].fs=2;S.ev.ddos.vec='dns'", "S.scrubs=[]"]) {
ev(setup+';compute()');
assert.ok(ev('Math.abs(R.ddos[0].reaching-R.ddos[0].filtered-(R.ddos[0].sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0)-R.ddos[0].leak)<1e-9'));
assert.ok(ev('R.ddos[0].leak<=R.ddos[0].reaching'));
}
// On-demand diversion must also work for an attack which began on day zero.
ev("S.scrubs=[{city:'fra',tier:1}];S.scrubMode='ondemand';S.day=2;compute()");
assert.equal(ev('R.ddos[0].leak'), 0);
assert.deepEqual(errors, []);
});
test('the NOC integrates DDoS mitigation totals into each live attack card without duplicate summaries on phones', () => {
const { ev, errors, dom } = load();
ev('ACT.start({})');
Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true });
ev("S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.transit[0].clean=true;S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={city:'fra',vec:'http',gbps:3840,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute();UI.left='noc';UI.leftOpen=true;renderLeft()");
const card = () => dom.window.document.querySelector('[data-act="rtbh"], [data-act="unrtbh"]').closest('.inc');
const text = () => card().textContent;
assert.match(card().querySelector('.nm').textContent, /🚨 Live attack: Frankfurt/);
assert.equal(dom.window.document.querySelector('.ddos-stats'), null, 'use the existing attack card');
assert.doesNotMatch(text(), /DDoS mitigation status|Attack size:|3840 Gbps|This attack:/);
assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'the attack size appears once');
assert.match(text(), /✓ After upstream scrubbing: 384 Gbps/);
assert.equal(text().match(/After upstream scrubbing/g).length, 1, 'show the upstream remainder once');
assert.doesNotMatch(text(), /Reaching your network|reaching your network|Upstream scrubbing active/);
assert.match(text(), /✓ Scrubbing in Frankfurt: 384 Gbps \/ 1T/);
assert.match(text(), /✓ Attack fully mitigated/);
ev('S.transit[0].clean=false;compute();renderLeft()');
assert.doesNotMatch(text(), /After upstream scrubbing|Reaching your network/);
assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'inactive upstream scrubbing does not repeat the attack size');
assert.match(text(), /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T/);
assert.match(text(), /~ 2\.84 Tbps is leaking through/);
assert.equal(text().match(/leaking through/g).length, 1, 'show the mitigation outcome once');
assert.doesNotMatch(text(), /Upstream scrubbing|Attack fully mitigated|leaks past mitigation/);
ev("S.transit[0].clean=true;S.pops.fra.rgen=3;S.ev.ddos.vec='dns';compute();renderLeft()");
assert.match(text(), /✓ Flowspec dropping: 326 Gbps/);
assert.doesNotMatch(text(), /Edge filters dropping/);
assert.match(text(), /✓ Scrubbing in Frankfurt: 57\.6 Gbps \/ 1T/);
assert.match(text(), /✓ Attack fully mitigated/);
ev('ACT.rtbh();renderLeft()');
assert.match(text(), /~ Blackholed: the junk is gone, and so is Frankfurt/);
assert.equal(text().match(/Blackholed:/g).length, 1);
assert.doesNotMatch(text(), /After upstream scrubbing|reaching your network|scrubbing in Frankfurt|Attack fully mitigated|leaking through/i);
assert.ok(card().querySelector('[data-act="unrtbh"]'), 'the existing controls stay in the card');
assert.deepEqual(errors, []);
});
test('overlapping floods share scrubbing capacity, have separate controls, and finish independently', () => {
const { ev, errors, dom } = load();
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:700,start:0,until:3};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:700,start:0,until:5}];compute();UI.left='noc';UI.leftOpen=true;renderLeft()");
assert.equal(ev('R.ddos.length'), 2);
assert.equal(ev('R.ddos.reduce((n,m)=>n+(m.sp?.parts.reduce((v,x)=>v+x.cleaned,0)||0),0)'), 1000);
assert.equal(ev('R.ddos.reduce((n,m)=>n+m.leak,0)'), 400, 'one center cannot spend its capacity twice');
const cards = [...dom.window.document.querySelectorAll('[data-act="rtbh"]')].map(b=>b.closest('.inc'));
assert.equal(cards.length, 2);
assert.match(cards[1].textContent, /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T · This attack: 300 Gbps/);
ev("ACT.rtbh({id:'two'})");
assert.equal(ev("S.ev.ddos.bh||false"), false, 'the selected attack gets the control');
assert.equal(ev('S.ev.ddosMore[0].bh'), true);
assert.ok(ev('R.ddos.every(m=>m.leak===0)'), 'blackholing a target city drops every flood to it');
ev("ACT.unrtbh({id:'one'});const old=Math.random;Math.random=()=>0.1;ACT.hackback({id:'two'});Math.random=old");
assert.equal(ev('ddosAll().length'), 1, 'hack-back ends only the selected attack');
ev('S.day=3;ddosExpire();compute()');
assert.equal(ev('ddosAll().length'), 0);
assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2, 'both attacks scored once');
ev('ddosExpire()');
assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2);
assert.deepEqual(errors, []);
});
test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => {
const { ev, errors } = load();
ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('ddosAll().length'), 1);
assert.equal(ev('S.ev.ddos.gbps'), 80);
assert.equal(ev('S.ev.ddosMore.length'), 0);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]);
ev("S.ev.ddosMore=[{id:'overlap',city:'fra',vec:'ack',gbps:50,until:5,start:0,sla:['customer']},null,{city:'bad',vec:'dns'}, {city:'fra',vec:'unknown'}];S.ddosStarts=[0,'bad',Infinity,-9,99];S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('ddosAll().length'), 2);
assert.equal(ev('S.ev.ddosMore[0].id'), 'overlap');
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]);
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev('R.ddos.length'), 2);
assert.deepEqual(errors, []);
});
test('simultaneous attacks each bill their protected customer only once', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.biz=[{id:'protected',name:'Shield',city:'fra',type:'scrub',bw:5,rate:900,mood:100,since:0,reqs:[]}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:6000,start:0,until:7};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:6000,start:0,until:7}];compute();dayTick()");
assert.equal(ev('S.stats.sla'), 2, 'same-day attacks have separate SLA identities');
ev('S=migrate(JSON.parse(JSON.stringify(S)));dayTick()');
assert.equal(ev('S.stats.sla'), 2, 'reloading does not pay the same credits twice');
assert.deepEqual(errors, []);
});
test('DDoS frequency rises with level and signed gaming customers, with a rolling weekly ceiling', () => {
const { ev, errors } = load();
ev("ACT.start({});S.day=50;S.lvl=1;S.biz=[]");
const base = ev('ddosRate()');
assert.equal(base, 0.5);
ev('S.lvl=13');
assert.equal(ev('ddosRate()'), base, 'level alone does not increase the non-gaming rate');
ev("S.biz=[{type:'game',city:'fra'}];S.lvl=1");
const early = ev('ddosRate()');
ev('S.lvl=13');
const level = ev('ddosRate()');
ev("S.biz=Array.from({length:20},(_,i)=>({type:i%2?'cgame':'game',city:'fra'}))");
const gaming = ev('ddosRate()');
assert.ok(base < early && early < level && level < gaming && gaming <= 7);
ev("S.offers=Array.from({length:50},()=>({type:'game'}));S.biz=[];S.lvl=1");
assert.equal(ev('ddosRate()'), base, 'unsigned offers do not attract attacks');
// Force every random spawn opportunity (with spicy chaos on), then verify each rolling seven-day window.
ev("S.rules=makeRules('bgp');");
ev('window.__starts=[];window.__oldRandom=Math.random;Math.random=()=>0');
for (let day = 50; day < 66; day++) {
ev(`S.day=${day};ddosTick();window.__starts.push(...ddosAll().filter(a=>a.start===S.day).map(a=>a.start))`);
assert.ok(ev('S.ddosStarts.length') <= 14);
}
ev('Math.random=window.__oldRandom');
const starts = JSON.parse(ev('JSON.stringify(window.__starts)'));
for (let day = 50; day < 66; day++) assert.ok(starts.filter(d=>d>day-7&&d<=day).length <= 14);
assert.ok(starts.length > 14, 'the allowance renews as starts leave the rolling window');
ev('for(let i=0;i<30;i++)ddosAttack()');
assert.equal(ev('S.ddosStarts.length'), 14, 'manual and incident starts cannot bypass the cap');
assert.deepEqual(errors, []);
});
test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood Season scaling', () => {
const { ev, errors } = load();
ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]');
assert.equal(ev('ddosSizeMean()'), 20000);
ev("S.scn={id:'flood',rules:{ddos:true}};S.day=365");
assert.equal(ev('ddosSizeMean()'), 400000);
ev('S.day=730');
assert.equal(ev('ddosSizeMean()'), 600000, 'Flood Season keeps growing after completion');
ev('S.scn=null;R.demand=300000');
assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks');
ev('S.lvl=1');
const early = ev('ddosSizeMax()');
ev('S.lvl=13');
const late = ev('ddosSizeMax()');
ev("S.biz=[{type:'game',city:'fra'}]");
assert.ok(early < late && late < ev('ddosSizeMax()'));
// Fixed quantiles show longer durations as both level and gaming exposure rise.
ev('window.__oldRandom=Math.random;Math.random=()=>0.95;S.lvl=1;S.biz=[];ddosAttack();window.__earlyDur=ddosAll().at(-1).until-S.day;S.lvl=13;S.biz=Array.from({length:40},()=>({type:\'game\',city:\'fra\',bw:0,rate:0}));ddosAttack();Math.random=window.__oldRandom');
assert.ok(ev('ddosAll().at(-1).until-S.day') > ev('window.__earlyDur'));
assert.equal(ev('ddosAll().at(-1).until-S.day'), 7);
assert.deepEqual(errors, []);
});
test('distributed attacks follow normal transit and peering traffic across regions', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:c==='fra'?100:300}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];S.pni=[{id:'pf',city:'fra',net:'ggl',tier:1}];S.ixp={nyc:1};S.rs={nyc:true};compute();window.__normal=JSON.stringify(R.ingressPorts);ddosAttack()");
const normal = JSON.parse(ev('window.__normal'));
const entries = JSON.parse(ev('JSON.stringify(ddosAll()[0].entries)'));
const total = Object.values(normal).reduce((n,p)=>n+p.traffic,0);
assert.ok(entries.some(p=>p.k==='t') && entries.some(p=>p.k==='p') && entries.some(p=>p.k==='ix'));
assert.deepEqual([...new Set(entries.map(p=>p.city))].sort(), ['fra','nyc']);
for (const en of entries) assert.ok(Math.abs(en.share-normal[en.k+':'+en.id].traffic/total)<1e-9);
assert.ok(Math.abs(entries.reduce((n,en)=>n+en.share,0)-1)<1e-9);
assert.match(ev('ddosPanel()'), /Live attack:/);
assert.doesNotMatch(ev('ddosPanel()'), /ports: .*regions:/, 'keep regional detail out of the live attack card');
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev('S.ev.ddos.entries.length'), entries.length, 'distributed shares survive a save round trip');
assert.deepEqual(errors, []);
});
test('distributed ingress applies upstream scrubbing only to its own port and uses regional centers', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:100}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2,clean:true},{id:'tn',city:'nyc',net:'cog',tier:2}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.25},{k:'t',id:'tn',city:'nyc',share:0.75}]};compute()");
assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 775);
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 750);
assert.equal(ev('R.useT.tn'), 400, 'the uncleaned flood fills its own ingress port');
assert.ok(ev('R.useT.tf') < 200, 'it cannot spill into the cleaned port');
assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 775 Gbps/);
assert.match(ev('ddosPanel()'), /~ 750 Gbps is leaking through/);
ev("S.scrubs.push({city:'nyc',tier:1});compute()");
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0);
assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 25\.0 Gbps \/ 100G/);
assert.match(ev('ddosPanel()'), /✓ Scrubbing in New York: 750 Gbps \/ 1T/);
assert.deepEqual(errors, []);
});
test('scrubbing hauls retain their real source on each link when several cities use one center', () => {
const { ev, errors, dom } = load();
ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['prg','ber'])ACT.buildPop({city:c});
for(const c in S.pops)S.pops[c].rgen=3;
S.links=[{id:'fp1',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100},
{id:'fp2',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100},
{id:'fb',a:'fra',b:'ber',kind:'wave',tier:2,km:420,mo:100},
{id:'pb',a:'prg',b:'ber',kind:'wave',tier:2,km:280,mo:100}];
S.transit=[{id:'tp',city:'prg',net:'cog',tier:2},{id:'tb',city:'ber',net:'cog',tier:2}];
S.scrubs=[{city:'fra',tier:1}];
S.ev.ddos={id:'spread',city:'ber',vec:'ack',gbps:100,start:0,until:7,
entries:[{k:'t',id:'tp',city:'prg',share:.5},{k:'t',id:'tb',city:'ber',share:.5}]};compute()`);
const sources = id => JSON.parse(ev(`JSON.stringify(Object.entries(R.ef[edgeKey(S.links.find(l=>l.id==='${id}'))].eg)
.filter(([key])=>key.startsWith('scrub:')).map(([key,g])=>({city:R.egDesc[key].city,g})).sort((a,b)=>a.city.localeCompare(b.city)))`));
assert.equal(ev('R.load.pb||0'), 0, 'Berlin does not feed the Prague link');
assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']);
assert.deepEqual(sources('fb').map(x=>x.city), ['ber']);
assert.ok(sources('fp1')[0].g>0 && sources('fb')[0].g>0);
assert.ok(Math.abs(sources('fp1')[0].g-ev('R.load.fp1+R.load.fp2'))<1e-9, 'the grouped record covers both parallel links exactly');
ev("selectLink('fp1');draw(0)");
const row = [...dom.window.document.querySelectorAll('#panelBody .row')].find(x=>x.querySelector('.nm')?.textContent==='Attack hauled to scrubbing in Frankfurt');
assert.ok(row);
assert.match(row.querySelector('.meta').textContent, /^Prague · /);
assert.equal(JSON.parse(row.querySelector('[data-act="goEgress"]').dataset.args).city, 'prg');
assert.deepEqual(JSON.parse(ev('JSON.stringify([...UI.feed])')), ['prg'], 'the map highlights the same source as the inspected link');
row.querySelector('[data-act="goEgress"]').click();
assert.equal(ev('UI.sel.id'), 'prg', 'Open goes to the actual source city');
// Reordering ingress and adding an overlapping flood must not change the attribution.
ev("S.ev.ddos.entries.reverse();S.ev.ddosMore=[{...S.ev.ddos,id:'overlap',gbps:20,entries:S.ev.ddos.entries.slice().reverse()}];compute()");
assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']);
assert.deepEqual(sources('fb').map(x=>x.city), ['ber']);
// When Berlin's direct link fails, its haul really does join Prague's route.
ev('S.links.find(l=>l.id==="fb").cut=S.day+1;compute()');
assert.ok(ev('R.load.pb')>0);
assert.deepEqual(sources('fp1').map(x=>x.city), ['ber','prg']);
assert.deepEqual(sources('pb').map(x=>x.city), ['ber']);
assert.ok(Math.abs(sources('fp1').reduce((n,x)=>n+x.g,0)-ev('R.load.fp1+R.load.fp2'))<1e-9, 'shared-path totals still equal the actual link load');
assert.deepEqual(errors, []);
});
function setupScrubLatency(ev) {
ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['par','nyc','ams'])ACT.buildPop({city:c});
for(const c in S.pops)S.pops[c].rgen=RG.findIndex(g=>g.fs===1);
S.links=[{id:'pf',a:'par',b:'fra',kind:'wave',tier:3,km:620/1.3,mo:100},
{id:'fn',a:'fra',b:'nyc',kind:'wave',tier:3,km:6000,mo:100},
{id:'fa',a:'fra',b:'ams',kind:'wave',tier:3,km:200,mo:100}];
S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];
S.scrubs=[{city:'fra',tier:0},{city:'par',tier:0}];
S.ev.ddos={id:'par-flood',city:'par',vec:'dns',gbps:33.8,start:0,until:7,
entries:[{k:'t',id:'tf',city:'fra',share:0.65},{k:'t',id:'tn',city:'nyc',share:0.35}]};compute()`);
}
test('distributed ingress does not give a locally protected victim a remote scrubbing latency', () => {
const { ev, errors, dom } = load();
setupScrubLatency(ev);
assert.ok(ev("R.haul.some(q=>q.city==='nyc'&&q.to==='par'&&q.ms>60)"), 'the remote ingress still travels to its scrubbing center');
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'both centers clean the distributed flood');
assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-20.28)<1e-9);
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0);
Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true });
ev("UI.left='noc';UI.leftOpen=true;renderLeft()");
const text = dom.window.document.getElementById('left').textContent;
assert.match(text, /Live attack: Paris/);
assert.match(text, /Scrubbing in Frankfurt: 8\.8 Gbps/);
assert.match(text, /Scrubbing in Paris: 4\.7 Gbps/);
assert.doesNotMatch(text, /Scrubbing traffic hauled over your backbone|\+\d+(\.\d+)? ms/);
// A local center is still nearest when it is full and other centers take overflow.
ev("S.ev.ddos.vec='ack';S.ev.ddos.gbps=300;compute()");
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
assert.deepEqual(errors, []);
});
test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => {
const { ev, errors } = load();
setupScrubLatency(ev);
ev("for(const c in S.pops)S.pops[c].rgen=3;S.scrubs=[{city:'fra',tier:0},{city:'ams',tier:0}];S.ev.ddos.vec='ack';S.ev.ddos.gbps=230;compute()");
assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'capacity spills between centers');
const card = ev('ddosOne(S.ev.ddos)');
assert.equal((card.match(/Scrubbing traffic hauled over your backbone/g)||[]).length, 1);
assert.match(card, /✓ Scrubbing traffic hauled over your backbone: Paris → Frankfurt \(\+3\.1 ms\)/);
// An overlapping attack has its own victim and nearest center.
ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entries:[{k:'t',id:'tn',city:'nyc',share:1}]}];compute()");
assert.doesNotMatch(ev('ddosOne(S.ev.ddosMore[0])'), /Scrubbing traffic hauled over your backbone/);
assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Frankfurt \(\+3\.1 ms\)/);
// Ignore a failed nearby center and use the live path to Amsterdam.
ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});S.ev.ddos.entries=[{k:'edge',city:'par',share:1}];compute()");
assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Amsterdam \(\+13\.0 ms\)/);
ev('S.ev.ddos.bh=true;compute()');
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
ev('S.ev.ddos.bh=false;S.scrubMode="ondemand";compute()');
assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/);
assert.deepEqual(errors, []);
});
test('a constrained remote haul leaves scrubbing capacity for the next overlapping flood', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc'])S.pops[c].rgen=3;S.links=[{id:'thin',a:'nyc',b:'fra',kind:'wave',tier:1,km:6000,mo:100}];S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'far',city:'nyc',vec:'http',gbps:600,start:0,until:7};S.ev.ddosMore=[{id:'near',city:'fra',vec:'http',gbps:900,start:0,until:7}];compute()");
const clean = JSON.parse(ev('JSON.stringify(R.ddos.map(m=>({id:m.attack.id,clean:m.sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0,leak:m.leak})))'));
assert.equal(clean.find(m=>m.id==='near').clean, 900);
assert.ok(clean.find(m=>m.id==='far').clean <= 100);
assert.ok(clean.reduce((n,m)=>n+m.clean,0) <= 1000);
for (const m of clean) assert.equal(m.clean+m.leak, m.id==='near'?900:600);
assert.deepEqual(errors, []);
});
test('distributed attack statistics survive an ingress outage and corrupted saved shares', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'a',city:'fra',share:0.25},{k:'t',id:'b',city:'nyc',share:0.75}]};S.pops.nyc.down=5;compute()");
assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 1000);
assert.equal(ev('ddosReport(S.ev.ddos).leak'), 1000);
ev("S.ev.ddos.entries.push({k:'t',id:'bad',city:'unknown',share:5},{k:'t',id:'bad2',city:'fra',share:-1});S=migrate(JSON.parse(JSON.stringify(S)));compute()");
assert.equal(ev('S.ev.ddos.entries.length'), 2);
assert.equal(ev('S.ev.ddos.entries.reduce((n,en)=>n+en.share,0)'), 1);
assert.deepEqual(errors, []);
});
test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, and stay within a third of the current size range', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=13;S.pops.fra.bb={d:150000};ACT.buyTransit({city:'fra',net:'cog',tier:2});compute()");
assert.equal(ev("ddosVectors().includes('racknet')||ddosVectors().includes('teamspooked')"), false);
ev("S.offers=[{type:'game'}]");
assert.equal(ev("ddosVectors().includes('racknet')"), false, 'an unsigned offer does not introduce gaming attacks');
ev("S.biz=[{type:'game',id:'gamer',name:'Gamer',city:'fra',bw:0,rate:0}];compute()");
for (const vec of ['racknet','teamspooked']) {
assert.equal(ev(`DDOS_VEC.${vec}.fs`), false);
const sizeMax = ev('ddosSizeMax()/3');
ev(`const old=Math.random;let n=0;Math.random=()=>n++===1?(ddosVectors().indexOf('${vec}')+0.5)/ddosVectors().length:0.999999;ddosAttack();Math.random=old`);
assert.equal(ev('ddosAll().at(-1).vec'), vec);
assert.ok(ev('ddosAll().at(-1).gbps') <= sizeMax);
assert.ok(ev('ddosAll().at(-1).gbps') > sizeMax*(1-0.00002), 'the upper randomized quantile approaches the one-third limit, including rare spikes');
}
ev("S.biz[0].type='cgame'");
assert.equal(ev("ddosVectors().includes('teamspooked')"), true, 'cloud gaming also attracts these vectors');
ev('S.biz=[]');
assert.equal(ev("ddosVectors().includes('teamspooked')"), false);
assert.equal(ev('ddosAll().length'), 2, 'existing attacks finish naturally after the gaming customer leaves');
assert.deepEqual(errors, []);
});
test('normal DDoS starts average half an attack per week without gaming and never exceed a seven-per-week expected rate', () => {
const { ev, errors } = load();
ev("ACT.start({});S.rules=makeRules('bgp');S.day=50");
const checks = JSON.parse(ev(`
const oldAttack=ddosAttack,oldRandom=Math.random,out=[];
try {
for(const [level,games] of [[1,0],[13,0],[1,1],[13,1],[13,10],[13,1000]]){
S.lvl=level;S.biz=Array.from({length:games},()=>({type:'game'}));
let starts=0,draw=0;ddosAttack=()=>{starts++};Math.random=()=>((draw++)+0.5)/14000;
for(let day=0;day<7000;day++)ddosTick();
out.push({level,games,expected:ddosRate(),observed:starts/1000});
}
} finally {ddosAttack=oldAttack;Math.random=oldRandom;}
JSON.stringify(out)
`));
for(const row of checks){
assert.ok(Math.abs(row.observed-row.expected)<=0.0011, JSON.stringify(row));
if(row.games===0)assert.equal(row.observed,0.5);
else assert.ok(row.expected>0.5&&row.expected<=7);
}
assert.ok(checks[3].expected>checks[2].expected, 'level increases gaming frequency');
assert.ok(checks[4].expected>checks[3].expected, 'more gaming customers increase frequency');
assert.ok(checks[3].expected<0.8, 'one gaming customer does not suddenly add several attacks per week, even at the last level');
assert.deepEqual(errors, []);
});
test('normal attack sizes match the one- and fifty-gamer targets while frequency rises gradually', () => {
const { ev, errors } = load();
ev('ACT.start({})');
const samples = JSON.parse(ev(`
const oldRandom=Math.random,out=[];
try {
for(const [level,demand] of [[1,0],[3,1850],[LEVELS.length,LV_REQ.at(-1).pk]]){
const counts=[];
for(const games of [0,1,2,5,10,20,50,100,1000]){
S.lvl=level;S.biz=Array.from({length:games},(_,i)=>({id:'g'+i,type:i%2?'cgame':'game',city:'fra',bw:0,rate:0}));
const vectors=ddosVectors();let sum=0;
for(let i=0;i<vectors.length;i++)for(const [roll,weight] of [[0.49,0.98],[0.99,0.02]]){
S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=demand;
let draw=0;Math.random=()=>draw++===1?(i+0.5)/vectors.length:roll;
ddosAttack(false);sum+=weight*S.ev.ddos.gbps;
}
counts.push({games,mean:sum/vectors.length,rate:ddosRate()});
}
out.push({level,demand,counts});
}
} finally {Math.random=oldRandom;}
JSON.stringify(out)
`));
for(const row of samples){
const [plain,first]=row.counts,fifty=row.counts.find(c=>c.games===50),hundred=row.counts.find(c=>c.games===100),many=row.counts.at(-1);
assert.ok(Math.abs(first.mean-plain.mean*3)<0.003, 'the first gamer triples the overall mean, allowing only bandwidth rounding: '+JSON.stringify(row));
assert.ok(Math.abs(fifty.mean-plain.mean*8)<0.01, 'fifty gamers bring eightfold sizes, allowing only bandwidth rounding');
assert.ok(hundred.mean>first.mean*3, 'growth continues across dozens of gaming customers');
assert.ok(hundred.mean>plain.mean*10 && hundred.mean<plain.mean*11, 'a hundred gamers bring roughly tenfold sizes');
assert.ok(many.mean<=plain.mean*12+0.01, 'high-exposure sizes approach the existing upper balance');
assert.equal(plain.rate,0.5);
assert.ok(first.rate<0.8);
assert.ok(hundred.rate>6 && many.rate<=7);
for(let i=1;i<row.counts.length;i++){
assert.ok(row.counts[i].mean>row.counts[i-1].mean, 'each sampled count increases actual spawned attack sizes');
assert.ok(row.counts[i].rate>row.counts[i-1].rate, 'each sampled count increases frequency');
}
}
assert.ok(Math.abs(samples[0].counts[0].mean-1)<0.001, 'the minimum-demand baseline still permits small attacks');
assert.ok(Math.abs(samples[1].counts[0].mean-740/13)<0.001, 'the 1.85 Tbps non-gaming example keeps its average');
assert.ok(Math.abs(samples[2].counts[0].mean-samples[2].demand*4/3/10)<0.001);
assert.deepEqual(errors, []);
});
test('normal attack sizes cover a broad ordinary range and a two-percent large tail without raising the mean', () => {
const { ev, errors } = load();
ev('ACT.start({});S.lvl=3;S.biz=[];R.demand=1850');
const distribution = JSON.parse(ev(`
const oldRandom=Math.random,ordinary=[],large=[];let sum=0;
try {
for(let i=0;i<10000;i++){
Math.random=()=>(i+0.5)/10000;
const g=ddosSize('syn');sum+=g;(g>100?large:ordinary).push(g);
}
} finally {Math.random=oldRandom;}
JSON.stringify({ordinary:{n:ordinary.length,min:Math.min(...ordinary),max:Math.max(...ordinary)},
large:{n:large.length,min:Math.min(...large),max:Math.max(...large),near500:large.some(g=>g>=490&&g<=510)},mean:sum/10000})
`));
assert.equal(distribution.ordinary.n, 9800);
assert.equal(distribution.large.n, 200);
assert.ok(distribution.ordinary.min>=8.9 && distribution.ordinary.min<10);
assert.ok(distribution.ordinary.max>85 && distribution.ordinary.max<=89.1);
assert.ok(distribution.ordinary.max/distribution.ordinary.min>9.9);
assert.ok(distribution.large.min>=356 && distribution.large.max<=535);
assert.ok(distribution.large.near500, 'the example network can occasionally face a roughly 500 Gbps flood');
assert.ok(Math.abs(distribution.mean-740/13)<0.001, 'the rare tail preserves the previous 56.923 Gbps average');
// Verify that real spawns use both bands, not just the standalone sampler.
for (const [roll,minimum,maximum] of [[0.49,8.9,89.1],[0.99,356,535]]) {
ev(`S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=1850;const old=Math.random;let n=0;Math.random=()=>{const i=n++;return i===1?(ddosVectors().indexOf('syn')+0.5)/ddosVectors().length:i===2?${roll}:0.5};try{ddosAttack()}finally{Math.random=old}`);
assert.equal(ev('S.ev.ddos.vec'), 'syn');
assert.ok(ev('S.ev.ddos.gbps')>=minimum && ev('S.ev.ddos.gbps')<=maximum);
}
assert.deepEqual(errors, []);
});
test('Flood Season retains its existing size quantiles and escalation when normal attacks gain rare spikes', () => {
const { ev, errors } = load();
ev("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.demand=1850");
for (const [day,expected] of [[0,[700,1400,2099]],[365,[1400,2800,4199]],[730,[2100,4200,6299]]]) {
ev(`S.day=${day}`);
const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,0.5,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn')})}finally{Math.random=old}JSON.stringify(sizes)"));
assert.deepEqual(actual, expected);
}
assert.deepEqual(errors, []);
});
test('the busier DDoS schedule needs spicy chaos or gaming customers; otherwise attacks come as before', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.day=50;S.lvl=13;S.biz=[];S.nextFail=1e9;S.nextEvent=1e9");
const ticks = () => ev("(()=>{const old=Math.random,oa=ddosAttack;let n=0;ddosAttack=()=>{n++};Math.random=()=>0;try{for(let i=0;i<30;i++)ddosTick();}finally{Math.random=old;ddosAttack=oa;}return n;})()");
assert.equal(ticks(), 0, 'no spicy chaos, no gamers: no extra schedule');
// DDoS stays one of the regular incidents instead: some roll of fireFailure() still starts one.
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return true;}return false;}finally{Math.random=old;}})()"), 'fireFailure can start an attack');
ev("S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];S.inc=[]");
ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
assert.ok(ticks() > 0, 'gaming customers bring their own attacks');
ev("S.biz=[];S.rules=makeRules('bgp')");
assert.ok(ticks() > 0, 'spicy chaos brings more attacks');
ev("S.rules=makeRules('freeze')");
assert.equal(ticks(), 0, 'Change Freeze has no attacks on either schedule');
ev("S.biz=[{type:'game',city:'fra',bw:5,rate:1,reqs:[]}]");
assert.equal(ticks(), 0, 'not even with gamers');
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'and fireFailure never rolls one');
ev("S.rules=makeRules('bgp');S.biz=[]");
assert.ok(ev("(()=>{const old=Math.random;try{for(let i=0;i<200;i++){const r=i/200;Math.random=()=>r;S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];fireFailure();if(ddosAll().length)return false;}return true;}finally{Math.random=old;S.inc=[];}})()"), 'spicy attacks come from their own schedule only, never twice');
ev("S.rules=makeRules('oncall')");
// Flood Season, not spicy: one flood at a time, 3 to 7 days apart, however old the scenario is.
ev("ACT.startScn({id:'flood',sure:1});S.biz=[]");
const gaps = JSON.parse(ev("(()=>{const o=[];for(const d of [0,1000])for(const r of [0,0.999]){S.day=d;const old=Math.random;Math.random=()=>r;o.push(floodGap());Math.random=old;}return JSON.stringify(o);})()"));
assert.deepEqual(gaps, [3, 7, 3, 7]);
ev("S.scn.nextDdos=S.day;ddosTick()");
assert.equal(ev('ddosAll().length'), 1);
ev("S.scn.nextDdos=S.day;ddosTick()");
assert.equal(ev('ddosAll().length'), 1, 'the next flood waits for the last one to end');
assert.deepEqual(errors, []);
});

View file

@ -5,8 +5,8 @@ module.exports = `
for(f of flows){
if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue;
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
const candidates=E.filter(e=>e.used<e.cap&&e.ok(f.n)&&
(TR?eff(e,f.n):base(e,f.n))===rank&&Dv[CIDX[e.city]]<Infinity)
const candidates=E.filter(e=>e.used<e.cap&&(f.pin?e.ek===f.pin:e.ok(f.n))&&
(f.pin?base(e):TR?eff(e,f.n):base(e,f.n))===rank&&Dv[CIDX[e.city]]<Infinity)
.sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]);
for(let i=0;i<candidates.length&&f.rem>1e-6;){
let j=i+1;while(j<candidates.length&&(candidates[j].pref==='high')===(candidates[i].pref==='high')&&

View file

@ -1326,3 +1326,20 @@ test('#166 every Brazilian exchange is named after its city, São Paulo included
assert.deepEqual(odd, []);
assert.deepEqual(errors, []);
});
test('link redundancy trials distinguish a bridge, a full fallback and a healthy alternate path without changing the game',()=>{
const {ev,errors}=load();
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}];S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0,trench:'main'}];compute();window.state=JSON.stringify(S);window.live=R;window.hot=UI.hotMap;window.cache=TE_CACHE");
let t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,true);assert.equal(t.loss,80);
assert.equal(ev('JSON.stringify(S)'),ev('state'));assert.equal(ev('R===live&&UI.hotMap===hot&&TE_CACHE===cache'),true);
ev("S.links.push({id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0});compute()");
t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,70);assert.equal(t.busy.length,2);
ev("S.links[1].tier=1;S.links[2].tier=1;compute()");t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,0);
ev("S.links[1].cut=S.day+5;compute()");assert.equal(ev("linkTrial('main').split"),true,'existing failures are respected');assert.equal(ev("linkTrial('a')"),null,'an already failed link is not tested');
ev("S.links=S.links.slice(0,1);S.links.push({...S.links[0],id:'parallel'});compute()");assert.equal(ev("linkTrial('main').split"),false,'only the selected link fails even when a trench is shared');assert.equal(ev("linkTrial('main').loss"),0);
ev("S.links[0]={...S.links[0],kind:'df',sys:'roadm',ch:['tp16'],pairs:1,regen:0,ready:0,own:true};compute()");assert.equal(ev("linkTrial('main').loss"),0,'dark fiber is tested as one link');
ev("window.innerWidth=360;ACT.linkCheck({id:'main'})");assert.match(ev("$('modalCard').textContent"),/One backhoe is not enough/);assert.equal(ev("$('modal').className"),'link-check');ev("ACT.phoneTab({t:'noc'})");assert.equal(ev("$('modal').hidden"),true);
ev("S.links[0]={...S.links[0],kind:'vxc',vt:1,prov:FABS[0].id};compute()");assert.equal(ev("linkTrial('main').loss"),0,'virtual circuits are tested individually');
ev("window.saveRef=S;window.liveRef=R;window.originalCompute=compute;compute=()=>{throw Error('trial failed')}");assert.throws(()=>ev("linkTrial('main')"),/trial failed/);ev('compute=originalCompute');assert.equal(ev('S===saveRef&&R===liveRef'),true,'even a failed trial restores the live state');
assert.deepEqual(errors,[]);
});

24
tests/link-trial.test.js Normal file
View file

@ -0,0 +1,24 @@
// #62 on a big network: a redundancy check routes once (the failed link), and uses the live routing as "before".
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('#62 a redundancy check computes only the trial, and matches comparing two fresh routings', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}]");
ev("S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0},{id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0}];compute()");
ev("window.__n=0;window.__c=compute;compute=function(){window.__n++;return window.__c.apply(this,arguments);}");
const t = JSON.parse(ev("JSON.stringify(linkTrial('main'))"));
assert.equal(ev('window.__n'), 1, 'one routing pass per check');
assert.equal(t.split, false);
assert.equal(t.loss, 70);
assert.equal(ev("linkTrial('nope')"), null);
assert.equal(ev('window.__n'), 1, 'an unknown link costs nothing');
ev('compute=window.__c');
// the old way: route the copy twice, before and after the cut
const old = ev(`(()=>{const save=S,live=R;try{S=JSON.parse(JSON.stringify(save));compute();const b=R;S.links[0].cut=S.day+1;compute();
const g=c=>Math.max(0,(b.citySrv[c]||0)-(R.citySrv[c]||0)),l2=Math.max(0,(b.l2.circuit||0)-(R.l2.circuit||0));
return Object.keys(S.pops).reduce((a,c)=>a+(g(c)>.01?g(c):0),0)+(l2>.01?l2:0);}finally{S=save;R=live;}})()`);
assert.equal(t.loss, old);
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,40 @@
// #131 on Safari: the custom metric field keeps focus through a button tap, and the panel skips re-rendering a
// focused field, so switching between multiplier and cost (or to a preset) left the old panel on screen.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const setup = (ev) => {
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()");
ev("window.L=S.links[0].id;ACT.selLink({id:L});renderAll();ACT.setMetric({id:L,v:'custom'});renderAll()");
};
test('#131 switching the custom metric mode re-renders even while the field has focus', () => {
const { ev, dom, errors } = load();
const d = dom.window.document;
setup(ev);
d.getElementById('metIn').focus();
assert.equal(d.activeElement.id, 'metIn');
ev("ACT.metricMode({id:L,k:'w'})");
assert.equal(d.getElementById('metIn').getAttribute('step'), '1', 'the field is now the exact cost');
assert.equal(+d.getElementById('metIn').value, ev("S.pairMet[edgeKey(S.links[0])].v"));
d.getElementById('metIn').focus();
ev("ACT.metricMode({id:L,k:'f'})");
assert.equal(d.getElementById('metIn').getAttribute('step'), '0.1', 'and back to a multiplier');
d.getElementById('metIn').focus();
ev("ACT.setMetric({id:L,v:'normal'})");
assert.equal(d.getElementById('metIn'), null, 'a preset hides the field');
assert.deepEqual(errors, []);
});
test('#131 the daily re-render still keeps a half-typed value', () => {
const { ev, dom, errors } = load();
const d = dom.window.document;
setup(ev);
const t = d.getElementById('metIn');
t.focus(); t.value = '3.5';
ev("S.day++;renderPanel()");
assert.equal(d.getElementById('metIn').value, '3.5');
assert.equal(d.activeElement.id, 'metIn');
assert.deepEqual(errors, []);
});

View file

@ -358,7 +358,7 @@ test('Flood Season: attacks keep coming, grow, and only count when service held'
assert.ok(ev('S.lvl') >= 3, 'starts with bigger gear unlocked');
// a few weeks in: several attacks start on their own schedule
let n = 0;
for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('!!(S.ev.ddos&&S.ev.ddos.start===S.day)')) n++; }
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%+
@ -409,8 +409,8 @@ test('#114 Only Spätzle-IX can be won by peering alone', () => {
const { ev, errors } = load();
ev("ACT.startScn({id:'stg',sure:1})");
assert.equal(ev("scnRule('local')&&scnRule('noTransit')"), true);
assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /45%.*300 Gbps/);
assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.45, 300]);
assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /50%.*300 Gbps/);
assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.5, 300]);
// a game saved before the fix picks the rule up on load
ev("const o=JSON.parse(JSON.stringify(S));delete o.scn.rules.local;migrate(o);window.__mig=o.scn.rules.local");
assert.equal(ev('window.__mig'), true);
@ -468,3 +468,29 @@ test('RouteScript: help, ready-made scripts and the AI button', () => {
ev("UI.dtab='overview';renderAll()");
assert.deepEqual(errors, []);
});
test('Flood Season keeps attacking and escalating after both success and timeout', () => {
for (const outcome of ['done', 'failed']) {
const { ev, errors, dom } = load();
ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9");
if (outcome === 'done') ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;S.day=100');
else ev('S.day=365');
ev('scnTick(S.day)');
assert.ok(ev(`!!S.scn.${outcome}`));
assert.ok([...dom.window.document.querySelectorAll('#modal [data-act="closeModal"]')].some(b=>b.textContent==='Keep playing'));
ev('ACT.closeModal();S.scn.nextDdos=S.day+1;dayTick()');
assert.equal(ev('S.ev.ddos.start'), ev('S.day'), 'Keep playing still spawns attacks');
const before = ev('S.day');
ev('S.scn.nextDdos=S.day+1;S.day+=8;dayTick()');
assert.ok(ev('ddosAll().at(-1).start') > before, 'subsequent attacks keep coming');
// Escalating frequency belongs to spicy chaos; calmer games keep the old 3 to 7 days.
ev("S.rules.chaos='spicy'");
const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])'));
assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age');
const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.9;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])'));
assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age');
assert.deepEqual(errors, []);
dom.window.close();
}
});

View file

@ -0,0 +1,81 @@
const test=require('node:test');
const assert=require('node:assert/strict');
const {load}=require('./harness');
function setup(ev,sub=false){ev(`ACT.start({});S.cash=1e9;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0;
S.pops.fra.rgen=mainRG(4);S.pops.fra.routers=16;S.pops.ams={...S.pops.fra};
S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sub:${sub},sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1}];
UI.sel={type:'link',id:'fiber'};renderPanel();`);}
const count=ev=>ev('S.links[0].ch.length');
for(const sub of [false,true])test(`typed counts buy and remove optics on ${sub?'subsea':'land'} fiber`,()=>{
const {ev,dom,errors}=load();try{
setup(ev,sub);const doc=dom.window.document;
const f=doc.querySelector('form.optic-count[data-optic="zr4"]'),input=f.elements.count;
input.focus();input.value='5';input.dispatchEvent(new dom.window.Event('input',{bubbles:true}));
const cost=ev("5*chCost(S.links[0],'zr4')"),cash=ev('S.cash');
assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`)));
ev('S.day++;renderPanel()');
assert.equal(doc.activeElement,input,'tick preserves the focused field');assert.equal(input.value,'5');
assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`)));
f.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true}));
assert.equal(count(ev),5);assert.equal(cash-ev('S.cash'),cost);
ev("ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),2);assert.equal(ev('S.spares.zr4'),3);
const before=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),5);assert.equal(ev('S.cash'),before);assert.equal(ev('S.spares.zr4'),0);
ev("ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(count(ev),0);assert.equal(ev('S.spares.zr4'),5);
assert.deepEqual(errors,[]);
}finally{dom.window.close();}
});
test('batch price matches individual channel purchases with spares, regen cards and tariffs',()=>{
const {ev,dom}=load();try{setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");
const expected=ev("2*Math.round(optCost('zr4')*REGEN_CH*2)+3*Math.round(optCost('zr4')*(1+REGEN_CH*2))");
assert.equal(ev("opticCountCost(S.links[0],'zr4',5)"),expected);
const cash=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(cash-ev('S.cash'),expected);
setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");const cash2=ev('S.cash');
ev("for(let i=0;i<5;i++)ACT.addCh({id:'fiber',o:'zr4'})");assert.equal(cash2-ev('S.cash'),expected);
}finally{dom.window.close();}
});
test('unaffordable batches, port limits and invalid input never partially change state',()=>{
const {ev,dom}=load();try{setup(ev);ev('S.cash=1');
ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),0);assert.equal(ev('S.cash'),1);
ev('S.cash=1e9;S.pops.ams.routers=1');const max=ev("Math.floor(portsMax('ams')-portsUsed('ams'))");
ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${max+1}})`);assert.equal(count(ev),0);assert.equal(ev('S.cash'),1e9);
ev('S.pops.ams.routers=16');
for(const n of ['NaN','Infinity','-1','1.5','65',"'3'"]){ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${n}})`);assert.equal(count(ev),0);}
ev("ACT.setChCount({id:'missing',o:'zr4',n:2});ACT.setChCount({id:'fiber',o:'missing',n:2})");assert.equal(ev('S.cash'),1e9);
}finally{dom.window.close();}
});
test('channel reservations and reach, line-system, level and router compatibility still apply',()=>{
const {ev,dom}=load();try{setup(ev);
ev("S.links[0].ch=Array(63).fill('zr8');ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),63);
setup(ev);ev("S.biz.push({type:'wwave',link:'fiber',slots:63});ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0);
setup(ev);ev("S.links[0].km=20000;ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0);
setup(ev);ev("S.links[0].sys='lite';ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0);
setup(ev);ev("S.lvl=1;S.done={};ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0);
setup(ev);ev("S.pops.ams.rgen=0;ACT.setChCount({id:'fiber',o:'tp32',n:2})");assert.equal(count(ev),0);
setup(ev);ev("S.links[0].ch=['zr4','zr8','zr4'];ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(ev("JSON.stringify(S.links[0].ch)"),'["zr8"]');
}finally{dom.window.close();}
});
test('plus and minus buttons work alongside typed counts',()=>{
const {ev,dom,errors}=load();try{setup(ev);const doc=dom.window.document;
const plus=()=>[...doc.querySelectorAll('[data-act="addCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4');
const minus=()=>[...doc.querySelectorAll('[data-act="rmCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4');
const input=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input');
plus().click();assert.equal(count(ev),1);assert.equal(input().value,'1');
input().value='4';input().dispatchEvent(new dom.window.Event('input',{bubbles:true}));
input().form.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true}));
assert.equal(count(ev),4);minus().click();assert.equal(count(ev),3);assert.equal(input().value,'3');
plus().click();assert.equal(count(ev),4);assert.equal(input().value,'4');assert.deepEqual(errors,[]);
}finally{dom.window.close();}
});
test('draft counts and quotes stay together when reopening a panel or using shortcuts',()=>{
const {ev,dom}=load();try{setup(ev);const doc=dom.window.document;
const field=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input');
field().value='5';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));
ev("UI.sel=null;renderPanel();$('panelBody').innerHTML='';UI.sel={type:'link',id:'fiber'};renderPanel()");
assert.equal(field().value,'5');
ev("ACT.addCh({id:'fiber',o:'zr4'});ACT.rmCh({id:'fiber',o:'zr4'})");
assert.equal(field().value,'0');assert.ok(field().form.querySelector('button').textContent.includes(ev('fmt$(0)')));
field().value='';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));ev('S.day++;renderPanel()');
assert.equal(field().value,'','empty in-progress entry survives a tick');
}finally{dom.window.close();}
});

155
tests/pni-all.test.js Normal file
View file

@ -0,0 +1,155 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev, cities = []) {
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0");
for (const city of cities) ev(`ACT.buildPop({city:'${city}'})`);
ev('for(const p of Object.values(S.pops))p.rgen=RG.length-1;compute()');
}
test('bulk PNIs add missing shared POPs and upgrade smaller ports once, preserving existing orders and LAGs', () => {
const { dom, ev, errors } = load();
setup(ev, ['ams', 'lon', 'par', 'nyc', 'sjc', 'sao']);
ev(`S.pni.push(
{id:'small',net:'drz',city:'fra',tier:0,n:2,site:'ab',pref:'high'},
{id:'big',net:'drz',city:'ams',tier:2},
{id:'equal',net:'drz',city:'lon',tier:1},
{id:'pending',net:'drz',city:'par',tier:0,ready:S.day+20},
{id:'augment',net:'drz',city:'nyc',tier:0,up:{tier:1,n:1,ready:S.day+20}});compute()`);
const before = ev('JSON.stringify(S)');
assert.deepEqual(JSON.parse(ev("JSON.stringify((b=>({shared:b.shared.length,orders:b.orders.length,kept:b.kept,cost:b.cost,mo:b.mo}))(pniBatch('drz',1)))")),
{ shared: 6, orders: 2, kept: 4, cost: 6750, mo: 650 });
assert.equal(ev('JSON.stringify(S)'), before, 'preview does not change the save');
const cash = ev('S.cash');
const existing = JSON.parse(ev("JSON.stringify(S.pni.filter(p=>p.id!=='small'))"));
ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:'drz',tier:1})");
assert.equal(ev('window.afterCount'), 1, 'one recompute/render/save for the whole batch');
assert.equal(ev('S.cash'), cash - 6750);
assert.equal(ev('S.pni.length'), 6);
assert.equal(ev("S.pni.filter(p=>p.city==='sao'||p.city==='tok').length"), 0, 'only shared owned POPs');
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(p=>['big','equal','pending','augment'].includes(p.id)))")), existing);
assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2);
assert.equal(ev("S.pni.find(p=>p.id==='small').site"), 'ab');
assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high');
assert.ok(ev("S.pni.find(p=>p.city==='sjc').ready>S.day"), 'new PNIs still take time');
ev("ACT.pniAll({net:'drz',tier:1})");
assert.equal(ev('S.cash'), cash - 6750, 'repeat clicks neither charge nor duplicate');
assert.equal(ev('window.afterCount'), 1);
ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));S.day=Math.max(...S.pni.map(p=>p.up?p.up.ready:p.ready||0));pniDay(S.day);compute()');
assert.equal(ev("S.pni.find(p=>p.id==='small').tier"), 1, 'augment survives save migration and delivers');
assert.equal(ev("S.pni.find(p=>p.city==='sjc').tier"), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('bulk PNIs skip router speed, port capacity and policy restrictions with city-specific reasons', () => {
const { dom, ev, errors } = load();
setup(ev, ['ams', 'lon', 'ash']);
ev(`S.pops.fra.rgen=0;S.pops.ams.rgen=1;
S.caches=Array.from({length:portsMax('ams')},()=>({id:uid(),city:'ams',net:'cfl'}));
while(['ams','lon'].some(c=>snub('msf',c)?.all))S.asn++;
compute();R.demTo.msf=1e4;ACT.pniAllOpen({net:'msf'});ACT.pniAllSize({v:'2'})`);
assert.equal(ev("pniBatch('msf',2).orders.length"), 1);
assert.equal(ev("pniBatch('msf',2).blocked.length"), 3);
const text = dom.window.document.getElementById('modalCard').textContent;
assert.match(text, /Frankfurt.*router can't take a 400G/s);
assert.match(text, /Amsterdam.*No free router ports/s);
assert.match(text, /Ashburn.*capacity|Ashburn.*sold out/s);
const cash = ev('S.cash');
ev("ACT.pniAll({net:'msf',tier:2})");
assert.equal(ev('S.pni.length'), 1);
assert.equal(ev('S.pni[0].city'), 'lon');
assert.equal(ev('S.cash'), cash - 3500);
assert.match(ev("S.log[0].t"), /blocked: 3/);
assert.deepEqual(errors, []);
dom.window.close();
});
test('insufficient funds refuse the entire eligible batch and execution rechecks a stale preview', () => {
const { dom, ev, errors } = load();
setup(ev, ['ams']);
ev("S.cash=pniBatch('drz',1).cost-1;ACT.pniAllOpen({net:'drz'})");
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
const cash = ev('S.cash');
ev("ACT.pniAll({net:'drz',tier:1})");
assert.equal(ev('S.cash'), cash);
assert.equal(ev('S.pni.length'), 0);
ev("S.cash=1e8;ACT.pniAllOpen({net:'drz'});delete S.pops.ams;S.pops.fra.rgen=0;ACT.pniAll({net:'drz',tier:2})");
assert.equal(ev('S.cash'), 1e8);
assert.equal(ev('S.pni.length'), 0, 'deleted POPs and unsupported speeds are rechecked on click');
assert.deepEqual(errors, []);
dom.window.close();
});
test('bulk PNI actions reject invalid networks, sizes, minimum ports, traffic thresholds and non-shared locations', () => {
const { dom, ev, errors } = load();
setup(ev);
ev('S.pops.fra.rgen=0');
const cash = ev('S.cash');
for (const net of ['missing', '__proto__', 'drz', 'nfx']) {
for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:'${net}',tier:${tier}})`);
}
ev("ACT.pniAll({net:'nfx',tier:0});R.demTo.nfx=0;ACT.pniAll({net:'nfx',tier:1})");
assert.equal(ev('S.pni.length'), 0);
assert.equal(ev('S.cash'), cash);
ev("delete S.pops.fra;ACT.pniAllOpen({net:'drz'});ACT.pniAll({net:'drz',tier:1})");
assert.match(dom.window.document.getElementById('modalCard').textContent, /no POPs in common/);
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('Doitsche 1G bulk orders and 10G augments keep paid-peering fees and conference delivery rules', () => {
const { dom, ev, errors } = load();
setup(ev, ['ams']);
ev("S.conf={until:S.day+10,reg:'EU'};Math.random=()=>0.5");
const cash = ev('S.cash');
assert.equal(ev("pniBatch('dtk',-1).cost"), 2400);
assert.equal(ev("pniBatch('dtk',-1).mo"), ev('2*(PORT[0].pni/2+NET.dtk.paidFee)'));
ev("ACT.pniAll({net:'dtk',tier:-1})");
assert.equal(ev('S.cash'), cash - 2400);
assert.equal(ev('S.stats.beerPni'), 1);
assert.equal(ev('S.pni.every(p=>p.g1&&pniG(p)===1&&p.ready===S.day+15)'), true);
ev('S.day+=15;pniDay(S.day);compute()');
assert.equal(ev("pniBatch('dtk',0).mo"), 200, 'upgrades add port costs, without charging the peering fee twice');
ev("ACT.pniAll({net:'dtk',tier:0});S.day=Math.max(...S.pni.map(p=>p.up.ready));pniDay(S.day)");
assert.equal(ev('S.pni.every(p=>!p.g1&&pniG(p)===10)'), true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('Traffic row buttons and size selection work by DOM events on phones in every language', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { dom, ev, errors } = load(lang === 'en' ? {} : { lang });
setup(ev);
dom.window.innerWidth = 360;
ev("ACT.launchBB({city:'fra'});ACT.dash();ACT.dashTab({k:'traffic'})");
const doc = dom.window.document;
const buttons = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')];
assert.ok(buttons.length > 0, lang);
assert.equal(buttons.some(b => JSON.parse(b.dataset.args).net === '_tail'), false);
const cash = ev('S.cash');
buttons.find(b => JSON.parse(b.dataset.args).net === 'cfl').click();
assert.equal(doc.getElementById('modal').hidden, false, lang);
let select = doc.querySelector('#modalCard select');
assert.equal(select.closest('label').textContent.includes(ev("tr('pni_all.pni_size')")), true, lang);
select.focus();
select.value = '0';
select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
select = doc.querySelector('#modalCard select');
assert.equal(select.value, '0', lang);
assert.equal(doc.activeElement, select, 'size changes preserve keyboard focus');
const submit = doc.querySelector('#modalCard [data-act="pniAll"]');
assert.equal(JSON.parse(submit.dataset.args).tier, 0, lang);
assert.equal(submit.disabled, false, lang);
assert.equal(ev('S.cash'), cash, 'opening or changing the preview spends nothing');
submit.click();
assert.equal(doc.getElementById('modal').hidden, true, lang);
assert.equal(ev("S.pni.some(p=>p.net==='cfl'&&p.city==='fra'&&p.tier===0)"), true, lang);
assert.equal(ev('S.cash'), cash - 1750, lang);
assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang);
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});

163
tests/pni-global.test.js Normal file
View file

@ -0,0 +1,163 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(ev) {
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=RG.length-1;compute()");
}
test('global PNIs cover every eligible network and shared POP, including the long tail, in one transaction', () => {
const { dom, ev, errors } = load();
setup(ev);
ev(`ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1;
S.pni.push({id:'small',net:'cfl',city:'fra',tier:0,n:2,site:'ab',pref:'high'},
{id:'big',net:'drz',city:'ams',tier:2},
{id:'pending',net:'nfx',city:'fra',tier:1,ready:S.day+30});
compute();for(const n of NETS)R.demTo[n.id]=1e4`);
const before = ev('JSON.stringify(S)');
const batch = JSON.parse(ev('JSON.stringify(pniBatch(null,1))'));
assert.equal(ev('JSON.stringify(S)'), before, 'global preview changes no game state');
assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'fra' && q.ex));
assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'ams' && !q.ex));
assert.ok(batch.orders.some(q => ev(`NET['${q.net}'].tail`)), 'small networks are included');
assert.equal(batch.orders.some(q => q.net === 'drz' && q.city === 'ams'), false, 'no downgrade');
assert.equal(batch.orders.some(q => q.net === 'nfx' && q.city === 'fra'), false, 'keep pending orders');
const cash = ev('S.cash');
ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:null,tier:1})");
assert.equal(ev('window.afterCount'), 1);
assert.equal(ev('S.cash'), cash - batch.cost);
assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length);
assert.equal(ev('new Set(S.pni.map(p=>p.net+"@"+p.city)).size'), ev('S.pni.length'));
assert.equal(ev("S.pni.every(p=>S.pops[p.city]&&NET[p.net].pops.includes(p.city))"), true);
assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2, 'LAG members stay together');
assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high');
assert.equal(ev("S.pni.find(p=>p.id==='big').tier"), 2);
assert.equal(ev('Object.keys(S.pops).every(c=>portsUsed(c)<=portsMax(c))'), true);
ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));compute()');
assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length);
assert.equal(ev("S.pni.find(p=>p.id==='small').up.tier"), 1);
const count = ev('S.pni.length');
ev('ACT.pniAll({net:null,tier:1})');
assert.equal(ev('S.cash'), cash - batch.cost, 'repeat clicks spend nothing');
assert.equal(ev('S.pni.length'), count);
assert.deepEqual(errors, []);
dom.window.close();
});
test('global PNIs share the available router ports, including four 10G breakouts per slot', () => {
for (const [tier, count] of [[1, 1], [0, 4]]) {
const { dom, ev, errors } = load();
setup(ev);
ev("S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));compute()");
assert.equal(ev(`pniBatch(null,${tier}).orders.length`), count);
assert.ok(ev(`pniBatch(null,${tier}).blocked.some(q=>/No free router ports/.test(q.why))`));
ev(`ACT.pniAll({net:null,tier:${tier}})`);
assert.equal(ev('S.pni.length'), count);
assert.equal(ev("portsUsed('fra')"), 8);
const cash = ev('S.cash');
ev(`ACT.pniAll({net:null,tier:${tier}})`);
assert.equal(ev('S.cash'), cash);
assert.deepEqual(errors, []);
dom.window.close();
}
});
test('global planning reserves ports for pending speed and LAG augments without mutating the save', () => {
for (const [tier, n] of [[1, 1], [0, 4]]) {
const { dom, ev, errors } = load();
setup(ev);
ev(`S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));
S.pni=[{id:'pending',city:'fra',net:'cfl',tier:0,n:1,up:{tier:${tier},n:${n},ready:S.day+30}}];compute()`);
const state = ev('JSON.stringify(S)');
assert.equal(ev('pniBatch(null,0).orders.length'), 0);
assert.equal(ev('pniBatch(null,1).orders.length'), 0);
assert.equal(ev('JSON.stringify(S)'), state);
const cash = ev('S.cash');
ev('ACT.pniAll({net:null,tier:1})');
assert.equal(ev('S.pni.length'), 1);
assert.equal(ev('S.cash'), cash);
assert.deepEqual(errors, []);
dom.window.close();
}
});
test('global PNIs require the full budget and reject unsupported sizes and an empty POP list', () => {
const { dom, ev, errors } = load();
setup(ev);
ev('S.cash=pniBatch(null,1).cost-1;ACT.pniAllOpen({net:null})');
const cash = ev('S.cash');
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
ev('ACT.pniAll({net:null,tier:1})');
assert.equal(ev('S.cash'), cash);
assert.equal(ev('S.pni.length'), 0, 'no partial purchase');
for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:null,tier:${tier}})`);
ev('ACT.pniAll({tier:1});S.pops={};ACT.pniAllOpen({net:null})');
assert.equal(ev('S.cash'), cash);
assert.equal(ev('S.pni.length'), 0);
assert.match(dom.window.document.getElementById('modalCard').textContent, /No shared POPs/);
assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the global batch, now in the Ops sheet, preserves scope, keyboard focus and translations on phones', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { dom, ev, errors } = load(lang === 'en' ? {} : { lang });
setup(ev);
dom.window.innerWidth = 360;
// The Traffic tab now points at the Ops sheet, where the one-off batches live.
ev("ACT.dash();ACT.dashTab({k:'traffic'})");
const doc = dom.window.document;
doc.querySelector('#dashCard [data-act="opsOpen"]').click();
const button = [...doc.querySelectorAll('#modalCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null);
assert.ok(button, lang);
button.click();
assert.equal(doc.querySelector('#modalCard h2').textContent, ev("tr('pni_all.peer_all_networks')"), lang);
const cash = ev('S.cash');
const select = doc.querySelector('#modalCard select');
assert.equal([...select.options].some(o => o.value === '-1'), false, '1G is not available for all networks');
select.focus();
select.value = '0';
select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
assert.equal(doc.activeElement, doc.querySelector('#modalCard select'));
const submit = doc.querySelector('#modalCard [data-act="pniAll"]');
assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang);
assert.equal(submit.disabled, false, lang);
assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed');
assert.equal(ev('S.cash'), cash, 'preview does not buy anything');
assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang);
const cost = ev('pniBatch(null,0).cost');
submit.click();
assert.equal(doc.getElementById('modal').hidden, true, lang);
assert.equal(ev('S.cash'), cash - cost, lang);
assert.ok(ev('new Set(S.pni.map(p=>p.net)).size') > 1, lang);
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});
test('bulk PNIs follow each network\'s own minimum port and lead time (pniMin, pniLead)', () => {
const { ev, errors } = load();
setup(ev);
ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1;compute();for(const n of NETS)R.demTo[n.id]=1e4");
// Ask everyone for 10G: networks that start at 100G get 100G, the rest get 10G.
const b = JSON.parse(ev('JSON.stringify(pniBatch(null,0))'));
const big = b.orders.filter(q => ev(`pniMin('${q.net}')`) > 0), small = b.orders.filter(q => ev(`pniMin('${q.net}')`) === 0);
assert.ok(big.length && small.length, 'the batch has networks of both kinds');
assert.ok(big.every(q => q.tier === ev(`pniMin('${q.net}')`)), 'never below a network\'s minimum');
assert.ok(small.every(q => q.tier === 0));
assert.equal(b.raised, big.length);
assert.equal(b.blocked.some(q => /does not do/.test(q.why)), false, 'nobody is blocked for the size alone');
// A single network still refuses a port below its minimum.
const t1 = ev("NETS.find(n=>pniMin(n.id)>0&&n.pops.includes('fra')).id");
const one = JSON.parse(ev(`JSON.stringify(pniBatch('${t1}',0))`));
assert.equal(one.orders.length, 0);
assert.ok(one.blocked.length > 0);
// Lead times come from pniLead per network, as for a single order: big networks about a month, others 2 to 6 weeks.
ev("const r=Math.random;Math.random=()=>0.5;ACT.pniAll({net:null,tier:0});Math.random=r");
const placed = JSON.parse(ev('JSON.stringify(S.pni.map(p=>({net:p.net,wait:p.ready-S.day,big:pniBig(p.net)})))'));
assert.equal(placed.length, b.orders.length);
assert.ok(placed.some(p => p.big) && placed.some(p => !p.big));
for (const p of placed) if (p.big) assert.equal(p.wait, 30, p.net); else assert.equal(p.wait, 14 + Math.floor(0.5 * 29), p.net);
assert.deepEqual(errors, []);
});

View file

@ -7,23 +7,24 @@ const { load } = require('./harness');
// `one` earns the goal star, `three` earns all three. A second land link on the same pair is a diverse route.
const REF = {
hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] },
eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['lon', 'ams', 'uly'], ['lon', 'ams', 'concerto'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] },
shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['nyc', 'chi', 'land'], ['chi', 'sjc', 'land'], ['sjc', 'dal', 'land'], ['dal', 'nyc', 'land']] },
smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['hel', 'cph', 'land'], ['cph', 'osl', 'land']] },
downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['adl', 'bne', 'land'], ['bne', 'syd', 'land']] },
aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['sjc', 'hnl', 'scx'], ['sjc', 'hnl', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] },
rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['tok', 'hkg', 'adc'], ['tok', 'hkg', 'apg'], ['hkg', 'sin', 'sjc2'], ['hkg', 'sin', 'land']] },
fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] },
kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'sea', 'hwk'], ['sea', 'hnl', 'hwk'], ['hnl', 'akl', 'hwk'], ['akl', 'syd', 'tasman'], ['akl', 'syd', 'scx']] },
guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']] },
flash: { one: [['nyc', 'lon', 'hibx']], three: [['nyc', 'lon', 'hibx'], ['nyc', 'lon', 'grace']] },
eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['ams', 'lon', 'concerto'], ['ams', 'lon', 'nshuttle'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] },
shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['chi', 'nyc', 'land'], ['chi', 'sjc', 'land'], ['dal', 'nyc', 'land'], ['dal', 'sjc', 'land']] },
smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['cph', 'osl', 'land'], ['cph', 'hel', 'land'], ['hel', 'sto', 'land']] },
downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['mel', 'syd', 'land'], ['bne', 'syd', 'land'], ['adl', 'mel', 'land'], ['adl', 'bne', 'land']] },
aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['hnl', 'sjc', 'scx'], ['hnl', 'sjc', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] },
rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['hkg', 'tok', 'apg'], ['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['hkg', 'sin', 'land']] },
fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] },
// Hawaiki is Seattle's only cable south, so the second way out runs overland to LA and on via Suva.
kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['suv', 'syd', 'scxn'], ['lax', 'sea', 'land'], ['lax', 'suv', 'scxn']] },
guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['mnl', 'tok', 'jup'], ['syd', 'tok', 'sushi'], ['gum', 'mnl', 'bifrost'], ['gum', 'syd', 'guam']] },
flash: { one: [['nyc', 'lon', 'hibx']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'hibx']] },
pingpong: { one: [['lax', 'tok', 'jup']], three: [['lax', 'tok', 'jup'], ['lax', 'sea', 'land'], ['sea', 'tok', 'fast']] },
suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['mrs', 'bom', 'twoaf'], ['bom', 'sin', 'land']] },
samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'mia', 'monet'], ['sao', 'for', 'land'], ['for', 'mia', 'monet']] },
sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land'], ['mil', 'lis', 'land']] },
braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix'], ['dub', 'nyc', 'havf']] },
nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land'], ['zrh', 'ams', 'land']] },
fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1], ['zrh', 'par', 'land', 1]] },
suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['bom', 'sin', 'land'], ['bom', 'mrs', 'twoaf']] },
samba: { one: [['sao', 'mia', 'monet']], three: [['for', 'sao', 'land'], ['for', 'sao', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] },
sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['lis', 'mil', 'land'], ['mad', 'par', 'land'], ['mil', 'par', 'land']] },
braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['lon', 'nyc', 'grace'], ['dub', 'nyc', 'havf'], ['dub', 'lon', 'celtix']] },
nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ams', 'zrh', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']] },
fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'zrh', 'land', 1], ['mrs', 'par', 'land', 1], ['mil', 'mrs', 'land', 1], ['mil', 'zrh', 'land', 1]] },
};
// Builds links the way a player does: POP at the first city, then the link picker for each hop.
@ -61,6 +62,45 @@ test('puzzle data: every puzzle is valid, solvable, and its 3-star reference ear
assert.deepEqual(errors, []);
});
// Brute force over every route between the puzzle's cities (one size: 10G, or 100G under minG): is any 3-star build
// cheaper than `limit`? Each cable is one failure unit; each overland link its own trench (a second one is diverse).
function cheaper3(ev, id, limit) {
const D = JSON.parse(ev(`(()=>{pzBegin(pzDef('${id}'));const P=S.pz,cs=[...P.cities,...P.via],tier=P.minG?1:0,o=[];
for(const a of cs)for(const b of cs)if(a<b)for(const r of pzRoutes(a,b)){if((P.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))continue;
o.push({a,b,cab:r.cab,cost:pzLinkCost(r,tier,false),ms:r.ms});if(!r.cab)o.push({a,b,cab:null,cost:pzLinkCost(r,tier,true),ms:r.ms,div:1});}
const pop={};for(const c of cs)pop[c]=pzPopCost(c);return JSON.stringify({P,o,pop});})()`));
const { P, o, pop } = D, unit = (i) => o[i].cab ? 'c' + o[i].cab : 't' + i;
const reach = (ls, skip) => { const adj = {}; for (const i of ls) { if (unit(i) === skip) continue; const { a, b } = o[i]; (adj[a] = adj[a] || []).push(b); (adj[b] = adj[b] || []).push(a); }
const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) for (const v of adj[q.pop()] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } return P.cities.every((c) => seen.has(c)); };
const lat = (ls) => { const d = { [P.lat[0]]: 0 }, done = new Set(); for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null) return Infinity; if (u === P.lat[1]) return d[u]; done.add(u);
for (const i of ls) { const l = o[i]; if (l.a !== u && l.b !== u) continue; const v = l.a === u ? l.b : l.a, nd = d[u] + l.ms + 0.05; if (!(nd >= d[v])) d[v] = nd; } } };
const ring = (ls) => { const nb = {}; for (const i of ls) { const { a, b } = o[i]; (nb[a] = nb[a] || new Set()).add(b); (nb[b] = nb[b] || new Set()).add(a); } const ns = Object.keys(nb);
if (ns.length < 3 || !ns.every((c) => nb[c].size === 2)) return false; let prev = null, cur = ns[0], n = 0; do { const nx = [...nb[cur]].find((x) => x !== prev); prev = cur; cur = nx; n++; } while (cur !== ns[0] && n <= ns.length); return n === ns.length; };
const ok = (ls) => { if (!reach(ls, null) || (P.ring && !ring(ls)) || (P.lat && lat(ls) > P.lat[2])) return false; return [...new Set(ls.map(unit))].every((u) => reach(ls, u)); };
let found = null;
const rec = (start, ls, cost) => { if (found) return; if (ls.length && cost < limit - 1) { const pops = new Set(P.cities); for (const i of ls) { pops.add(o[i].a); pops.add(o[i].b); } const tot = cost + [...pops].reduce((x, c) => x + pop[c], 0); if (tot < limit - 1 && ok(ls)) { found = tot; return; } }
if (ls.length >= 7) return; for (let i = start; i < o.length; i++) { if (o[i].div && !ls.some((j) => !o[j].div && !o[j].cab && o[j].a === o[i].a && o[j].b === o[i].b)) continue; if (cost + o[i].cost < limit - 1) rec(i + 1, [...ls, i], cost + o[i].cost); } };
rec(0, [], 0);
return found;
}
test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, tight N-1 Club', () => {
const { ev, errors } = load();
const SLACK = { hello: [0.15, 0.2], fire: [0.09, 0.11], speed: [0.09, 0.11], n1: [0.05, 0.08] };
const rows = JSON.parse(ev('JSON.stringify(PZ.filter(p=>p.budget).map(p=>({id:p.id,pack:p.pack,budget:p.budget})))'));
for (const { id, pack, budget } of rows) {
ev(`pzBegin(pzDef('${id}'))`);
build(ev, REF[id].three);
const e = evalP(ev);
assert.equal(e.stars, 3, id);
assert.equal(cheaper3(ev, id, e.spend), null, `${id}: the reference is the cheapest 3-star build`);
const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack];
assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`);
}
assert.match(ev("PZ_PACKS[0].d"), /Roomy budgets/, 'the first pack does not promise "no budget"');
assert.deepEqual(errors, []);
});
test('stars: goal, budget, N-1 and twists each count', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('braces'))");
@ -77,6 +117,15 @@ test('stars: goal, budget, N-1 and twists each count', () => {
build(ev, REF.shining.one);
ev("ACT.pzLinkTo({a:'nyc',b:'chi'});ACT.pzVia({v:'land'});ACT.pzDiv({v:0});ACT.pzLink({tier:0})");
assert.equal(ev("new Set(S.links.filter(l=>edgeKey(l)==='chi|nyc').map(pzUnit)).size"), 1, 'same trench shares the cut');
// A cable fails as a whole: two waves on one cable, even between different cities, are one cut.
ev("pzBegin(pzDef('guam'))");
build(ev, [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']]);
e = evalP(ev);
assert.ok(e.goal && !e.n1, 'both of Sydney\'s links ride the Guam cable: one anchor splits Sydney off');
assert.equal(ev("new Set(S.links.filter(l=>l.cable==='guam').map(pzUnit)).size"), 1, 'one cable, one failure unit');
assert.ok(ev("document.getElementById('pzBox').textContent").includes('One cut splits it: ' + ev('CAB.guam.name')), 'the weak spot names the cable');
ev("ACT.pzRmLink({id:S.links[3].id})");build(ev, [['tok', 'syd', 'sushi']]);
assert.equal(evalP(ev).stars, 3, 'a second cable into Sydney fixes it');
// Twists: no subsea, ring, latency, minimum size, cities to avoid.
ev("pzBegin(pzDef('sharks'))");build(ev, REF.sharks.one);
assert.ok(evalP(ev).goal);
@ -121,12 +170,14 @@ test('no clock in a puzzle: days never pass, nothing breaks, no bills', () => {
test('the main save is byte-identical before and after playing and solving a puzzle', () => {
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:'ams'});save(true);window.__slot=UI.slot");
const before = ev("slotRaw(UI.slot||window.__slot)");
let before = ev("slotRaw(UI.slot||window.__slot)");
const name = ev('S.name'), day = ev('S.day');
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('modalCard').textContent"), /Hello, World/);
ev("ACT.pzStart({id:'hello'})");
assert.equal(ev('S.mode'), 'puzzle');
before = ev("slotRaw(window.__slot)");// entering saves the network once more (a new stamp, the same game)
assert.equal(JSON.parse(before).name, name);
build(ev, REF.hello.three);
ev("save(true);for(let i=0;i<5;i++)frame(performance.now()+6000*i);window.dispatchEvent(new Event('pagehide'));ACT.exportSave({})");
assert.equal(ev("slotRaw(UI.slot||window.__slot)"), before, 'untouched while in the puzzle');
@ -180,16 +231,16 @@ test('weekly puzzle: stable seed per ISO week, solvable, share string and streak
assert.equal(w.key, '2026-W44');
assert.ok(w.cities.length >= 4 && w.cities.length <= 5 && w.budget > 0);
// Every week of a few years can be solved with three stars by its own reference ring.
for (let i = 0; i < 160; i += 7) {
for (let i = 0; i < 400; i += 7) {
ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`);
const ring = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')).ref)'));
const links = ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; });
build(ev, links);
const w = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')))'));
const cabs = w.refVia.filter((v) => v !== 'land');
assert.equal(new Set(cabs).size, cabs.length, `week +${i}: no two hops of the reference ring share a cable`);
build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]]));
assert.equal(evalP(ev).stars, 3, `week +${i}`);
}
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))");
const ring = w.ref;
build(ev, ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; }));
build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]]));
assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$\d+k · seriesoftub\.es$/);
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1);
// A streak counts weeks in a row; a gap starts again.
@ -253,3 +304,146 @@ test('puzzles in every language', () => {
assert.deepEqual(errors, [], lang);
}
});
test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('kiwi'))");
assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market');
assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')"));
assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO"));
ev("selectCity('suv')");
assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo'));
assert.deepEqual(errors, []);
});
test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))");
const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)"));
build(ev, REF.braces.one);
const two = evalP(ev).spend;
assert.deepEqual(rec(), { st: 2, sp: two });
// A gold-plated third link: N-1 but over budget is still two stars, and dearer, so the best stays.
ev("ACT.pzLinkTo({a:'dub',b:'nyc'});ACT.pzVia({v:'havf'});ACT.pzLink({tier:2});closeModal()");
assert.equal(evalP(ev).stars, 2);
assert.deepEqual(rec(), { st: 2, sp: two });
// Shrinking it to 10G earns the third star: the best spend starts again at the 3-star build.
ev('ACT.pzTier({id:S.links[2].id,tier:0})');
const three = evalP(ev);
assert.equal(three.stars, 3);
assert.deepEqual(rec(), { st: 3, sp: three.spend });
// With a looser budget, a dearer 3-star build does not replace it; going back to the cheaper one keeps it.
ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:1})');
assert.equal(evalP(ev).stars, 3);
assert.deepEqual(rec(), { st: 3, sp: three.spend });
// A cheaper 3-star build after a dearer first one is recorded (the old code only recorded star rises).
ev("localStorage.removeItem('sot-puzzles')");
ev('ACT.pzTier({id:S.links[1].id,tier:1})');
const dear = evalP(ev).spend;
assert.deepEqual(rec(), { st: 3, sp: dear });
ev('ACT.pzTier({id:S.links[1].id,tier:0});ACT.pzTier({id:S.links[0].id,tier:0})');
assert.deepEqual(rec(), { st: 3, sp: three.spend });
// Fewer stars never overwrite more.
ev('ACT.pzRmLink({id:S.links[2].id})');
assert.deepEqual(rec(), { st: 3, sp: three.spend });
ev('ACT.puzzleMenu({})');
assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`)));
assert.deepEqual(errors, []);
});
test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
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:'ams'});save(true)");
ev("toast('main game news','bad',[{l:'Fix',act:'opsOpen',args:{}}]);save(true)");
assert.ok(ev("document.querySelectorAll('#toasts .toast').length") > 0);
ev("window.__slot=UI.slot;ACT.pzStart({id:'hello'})");
const before = ev("slotRaw(__slot)");
assert.equal(ev("[...document.querySelectorAll('#toasts .toast')].filter(t=>/main game news/.test(t.textContent)).length"), 0, 'main-game toasts are cleared');
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({})",
"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);
assert.equal(st(), s0, `${a} does nothing in a puzzle`);
}
assert.equal(ev('S.mode'), 'puzzle');
// A leftover toast button is a no-op too, through the real click path.
ev("toast('stray','',[{l:'Go',act:'opsOpen',args:{}}]);document.querySelector('#toasts [data-act=opsOpen]').click()");
assert.equal(st(), s0);
ev("toast('puzzle news','good')");
ev('ACT.pzLeave({})');
assert.equal(ev("document.querySelectorAll('#toasts .toast').length"), 0, 'puzzle toasts do not follow you home');
assert.equal(ev("slotRaw(__slot)"), before);
// Back in the main game, the same actions work again.
ev("ACT.addRouter({city:'ams'})");
assert.equal(ev('S.pops.ams.routers'), 2);
assert.deepEqual(errors, []);
});
test('a city to avoid reads as a rule, not a goal that can fail', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('nofra'))");
const tw = () => ev("[...document.querySelectorAll('#pzBox .pztw')].map(x=>x.className+'|'+x.textContent).join('\\n')");
assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/);
assert.doesNotMatch(tw(), /[✓✗].*Frankfurt/);
build(ev, REF.nofra.three);
assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/, 'still a rule once solved');
assert.equal(evalP(ev).stars, 3);
assert.deepEqual(errors, []);
});
test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a clear mark', () => {
const { ev, errors } = load();
// jsdom has no layout: read the phone media rules from the page's stylesheet (Chromium at 360 px measures 40 px).
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]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),mw:r.style.getPropertyValue('min-width'),pos:r.style.getPropertyValue('position'),bottom:r.style.getPropertyValue('bottom')})))`));
const tap = rules.find((r) => /#pzBox \.btns \.b/.test(r.sel) && /#pzBox \.pzh \.b/.test(r.sel));
assert.ok(tap && parseFloat(tap.mh) >= 40 && parseFloat(tap.mw) >= 40, `Undo/Reset/Back/☰ are at least 40 px (${JSON.stringify(tap)})`);
const pin = rules.find((r) => /^#pzBox ?> ?\.btns$/.test(r.sel));
assert.ok(pin && pin.pos === 'sticky' && parseFloat(pin.bottom) === 0, `the action row stays at the foot of a scrolling sheet (${JSON.stringify(pin)})`);
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));pzBegin(pzDef('braces'))");
const chips = () => ev("[...document.querySelectorAll('#pzBox .pzc')].map(x=>x.textContent).join('|')");
assert.equal(chips(), '○ New York|○ London|○ Dublin', 'not reached yet: a hollow mark, nothing that looks cut off');
assert.doesNotMatch(chips(), /…/);
build(ev, [['nyc', 'lon', 'grace']]);
ev("ACT.pzPop({city:'dub'})");
assert.equal(chips(), '✓ New York|✓ London|◐ Dublin');
assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes');
assert.deepEqual(errors, []);
});
test('results pull you on: Next is the big tap after three stars, stars left in the pack, and a nudge when 3 stars are one link away', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))");
build(ev, REF.braces.one);
let card = ev("document.getElementById('modalCard').textContent");
assert.equal(evalP(ev).stars, 2);
assert.match(card, /So close: one more link and a backhoe can't touch you\./, 'Dublin to New York would do it, within budget');
assert.match(ev("document.getElementById('pzBox').textContent"), /So close/);
assert.match(card, /10 ⭐ left in this pack/, '4 puzzles × 3 stars, 2 won');
assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')"));
assert.ok(!ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"));
build(ev, [['dub', 'nyc', 'havf']]);
card = ev("document.getElementById('modalCard').textContent");
assert.match(card, /9 ⭐ left in this pack/);
assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"), 'three stars: the big Next layout');
assert.ok(ev("document.activeElement===document.querySelector('#modalCard .pznext')"), 'the big button has the focus');
assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars');
assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/, 'the last pack points back to the list');
ev("pzBegin(pzDef('eurotrip'))");build(ev, REF.eurotrip.three);
assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/);
assert.equal(ev("document.activeElement.dataset.act"), 'pzStart');
// No nudge when no single link fits the budget: an over-budget gold plate is not "close".
ev("pzBegin(pzDef('braces'));S.pz.budget=245000");
build(ev, REF.braces.one);
assert.equal(evalP(ev).stars, 2);
assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /So close/);
assert.match(ev("document.getElementById('modalCard').textContent"), /One backhoe away/);
// A finished pack says so.
ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{sharks:{st:3},braces:{st:3},nofra:{st:3},fatpipes:{st:2}}}));pzBegin(pzDef('fatpipes'))");
build(ev, REF.fatpipes.three);
assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/);
assert.deepEqual(errors, []);
});

View file

@ -610,7 +610,8 @@ test('Australia: hard mode start in Sydney, dear transit and waves, cheap IX por
assert.equal(ev('S.home'), 'syd');
assert.equal(ev("regionMult('syd')"), 3, 'transit into Australia costs more than Asia');
assert.ok(ev("regionMult('syd')>regionMult('sin')&&regionMult('syd')<regionMult('icn')"));
assert.equal(ev("regionMult('akl')"), 1.8, 'Auckland keeps the Oceania price');
assert.ok(ev("regionMult('akl')") < ev('AU_TRANSIT'), 'Auckland is not priced like Australia');
assert.equal(ev("regionMult('akl')"), ev("Math.round(1.8*txComp('akl')*10)/10"), 'Auckland pays the Oceania price, adjusted for its market');
assert.equal(ev("waveMarket('syd','lax',true).reg"), 2.6, 'any subsea wave touching Australia');
assert.equal(ev("waveMarket('mel','syd',false).reg"), 1.8);
assert.ok(ev("ixPortMo('syd',1)<PORT[1].ix"), 'IX ports are the cheap exception');
@ -1070,3 +1071,30 @@ test('city density: no small city crowds a bigger one, Brazil is slimmer than Eu
ev('cam.x=CITY.cpv.x;cam.y=CITY.cpv.y;cam.z=6;draw(0)');
assert.deepEqual(errors, []);
});
test('prices follow real connectivity: thin markets cost more, hubs stay put', () => {
const { ev, errors } = load();
start(ev);
assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(CITY_PDB).filter(c=>!CITY[c]))')), [], 'every entry is a city on the map');
assert.deepEqual(JSON.parse(ev('JSON.stringify(CITIES.filter(c=>!CITY_PDB[c.id]).map(c=>c.id))')), [], 'every city has data, so none keeps the plain price by accident');
assert.ok(ev('Object.values(CITY_PDB).every(q=>Array.isArray(q)&&q.length===3&&q.every(x=>Number.isInteger(x)&&x>=0)&&q[1]>=0)'), '[facilities, presences, ASNs], whole numbers');
// The cities that used to have none: thin markets cost more than Frankfurt, and the Arctic has no neutral data center.
for (const c of ['dus', 'rix', 'mct', 'mle', 'fuk', 'sju', 'kin', 'anc', 'tik']) assert.ok(ev(`txComp('${c}')`) > 1, `${c} is no hub`);
for (const c of ['brw', 'tik', 'pvs', 'hav']) assert.equal(ev(`colo('${c}')`), 1.5, `${c}: no carrier-neutral data center`);
assert.ok(ev("txComp('dus')") < ev("txComp('rix')") && ev("txComp('rix')") < ev("txComp('mle')"), 'Düsseldorf, Riga, Malé: ever thinner');
// A city without data keeps the plain regional price.
assert.equal(ev("(()=>{const q=CITY_PDB.fra;delete CITY_PDB.fra;const r=[txComp('fra'),colo('fra'),popMo('fra')];CITY_PDB.fra=q;return r.join()})()"), `1,1,${ev('POP_MO')}`);
assert.equal(ev("regionMult('syd')"), ev('AU_TRANSIT'), 'Australia keeps its hand-set transit price');
for (const c of ['fra', 'ams', 'lon', 'nyc']) assert.equal(ev(`txComp('${c}')`), 1, `${c} is a hub`);
assert.equal(ev("regionMult('sao')"), 1.6, 'São Paulo keeps the South American price');
assert.ok(ev("regionMult('rbr')") > ev("regionMult('sao')") * 1.5, 'Rio Branco has few sellers');
assert.ok(ev("txComp('rbr')") <= 1.8);
assert.equal(ev("colo('rbr')"), 1.5, 'no neutral data center');
assert.equal(ev("popCost('rbr')"), ev('POP_COST') * 1.5);
assert.equal(ev("popMo('fra')"), ev('POP_MO'));
ev("ACT.buildPop({city:'rbr'});compute()");
assert.ok(ev('R.cost.pops') >= ev("popMo('rbr')"), 'running cost uses the city rent');
ev("selectCity('rbr')");
assert.ok(ev("CITY_PDB.sao[2]>=2000&&CITY_PDB.nyc[2]>=2000&&CITY_PDB.kgl[2]<2000"), 'Brazil and the US are dense in ASNs, Rwanda is not');
assert.deepEqual(errors, []);
});

View file

@ -38,6 +38,7 @@ test('indexed routing matches the simple allocation loop across network changes'
"S.te.script='prefer transit Cogentle\\nprepend transit Cogentle 2\\nprotect customers'",
"S.ev.rpki={nets:['ggl','nfx'],until:S.day+3};S.ev.depeer=S.day+3",
"S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}",
"S.ev.ddos.entries=[{k:'t',id:'transit0',city:'fra',share:.4},{k:'t',id:'transit4',city:'nyc',share:.6}]",
"S.links[0].eqDown=S.day+2;S.links[1].cut=S.day+2;S.links[2].loss={until:S.day+2,f:0.5}",
"S.links[4].chFail={until:S.day+2,o:'tp16'};S.links[6].ch.push('zr4');S.links[8].regen=2",
"S.day+=4;S.pni.splice(0,20);S.caches.splice(0,10);S.transit[0].pref='high'",
@ -53,3 +54,28 @@ test('indexed routing matches the simple allocation loop across network changes'
} finally { dom.window.close(); }
});
// Islands: POPs no backbone joins. Exit lists are split per island (a flow only scans exits it can reach),
// and must route exactly like the full scan, also when a cut splits an island or joins two.
test('indexed routing matches the simple allocation loop on a network of islands', () => {
const { ev, dom, errors } = load();
try {
network(ev);
ev("S.links=S.links.filter(l=>!['df4','df9','w3','w4','w8','w9'].includes(l.id));compute()");
assert.ok(ev("Object.keys(S.pops).some(c=>!pathExists('fra',c))"), 'the network is in pieces');
const changes = [
'',
"S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')",
"S.te={on:true,script:'prefer pni for goggle\\nspill at 80%'}",
"S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}",
"S.links[0].cut=S.day+2",
"S.te=null;S.links[0].cut=0;S.links.push({id:'join',a:'par',b:'pek',kind:'wave',tier:2,km:8000,cut:0,mo:100})",
];
for (const change of changes) {
ev(change);
ev('window.priorR=JSON.stringify(R);referenceCompute();window.expectedR=JSON.stringify(R);R=JSON.parse(priorR);compute()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(R)')), JSON.parse(ev('expectedR')), change || 'baseline');
}
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});

73
tests/sales-trial.test.js Normal file
View file

@ -0,0 +1,73 @@
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');
// The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without
// it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs.
const ORIGINAL = `(function(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null;
if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null;
if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id;
if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;}
const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
try{S={...S,biz:S.biz};
if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();}
const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null;
}finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}})`;
test('the faster sales trial signs exactly the offers the two-pass trial signs', () => {
const { ev, dom, errors } = load();
try {
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`);
assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs');
const seen = { yes: 0, no: 0, skipped: 0, third: 0 };
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
for (let day = 0; day < 6; day++) {
ev(`__reseed(${1000 + day});S.offers=[];for(let i=0;i<10;i++)spawnOffer();`);
// Small offers that fit, and on alternate days a squeeze, so offers fail on capacity and on others' service too.
ev(`for(const o of S.offers)o.bw=Math.max(1,Math.round(o.bw*${day % 2 ? 1 : 0.05}))`);
if (day % 2) ev('for(const c in S.pops)S.pops[c].bb&&(S.pops[c].bb.d*=1.3)');
// And circuits over the busiest links, which take bandwidth from customers who had it.
ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2))
S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`);
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`;
const before = ev('JSON.stringify(R.load)+R.served');
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone');
const slow = ev(`JSON.stringify(slowOffer(${o}))`);
assert.equal(fast, slow, `offer ${id} (${ev(`${o}.type`)}) on day ${day}`);
if (fast !== 'null') seen.yes++; else seen.no++;
if (n === 1) seen.skipped++;
if (n === 2) seen.third++;
}
ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()');
}
assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${JSON.stringify(seen)})`);
assert.ok(seen.skipped >= 5, `the second pass is often skipped (${JSON.stringify(seen)})`);
assert.ok(seen.third >= 3, `and run when the offer hurts someone (${JSON.stringify(seen)})`);
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});
test('with a scenic circuit the sales trial keeps both passes in their original order', () => {
const { ev, dom, errors } = load();
try {
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`);
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();');
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`;
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id);
assert.ok(n === 0 || n === 2, 'both passes, as before');
}
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});

View file

@ -9,6 +9,30 @@ function network(ev) {
ev("const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});};L('fra','ams',3);L('fra','par',3);L('ams','lon',2,'uly');closeModal()");
}
test('gaming offers and signed customers show their DDoS risk in Deals, city panels and customer lists', () => {
const { ev, errors, dom } = load();
ev("ACT.start({});S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.offers=['game','cgame','host'].map(type=>({id:type,city:'fra',name:type,bw:5,rate:100,reqs:[],exp:S.day+30,type}));UI.left='deals';UI.leftOpen=true;renderLeft()");
const notes = (root, action) => {
const buttons = [...root.querySelectorAll(`[data-act="${action}"]`)];
assert.equal(buttons.length, 3);
for (const button of buttons) {
const id = JSON.parse(button.dataset.args).id;
const count = (button.closest('.row').textContent.match(/Gaming attracts attacks/g)||[]).length;
assert.equal(count, id==='game'||id==='cgame'?1:0, `risk note for ${id}`);
}
};
assert.equal(ev('gamingCount()'), 0, 'offers disclose future risk before signing');
notes(dom.window.document.getElementById('leftBody'), 'accept');
ev("selectCity('fra');ACT.tab({t:'cust'})");
notes(dom.window.document.getElementById('panelBody'), 'accept');
ev("for(const id of ['game','cgame','host'])ACT.accept({id});UI.tab='cust';renderPanel()");
assert.equal(ev('gamingCount()'), 2, 'the note uses the same customer classification as the attack calculation');
notes(dom.window.document.getElementById('panelBody'), 'dropBiz');
ev('ACT.custOpen({})');
notes(dom.window.document.getElementById('custSec'), 'custGo');
assert.deepEqual(errors, []);
});
test('event networks pay in full when the crowd is served, nothing up front', () => {
const { ev, errors } = load();
seed(ev, 4);

View file

@ -0,0 +1,564 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// A small network with a hired intern, every order off, no cash floor and no fat fingers (Change Freeze).
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"ACT.launchBB({city:'fra'});S.pops.fra.bb.d=300;S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()";
function game(t, extra = '') {
const h = load();
t.after(() => h.dom.window.close());
h.ev(BASE);
if (extra) h.ev(extra);
return h;
}
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()");
const on = (ev, k, p = {}, cap) => ev(`S.ops.on.${k}=true;S.ops.p.${k}=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.${k}=${cap};`}`);
const shift = ev => ev('opsDay(S.day)');
const cash = ev => ev('S.cash');
// The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same.
function twins(t, extra, order, manual, pick) {
const A = game(t), B = game(t);
// Hire first: hiring recomputes, which would wipe any routing state the case stages.
hire(A.ev); hire(B.ev);
if (extra) { A.ev(extra); B.ev(extra); }
order(A.ev);
const a0 = cash(A.ev); shift(A.ev); const a1 = cash(A.ev);
const b0 = cash(B.ev); B.ev(manual); const b1 = cash(B.ev);
assert.ok(a0 - a1 > 0, 'the order did some paid work');
assert.equal(a0 - a1, b0 - b1, 'the shift cost exactly what the clicks cost');
if (pick) assert.equal(A.ev(pick), B.ev(pick), 'and left the network the same');
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
return A;
}
test('a new game has no intern and every order off; nothing runs and no random numbers are drawn', t => {
const { ev, errors } = game(t);
assert.equal(ev('S.ops.intern'), null);
assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false);
ev("for(const k in S.ops.on)S.ops.on[k]=true");
const r = ev('window.__n=0;window.__r=Math.random;Math.random=()=>{__n++;return __r()};const s=JSON.stringify(S);opsDay(S.day);Math.random=__r;s===JSON.stringify(S)&&__n===0');
assert.equal(r, true, 'no intern: orders never run, even switched on');
assert.deepEqual(errors, []);
});
test('the intern is hired from customer level 2 (or with gates open), costs a monthly salary, and can be let go', t => {
const { ev, errors } = game(t);
ev("S.lvl=1;ACT.opsHire({id:'kevin'})");
assert.equal(ev('S.ops.intern'), null, 'level 1: not yet');
ev("S.rules=makeRules('sandbox');S.rules.preset='freeze';ACT.opsHire({id:'annie'})");
assert.equal(ev('S.ops.intern'), 'annie', 'gates open');
ev("S.ops.intern=null;S.rules=makeRules('freeze');S.lvl=2;compute()");
const mo = ev('R.costMo'), c0 = cash(ev);
ev("ACT.opsHire({id:'tracy'})");
assert.equal(ev('S.ops.intern'), 'tracy');
assert.equal(c0 - cash(ev), ev('INTERN_MO'), 'first month up front');
assert.equal(ev('R.costMo') - mo, ev('INTERN_MO'), 'then a monthly salary');
ev("ACT.opsFire();ACT.opsFire()");
assert.equal(ev('S.ops.intern'), null);
assert.deepEqual(errors, []);
});
test('transit headroom adds a LAG member, exactly as the + member button would', t => {
const A = twins(t, "S.transit[0].hist=[60,80,70]",
ev => on(ev, 'transit', { x: 1.5 }),
"ACT.lagT({id:S.transit[0].id,d:1})", "JSON.stringify(S.transit.map(t=>[t.net,t.tier,t.n||1]))");
assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up transit in Frankfurt \+1×100G/);
});
test('transit headroom buys a new port from a chosen provider and stops at the multiple', t => {
const A = twins(t, "S.transit[0].hist=[100]",
ev => on(ev, 'transit', { x: 2, prov: 'ntt' }),
"ACT.buyTransit({city:'fra',net:'ntt',tier:1})", "JSON.stringify(S.transit.map(t=>[t.net,t.tier,t.n||1]))");
assert.ok(A.ev("S.transit.reduce((a,t)=>a+lagCap(PORT[t.tier].g,t.n),0)") >= 200);
});
test('routers: add one above the load level, as Add router would', t => {
twins(t, "R.nodeLoad.fra=R.nodeCap.fra*0.85",
ev => on(ev, 'routers', { at: 80, how: 'add' }),
"ACT.addRouter({city:'fra'})", 'S.pops.fra.routers');
});
test('routers: swap generation only where a second router carries the traffic', t => {
const { ev, errors } = game(t, 'R.nodeLoad.fra=R.nodeCap.fra*0.95');
hire(ev); on(ev, 'routers', { at: 80, how: 'swap' });
shift(ev);
assert.equal(ev('S.pops.fra.rgen'), 1, 'one router: a swap would be an outage, so no');
ev('S.pops.fra.routers=2;compute();R.nodeLoad.fra=R.nodeCap.fra*0.95');
const want = ev('swapCost("fra",mainRG(RG[1].cls+1))'), c0 = cash(ev);
shift(ev);
assert.equal(ev('S.pops.fra.rgen'), ev('mainRG(RG[1].cls+1)'));
assert.equal(c0 - cash(ev), want, 'paid the swap price after trade-in');
assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false);
assert.deepEqual(errors, []);
});
test('caches: free boxes only once the network sends enough traffic locally', t => {
const { ev, errors } = game(t);
hire(ev);
const best = ev("NETS.filter(n=>n.cache&&(R.demTo[n.id]||0)>=n.cache.min).map(n=>(R.cityDem.fra||0)*NSH[n.id]).sort((a,b)=>b-a)[0]||0");
assert.ok(best > 0, 'some network qualifies for a cache in this game');
on(ev, 'caches', { g: 50 });
if (best < 50) { shift(ev); assert.equal(ev('S.caches.length'), 0, 'below the threshold: nothing'); }
on(ev, 'caches', { g: 1 });
const c0 = cash(ev);
shift(ev);
const want = JSON.parse(ev("JSON.stringify(utilityCaches('fra'))"));
assert.ok(ev('S.caches.length') > 0);
assert.equal(want.add.filter(x => ev(`(R.cityDem.fra||0)*NSH['${x.net}']`) >= 1).length, 0, 'every eligible box is in');
assert.equal(cash(ev), c0, 'caches are free to rack');
assert.deepEqual(errors, []);
});
test('IX: weekly route servers and every willing peer, the same as the #192 batch', t => {
const A = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0})"), B = game(t, "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0})");
hire(A.ev); on(A.ev, 'ix');
A.ev('S.day=13');shift(A.ev);
assert.equal(A.ev('Object.keys(S.rs).length'), 0, 'not on a weekday the intern skips');
A.ev('S.day=14');shift(A.ev);
B.ev('ACT.utilityRouteServers();ACT.utilityPeers()');
assert.equal(A.ev('JSON.stringify(S.rs)'), B.ev('JSON.stringify(S.rs)'));
assert.equal(A.ev('JSON.stringify(Object.keys(S.peers).sort())'), B.ev('JSON.stringify(Object.keys(S.peers).sort())'));
assert.equal(A.ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0);
assert.deepEqual(A.errors, []);
});
test('PNI: weekly, big enough networks only, paid peering left out by default, at each network\'s own size and lead time', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;compute()");
hire(ev); on(ev, 'pni', { g: 5, tier: 1 }, 0);
ev('S.day=17;S.pops.fra.bb.d=3000;S.pops.ams.bb={d:3000};compute()');
const plan = JSON.parse(ev("JSON.stringify(pniBatch(null,1).orders.filter(q=>(R.cityDem[q.city]||0)*NSH[q.net]>=5&&(NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).map(q=>({k:q.city+q.net,cost:q.cost,tier:q.tier,big:pniBig(q.net)})))"));
assert.ok(plan.length > 0);
const c0 = cash(ev);
shift(ev);
const got = JSON.parse(ev('JSON.stringify(S.pni.map(p=>({k:p.city+p.net,tier:p.tier,ready:p.ready})))'));
assert.deepEqual(got.map(p => p.k).sort(), plan.map(p => p.k).sort());
// Lead times are each network's own (pniLead), quick here under Change Freeze.
for (const p of plan) { const g = got.find(x => x.k === p.k); assert.equal(g.tier, p.tier); assert.ok(g.ready > 17 && g.ready <= 17 + ev(p.big ? 'leadDays(365)' : 'leadDays(42)'), p.k); }
assert.equal(c0 - cash(ev), plan.reduce((a, p) => a + p.cost, 0), 'the same setup fees as the bulk order');
assert.equal(ev("S.pni.some(p=>NET[p.net].pol==='paid'&&!paidFree(NET[p.net]))"), false);
assert.deepEqual(errors, []);
});
test('sales: decline offers below the minimum, sign the ready ones with #185\'s trial', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, 'sales', { acc: true, min: 5000 });
ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()');
ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:30},{id:'gen',city:'fra',name:'Gen',type:'dia',bw:10,rate:600,reqs:['gen'],exp:30}]");
shift(ev);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')), ['big']);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))')), ['gen'], 'unmet requirements wait, the tiny one is gone');
assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, signed a customer/);
assert.deepEqual(errors, []);
});
test('repairs: rush what has a price, as the Rush repair button would', t => {
twins(t, "S.links=[{id:'f',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,mo:1}];S.inc=[{id:'amp',type:'amp',ref:'f',until:10,cost:3000,msg:'amp'}];S.pops.ams={day:0,bb:null,boost:0,down:0,routers:1,gen:false}",
ev => on(ev, 'repair'), "ACT.fixInc({id:'amp'})", 'S.inc.length');
});
test('optics: light hot fiber with the optic already in it, at the #177 batch price', t => {
const extra = "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();R.load.f=dfCap(S.links.at(-1))*0.95";
const A = twins(t, extra, ev => on(ev, 'optics', { at: 70 }),
"ACT.setChCount({id:'f',o:'zr4',n:2})", "JSON.stringify(S.links.find(l=>l.id==='f').ch)");
assert.equal(A.ev("S.links.find(l=>l.id==='f').ch.length"), 2, 'one more channel brings the fiber under the level');
});
test('decommission: smaller parallel waves go once the bigger link has room, never one a customer needs', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier] of [['w1',0],['w2',0],['big',2]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:450,sub:false,cut:0,mo:100,trench:id});compute()");
hire(ev); on(ev, 'decom', { keep: true });
ev("R.load={w1:1,w2:1,big:10}");
shift(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 'w1'], 'one small wave kept as a spare');
on(ev, 'decom', { keep: false });
ev("S.biz.push({id:'c',name:'C',type:'l2vpn',city:'fra',city2:'ams',bw:1,rate:1,reqs:['diverse'],mood:100,since:0});R.load={w1:1,big:10}");
shift(ev);
assert.ok(ev("S.links.some(l=>l.id==='w1')"), 'a diverse-path customer still needs it');
ev("S.biz=[];R.load={w1:1,big:10}");
shift(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id))")), ['big']);
assert.deepEqual(errors, []);
});
test('the monthly budget cap and the cash floor stop the intern; a new month resets the budget', t => {
const { ev, errors } = game(t);
hire(ev); ev('S.transit[0].hist=[600]'); on(ev, 'transit', { x: 3 }, 10000);
const c0 = cash(ev);
shift(ev);
const spent = c0 - cash(ev);
assert.ok(spent > 0 && spent <= 10000, 'some work, never over the cap');
assert.equal(ev('S.ops.spent.transit'), spent);
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Keep transit headroom/);
const c1 = cash(ev);
shift(ev);
assert.equal(cash(ev), c1, 'the same month: nothing more');
// The next step (four 100G members to 400G, $16k) never fits a $10k month; the budget still starts again.
ev('S.day+=30;S.ops.cap.transit=50000');
shift(ev);
assert.ok(cash(ev) < c1, 'a new month, a new budget');
assert.equal(ev('S.ops.spent.transit'), c1 - cash(ev), 'counted from zero');
ev("S.ops.cap.transit=0;S.ops.floor=1e6;S.cash=1e6+500;S.transit[0].hist=[1e5]");
const c2 = cash(ev);
shift(ev);
assert.equal(cash(ev), c2, 'the cash floor holds even without a cap');
assert.deepEqual(errors, []);
});
test('pause: an order switched off does nothing, and per-POP switches leave a city alone', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buyTransit({city:'ams',net:'cog',tier:1});for(const t of S.transit)t.hist=[90]");
hire(ev); on(ev, 'transit', { x: 2 });
ev("ACT.opsToggle({k:'transit'})");
const s0 = ev('JSON.stringify(S.transit)');
shift(ev);
assert.equal(ev('JSON.stringify(S.transit)'), s0);
ev("ACT.opsToggle({k:'transit'});ACT.opsPop({k:'transit',city:'ams'});closeModal()");
shift(ev);
assert.ok(ev("(S.transit.find(t=>t.city==='fra').n||1)") > 1, 'Frankfurt topped up');
assert.equal(ev("(S.transit.find(t=>t.city==='ams').n||1)"), 1, 'Amsterdam left alone');
assert.deepEqual(errors, []);
});
test('the shift runs inside dayTick, respects a stopped clock, batches its work and recomputes once', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'caches', { g: 1 });
const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n");
assert.equal(n, 1, 'one recompute for the whole shift');
const d = ev('S.day');
ev('dayTick()');
assert.equal(ev('S.ops.log[0].d'), d + 1);
ev("S.rules.clock=false;const before=JSON.stringify(S.ops);dayTick();window.__same=before===JSON.stringify(S.ops)");
assert.equal(ev('__same'), true, 'no clock, no shift');
assert.deepEqual(errors, []);
});
test('the NOC gets one notice a week, the shift report; the daily lines stay in the Ops sheet', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[600]");
ev('S.day=14');
hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'sales', { acc: true, min: 5000 });
ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()');
const n0 = ev('S.log.length');
for (let d = 14; d < 21; d++) {
if (d === 15) ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:60},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:60}]");
ev(`S.day=${d}`); shift(ev);
}
assert.equal(ev('S.log.length'), n0, 'a whole week of shifts: no NOC notice yet');
assert.ok(ev('S.ops.log.length') >= 2, 'the Ops sheet has the daily detail');
ev('S.day=21'); shift(ev);
assert.equal(ev('S.log.length'), n0 + 1, 'one notice for the week');
assert.match(ev('S.log[0].t'), /^Kevin's week Kevin signed a customer \(\+\$6\.0k\/mo\), topped up transit .*declined a tiny offer.*Week total: \$[\d.]+k up front, \+\$[\d.]+k\/mo\./);
assert.equal(ev('S.log[0].k'), 'good');
ev('S.day=22'); shift(ev);
assert.equal(ev('S.log.length'), n0 + 1, 'and nothing more until the next week ends');
// Only the sales order now: one tiny offer declined on day 23, reported when the week ends.
ev("for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.sales=true;S.offers=[{id:'t2',city:'fra',name:'T2',type:'dia',bw:1,rate:600,reqs:[],exp:60}];S.day=23");shift(ev);
ev("S.day=28");shift(ev);
assert.equal(ev('S.log.length'), n0 + 2);
assert.match(ev('S.log[0].t'), /declined a tiny offer\.$/, 'nothing spent: no money line');
assert.equal(ev('S.log[0].k'), '');
ev("S.day=35");shift(ev);
assert.equal(ev('S.log.length'), n0 + 2, 'an idle week: no notice');
assert.deepEqual(errors, []);
});
test('the Ops sheet opens with the intern\'s mood and the weekly shift report, at 360 px, in every language', t => {
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
const h = load(lang === 'en' ? {} : { lang });
const { ev, dom, errors } = h;
ev(BASE); ev('S.day=14'); dom.window.innerWidth = 360;
hire(ev);
ev('opsModal()');
const mood = () => dom.window.document.querySelector('#modalCard .ops-mood').textContent;
assert.equal(mood(), ev("tr('ops.mood_new',{name:opsName()})"), lang + ': a new hire says so');
on(ev, 'transit', { x: 1.5 }, 0);
ev("S.transit[0].hist=[600];S.day=21");shift(ev);ev("S.transit[0].hist=[6000];S.day=28");shift(ev);ev('opsModal()');
const reps = [...dom.window.document.querySelectorAll('#modalCard .ops-rep')];
assert.equal(reps.length, 2, lang + ': last week, and this week so far');
assert.equal(reps[0].lastElementChild.textContent, ev('opsWeekLine(S.ops.rep)'), lang);
assert.ok(mood().length > 10, lang);
assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /\bops\.[a-z_]+/, lang);
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});
test('the mood follows the week, with no dice', t => {
const { ev, errors } = game(t);
ev('S.day=100'); hire(ev); ev('S.day=110');
const quiet = ev('opsMood()');
assert.equal(ev('opsMood()'), quiet, 'the same day reads the same');
assert.ok([ev("tr('ops.mood_quiet',{name:'Kevin'})"), ev("tr('ops.mood_kevin')")].includes(quiet));
ev("S.ops.wk=opsWkNew(Math.floor(S.day/7));S.ops.wk.n.sales=1");
assert.equal(ev('opsMood()'), ev("tr('ops.mood_sales',{name:'Kevin'})"));
ev("S.ops.wk.n.broke=1;delete S.ops.wk.n.sales");
assert.equal(ev('opsMood()'), ev("tr('ops.mood_broke',{name:'Kevin'})"));
assert.deepEqual(errors, []);
});
test('fat fingers: never under Change Freeze, rare and harmless in On-call and BGP at 3 a.m.', t => {
const { ev, errors } = game(t);
hire(ev);
ev('window.__r=Math.random;Math.random=()=>0');
for (let i = 0; i < 50; i++) shift(ev);
assert.equal(ev('S.ops.log.some(e=>e.f!==undefined)'), false, 'Change Freeze: never, even on the unluckiest roll');
for (const p of ['oncall', 'bgp']) {
ev(`S.rules=makeRules('${p}');S.ops.log=[]`);
const c0 = cash(ev), links = ev('S.links.length'), pops = ev('Object.keys(S.pops).length');
shift(ev);
assert.equal(ev('S.ops.log[0].f!==undefined'), true, p);
assert.ok(c0 - cash(ev) <= 20000, 'costs a little at most');
assert.equal(ev('S.links.length'), links); assert.equal(ev('Object.keys(S.pops).length'), pops);
}
ev('Math.random=__r');
assert.ok(ev("OPS_FF_RATE.oncall<0.01&&OPS_FF_RATE.bgp<0.02"), 'rare');
assert.deepEqual(errors, []);
});
test('a new POP from the template costs exactly the clicks it replaces', t => {
const A = game(t), B = game(t);
hire(A.ev); hire(B.ev);
const q = JSON.parse(A.ev("JSON.stringify(opsTplQuote('ams'))"));
assert.ok(q.net && q.ix && q.kit);
const a0 = cash(A.ev); A.ev("ACT.opsNewPop({city:'ams'})"); const a1 = cash(A.ev);
const b0 = cash(B.ev);
B.ev(`ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});ACT.buyTransit({city:'ams',net:'${q.net}',tier:0});ACT.buyIx({city:'ams',tier:0});ACT.utilityKit({city:'ams',cost:utilityKit('ams').cost})`);
assert.equal(a0 - a1, q.cost, 'the quoted price');
assert.equal(a0 - a1, b0 - cash(B.ev), 'the same as clicking it');
assert.equal(A.ev('JSON.stringify([S.pops.ams.gen,S.pops.ams.site2,S.pops.ams.routers,!!S.pops.ams.bb,S.ixp.ams])'), B.ev('JSON.stringify([S.pops.ams.gen,S.pops.ams.site2,S.pops.ams.routers,!!S.pops.ams.bb,S.ixp.ams])'));
A.ev('S.cash=10');A.ev("ACT.opsNewPop({city:'lon'})");
assert.equal(A.ev('!!S.pops.lon'), false, 'all or nothing on the price');
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
});
test('saves: old saves load with no intern and everything off, settings survive a reload, junk is repaired', t => {
const { ev, errors } = game(t);
ev("delete S.ops;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.ops.intern'), null);
assert.equal(ev('Object.values(S.ops.on).some(Boolean)'), false);
hire(ev);
ev("on=1;S.ops.on.pni=true;S.ops.p.pni={g:50,tier:2,paid:true};S.ops.cap.pni=1e6;S.ops.skip.fra=['caches'];save();S=migrate(JSON.parse(slotRaw(UI.slot)))");
assert.equal(ev("S.ops.intern==='kevin'&&S.ops.on.pni&&S.ops.p.pni.tier===2&&S.ops.cap.pni===1e6&&S.ops.skip.fra[0]==='caches'"), true);
ev(`S.ops={intern:'mallory',on:{transit:'yes',hack:true},p:{transit:{x:99,prov:'nobody'}},cap:{transit:-5},spent:{transit:'lots'},skip:{atlantis:['transit'],fra:['ix','transit']},
log:[{d:1,i:'kevin',r:[['transit',2,['fra +1×100G','<img>']],['evil',1,[]]],f:99,c:'fra'},'junk'],floor:3,tpl:{bb:'no'}};S=migrate(S)`);
assert.equal(ev('S.ops.intern'), null);
assert.equal(ev("S.ops.on.transit===false&&!('hack' in S.ops.on)"), true);
assert.equal(ev("opsP('transit','x')===1.5&&opsP('transit','prov')==='cheap'&&opsCap('transit')===50000&&S.ops.spent.transit===0"), true);
assert.equal(ev("JSON.stringify(S.ops.skip)"), '{"fra":["transit"]}');
assert.equal(ev("JSON.stringify(S.ops.log)"), '[{"d":1,"i":"kevin","r":[["transit",2,["fra +1×100G"]]]}]');
assert.equal(ev('S.ops.floor===50000&&S.ops.tpl.bb===true'), true);
ev(`S.ops.wk={w:3,i:'kevin',n:{sales:2,evil:9,transit:'x'},wh:{transit:['fra +1×100G','<b>']},up:-5,mo:'a',rev:41000,ff:99};S.ops.rep={i:'mallory'};S=migrate(S)`);
assert.equal(ev("JSON.stringify(S.ops.wk)"), '{"w":3,"i":"kevin","n":{"sales":2},"wh":{"transit":["fra +1×100G"]},"up":0,"mo":0,"rev":41000,"ff":7}');
assert.equal(ev('S.ops.rep'), null);
assert.deepEqual(errors, []);
});
test('the Ops sheet works at 360 px in every language, from the NOC tab and the phone tab bar', t => {
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
const h = load(lang === 'en' ? {} : { lang });
const { ev, dom, errors } = h;
ev(BASE);
dom.window.innerWidth = 360;
const doc = dom.window.document;
ev("ACT.phoneTab({t:'noc'})");
const open = doc.querySelector('#leftBody [data-act="opsOpen"]');
assert.ok(open, lang);
open.click();
const hireBtn = doc.querySelector('#modalCard [data-act="opsHire"]');
assert.ok(hireBtn, lang);
hireBtn.click();
assert.ok(ev('opsHired()'), lang);
doc.querySelector('#modalCard [data-act="opsToggle"]').click();
assert.equal(doc.querySelector('#modalCard [data-act="opsToggle"]').getAttribute('aria-pressed'), 'true', lang);
doc.querySelector('#modalCard [data-act="opsParam"]').click();
const txt = doc.getElementById('modalCard').textContent;
assert.doesNotMatch(txt, /\bops\.[a-z_]+/, lang);
assert.ok(doc.querySelector('#modalCard select[data-chg="opsCity"]'), lang);
ev("closeModal();selectCity('ams')");
assert.ok(doc.querySelector('#panelBody [data-act="opsNewPop"]'), lang);
assert.doesNotMatch(doc.getElementById('panelBody').textContent, /\bops\.[a-z_]+/, lang);
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});
test('sales trial at most one offer a shift, and an offer that did not fit waits a week', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, 'sales', { acc: true, min: 0 });
ev("S.offers=['a','b','c'].map(id=>({id,city:'fra',name:id,type:'dia',bw:1e5,rate:600,reqs:[],exp:60}));window.__t=0;window.__a=autoOffer;autoOffer=o=>{__t++;return __a(o)}");
shift(ev);
assert.equal(ev('__t'), 1, 'one routing trial per shift');
for (let i = 0; i < 2; i++) { ev('S.day++'); shift(ev); }
assert.equal(ev('__t'), 3, 'each offer once');
ev('S.day++'); shift(ev);
assert.equal(ev('__t'), 3, 'too big for the network: not tried again within the week');
ev('S.day+=7'); shift(ev);
assert.equal(ev('__t'), 4);
ev('autoOffer=__a');
assert.deepEqual(errors, []);
});
test('re-hiring in a later month starts on a fresh budget, not last month\'s spending', t => {
const { ev, errors } = game(t);
hire(ev);
ev("S.ops.spent.transit=50000;ACT.opsFire();ACT.opsFire();S.day=400;ACT.opsHire({id:'kevin'});closeModal()");
assert.equal(ev('S.ops.spent.transit'), 0);
assert.equal(ev('S.ops.mon'), ev('Math.floor(S.day/30)'));
ev("S.ops.spent.transit=1234;ACT.opsFire();ACT.opsFire();ACT.opsHire({id:'annie'});closeModal()");
assert.equal(ev('S.ops.spent.transit'), 1234, 'the same month: what was spent stays spent');
assert.deepEqual(errors, []);
});
test('transit never comes from a provider that breaks a promise: no-Cogentle customers, bank covenants, the Spat', t => {
const { ev, errors } = game(t, "S.transit=[];ACT.buyTransit({city:'fra',net:'lvl',tier:0});compute();S.transit[0].hist=Array(30).fill(200)");
hire(ev); on(ev, 'transit', { x: 1.5 });
assert.equal(ev("cheapestTransit('fra').id"), 'cog', 'Cogentle is the cheapest here, so it would be the pick');
ev("S.biz.push({id:'b1',city:'fra',name:'X',type:'dia',bw:1,rate:100,mood:100,since:S.day,reqs:['nocog']})");
assert.equal(ev("reqOk(S.biz[0])"), true);
shift(ev);
assert.ok(ev('S.transit.length') > 1 || ev('S.transit[0].n') > 1, 'the intern still topped up');
assert.equal(ev("S.transit.some(t=>t.net==='cog')"), false);
assert.equal(ev("reqOk(S.biz[0])"), true, 'the customer still gets what they signed for');
ev("S.ops.p.transit={x:1.5,prov:'cog'}");
assert.notEqual(ev("opsProv('fra').id"), 'cog', 'even when the player picked Cogentle');
assert.notEqual(ev("opsTplQuote('ams').net"), 'cog', 'and the new-POP template too');
// A bank covenant says the same.
ev("S.biz=[];S.loans=[{bank:'db',covs:['nocog'],pay:1,bal:1}]");
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
// Cogentle is not speaking to Goggle: the Spat scenario, or a de-peering.
ev("S.loans=[]");
assert.equal(ev("cheapestTransit('fra').id"), 'cog');
ev("S.ev.depeer=S.day+5");
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
ev("S.ev.depeer=0;S.scn={id:'spat',rules:{spat:true}}");
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
// Two upstreams: once met, never undone (adding is fine; the order never removes).
ev("S.scn=null;S.biz=[{id:'b2',city:'fra',name:'Y',type:'dia',bw:1,rate:1,mood:100,since:0,reqs:['twoup']}]");
assert.ok(ev("cheapestTransit('fra')"));
ev("S.transit=[]");
assert.equal(ev("cheapestTransit('fra')"), undefined, 'a lone first upstream would break "two upstreams"');
assert.deepEqual(errors, []);
});
test('decommission keeps its spare in another trench than the big link', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T1'],['s2',0,'T2']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:tr});compute()");
hire(ev); on(ev, 'decom', { keep: true });
ev("R.load={big:1,s1:0,s2:0}");
shift(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 's2'], 'the 100G in the same trench goes, the 10G in its own trench stays');
// Every small wave shares the big one's trench: keep the largest, as before.
ev("S.links=S.links.filter(l=>l.id==='big');for(const [id,tier] of [['a',1],['b',0]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:'T1'});compute();R.load={big:1}");
shift(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['a', 'big']);
assert.deepEqual(errors, []);
});
test('decommission sees the traffic of a customer signed earlier in the same shift', t => {
const { ev, errors } = game(t, "S.pops.fra.bb.d=30;ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T2'],['s2',1,'T3']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:1000,trench:tr});compute()");
hire(ev); on(ev, 'sales', { acc: true, min: 0 }); on(ev, 'decom', { keep: false });
ev("S.offers=[{id:'o1',city:'fra',city2:'ams',name:'Bulk Co',type:'l2vpn',bw:450,rate:20,reqs:[],exp:S.day+20}]");
shift(ev);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')).length, 1, 'signed');
assert.equal(ev('S.links.length'), 3, 'its 450G needs every wave, so none goes');
ev('compute()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(bizWhy(S.biz[0]))')), []);
assert.deepEqual(errors, []);
});
test('no recompute on a shift that only declined offers or stopped at a budget', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, 'sales', { acc: false, min: 50000 }); on(ev, 'transit', { x: 3 }, 10000);
ev("S.ops.spent.transit=10000;S.transit[0].hist=[600];S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30}]");
const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n");
assert.equal(n, 0, 'nothing in the network changed');
assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, stopped at the budget/);
ev("S.ops.spent.transit=0");
assert.equal(ev("window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"), 1, 'a real job still recomputes once');
assert.deepEqual(errors, []);
});
test('per-POP exceptions go with the POP: on decommission, and in a save that lost it', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buildPop({city:'lon'});compute()");
hire(ev);
ev("ACT.opsPop({k:'transit',city:'ams'});ACT.opsPop({k:'caches',city:'lon'});closeModal()");
ev("decommission(['ams'])");
assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}');
ev("ACT.buildPop({city:'ams'});closeModal()");
assert.equal(ev("opsHere('transit','ams')"), true, 'a rebuilt POP starts with every order on');
ev("S.ops.skip.par=['transit'];S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}', 'no POP in Paris: its exception is dropped on load');
assert.deepEqual(errors, []);
});
test('one order that throws is paused and noted; the rest of the shift and the day still run', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
hire(ev); on(ev, 'repair'); on(ev, 'transit', { x: 1.5 });
ev("window.__r=OPS_RUN.repair;OPS_RUN.repair=()=>{throw new Error('boom')};window.__e=console.error;console.error=()=>{}");
const d = ev('S.day'), saves = ev("window.__s=0;window.__sv=save;save=()=>{__s++;return __sv()};S.day=29;dayTick();save=__sv;__s");
ev("OPS_RUN.repair=__r;console.error=__e");
assert.ok(d >= 0 && saves >= 1, 'dayTick reached the save on day 30');
assert.equal(ev('S.ops.on.repair'), false, 'the broken order is paused');
assert.ok(ev("(S.transit[0].n||1)") > 1, 'the next order still ran');
assert.match(ev('opsEntry(S.ops.log[0])'), /got stuck on Rush repairs and paused it/);
assert.deepEqual(errors, []);
});
test('the fat-fingered LAG member respects a paused transit order and per-POP exceptions', t => {
const { ev, errors } = game(t);
hire(ev);
// Each shift rolls: fat finger yes, the only POP, the LAG slip (index 3).
ev("S.rules=makeRules('bgp');window.__r=Math.random;window.__k=0;Math.random=()=>[0,0,0.7][__k++%3]");
const n0 = ev('S.transit[0].n||1'), c0 = cash(ev);
shift(ev);
assert.equal(ev('__k'), 3);
assert.equal(ev('S.ops.log[0].f'), 0, 'transit order paused: a harmless label instead');
assert.equal(ev('S.transit[0].n||1'), n0); assert.equal(cash(ev), c0);
on(ev, 'transit', { x: 1 }); ev("ACT.opsPop({k:'transit',city:'fra'});closeModal();S.transit[0].hist=[0]");
shift(ev);
assert.equal(ev('S.ops.log[0].f'), 0, 'Frankfurt excepted: the same');
ev("ACT.opsPop({k:'transit',city:'fra'});closeModal()");
shift(ev);
assert.equal(ev('S.ops.log[0].f'), 3, 'allowed: the extra member');
assert.equal(ev('S.transit[0].n||1'), n0 + 1);
ev('Math.random=__r');
assert.deepEqual(errors, []);
});
test('caches: the cash floor and a running-cost budget hold; the panel and the log show what a month costs', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, 'caches', { g: 1 });
const add = () => ev("utilityCaches('fra').add.filter(x=>(R.cityDem.fra||0)*NSH[x.net]>=1).length");
assert.ok(add() >= 2, 'several boxes on offer');
ev('S.ops.floor=50000;S.cash=1000');
shift(ev);
assert.equal(ev('S.caches.length'), 0, 'below the floor: no new rent either');
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Accept free caches/);
ev('S.cash=1e8;S.ops.cap.caches=1000');
const m0 = ev('opsMoNow()');
shift(ev);
assert.equal(ev('S.caches.length'), 2, 'a $1k/mo budget fits two $400/mo boxes');
assert.equal(ev('S.ops.addMo.caches'), 800);
assert.equal(ev('opsMoNow()') - m0, 800);
assert.equal(ev('S.ops.log[0].mo'), 800);
assert.match(ev('opsEntry(S.ops.log[0])'), /racked 2 free caches \(Frankfurt\).*Cost: \$0 up front, \+\$800\/mo\./);
ev('opsModal()');
const txt = ev("document.getElementById('modalCard').textContent");
assert.match(txt, /each box costs \$400\/mo/);
assert.match(txt, /Adds at most: \+\$1\.0k\/mo/);
assert.match(txt, /This month: \$0 up front, \+\$800\/mo on the bill/);
ev('S.day+=30;S.ops.cap.caches=0'); shift(ev);
assert.equal(ev('S.ops.addMo.caches'), (ev('S.caches.length') - 2) * 400, 'a new month counts from zero');
assert.deepEqual(errors, []);
});
test('transit: the log line and budget line show the monthly cost a top-up adds', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
hire(ev); on(ev, 'transit', { x: 1.5 });
const m0 = ev('opsMoNow()'), c0 = cash(ev);
shift(ev);
const mo = ev('opsMoNow()') - m0;
assert.ok(mo > 0);
assert.equal(ev('S.ops.log[0].up'), c0 - cash(ev));
assert.equal(ev('S.ops.log[0].mo'), Math.round(mo));
assert.equal(ev('Math.round(S.ops.addMo.transit)'), Math.round(mo));
assert.match(ev('opsEntry(S.ops.log[0])'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./);
assert.deepEqual(errors, []);
});

View file

@ -23,8 +23,12 @@ test('cones are built once at load and hold customers of customers', () => {
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>ANC[n.id].some(u=>NET[u].type==='t1'))"), true, 'from a Tier 1, directly or through a carrier');
assert.equal(ev("NET.tail45.up.join()"), 'mag', 'Auckland has no Tier 1: Hobbit Hole buys from a carrier that is there');
assert.equal(ev("NETS.filter(n=>n.tail).map(n=>n.up.join('+')).join()"), ev("NETS.filter(n=>n.tail).map(n=>tailUp(n.name,n.pops).join('+')).join()"), 'stable: picked by name');
// Australians buy only from Australian carriers, so a Tier 1 PNI is still no back door into Australia.
assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false);
// Australia's big ISPs buy only from Australian carriers, so a Tier 1 PNI is no back door to them.
assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg','inp'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false);
// The smaller ones that buy from a Tier 1 or a carrier of one do come along, and these are exactly the ones.
const au = "NETS.filter(n=>n.type==='eye'&&n.pops.length&&n.pops.every(c=>CITY[c].au)&&t1Need().some(t=>CONE_S[t.id].has(n.id))).map(n=>n.id).sort().join()";
assert.equal(ev(au), 'ddo,ext,spn,tail44', 'Doodoo, Lintel, Spin2wintel, Kangaroo Courier');
assert.equal(ev("[NET.tail44.name,NET.tail44.up.join(),NET.ddo.up.join(),NET.spn.up.join(),NET.ext.up.join(),NET.voc.up.join(),NET.spl.up.join()].join('|')"), 'Kangaroo Courier|cog|voc|voc|spl|ntt,tly|tly');
assert.deepEqual(errors, []);
});
@ -146,3 +150,48 @@ test('routing with cones costs about what it did: exits are asked once, cones ar
assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`);
assert.deepEqual(errors, []);
});
test('the panel names the peer that really carries a network, not the first Tier 1 it buys from', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50");
// a long-tail network that buys from Cogentle first and Level Tree second; peer only with Level Tree
const t = ev("NETS.find(n=>n.tail&&n.up.length===2&&n.up[0]==='cog'&&n.up[1]==='lvl').id");
ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pl',net:'lvl',city:'fra',tier:2}];compute()");
assert.equal(ev(`R.cone.${t}`), 'lvl');
ev(`UI.left='goals';UI.leftOpen=true;ACT.netFocus({id:'${t}'})`);
const txt = dom.window.document.getElementById('leftBody').textContent;
assert.match(txt, /Reached through the customer cone of Level Tree/);
assert.doesNotMatch(txt, /customer cone of Cogentle/);
// over an exchange: the member you have a session with
ev("S.pni=[];compute()");
assert.equal(ev(`!!R.cone.${t}`), false);
assert.match(ev(`(ACT.netFocus({id:'${t}'}),document.getElementById('leftBody').textContent)`), /Buys transit from Cogentle/);
assert.deepEqual(errors, []);
});
test('a traceroute down a two-level cone shows every network on the way', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50");
// Doodoo buys from Hocus Pocus, which buys from Not That Telecom; a PNI with Not That Telecom only
ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pn',net:'ntt',city:'fra',tier:2}];compute()");
const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'ddo'}))"));
assert.deepEqual(tr.asPath, [ev('S.asn'), ev('NET.ntt.asn'), ev('NET.voc.asn'), ev('NET.ddo.asn')]);
assert.match(tr.text, /Not That Telecom hands it to its customer Hocus Pocus/);
assert.match(tr.text, /Hocus Pocus hands it to its customer Doodoo/);
assert.equal(ev("coneChain('ntt','ddo').join()"), 'ntt,voc,ddo');
assert.equal(ev("R.cone.ddo"), 'ntt');
assert.deepEqual(errors, []);
});
test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => {
const { ev, errors } = load();
ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()");
const reach = (ts) => ev(`S.pni=[];for(const t of ${JSON.stringify(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`);
const T = ['lvl', 'ntt', 'tly', 'cog', 'tat'];
const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()");
assert.match(goal, /R\.reach>=0\.5/);
for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++)
assert.ok(reach([T[i], T[j]]) < 0.5, `${T[i]}+${T[j]} is not enough`);
assert.ok(reach(['lvl', 'ntt', 'tly']) >= 0.5, 'three Tier 1 PNIs and the exchange can be');
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,120 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(t) {
const h = load();
t.after(() => h.dom.window.close());
h.ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;compute()");
return h;
}
test('kit balances each provider with minimal moves while buying the missing hardware', t => {
const { ev, errors } = setup(t);
ev("for(const [net,n] of [['cfl',4],['ggl',3]])for(let i=0;i<n;i++)S.caches.push({id:net+i,city:'fra',net});S.pops.ams={day:0,routers:1};S.caches.push({id:'elsewhere',city:'ams',net:'cfl',site:'b'});compute()");
const before = ev('S.cash'), ids = ev('S.caches.map(c=>c.id).join()');
const quote = JSON.parse(ev("JSON.stringify(utilityKit('fra'))"));
assert.equal(quote.moves.length, 3);
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
assert.equal(ev('S.cash'), before - quote.cost);
assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='cfl'&&c.site==='b').length"), 2);
assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='ggl'&&c.site==='b').length"), 1);
assert.equal(ev("S.caches.find(c=>c.id==='elsewhere').site"), 'b');
assert.equal(ev('S.caches.map(c=>c.id).join()'), ids);
assert.equal(ev("utilityKit('fra').moves.length"), 0);
const stable = ev('JSON.stringify(S.caches)');
ev("ACT.utilityKit({city:'fra',cost:0})");
assert.equal(ev('JSON.stringify(S.caches)'), stable);
assert.deepEqual(errors, []);
});
test('an already equipped PoP can balance caches for free, even with negative cash', t => {
const { ev, errors } = setup(t);
ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:3});for(const [net,site] of [['cfl','a'],['ggl','b']])for(let i=0;i<4;i++)S.caches.push({id:net+i,city:'fra',net,site});S.cash=-1;compute();selectCity('fra');ACT.tab({t:'links'})");
assert.equal(ev("utilityKit('fra').moves.length"), 4, 'overall counts match but provider counts do not');
assert.equal(ev("document.querySelector('#panelBody [data-act=utilityKit]').disabled"), false);
ev("document.querySelector('#panelBody [data-act=utilityKit]').click()");
assert.equal(ev('S.cash'), -1);
assert.equal(ev('S.pops.fra.routers'), 3);
for (const net of ['cfl', 'ggl'])
assert.equal(ev(`S.caches.filter(c=>c.net==='${net}'&&c.site==='b').length`), 2);
assert.deepEqual(errors, []);
});
test('a rejected kit purchase never moves caches or partially installs hardware', t => {
const { ev, errors } = setup(t);
ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];S.cash=1;compute()");
const before = ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})');
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});ACT.utilityKit({city:'fra',cost:-1})");
assert.equal(ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})'), before);
assert.deepEqual(errors, []);
});
test('odd provider totals are balanced across the whole PoP with the fewest moves', t => {
const { ev, errors } = setup(t);
ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:2});for(const [net,n] of [['nfx',3],['cfl',1],['ggl',1]])for(let i=0;i<n;i++)S.caches.push({id:net+i,city:'fra',net});compute()");
assert.equal(ev("utilityCacheMoves('fra').length"), 2, 'five boxes all in A require two moves');
ev("ACT.utilityKit({city:'fra',cost:0})");
assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 2);
assert.equal(ev("['nfx','cfl','ggl'].every(net=>Math.abs(S.caches.filter(c=>c.net===net&&c.site==='b').length-S.caches.filter(c=>c.net===net&&c.site!=='b').length)<=1)"), true);
assert.equal(ev("utilityCacheMoves('fra').length"), 0);
assert.deepEqual(errors, []);
});
test('cache batch fills missing provider/site pairs, keeps extra boxes and respects eligibility', t => {
const { ev, errors } = setup(t);
ev("Object.assign(S.pops.fra,{site2:true,routers:2});S.caches=[{id:'keep1',city:'fra',net:'cfl'},{id:'keep2',city:'fra',net:'cfl',site:'a'}];compute();R.demTo={cfl:NET.cfl.cache.min,ggl:NET.ggl.cache.min-1}");
const cash = ev('S.cash'), mo = ev('R.cost.caches');
assert.equal(ev("utilityCaches('fra').add.length"), 1);
ev("ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
assert.equal(ev('S.cash'), cash, 'cache hardware is free');
assert.equal(ev('R.cost.caches'), mo + ev('CACHE_MO'));
assert.equal(ev("S.caches.filter(c=>c.net==='cfl'&&c.site==='b').length"), 1);
assert.equal(ev("S.caches.filter(c=>c.net==='cfl').length"), 3, 'extra existing A box kept');
assert.equal(ev("S.caches.some(c=>c.net==='ggl')"), false);
const stable = ev('JSON.stringify(S.caches)');
ev("R.demTo={cfl:NET.cfl.cache.min};ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
assert.equal(ev('JSON.stringify(S.caches)'), stable);
assert.deepEqual(errors, []);
});
test('one-site requests add only A, then a new second site gets exactly its missing boxes', t => {
const { ev, errors } = setup(t);
ev("R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
assert.equal(ev('S.caches.length'), 5);
assert.equal(ev("S.caches.every(c=>c.site==='a')"), true);
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})");
assert.equal(ev('S.caches.length'), 10);
assert.equal(ev("NETS.filter(n=>n.cache).every(n=>['a','b'].every(s=>S.caches.filter(c=>c.net===n.id&&c.site===s).length===1))"), true);
ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
assert.equal(ev('S.caches.length'), 10);
assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 5);
assert.deepEqual(errors, []);
});
test('cache requests reject stale eligibility and insufficient port capacity atomically', t => {
const { ev, errors } = setup(t);
ev("S.pops.fra.site2=true;for(let i=0;i<7;i++)S.caches.push({id:'full'+i,city:'fra',net:'nfx'});compute();R.demTo={cfl:NET.cfl.cache.min};window.q=utilityCaches('fra');ACT.utilities()");
assert.equal(ev('q.free'), 1);
assert.equal(ev('q.add.length'), 2);
assert.equal(ev("document.querySelector('[data-act=utilityCaches]').disabled"), true);
const before = ev('JSON.stringify(S.caches)');
ev("ACT.utilityCaches({city:'fra',quote:q.key})");
assert.equal(ev('JSON.stringify(S.caches)'), before);
ev("S.pops.fra.routers=2;R.demTo.ggl=NET.ggl.cache.min;ACT.utilityCaches({city:'fra',quote:q.key,modal:true})");
assert.equal(ev('JSON.stringify(S.caches)'), before);
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
ev("ACT.utilityCaches({city:'not-a-city',quote:''})");
assert.deepEqual(errors, []);
});
test('balanced caches keep serving when either site fails', t => {
const { ev, errors } = setup(t);
ev("Object.assign(S.pops.fra,{site2:true,routers:2,rgen:RG.length-1,bb:{d:5000}});S.caches=[{id:'one',city:'fra',net:'ggl'},{id:'two',city:'fra',net:'ggl'}];compute();ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
for (const site of ['a', 'b']) {
ev(`S.inc=[{id:'site-failure',type:'site',ref:'fra',site:'${site}',until:S.day+2}];compute()`);
assert.ok(ev('Object.values(R.useCache).reduce((a,b)=>a+b,0)') > 0);
assert.equal(ev(`S.caches.filter(c=>(c.site||'a')==='${site}').every(c=>!R.useCache[c.id])`), true);
}
assert.deepEqual(errors, []);
});

159
tests/utilities.test.js Normal file
View file

@ -0,0 +1,159 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
function setup(t, opts) {
const h = load(opts);
t.after(() => h.dom.window.close());
h.ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;UI.speed=0;compute()");
return h;
}
test('redundancy kit matches normal purchases, including cash, monthly costs and save reload', t => {
const a = setup(t), b = setup(t);
const quote = JSON.parse(a.ev("JSON.stringify(utilityKit('fra'))"));
const cash = a.ev('S.cash'), monthly = a.ev('R.costMo');
a.ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
b.ev("ACT.addGen({city:'fra'});ACT.addSite({city:'fra'});ACT.addRouter({city:'fra'})");
for (const expr of ['S.pops.fra', 'R.cost'])
assert.deepEqual(JSON.parse(a.ev(`JSON.stringify(${expr})`)), JSON.parse(b.ev(`JSON.stringify(${expr})`)));
assert.equal(a.ev('S.cash'), cash - quote.cost);
assert.equal(a.ev('S.cash'), b.ev('S.cash'));
assert.equal(a.ev('R.costMo'), monthly + quote.mo);
const before = a.ev('JSON.stringify(S)');
a.ev("ACT.utilityKit({city:'fra',cost:0})");
assert.equal(a.ev('JSON.stringify(S)'), before, 'repeat does not buy more hardware');
a.ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
assert.equal(a.ev('S.pops.fra.gen && S.pops.fra.site2 && S.pops.fra.routers===2'), true);
assert.deepEqual(a.errors, []);
assert.deepEqual(b.errors, []);
});
test('kit is all-or-nothing, rejects stale quotes and handles missing PoPs', t => {
const { ev, errors } = setup(t);
ev("window.quote=utilityKit('fra').cost;S.cash=quote-1");
const before = ev('JSON.stringify(S.pops.fra)');
ev("ACT.utilityKit({city:'fra',cost:quote})");
assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
assert.equal(ev('S.cash'), ev('quote-1'));
ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+1,modal:true})");
assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})");
assert.deepEqual(errors, []);
});
test('kit buys only missing components and preserves extra routers and service placement', t => {
const { ev, errors } = setup(t);
ev("S.pops.fra.routers=4;S.pops.fra.gen=true;S.pops.fra.rgen=3;S.transit.push({id:'test',city:'fra',net:'cog',tier:0,site:'a'});compute()");
const cash = ev('S.cash');
assert.equal(ev("utilityKit('fra').cost"), ev('SITE2_COST'));
ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})");
assert.equal(ev('S.cash'), cash - ev('SITE2_COST'));
assert.equal(ev('S.pops.fra.routers'), 4);
assert.equal(ev('S.pops.fra.rgen'), 3);
assert.equal(ev('S.transit[0].site'), 'a');
assert.deepEqual(errors, []);
});
test('bulk peering covers rival IXs, respects policy and is idempotent', t => {
const { ev, errors } = setup(t);
ev("ACT.buildPop({city:'ams'});ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});ACT.rs({city:'ams'});compute()");
const expected = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.requests.map(id=>id+'@'+r.ix)))"));
assert.ok(expected.length > 0);
assert.ok(expected.some(k => k.endsWith('@ams~3')));
const blocked = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.blocked.map(b=>b.id+'@'+r.ix)))"));
assert.ok(blocked.length > 0);
const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), pnis = ev('JSON.stringify(S.pni)');
ev('ACT.utilityPeers()');
for (const k of expected) assert.equal(ev(`S.peers[${JSON.stringify(k)}]`), true, k);
for (const k of blocked) assert.equal(ev(`!!S.peers[${JSON.stringify(k)}]`), false, k);
assert.equal(ev('S.cash'), cash);
assert.equal(ev('JSON.stringify(S.ixp)'), ports);
assert.equal(ev('JSON.stringify(S.pni)'), pnis);
const peers = ev('JSON.stringify(S.peers)');
ev('ACT.utilityPeers()');
assert.equal(ev('JSON.stringify(S.peers)'), peers);
assert.equal(ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0);
assert.deepEqual(errors, []);
});
test('bulk peering skips disconnected IXs, route server coverage and existing down sessions', t => {
const { ev, errors } = setup(t);
assert.equal(ev('utilityPeers().length'), 0);
ev("ACT.utilityPeers();ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});S.peers['ggl@fra']=true;compute()");
assert.equal(ev("utilityPeers()[0].requests.includes('drz')"), false);
assert.equal(ev("utilityPeers()[0].requests.includes('ggl')"), false);
ev("ACT.cancelIx({city:'fra',sure:1,ok:1});ACT.utilityPeers()");
assert.equal(ev('utilityPeers().length'), 0);
assert.deepEqual(errors, []);
});
test('utilities are available from the Ops sheet in the menu and from PoP Infra in every language', t => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { ev, dom, errors } = setup(t, lang === 'en' ? {} : { lang });
ev('ACT.menu()');
dom.window.document.querySelector('#modalCard [data-act="opsOpen"]').click();
assert.ok(dom.window.document.querySelector('#modalCard [data-act="utilities"]'), lang);
ev("selectCity('fra');ACT.tab({t:'links'})");
assert.ok(dom.window.document.querySelector('#panelBody [data-act="utilityKit"]'), lang);
ev('ACT.utilities()');
assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra');
assert.ok(!dom.window.document.querySelector('#modalCard').textContent.includes('utilities.'), lang);
assert.deepEqual(errors, [], lang);
}
});
test('join all route servers preserves existing sessions and covers rival and remote IX ports', t => {
const { ev, errors } = setup(t);
ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});window.fabric=FABS.find(f=>f.cities.includes('fra')&&f.cities.includes('ams')).id;S.links.push({id:'remote',a:'fra',b:'ams',kind:'vxc',prov:fabric,vt:1,km:kmBetween('fra','ams'),sub:false,mo:0,cut:0,day:S.day});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});compute()");
assert.equal(ev("isRemote('ams')"), true);
assert.deepEqual(JSON.parse(ev('JSON.stringify(utilityRouteServers().sort())')), ['ams', 'ams~3']);
const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), peers = ev('JSON.stringify(S.peers)');
ev('ACT.utilityRouteServers()');
assert.equal(ev("S.rs.fra && S.rs.ams && S.rs['ams~3']"), true);
assert.equal(ev("ixSessions('ams').has('drz')"), true);
assert.equal(ev('S.cash'), cash);
assert.equal(ev('JSON.stringify(S.ixp)'), ports);
assert.equal(ev('JSON.stringify(S.peers)'), peers);
const rs = ev('JSON.stringify(S.rs)');
ev('ACT.utilityRouteServers()');
assert.equal(ev('JSON.stringify(S.rs)'), rs, 'repeat never toggles a session off');
assert.equal(ev('utilityRouteServers().length'), 0);
assert.deepEqual(errors, []);
});
test('route-server batch leaves peering policy and player-owned exchanges alone', t => {
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()");
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');
assert.match(ev("document.getElementById('modalCard').textContent"), /Off while your peering policy/);
ev("S.myIx.fra={members:[],fab:0};S.rs.fra=false;ACT.utilityRouteServers()");
assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control');
assert.deepEqual(errors, []);
});
test('#192 the Infra tab shows the kit as one line, without repeating its rows', t => {
for (const w of [1280, 360]) {
const { ev, dom, errors } = setup(t);
ev(`window.innerWidth=${w}`);
ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];compute();selectCity('fra');ACT.tab({t:'links'})");
const body = dom.window.document.getElementById('panelBody');
const txt = body.textContent;
assert.match(txt, /PoP redundancy kit · One-off: /);
assert.doesNotMatch(txt, /Second site(None|Installed)/, 'no second copy of the second-site row');
assert.doesNotMatch(txt, /At least two routers/, 'no second copy of the routers row');
assert.doesNotMatch(txt, /Request missing caches/, 'caches are in the Peering tab and Utilities');
assert.equal(body.querySelectorAll('section h3').length, [...body.querySelectorAll('section h3')].filter(h => h.textContent !== 'PoP redundancy kit').length);
assert.equal(txt.split('Backup generator').length - 1, 1, 'the generator shows once, in Power');
assert.ok(body.querySelector('[data-act="utilityKit"]'), 'the kit is one tap away');
body.querySelector('[data-act="utilities"]').click();
assert.match(dom.window.document.getElementById('modalCard').textContent, /At least two routers/, 'the full kit is in Utilities');
assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra');
assert.deepEqual(errors, [], `${w}px`);
}
});

240
tests/weekly-puzzle.test.js Normal file
View file

@ -0,0 +1,240 @@
// The published weekly puzzle: Sunday 06:00 Berlin weeks, the generator (scripts/weekly-puzzle.js), its --check,
// and the game's fetch: only when Puzzles opens, validated strictly, with the seeded weekly as the fallback.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { load } = require('./harness');
const G = require('../scripts/weekly-puzzle');
const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-'));
const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8')));
const tick = () => new Promise((r) => setTimeout(r, 30));
test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run across New Year', () => {
const { ev, errors } = load();
const key = (iso) => ev(`pzWeekKey(new Date('${iso}'))`), start = (k) => ev(`new Date(pzWeekStart('${k}')).toISOString()`);
// Winter (CET, UTC+1): 06:00 Berlin is 05:00 UTC.
assert.equal(key('2026-11-01T04:59:59Z'), '2026-W44');
assert.equal(key('2026-11-01T05:00:00Z'), '2026-W45', 'the week starting Sunday 1 Nov is named after its Monday');
assert.equal(key('2026-11-07T23:00:00Z'), '2026-W45', 'Saturday night is still the same week');
assert.equal(start('2026-W45'), '2026-11-01T05:00:00.000Z');
// Summer (CEST, UTC+2): 06:00 Berlin is 04:00 UTC.
assert.equal(key('2026-07-05T03:59:00Z'), '2026-W27');
assert.equal(key('2026-07-05T04:00:00Z'), '2026-W28');
// The weekends the clocks change: the change is at 01:00 UTC that same Sunday, before the week starts.
assert.equal(start('2026-W14'), '2026-03-29T04:00:00.000Z', 'spring forward: first CEST Sunday');
assert.equal(start('2026-W13'), '2026-03-22T05:00:00.000Z');
assert.equal(start('2026-W44'), '2026-10-25T05:00:00.000Z', 'fall back: first CET Sunday');
assert.equal(start('2026-W43'), '2026-10-18T04:00:00.000Z');
assert.equal(key('2026-03-29T03:59:00Z'), '2026-W13');
assert.equal(key('2026-03-29T04:00:00Z'), '2026-W14');
assert.equal(key('2026-10-25T04:59:00Z'), '2026-W43');
assert.equal(key('2026-10-25T05:00:00Z'), '2026-W44');
// New Year: 2026 has 53 ISO weeks, 2027 has 52.
assert.equal(key('2026-12-27T05:00:00Z'), '2026-W53');
assert.equal(key('2027-01-03T04:59:00Z'), '2026-W53');
assert.equal(key('2027-01-03T05:00:00Z'), '2027-W01');
assert.equal(key('2027-12-26T05:00:00Z'), '2027-W52');
assert.equal(key('2028-01-02T05:00:00Z'), '2028-W01');
assert.equal(ev("pzKeyAdd('2026-W53',1)"), '2027-W01');
assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53');
assert.equal(ev("pzPrevKey('2028-W01')"), '2027-W52');
assert.equal(ev("pzWeekStart('2027-W53')"), null, '2027 has no week 53');
assert.equal(ev("pzWeekStart('2026-W00')"), null);
assert.equal(ev("pzWeekStart('nope')"), null);
// Every week of ten years: 7 days apart (give or take the DST hour), keys round-trip, never two Sundays the same key.
let k = '2026-W01', seen = new Set();
for (let i = 0; i < 522; i++) {
const t = ev(`pzWeekStart('${k}')`), n = ev(`pzKeyAdd('${k}',1)`), tn = ev(`pzWeekStart('${n}')`);
assert.equal(new Date(t).getUTCDay(), 0, `${k} starts on a Sunday`);
assert.ok([7 * 864e5, 7 * 864e5 - 3600e3, 7 * 864e5 + 3600e3].includes(tn - t), `${k} → ${n}`);
assert.equal(ev(`pzWeekKey(${t})`), k);
assert.equal(ev(`pzWeekKey(${t - 1})`), ev(`pzPrevKey('${k}')`));
assert.ok(!seen.has(k)); seen.add(k); k = n;
}
// The countdown.
assert.equal(ev("pzWkNext(Date.parse('2026-10-29T14:00:00Z'))"), 'Next weekly puzzle in 2 d 15 h');
assert.equal(ev("pzWkNext(Date.parse('2026-11-01T03:20:00Z'))"), 'Next weekly puzzle in 1 h 40 min');
assert.deepEqual(errors, []);
});
// Weeks already out are not compared with a fresh run: a later release may change prices, and a published week stays as
// it was (--check still makes sure the weeks not over yet can be solved).
test('generator: deterministic for a week', () => {
const g = G.game(), a = tmp(), b = tmp();
const first = G.list(DIR).slice(-3)[0];
const keys = Math.min(3, G.list(DIR).length);
for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d));
for (const k of G.list(a)) {
assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`);
}
assert.ok(G.list(DIR).length >= 3, 'the release ships with weeklies in place');
});
test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => {
const g = G.game(), d = tmp();
let k = '2027-W10';
const out = [];
for (let i = 0; i < 12; i++, k = g.ev(`pzKeyAdd('${k}',1)`)) { const j = G.generate(g, k, d); G.writeWeek(d, j); out.push(j); }
assert.deepEqual(G.check(g, d, 0), [], 'every week verifies: both references earn their stars in the game');
for (let i = 1; i < out.length; i++) {
assert.notEqual(out[i].theme, out[i - 1].theme, `${out[i].key}: not last week's theme`);
for (const c of out[i].cities) assert.ok(!out[i - 1].cities.includes(c), `${out[i].key}: ${c} was a city last week too`);
}
assert.ok(new Set(out.map((j) => j.theme)).size >= 5, 'most themes come round in a quarter');
for (const j of out) {
assert.ok(j.cities.length >= 3 && j.cities.length <= 6);
assert.ok(j.ref.one <= j.ref.three && j.ref.three <= j.budget && j.budget <= j.ref.three * 1.06 + 10000, `${j.key}: budget ${j.budget} just above the N-1 build ${j.ref.three}`);
assert.ok(JSON.stringify(j).length < 600, 'small file');
assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']);
}
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key));
});
test('--check passes on the committed files and rejects tampered ones', () => {
const g = G.game();
// Weeks still to come are re-solved; past ones are checked the way the game reads them.
assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify');
const bad = (edit, why) => {
const d = tmp();
for (const k of G.list(DIR).slice(-3)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json'));
G.writeIndex(d);
const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8'));
const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j));
assert.notDeepEqual(G.check(g, d, 0), [], why);
};
bad((j) => { j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; }, 'a budget nobody can earn three stars under');
bad((j) => { j.cities[0] = 'xxx'; }, 'an unknown city');
bad((j) => { j.name.l = 'puzzles.hello_world'; }, 'a label that is not a weekly name');
bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take');
bad((j) => { j.extra = '<img src=x onerror=alert(1)>'; }, 'an unknown field');
bad((j) => { j.key = '2030-W01'; }, 'a file under another week\'s name');
bad((j) => { j.twist = { lat: [j.cities[0], j.cities[1], 0.5] }; }, 'an impossible latency target');
bad(() => '{nope', 'not JSON');
bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks');
});
test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => {
const { ev, errors } = load();
ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}");
ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()");
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing on the title screen');
assert.equal(ev("UI.pzWk===undefined"), true);
ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()");
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing while playing');
ev('ACT.puzzleMenu({})');
const key = ev('pzWeekKey(new Date())');
assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/puzzles/.test(u)))"), JSON.stringify([`puzzles/weekly/${key}.json`]), 'one relative, same-origin request');
ev('closeModal();ACT.puzzleMenu({})');
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 1, 'once is enough while it is loading');
await tick();
assert.deepEqual(errors, []);
});
test('the published puzzle is played when it is good, the seeded one when it is missing, offline or bad', async () => {
const src = committed()[1], { ev, dom, errors } = load();
const key = ev('pzWeekKey(new Date())'), good = { ...src, key };
const serve = (how) => { ev(`UI.pzWk=null;window.fetch=()=>${how}`); ev('ACT.puzzleMenu({})'); };
const seeded = JSON.parse(ev('JSON.stringify(pzWeekly())'));
for (const [how, why] of [
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
["Promise.reject(new TypeError('offline'))", 'offline'],
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'],
]) {
serve(how);
await tick();
assert.equal(ev('UI.pzWk.st'), 'fb', why);
assert.deepEqual(JSON.parse(ev('JSON.stringify(pzWkDef().cities)')), seeded.cities, `${why}: the seeded weekly stands in`);
assert.match(ev("document.getElementById('pzWk').textContent"), new RegExp(`Weekly puzzle ${key}`));
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), false);
}
// While it loads, the button waits a moment.
ev("UI.pzWk=null;window.fetch=()=>new Promise(()=>{})");
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/);
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true);
// The good one.
serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`);
await tick();
assert.equal(ev('UI.pzWk.st'), 'ok');
const row = ev("document.getElementById('pzWk').textContent");
assert.ok(row.includes(ev('pzName(pzWkDef())')), 'its pun name');
assert.ok(row.includes(ev('pzTxt(pzWkDef().wj)')), 'its joke');
assert.match(row, /New this Sunday!/);
assert.match(row, /Next weekly puzzle in \d+ (d \d+ h|h \d+ min)/);
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
assert.equal(ev('S.pz.key'), key);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.pz.cities)')), good.cities);
assert.equal(ev('S.pz.budget'), good.budget);
assert.match(ev("document.getElementById('pzBox').textContent"), new RegExp(ev('pzTxt(S.pz.wj)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
// Solve it with three stars: the share line and the streak use the published key.
const sol = G.solve(G.world(ev), { cities: good.cities, via: good.via, avoid: good.avoid, ring: !!good.twist.ring, noSub: false, lat: good.twist.lat || null }).three;
for (const l of sol.links) {
if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`);
ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`);
}
assert.equal(ev('pzEval().stars'), 3);
assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`));
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
assert.equal(p.wk[key].st, 3);
assert.equal(p.streak.last, key);
ev('ACT.pzLeave({})');
assert.doesNotMatch(ev("document.querySelector('.door[data-door=puzzle]').textContent"), /New this Sunday/, 'played: no badge');
void dom;
assert.deepEqual(errors, []);
});
test('the file is checked field by field', () => {
const { ev, errors } = load();
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`);
assert.ok(ok(j));
const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); };
no((o) => { o.v = 2; }, 'a newer schema');
no((o) => { o.theme = 'constructor'; }, 'an unknown theme');
no((o) => { o.cities = ['fra']; }, 'too few cities');
no((o) => { o.cities = [...o.cities, o.cities[0]]; }, 'a city twice');
no((o) => { o.via = [o.cities[0]]; }, 'a goal city as a stepping stone');
no((o) => { o.cities[0] = 'pek'; }, 'a city that needs a licence');
no((o) => { o.budget = '240000'; }, 'a budget as text');
no((o) => { o.budget = 1e9; }, 'a silly budget');
no((o) => { o.twist = { ring: 'yes' }; }, 'a twist that is not true');
no((o) => { o.twist = { avoidAll: true }; }, 'an unknown twist');
no((o) => { o.name = { l: 'puzzles_weekly.name_tour_de_reg', p: { reg: 'XX' } }; }, 'an unknown region');
no((o) => { o.name = { l: 'puzzles_weekly.name_race_to_b', p: { b: '<b>' } }; }, 'markup as a city');
no((o) => { o.joke = 'Ha ha'; }, 'raw English');
no((o) => { o.__proto__ = { budget: 1 }; o.extra = 1; }, 'extra fields');
assert.equal(ev(`pzWkValid(null,'${k}')`), null);
assert.equal(ev(`pzWkValid([],'${k}')`), null);
// Every label a theme may use exists in English, and every file names its text in the player's language.
assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))"));
for (const f of committed()) {
const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`);
assert.ok(d, f.key);
assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`);
}
assert.deepEqual(errors, []);
});
test('weekly puzzle in every language and on a 360 px phone', async () => {
const f = committed()[0];
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
const { ev, errors } = load({ lang });
const key = ev('pzWeekKey(new Date())');
ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`);
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()");
ev('ACT.puzzleMenu({})');
await tick();
const row = ev("document.getElementById('pzWk').textContent");
assert.doesNotMatch(row, /puzzles(_weekly)?\.|\{/, `${lang}: no raw labels or placeholders`);
assert.notEqual(ev('pzName(pzWkDef())'), ev("EN[pzWkDef().wn.l]"), `${lang}: translated name`);
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
assert.doesNotMatch(ev("document.getElementById('pzBox').textContent"), /puzzles(_weekly)?\./);
assert.deepEqual(errors, [], lang);
}
});