feat(traceroute): choose how the trace is routed

The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit. traceMode is classified in the MCP tables.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Lambro-codes 2026-11-04 04:32:17 +01:00
parent b2366ed260
commit b57c022860
5 changed files with 65 additions and 6 deletions

View file

@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit.
- Every capital in Africa is on the map, which puts every capital of the world in the game: 33 new cities from Porto-Novo, Bamako and Niamey to Khartoum, Juba, Mogadishu, Brazzaville, Tripoli, Rabat and Pretoria. Each country brings its real telcos, Nigeria gets its wholesale backbone up to Abuja, and the island capitals of the Comoros, São Tomé and Equatorial Guinea sit on their real cables.
- Every capital in South, East and Southeast Asia and the Pacific is on the map: Thimphu, Kathmandu, Bandar Seri Begawan, Phnom Penh, Vientiane, Ulaanbaatar, Naypyidaw, Pyongyang, Dili, Hanoi and Wellington, with the island capitals Tarawa, Palikir, Yaren, Funafuti and Port Vila. Each country brings its real telcos, North Korea reaches the world only through China and Russia, and the islands hang on their real cables.
- Every capital in the Middle East, the Caucasus and Central Asia is on the map, from Yerevan and Baku to Kabul, Tehran, Baghdad, Jerusalem, Amman, Kuwait City, Beirut, Damascus, Sanaa and Manama, with Ankara and Islamabad. Each country brings its real telcos, and Bahrain is an island on the Gulf's cables.

View file

@ -509,6 +509,7 @@ const API_CMD={
};
const API_VIEW={
traceMode:{args:[['m','string']],doc:'Redo the open traceroute in a routing mode: normal, fast or scenic.'},
help:{args:[],doc:'Open the how-to-play modal.'},
dash:{args:[],doc:'Open the NOC dashboard.'},
dashClose:{args:[],doc:'Close the NOC dashboard.'},

View file

@ -1,9 +1,13 @@
/* ---------- traceroute and looking glass ---------- */
const slug=t=>String(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x';
function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
// The three ways a customer's circuit can be routed (RT in 90-sites-and-service.js), applied to the trace: follow the metrics,
// lowest latency, or the quietest links (one path; a scenic circuit may share the load between two).
const TR_MODES=['normal','fast','scenic'];
const trUtil=l=>{const c=capOf(l);return c>0?Math.max(0,((R.load&&R.load[l.id])||0)/c):0;};
function trPaths(src,mode){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={};
// Every link between two cities costs what the pair costs, as in compute(); the trace shows an active link over one on standby.
const pw={};for(const l of live){const k=edgeKey(l);pw[k]=Math.min(pw[k]??Infinity,pairW(k,l.km));}
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=pw[edgeKey(l)]+(l.standby?1e-6:0);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const k=edgeKey(l),w=(mode==='fast'?linkLat(l)+0.05:mode==='scenic'?pw[k]*(1+10*trUtil(l)):pw[k])+(l.standby?1e-6:0);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);}
const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]<ud){u=k;ud=dist[k];}if(u===null)break;done.add(u);for(const [v,l,w] of adj[u]||[]){const nd=ud+w;if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=l;}}}
const path=dst=>{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};}
function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[];
@ -16,7 +20,7 @@ function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev
// coneChain(peer,net): [peer, …, net], the shortest walk down customer links (the network's up lists, read backwards).
function coneChain(top,id){const prev={[id]:null},q=[id];while(q.length){const x=q.shift();if(x===top)break;for(const u of NET[x].up||[])if(NET[u]&&!(u in prev)){prev[u]=x;q.push(u);}}
if(!(top in prev))return [top,id];const out=[];for(let x=top;x!==null;x=prev[x])out.push(x);return out;}
function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1;
function traceroute(src,to,mode){mode=TR_MODES.includes(mode)?mode:'normal';const P=trPaths(src,mode),me=slug(S.name)+'.net',lines=[],ip=(a,b)=>`100.64.${a%250}.${b%250}`;let rtt=0.3,n=1;
const hop=(host,addr,extra,note)=>{rtt+=extra;lines.push(`${String(n++).padStart(2)} ${host} (${addr}) ${rtt.toFixed(1)} ms${note?' ← '+note:''}`);};
hop(`lo0.cr1.${src}.${me}`,ip(hstr(src),1),0,tr('traceroute.city_your_router',{city:CITY[src].name}));
const walk=path=>{for(const h of path){const l=h.l,lat=linkLat(l)*2+0.15;hop(`ae${1+hstr(l.id)%9}.cr1.${h.to}.${me}`,ip(hstr(h.to),2),lat,`${CITY[h.to].name} · ${l.kind==='df'?tr('common.own_dark_fiber'):l.kind==='vxc'?tr('common.fabric_circuit'):l.cable?CAB[l.cable].name:tr('common.terrestrial_wave')} · ${capName(l)}`);}};
@ -45,12 +49,13 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[]
const order=e.via?tr('traceroute.a_peer_s_customers_come_after'):{c:tr('traceroute.caches_beat_pnis'),p:tr('traceroute.pnis_beat_ix_peering'),ix:tr('traceroute.ix_peering_beats_transit'),t:tr('traceroute.transit_is_the_last_resort')}[e.k];
const cn=cnCity(src)!==!!N.cn?' '+tr('traceroute.crossing_the_great_firewall_here',{p:S.ev.gfw>S.day?35:20}):'';
return {text:lines.join('\n'),why:`${tr('traceroute.exit_exit_in_city',{exit:e.lab,city:CITY[e.city].name})} ${tr('traceroute.rule_and_closer_exits_win_ties',{rule:order[0].toUpperCase()+order.slice(1)})}${e.pref!=='normal'?tr('traceroute.this_one_is_set_to_mode',{mode:e.pref==='high'?tr('common.prefer'):tr('common.backup_only')}):''}.${direct}${e.used>=e.cap*0.999?' '+tr('traceroute.it_is_full_so_some_traffic'):''}${cn}`,asPath};}
function traceModal(src,to){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0];
const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)}):traceroute(src,{city:t.slice(5)});
function traceModal(src,to,mode){const pops=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name));src=src&&S.pops[src]?src:UI.trFrom&&S.pops[UI.trFrom]?UI.trFrom:S.home&&S.pops[S.home]?S.home:pops[0];
const nets=NETS.slice().sort((a,b)=>b.share-a.share),t=to||UI.trTo||'net:ggl';UI.trFrom=src;UI.trTo=t;mode=TR_MODES.includes(mode)?mode:UI.trMode||'normal';UI.trMode=mode;
const r=t.startsWith('net:')?traceroute(src,{net:t.slice(4)},mode):traceroute(src,{city:t.slice(5)},mode);
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('common.looking_glass')}</div><h2 style="font-size:26px">${tr('common.traceroute')}</h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
<div class="trsel"><label>${tr('common.from')} <select id="trFrom">${pops.map(c=>`<option value="${c}"${c===src?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</select></label>
<label>${tr('common.to')} <select id="trTo"><optgroup label="${tr('common.networks')}">${nets.map(n=>`<option value="net:${n.id}"${t==='net:'+n.id?' selected':''}>${esc(n.name)} (AS${n.asn})</option>`).join('')}</optgroup><optgroup label="${tr('common.your_pops')}">${pops.filter(c=>c!==src).map(c=>`<option value="city:${c}"${t==='city:'+c?' selected':''}>${esc(CITY[c].name)}</option>`).join('')}</optgroup></select></label>${btn(tr('common.run'),'traceRun',{},'pink sm')}</div>
<div class="btns"><span class="meta" style="align-self:center">${tr('common.route_4a2e')}</span>${TR_MODES.map(m=>btn(RT[m],'traceMode',{m},mode===m?'pink sm':'ghost sm')).join('')}</div>
<pre class="term">${esc(r.text)}</pre>${r.asPath?`<p class="meta">${tr('traceroute.as_path_path',{path:r.asPath.map(a=>'AS'+a).join(' → ')})}</p>`:''}<p class="note">${esc(r.why)}</p>
<div class="btns">${btn(tr('common.copy'),'traceCopy',{},'ghost sm')}</div>`);UI.trText=r.text;}

View file

@ -18,6 +18,7 @@ Object.assign(ACT,{
teToggle:()=>{if(!S.te)return;S.te.on=!S.te.on;after();},
trace:({city})=>traceModal(city),
traceRun:()=>{const f=$('trFrom'),t=$('trTo');traceModal(f&&f.value,t&&t.value);},
traceMode:({m})=>{if(!TR_MODES.includes(m))return;const f=$('trFrom'),t=$('trTo');sfx('click');traceModal(f&&f.value,t&&t.value,m);},
traceCopy:()=>{try{navigator.clipboard.writeText(UI.trText||'');toast(tr('route_script_and_tools.copied_paste_it_into_your_favourite'),'good');}catch(e){}},
share:()=>shareModal(),
shareDl:()=>shareFile(f=>{if(!f)return;const a=document.createElement('a');a.href=URL.createObjectURL(f);a.download=f.name;document.body.appendChild(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},1000);track('share_download');}),

View file

@ -0,0 +1,51 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// A triangle: Frankfurt-Amsterdam direct, or round through Paris.
function setup(ev) {
ev("ACT.start({});S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0");
ev("ACT.launchBB({city:'fra'});ACT.buildPop({city:'par'});ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
[['fra', 'par'], ['par', 'ams'], ['fra', 'ams']].forEach(([a, b], i) => ev(`UI.via=null;openLinkModal('${a}','${b}');ACT.buildLink({tier:1});closeModal();S.links[S.links.length-1].tag=${i}`));
ev("var D=S.links.find(l=>l.tag===2);compute()");
}
const hops = (ev, mode) => ev(`trPaths('fra',${JSON.stringify(mode)}).path('ams').length`);
test('a trace can follow the metrics, the lowest latency or the quietest links', () => {
const { ev, errors } = load();
setup(ev);
assert.equal(hops(ev, 'normal'), 1, 'the short way round is the direct link');
ev("ACT.setMetric({id:D.id,v:'avoid'})");
assert.equal(hops(ev, 'normal'), 2, 'an avoided direct link sends the metric route round through Paris');
assert.equal(hops(ev, 'fast'), 1, 'but lowest latency ignores the metric and goes direct');
ev("ACT.setMetric({id:D.id,v:'normal'});compute()");
assert.equal(hops(ev, 'scenic'), 1, 'with nothing busy, scenic is the plain route');
ev("R.load[D.id]=capOf(D)*0.95");
assert.equal(hops(ev, 'scenic'), 2, 'a busy direct link sends scenic round the quiet way');
assert.equal(hops(ev, 'normal'), 1, 'while the metric route does not care');
assert.equal(ev("trPaths('fra').path('ams').length"), 1, 'old callers without a mode still follow the metrics');
assert.equal(JSON.parse(ev("JSON.stringify(traceroute('fra',{city:'ams'},'nonsense'))")).text.includes('traceroute to'), true, 'an unknown mode falls back');
assert.deepEqual(errors, []);
});
test('the looking glass has the three route buttons, like a customer circuit, and each one re-runs the trace', () => {
const { ev, dom, errors } = load();
const doc = dom.window.document;
setup(ev);
ev("ACT.setMetric({id:D.id,v:'avoid'});ACT.trace({city:'fra'})");
const btns = () => [...doc.querySelectorAll('[data-act="traceMode"]')];
assert.equal(doc.getElementById('trMode'), null, 'no drop-down');
assert.deepEqual(btns().map(b => JSON.parse(b.dataset.args).m), ['normal', 'fast', 'scenic']);
assert.deepEqual(btns().map(b => b.className.includes('pink')), [true, false, false], 'the chosen one is highlighted');
doc.getElementById('trTo').value = 'city:ams';
btns()[1].click();
assert.equal(ev("UI.trMode"), 'fast');
assert.deepEqual(btns().map(b => b.className.includes('pink')), [false, true, false]);
assert.match(doc.querySelector('.term').textContent, /traceroute to ams/, 'the chosen destination is kept');
assert.equal((doc.querySelector('.term').textContent.match(/cr1\.ams/g) || []).length, 1, 'one hop: straight there');
ev("ACT.traceMode({m:'nonsense'})");
assert.equal(ev("UI.trMode"), 'fast', 'an unknown mode changes nothing');
ev("ACT.traceRun()");
assert.equal(ev("UI.trMode"), 'fast', 'Run keeps the mode');
assert.deepEqual(errors, []);
});