seriesoftubes/tests/speed.test.js
Frederic Jung a887b65a2f Make big networks fast: routing, panels and map drawing
A network with a hundred POPs and a thousand peering ports froze the game for
most of a second every day and after every click, because routing checked all
~1,800 exits for each of ~14,000 flows. Now:

- compute(): exits are asked once per network which networks they reach, each
  flow scans only those, and the first ECMP group is found without sorting. The
  graph runs on city indices with a typed-array Dijkstra (same heap moves, same
  ties), routers and per-link traffic are kept in typed arrays, the diverse-path
  check reuses one live-link graph, and R.ef is put together when a link is read.
  Results are bit-identical to before.
- Panels and the NOC dashboard are patched in place (morph) instead of being
  rebuilt, so the browser no longer restyles 1,500 rows every tick. Buttons whose
  action changed are swapped out, keeping #44's tap protection.
- The Networks tab works out each IX port's sessions once instead of once per
  network.
- draw() reuses screen-point buffers, a per-frame pair index and cached label
  widths, strokes the dotted fiber line on the path it already has, and uses
  native roundRect: about a third fewer canvas calls per frame, same output.
2026-10-26 00:03:05 +01:00

101 lines
6.8 KiB
JavaScript

const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// A network on four continents: POPs, waves, transit, IX ports, PNIs, caches and customers.
function bigNet(ev) {
ev("ACT.start({});S.cash=1e10;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("for(const c of ['ams','lon','par','nyc','ash','chi','sjc','tok','hkg','sin','syd','sao'])ACT.buildPop({city:c})");
ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['lon','nyc'],['nyc','ash'],['ash','chi'],['chi','sjc'],['sjc','syd'],['tok','hkg'],['hkg','sin'],['sin','syd'],['nyc','sao']]){UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();}");
ev("for(const c in S.pops){S.pops[c].bb=S.pops[c].bb||{d:0};S.pops[c].bb.d=500;}");
ev("for(const [c,n] of [['fra','cog'],['nyc','lvl'],['sin','cog'],['tok','lvl']])ACT.buyTransit({city:c,net:n,tier:1})");
ev("for(const c of ['fra','ams','lon','nyc','sin','tok'])ACT.buyIx({city:c,tier:1,signed:true});for(const c in S.ixp)ACT.rs({city:c});compute()");
ev("for(const n of ['ggl','nfx','fbk','amz','akm'])for(const c of ['fra','nyc','sin'])ACT.pni({city:c,net:n,tier:1});compute()");
ev("for(const n of ['nfx','ggl'])for(const c of ['fra','nyc','sin','lon'])ACT.cache({city:c,net:n})");
ev("for(let i=0;i<150;i++){S.offers=[];spawnOffer();for(const o of S.offers.slice())if(bHas(o))ACT.accept({id:o.id});}closeModal();compute()");
}
test('a preferred exit far away still wins over a normal one next door', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'})");
ev("UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'ams',net:'tly',tier:1});compute()");
assert.equal(ev('S.links.length'), 1);
const use = () => JSON.parse(ev("JSON.stringify(S.transit.map(t=>R.useT[t.id]||0))"));
assert.equal(use()[1], 0, 'normal: the local transit carries it all');
ev("S.transit[1].pref='high';compute()");
const [fra, ams] = use();
assert.ok(ams > 0 && ams > fra, `preferred: Amsterdam's transit comes first (${fra} / ${ams})`);
assert.deepEqual(errors, []);
});
test('what crosses each link adds up, and is put together when it is looked at', () => {
const { ev, errors } = load();
bigNet(ev);
assert.ok(ev("Object.keys(R.ef).length") > 5, 'traffic on many links');
// every push adds the same amount to one egress, one network and one source city
const bad = ev(`Object.keys(R.ef).filter(k=>{const r=R.ef[k],s=o=>Object.values(o).reduce((a,b)=>a+b,0),n=s(r.net);
const load=S.links.filter(l=>edgeKey(l)===k).reduce((a,l)=>a+(R.load[l.id]||0),0);
return Math.abs(n-s(r.eg))>1e-6*(1+n)||Math.abs(n-s(r.dst))>1e-6*(1+n)||Math.abs(n-load)>1e-6*(1+n);}).join()`);
assert.equal(bad, '', 'per network, per egress, per source city and the link load agree');
assert.equal(ev("const k=Object.keys(R.ef)[0];R.ef[k]===R.ef[k]"), true, 'the same record every time');
assert.equal(ev("JSON.parse(JSON.stringify(R)).ef[Object.keys(R.ef)[0]].net!==undefined"), true);
// the link panel reads it
ev("const k=Object.keys(R.ef)[0],l=S.links.find(x=>edgeKey(x)===k);selectLink(l.id)");
assert.match(ev("document.getElementById('panelBody').textContent"), /Content from/);
assert.deepEqual(errors, []);
});
test('a big network routes every flow to an exit with room, and caches serve their own city', () => {
const { ev, errors } = load();
bigNet(ev);
for (let d = 0; d < 20; d++) ev('dayTick()');
assert.ok(ev('R.served>0&&R.served<=R.demand+1e-6'));
assert.equal(ev(`[...S.transit.map(t=>[R.useT[t.id]||0,lagCap(PORT[t.tier].g,t.n)]),...S.pni.map(p=>[R.usePni[p.id]||0,lagCap(PORT[p.tier].g,p.n)]),...S.caches.map(c=>[R.useCache[c.id]||0,CACHE_CAP])].filter(([u,c])=>u>c+1e-6).length`), 0, 'no port over capacity');
assert.equal(ev("Object.keys(S.pops).filter(c=>R.citySrv[c]>R.cityDem[c]+1e-6).length"), 0, 'no city served more than it asked for');
assert.ok(ev('S.caches.length>0&&S.caches.every(c=>R.useCache[c.id]>0)'), 'every cache serves its own city');
assert.deepEqual(errors, []);
});
test('panels are patched in place: the same HTML, and buttons that now do something else are new', () => {
const { ev, errors } = load();
bigNet(ev);
ev("selectCity('fra');ACT.tab({t:'peer'})");
const fresh = "(()=>{const d=document.createElement('div');d.innerHTML=UI._ph;return d.innerHTML;})()";
const same = () => ev(`(()=>{const a=[...document.getElementById('panelBody').querySelectorAll('*')],d=document.createElement('div');d.innerHTML=UI._ph;const b=[...d.querySelectorAll('*')];
return a.length===b.length&&a.every((x,i)=>x.nodeName===b[i].nodeName&&x.attributes.length===b[i].attributes.length&&[...b[i].attributes].every(t=>x.getAttribute(t.name)===t.value)&&(x.children.length||x.textContent===b[i].textContent));})()`);
assert.equal(same(), true);
ev("window.__tab=document.querySelector('#panelBody [data-act=\"tab\"]')");
for (let d = 0; d < 3; d++) ev('dayTick();renderPanel()');
assert.equal(same(), true, 'patched panel matches a fresh render');
assert.equal(ev("window.__tab===document.querySelector('#panelBody [data-act=\"tab\"]')"), true, 'an unchanged button stays the same button');
// another city: its buttons act on that city, so a tap that started on the old ones cannot fire them (#44)
ev("window.__btn=[...document.querySelectorAll('#panelBody [data-act]')].find(b=>(b.dataset.args||'').includes('\"fra\"'))");
ev("selectCity('nyc');ACT.tab({t:'peer'})");
assert.equal(same(), true);
assert.equal(ev("document.getElementById('panelBody').contains(window.__btn)"), false);
assert.ok(ev(fresh).length > 1000);
assert.deepEqual(errors, []);
});
test('the network list shows where you connect to each network', () => {
const { ev, errors } = load();
bigNet(ev);
// one index for the whole list says the same as asking network by network
assert.equal(ev("const w=netWhereIdx();NETS.filter(n=>netWhere(n,w)!==netWhere(n)).length"), 0);
assert.ok(ev("netWhere(NET.ggl).includes('goConn')"));
ev("UI.leftOpen=true;ACT.leftTab({t:'nets'})");
assert.match(ev("document.getElementById('leftBody').textContent"), /Goggle/);
assert.deepEqual(errors, []);
});
test('the map draws a big network at every zoom, with a city or a link selected', () => {
const { ev, errors } = load();
bigNet(ev);
ev("localStorage.setItem('sot-anim','on');UI.anim='on'");
for (const sel of ['null', "{type:'city',id:'fra'}", "{type:'link',id:S.links[2].id}"]) {
for (const z of [0.35, 0.6, 1.2, 2.5, 6]) ev(`UI.sel=${sel};cam.z=${z};draw(1000);draw(1016)`);
}
assert.ok(ev('ctx.calls.n') > 1000);
assert.ok(ev("hitLink(...toS(CITY.fra.x,CITY.fra.y,0))!==undefined"));
assert.deepEqual(errors, []);
});