Merge v2 (the eight community PRs) under the ruleset, puzzles and Tier 1 by cone

Integration base for performance work: origin/v2-orders' merge of v2 and the
ruleset, onto v2-doors. Pinned attack flows (#153) route at their port's plain
rank (no customer cone), and that rank is always tried even when RouteScript
moved every other exit off it.
This commit is contained in:
Frederic Jung 2026-10-28 18:05:45 +01:00
commit d0fbbed96a
No known key found for this signature in database
61 changed files with 3064 additions and 200 deletions

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

@ -0,0 +1,363 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
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});compute()");
}
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('auto-accept waits five real seconds at every game speed and the toggle stops it', () => {
for (const speed of [0.5, 1, 2, 4, 8]) {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'first');
ev("ACT.autoToggle({k:'autoSales'});UI.autoSalesAt=1000");
const start = ev('UI.autoSalesAt');
ev(`UI.speed=${speed};automationTick(${start + 4999})`);
assert.equal(ev('S.biz.length'), 0, speed);
ev(`automationTick(${start + 5000})`);
assert.equal(ev('S.biz[0].id'), 'first', speed);
offer(ev, 'second');
ev(`automationTick(${start + 9999})`);
assert.equal(ev('S.biz.length'), 1, speed);
ev(`automationTick(${start + 10000})`);
assert.equal(ev('S.biz.length'), 2, speed);
ev("ACT.autoToggle({k:'autoSales'})");
offer(ev, 'off');
ev(`automationTick(${start + 20000});ACT.accept({id:'off',auto:true})`);
assert.equal(ev('S.biz.length'), 2, speed);
assert.equal(ev('S.offers[0].id'), 'off', speed);
assert.deepEqual(errors, []);
dom.window.close();
}
});
test('Accept buttons share a real-time countdown in Deals, city offers and fiber broker offers', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
offer(ev, 'waiting', { reqs: ['gen'] });
ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';UI.leftOpen=true;renderAll()");
assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0);
ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()");
const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')];
const readyCounts = () => counts().filter(el => el.dataset.autoSales === 'ready');
assert.ok(readyCounts().length >= 2, 'Deals and the city panel both show it');
assert.ok(readyCounts().every(el => el.textContent === '(5)'));
assert.ok(counts().filter(el => el.dataset.autoSales === 'waiting').every(el => el.textContent === ''), 'unmet requirements have no countdown');
ev('testNow=2001;renderAutoCountdown()');
assert.ok(readyCounts().every(el => el.textContent === '(4)'));
ev('testNow=3000;UI.speed=8;renderAutoCountdown()');
assert.ok(readyCounts().every(el => el.textContent === '(3)'));
ev('UI.speed=0.5;renderAll();renderAutoCountdown()');
assert.ok(readyCounts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone');
assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/);
ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})");
offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' });
ev("compute();UI.sel={type:'link',id:'fiber'};renderPanel()");
const broker = dom.window.document.querySelector('#panelBody [data-act="accept"] [data-auto-sales]');
assert.ok(broker);
assert.equal(broker.textContent, '(3)');
ev('testNow=6000;automationTick(testNow);renderAutoCountdown()');
assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true);
assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements');
offer(ev, 'next-ready');
ev('renderAll();renderAutoCountdown()');
assert.ok(counts().filter(el => el.dataset.autoSales === 'next-ready').every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown');
ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()");
assert.equal(counts().length, 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('only ready offers get a countdown, including after requirements or capacity change', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
offer(ev, 'needs-generator', { reqs: ['gen'] });
offer(ev, 'too-big', { bw: 1000 });
offer(ev, 'expired', { exp: 0 });
ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});ACT.autoToggle({k:'autoSales'});renderAutoCountdown()");
const count = id => dom.window.document.querySelector(`#leftBody [data-auto-sales="${id}"]`).textContent;
assert.equal(count('ready'), '(5)');
assert.equal(count('needs-generator'), '');
assert.equal(count('too-big'), '');
assert.equal(count('expired'), '');
ev('S.pops.fra.gen=true;after()');
assert.equal(count('needs-generator'), '(5)', 'becoming eligible shows the timer');
ev('S.pops.fra.gen=false;compute();renderAutoCountdown()');
assert.equal(count('needs-generator'), '', 'a requirement becoming false hides it immediately');
ev("S.offers.find(o=>o.id==='too-big').bw=2;after()");
assert.equal(count('too-big'), '(5)', 'actions invalidate the capacity preview');
ev('testNow=6000;automationTick(testNow);renderAutoCountdown()');
assert.equal(ev("S.offers.some(o=>o.id==='needs-generator')"), true, 'acceptance checks requirements again');
assert.deepEqual(errors, []);
dom.window.close();
});
test('readiness trials are shared between views and are not repeated for every redraw', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'ready');
ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';window.originalAutoOffer=autoOffer;window.trials=0;window.autoOffer=o=>{trials++;return originalAutoOffer(o)};ACT.autoToggle({k:'autoSales'})");
assert.equal(ev('trials'), 1);
ev('renderAll();compute();renderAll();renderAutoCountdown()');
assert.equal(ev('trials'), 1, 'ordinary routing refreshes reuse the preview');
ev('after()');
assert.equal(ev('trials'), 2, 'a real action refreshes readiness');
ev('window.autoOffer=originalAutoOffer');
assert.deepEqual(errors, []);
dom.window.close();
});
test('auto-accept 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.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
assert.equal(ev('S.biz.length'), 0);
assert.equal(ev('S.offers.length'), 5);
assert.equal(ev('S.log.length'), log, 'no repeated failed manual-action toasts');
ev('S.pops.fra.gen=true;compute();automationTick(10000)');
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 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.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
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('auto-accept 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.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)");
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.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
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.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
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.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)');
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('auto-pay rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its toggle', () => {
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.autoRepair=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(1)`);
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('automationTick(2)');
assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment');
ev('S.cash=40000;automationTick(3)');
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.autoToggle({k:'autoRepair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});automationTick(4)");
assert.equal(ev('S.cash'), 10000);
assert.equal(ev("S.inc.some(i=>i.id==='new')"), true);
assert.deepEqual(errors, []);
dom.window.close();
});
test('automation pauses with the game, dialogs, hidden pages and game over', () => {
const { ev, dom, errors } = load();
setup(ev);
offer(ev, 'paused');
ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;UI.speed=0;automationTick(5000)');
assert.equal(ev('S.biz.length'), 0);
ev('UI.speed=1;automationTick(9999)');
assert.equal(ev('S.biz.length'), 0, 'resume starts a fresh five-second wait');
ev("openModal('<p>Menu</p>');automationTick(10000);closeModal()");
ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'hidden'});automationTick(15000)");
ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'visible'});S.lost=true;automationTick(20000);S.lost=false;automationTick(24999)");
assert.equal(ev('S.biz.length'), 0);
ev('automationTick(25000)');
assert.equal(ev('S.biz.length'), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('the frame loop repairs new incidents without waiting for the sales timer', () => {
const { ev, dom, errors } = load();
setup(ev);
ev(`S.autoRepair=true;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1}];
window.originalDay=dayTick;window.dayTick=()=>{S.links[0].eqDown=10;S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'Broken amp'})};
window.cashBefore=S.cash;last=0;acc=DAY_MS;frame(16);window.dayTick=originalDay`);
assert.equal(ev('S.cash'), ev('cashBefore-1000'));
assert.equal(ev('S.inc.length'), 0);
assert.equal(ev('S.links[0].eqDown'), 0);
assert.deepEqual(errors, []);
dom.window.close();
});
test('toggles persist, old and malformed saves default off, and the timer resets for another game', () => {
const { ev, dom, errors } = load();
setup(ev);
assert.equal(ev('S.autoSales||S.autoRepair'), false);
ev("ACT.autoToggle({k:'autoSales'});ACT.autoToggle({k:'autoRepair'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))");
assert.equal(ev('S.autoSales&&S.autoRepair'), true);
ev("delete S.autoSales;delete S.autoRepair;S=migrate(S)");
assert.equal(ev('S.autoSales||S.autoRepair'), false);
ev("S.autoSales='true';S.autoRepair=1;S=migrate(S);ACT.autoToggle({k:'cash'})");
assert.equal(ev('S.autoSales||S.autoRepair'), false);
ev('UI.autoGame=S;UI.autoSalesAt=0;S=migrate(JSON.parse(JSON.stringify(S)));S.autoSales=true;compute()');
offer(ev, 'imported');
ev('automationTick(100000)');
assert.equal(ev('S.biz.length'), 0, 'an imported game does not inherit another game timer');
ev('automationTick(105000)');
assert.equal(ev('S.biz.length'), 1);
assert.deepEqual(errors, []);
dom.window.close();
});
test('both toggle buttons work by keyboard-compatible DOM events on phones in every language', () => {
for (const lang of ['en', 'it', 'pt', 'fr', 'es']) {
const { ev, dom, errors } = load(lang === 'en' ? {} : { lang });
setup(ev);
dom.window.innerWidth = 360;
for (const [tab, key] of [['deals', 'autoSales'], ['noc', 'autoRepair']]) {
ev(`ACT.leftTab({t:'${tab}'});renderAll()`);
const button = [...dom.window.document.querySelectorAll('#leftBody [data-act="autoToggle"]')].find(b => JSON.parse(b.dataset.args).k === key);
assert.ok(button, lang);
assert.equal(button.getAttribute('aria-pressed'), 'false', lang);
button.focus();
button.click();
const updated = dom.window.document.querySelector('#leftBody [data-act="autoToggle"]');
assert.equal(updated.getAttribute('aria-pressed'), 'true', lang);
assert.equal(ev(`S.${key}`), true, lang);
assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /automation\./, lang);
}
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});

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?rank0(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,[]);
});

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%+
@ -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();
}
});

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

@ -0,0 +1,161 @@
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 Traffic button 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;
ev("ACT.dash();ACT.dashTab({k:'traffic'})");
const doc = dom.window.document;
const button = [...doc.querySelectorAll('#dashCard [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

@ -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,25 @@ 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.ok(ev('Object.keys(CITY_PDB).length') >= 190, 'real-world data for most cities');
// 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'",

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,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(localStorage.getItem('sot-save-v1')));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, []);
});

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

@ -0,0 +1,137 @@
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(localStorage.getItem('sot-save-v1')));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 menu and 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()');
assert.ok(dom.window.document.querySelector('[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, []);
});