Merge #96: RouteScript local-pref, AS-path prepending, protected customers and an optimizer

Ported onto #89's routing loop: the prepend share is its own transit exit,
local-pref and prepending get their own ranks, and protect customers runs
business flows through every rank before home users. Portuguese for the
five new strings.
This commit is contained in:
Frederic Jung 2026-10-26 07:01:33 +01:00
commit 1858098a4d
No known key found for this signature in database
5 changed files with 93 additions and 15 deletions

View file

@ -7,6 +7,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- Series of Tubes now speaks Portuguese (Brazil). The game follows your browser's language the first time, and you can switch to Português under Settings or on the title screen.
- RouteScript speaks more BGP. `prefer transit` and `avoid transit` set which upstream goes first, like local-pref, `prepend transit PROVIDER 1-3` moves part of an upstream's traffic away, the way AS-path prepending nudges the rest of the internet, and `protect customers` routes business traffic first when links are congested, so home users take the hit instead of your SLAs. A new Optimize button drafts a script from live traffic and points out networks you could reach over an IX or a PNI instead of transit.
- Fiber between nearby cities bends gently again instead of looping wide around the neighbourhood, so dense regions like Toronto, Ottawa and Montreal stay readable.
- Swapping router models now sells the old ones on eBuy for 30% of their price, and removing a router does too (#82). A POP takes one swap a day, so a double click no longer buys two upgrades, and optics and waves now say which port speed they need instead of naming one model.
- Hamburg and Munich join the map, with the Moin-IX and the Brezn-IX. Stuttgart and Frankfurt are back where they belong on the map, with Stuttgart between Frankfurt and Zurich instead of halfway to Prague.

View file

@ -2434,4 +2434,9 @@
"+{n} more connections":"+{n} altre connessioni",
"+{n} more customer":"+{n} altro cliente",
"+{n} more customers":"+{n} altri clienti",
"line {n}: prepend 1 to 3 times":"riga {n}: prepend da 1 a 3 volte",
"# Suggested by the optimizer from live traffic. Check it, then deploy.":"# Suggerito dall’ottimizzatore in base al traffico reale. Controllalo, poi fai il deploy.",
"# {net}: {g} over transit, but it peers at {ix} in {city}, where you have a POP. Get a port there.":"# {net}: {g} via transit, ma fa peering a {ix} a {city}, dove hai un POP. Prendi una porta lì.",
"# {net}: {g} over the IX. A PNI would take it off the shared port.":"# {net}: {g} via IX. Un PNI lo toglierebbe dalla porta condivisa.",
"Optimize":"Ottimizza",
};

View file

@ -2434,4 +2434,9 @@
"+{n} more connections":"+{n} conexões a mais",
"+{n} more customer":"+{n} cliente a mais",
"+{n} more customers":"+{n} clientes a mais",
"line {n}: prepend 1 to 3 times":"linha {n}: prepend de 1 a 3 vezes",
"# Suggested by the optimizer from live traffic. Check it, then deploy.":"# Sugerido pelo otimizador a partir do tráfego ao vivo. Confira e depois faça o deploy.",
"# {net}: {g} over transit, but it peers at {ix} in {city}, where you have a POP. Get a port there.":"# {net}: {g} via transit, mas faz peering no {ix} em {city}, onde você tem um POP. Pegue uma porta lá.",
"# {net}: {g} over the IX. A PNI would take it off the shared port.":"# {net}: {g} via IX. Um PNI tiraria isso da porta compartilhada.",
"Optimize":"Otimizar",
};

View file

@ -1696,6 +1696,13 @@ cap transit cogentle at 20 gbps
avoid transit for goggle
# Move traffic before links are completely full
spill at 85%
# Local-pref: use the cheap upstream first, the pricey one last
# prefer transit cogentle
# avoid transit level tree
# AS-path prepending: ask the world to send less via one upstream (a hint, not an order)
# prepend transit drizzle electric 2
# Business customers first when links are congested; home users get what is left
# protect customers
# Maintenance window? Drain a POP's exits, or steer around a link
# drain paris
# avoid link frankfurt-amsterdam
@ -1707,25 +1714,40 @@ function teFind(word,list,label){const w=slug(word);if(!w)return {err:tr('missin
const pre=list.filter(x=>w.length>=3&&slug(x.name).startsWith(w));if(pre.length===1)return {v:pre[0].id};
const best=list.map(x=>({x,d:Math.min(lev(w,slug(x.name)),lev(w,x.id))})).sort((a,b)=>a.d-b.d)[0];
return {err:tr('unknown {what} “{word}”',{what:label,word})+(best&&best.d<=3?tr('. Did you mean {name}?',{name:best.x.name}):'')};}
function teParse(src){const out={spill:null,cap:{},net:{},drain:new Set(),avoid:new Set(),blackhole:false,errors:[],n:0};
function teParse(src){const out={spill:null,cap:{},net:{},up:{},prep:{},protect:false,drain:new Set(),avoid:new Set(),blackhole:false,errors:[],n:0};
const lines=String(src||'').split('\n').slice(0,60);
lines.forEach((raw,i)=>{const line=raw.replace(/#.*/,'').trim().toLowerCase();if(!line)return;const L=i+1;let m;
if(m=line.match(/^spill\s+at\s+(\d{1,3})\s*%$/)){const v=+m[1];if(v<20||v>100)out.errors.push(tr('line {n}: spill must be between 20% and 100%',{n:L}));else{out.spill=v/100;out.n++;}return;}
if(m=line.match(/^(prefer|avoid)\s+(pni|ix|transit)\s+for\s+(.+)$/)){const r=teFind(m[3],NETS,tr('network'));if(r.err){out.errors.push(tr('line {n}: {err}',{n:L,err:r.err}));return;}const o=out.net[r.v]=out.net[r.v]||{};o[m[1]]=TE_KINDS[m[2]];out.n++;return;}
if(m=line.match(/^cap\s+transit\s+(.+?)\s+at\s+(\d+(?:\.\d+)?)\s*(gbps|tbps|g|t)$/)){const r=teFind(m[1],NETS.filter(n=>n.price),tr('transit provider'));if(r.err){out.errors.push(tr('line {n}: {err}',{n:L,err:r.err}));return;}out.cap[r.v]=+m[2]*(m[3][0]==='t'?1000:1);out.n++;return;}
if(m=line.match(/^(prefer|avoid)\s+transit\s+(?!for\s)(.+)$/)){const r=teFind(m[2],NETS.filter(n=>n.price),tr('transit provider'));if(r.err){out.errors.push(tr('line {n}: {err}',{n:L,err:r.err}));return;}out.up[r.v]=m[1];out.n++;return;}
if(m=line.match(/^prepend\s+transit\s+(.+?)\s+(\d+)$/)){const v=+m[2];if(v<1||v>3){out.errors.push(tr('line {n}: prepend 1 to 3 times',{n:L}));return;}const r=teFind(m[1],NETS.filter(n=>n.price),tr('transit provider'));if(r.err){out.errors.push(tr('line {n}: {err}',{n:L,err:r.err}));return;}out.prep[r.v]=v;out.n++;return;}
if(line==='protect customers'){out.protect=true;out.n++;return;}
if(m=line.match(/^drain\s+(.+)$/)){const r=teFind(m[1],CITIES,tr('city'));if(r.err){out.errors.push(tr('line {n}: {err}',{n:L,err:r.err}));return;}out.drain.add(r.v);out.n++;return;}
if(m=line.match(/^avoid\s+link\s+(.+?)\s*(?:-|\bto\b|→)\s*(.+)$/)){const a=teFind(m[1],CITIES,tr('city')),b=teFind(m[2],CITIES,tr('city'));if(a.err||b.err){out.errors.push(tr('line {n}: {err}',{n:L,err:a.err||b.err}));return;}out.avoid.add(a.v<b.v?a.v+'|'+b.v:b.v+'|'+a.v);out.n++;return;}
if(line==='blackhole ddos'){out.blackhole=true;out.n++;return;}
out.errors.push(tr("line {n}: I don't understand “{text}”. Try: spill at 80%, prefer pni for goggle, avoid transit for netchill, cap transit cogentle at 20 gbps, drain paris, avoid link fra-ams, blackhole ddos",{n:L,text:raw.trim().slice(0,40)}));});
return out;}
// Share of an upstream's traffic that moves away for each prepend: prepending is a hint, not an order.
const PREPEND_F=[0,0.35,0.6,0.75];
function teOptimize(){const L=[tr('# Suggested by the optimizer from live traffic. Check it, then deploy.'),'spill at 85%'];
if(S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber))L.push('protect customers');
const ups=[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*regionMult(t.city)))})).sort((a,b)=>a.p-b.p);
if(ups.length>1){L.push('prefer transit '+NET[ups[0].n].name.toLowerCase());L.push('avoid transit '+NET[ups[ups.length-1].n].name.toLowerCase());}
const tips=[];
for(const n of NETS){const g=(R.netEg[n.id]||{}).t||0;if(g<1)continue;const at=Object.keys(S.pops).find(c=>S.ixp[c]===undefined&&ixStatic(c).some(x=>ixMembers(x).includes(n.id)));
if(at)tips.push([g,tr('# {net}: {g} over transit, but it peers at {ix} in {city}, where you have a POP. Get a port there.',{net:n.name,g:fmtG(g),ix:ixName(at),city:CITY[at].name})]);}
for(const n of NETS){const g=(R.netEg[n.id]||{}).ix||0;if(g>=50&&!S.pni.some(p=>p.net===n.id))tips.push([g,tr('# {net}: {g} over the IX. A PNI would take it off the shared port.',{net:n.name,g:fmtG(g)})]);}
tips.sort((a,b)=>b[0]-a[0]).slice(0,5).forEach(x=>L.push(x[1]));
return L.join('\n');}
let TE_CACHE={src:null,p:null};
function teRules(){if(!S||!S.te||!S.te.on||!S.te.script)return null;if(TE_CACHE.src!==S.te.script)TE_CACHE={src:S.te.script,p:teParse(S.te.script)};return TE_CACHE.p.errors.length?null:TE_CACHE.p;}
function teModal(msg){const src=UI.teDraft!==undefined?UI.teDraft:(S.te.script||TE_EXAMPLE);
openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">${tr('Auto-TE controller')}</div><h2 style="font-size:26px">RouteScript</h2></div><button class="x" data-act="teClose" aria-label="${tr('Close')}">×</button></div>
<p class="tagline">${tr('Write rules, check them against live traffic, then deploy. A bad deploy is a very real way to break your network.')}</p>
<textarea id="teSrc" class="tecode" spellcheck="false" autocapitalize="off" autocomplete="off" rows="12">${esc(src)}</textarea>
${msg||''}<div class="btns" style="margin-top:8px">${btn(tr('Check (dry run)'),'teCheck',{},'')}${btn(tr('Deploy'),'teDeploy',{},'pink')}${S.te.script?btn(tr('Remove script'),'teClear',{},'ghost sm'):''}${btn(tr('Reset to example'),'teExample',{},'ghost sm')}</div>
<p class="meta" style="margin-top:8px"><b>${tr('Rules:')}</b> <code>spill at 80%</code> · <code>prefer pni|ix|transit for NETWORK</code> · <code>avoid pni|ix|transit for NETWORK</code> · <code>cap transit PROVIDER at 20 gbps</code> · <code>drain CITY</code> · <code>avoid link CITY-CITY</code> · <code>blackhole ddos</code></p>
${msg||''}<div class="btns" style="margin-top:8px">${btn(tr('Check (dry run)'),'teCheck',{},'')}${btn(tr('Deploy'),'teDeploy',{},'pink')}${S.te.script?btn(tr('Remove script'),'teClear',{},'ghost sm'):''}${btn(tr('Optimize'),'teOpt',{},'ghost sm')}${btn(tr('Reset to example'),'teExample',{},'ghost sm')}</div>
<p class="meta" style="margin-top:8px"><b>${tr('Rules:')}</b> <code>spill at 80%</code> · <code>prefer pni|ix|transit for NETWORK</code> · <code>avoid pni|ix|transit for NETWORK</code> · <code>cap transit PROVIDER at 20 gbps</code> · <code>prefer|avoid transit PROVIDER</code> · <code>prepend transit PROVIDER 1-3</code> · <code>protect customers</code> · <code>drain CITY</code> · <code>avoid link CITY-CITY</code> · <code>blackhole ddos</code></p>
${S.te.script?`<p class="meta">${tr('Live: {state} · {rules}',{state:S.te.on?tr('deployed'):tr('controller is off'),rules:teRules()?tr('{n} rules active',{n:teRules().n}):tr('not active')})}</p>`:''}`);}
function teTrial(src){const keep=S.te.script,on=S.te.on,before={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0};
S.te.script=src;S.te.on=true;compute();const after={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0,bh:R.teBlack||0};
@ -1736,7 +1758,7 @@ function compute(){
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length;
// The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order.
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
const edges={},TRX=teRules(),live=[];let NE=0;
const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={};
for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[],res:0,ld:0,tr:null,pl:0};adj[ai].push([bi,e]);adj[bi].push([ai,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f*(TRX&&TRX.avoid.has(key)?60:1));e.lat=Math.min(e.lat,linkLat(l));}
// Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by.
@ -1746,7 +1768,10 @@ function compute(){
const E=[], ev=S.ev;
const depeer=ev.depeer>day||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue;
E.push({k:'t',prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:labOf(N_('{net} transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak});}
// AS-path prepending (#96) moves part of the port to a last-resort exit of its own.
const cap=Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),pf=TRX&&TRX.prep[t.net]?PREPEND_F[TRX.prep[t.net]]:0;
const ex={k:'t',net:t.net,prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:labOf(N_('{net} transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:cap*(1-pf),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak};
E.push(ex);if(pf)E.push({...ex,cap:cap*pf,prep:true});}
// `nets`: every network ok() can say yes to, so it need not be asked about the other hundred.
for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c]))continue;const set=ixSessions(c);R2.sessions+=set.size;
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:labOf(N_('{ix} peering'),'ix',ixName(c)),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n),nets:set});}
@ -1766,7 +1791,7 @@ function compute(){
const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net));
const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1);
// Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index).
const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk)=>{const n=NETS[j];flows.push({c,n:n.id,rem,cache,junk,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j});};
const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j];flows.push({c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j});};
// Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give).
const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}}
// Traffic shares by network index, and their sums, for each share table (and with Russia's throttle).
@ -1800,8 +1825,10 @@ function compute(){
R2.cityBlocked=R2.cityBlocked||{};
const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr;
for(let j=0;j<NN;j++){const n=NETS[j],a=d0*sa[j]*thr(n.id)*(rtbh?0:edge?0.9:1)*(mtuH&&mtuH.net===n.id?mtuH.f:1)*(kr&&ev.krroute>day&&n.id==='fbk'?0.8:1);if(a<=0)continue;
if(cacheNets.has(n.id)){flow(c,ci,cn,j,a*0.85,true,false);flow(c,ci,cn,j,a*0.15,false,false);}
else flow(c,ci,cn,j,a,false,false);}
const bf=d0>0?biz/d0:0,parts=TRX&&TRX.protect&&bf>0?[[a*bf,true],[a*(1-bf),false]]:[[a,false]];
for(const [x,bz] of parts){if(x<=0)continue;if(cacheNets.has(n.id)){flow(c,ci,cn,j,x*0.85,true,false,bz);flow(c,ci,cn,j,x*0.15,false,false,bz);}
else flow(c,ci,cn,j,x,false,false,bz);}}
R2.bizDem[c]=biz*d/(d0||1);R2.bizSrv[c]=0;
}
if(Object.keys(S.pops).length)for(let j=0;j<NN;j++)R2.demTo[NETS[j].id]=DEMTO[j];
/* While routing, each edge keeps its own room (res) and load (ld). Routers only exist in POPs (HAS): their room,
@ -1861,8 +1888,11 @@ function compute(){
if(D[dst]===Infinity||D[dst]>2*base+60){teCache.set(key,false);return null;}
const Q=walkI(P,src,dst);teCache.set(key,Q);return Q;};
const base=e=>e.pref==='low'?4:e.rank;
const eff=(e,n)=>{let r=base(e);if(TR){if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;};
const RANKS=TR?[0,0.5,1,2,3,4,4.5,4.6]:[0,1,2,3,4];
// LOCAL_PREF on an upstream moves it ahead of or behind the other transits, never ahead of peering (#96).
const eff=(e,n)=>{let r=base(e);if(TR){if(e.k==='t'&&TR.up[e.net])r=TR.up[e.net]==='prefer'?2.9:3.5;if(e.prep)r=4.4;if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;};
const RANKS=TR?[0,0.5,1,2,2.9,3,3.5,4,4.4,4.5,4.6]:[0,1,2,3,4];
// With `protect customers`, business flows take every rank first; home users get what is left.
const PASSES=TR&&TR.protect?[x=>x.bz,x=>!x.bz]:null;
// Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order.
// Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order.
const byRank={};for(const id of NET_IDS){const m=byRank[id]={};for(const e of okBy[id]){const r=TR?eff(e,id):base(e);(m[r]||(m[r]=[])).push(e);}
@ -1881,7 +1911,7 @@ function compute(){
e.used+=amt;f.rem-=amt;
if(!f.junk){let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn;
if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
SRV[f.ci]+=ok;R2.served+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok;}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;}
SRV[f.ci]+=ok;R2.served+=ok;if(f.bz)R2.bizSrv[f.c]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok;}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;}
return amt;
};
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
@ -1896,10 +1926,10 @@ function compute(){
const sendGroup=g=>{for(const e of g)e.vis=vis;
if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=f.rem;if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));}
for(const e of g){if(f.rem<=1e-6)break;send(e,f.rem);}};
for(const rank of RANKS){
for(const pass of PASSES||[null])for(const rank of RANKS){
if(TR?!E.length:!E.some(e=>base(e)===rank))continue;
for(f of flows){
if(f.rem<=1e-6||(rank===0&&!f.cache))continue;
if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue;
const lst=byRank[f.n][rank];if(!lst)continue;
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
/* Groups are tried nearest first, preferred exits before the rest, in the order a stable sort of the usable
@ -1933,7 +1963,7 @@ function compute(){
Object.defineProperty(R2,'efg',{value:efg});}
for(const k in edges){const e=edges[k],ld=e.ld||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;}
R2.peerShare=R2.served>0?R2.peered/R2.served:0;
for(const e of E){if(e.k==='t')R2.useT[e.id]=e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}
for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}
// money
const C=R2.cost,V=R2.rev,pm=S.priceMul;
C.pops=Object.values(S.pops).reduce((a,p)=>a+POP_MO+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0);
@ -2069,7 +2099,9 @@ function diversityPossible(a,b,state=S){
}
function fiberOk(b){const l=S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs')return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day);}
function soldSlots(l){return S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);}
function bizSf(b){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):sfOf(R,b.city);}
function bizSf(b){const T=BIZ_T[b.type];return T.fiber?(fiberOk(b)?1:0):T.l2?clamp((R.l2[b.id]||0)/b.bw,0,1):bizSfOf(R,b.city);}
// Protected business traffic has its own served share; without the rule it shares the city's.
function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules().protect&&d>1e-6?clamp(r.bizSrv[c]/d,0,1):sfOf(r,c);}
function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);}
function bHas(o){return bCities(o).every(c=>S.pops[c]);}
function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day<b.start+b.dur;}
@ -2710,6 +2742,7 @@ const ACT={
dkStay:({city})=>{S.stats.retained=1;const dk=dkState();dk.ret[city]=S.day+180;dk.retUsed[city]=true;UI.confirm=null;closeModal();toast(tr('<b>40% off {ix} for 6 months.</b><br>Your account manager is relieved. Read the small print later.',{ix:esc(ixName(city))}),'good');after();},
teEdit:()=>{if(!S.te)return;UI.teDraft=undefined;teModal();},
teClose:()=>{const t=$('teSrc');if(t)UI.teDraft=t.value;closeModal();},
teOpt:()=>{UI.teDraft=teOptimize();teModal();},
teExample:()=>{UI.teDraft=TE_EXAMPLE;teModal();},
teClear:()=>{S.te.script='';UI.teDraft=undefined;TE_CACHE={src:null,p:null};after();teModal(`<p class="note">${tr('Script removed. Plain Auto-TE is back in charge.')}</p>`);},
teCheck:()=>{const t=$('teSrc');const src=t?t.value:'';UI.teDraft=src;const p=teParse(src);if(p.errors.length){teModal(`<pre class="term err">${esc(p.errors.join('\n'))}</pre>`);return;}const r=teTrial(src);teModal(`<pre class="term">${esc(trn('✓ {n} rule OK','✓ {n} rules OK',p.n)+'\n'+tr('served {a} → {b}',{a:fmtG(r.before.served),b:fmtG(r.after.served)})+'\n'+tr('transit {a}/mo → {b}/mo',{a:fmt$(r.before.tc),b:fmt$(r.after.tc)})+'\n'+tr('spilled {g} onto alternate paths',{g:fmtG(r.after.moved)})+(r.after.bh?'\n'+tr('blackholed {g}',{g:fmtG(r.after.bh)}):''))}</pre>`);},

View file

@ -172,6 +172,40 @@ test('RouteScript: parses safely, reports errors helpfully, and changes routing'
assert.deepEqual(errors, []);
});
test('RouteScript BGP: local-pref and prepending move transit, protected customers go first, the optimizer drafts a script', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'fra',net:'lvl',tier:1});ACT.buyTE();for(let i=0;i<30;i++)dayTick();compute()");
const use = n => ev(`R.useT[S.transit.find(t=>t.net==='${n}').id]||0`);
const p = JSON.parse(ev("JSON.stringify(teParse('prefer transit level tree\\navoid transit cogentle\\nprepend transit cogentle 2\\nprotect customers\\nprepend transit cogentle 9'))"));
assert.equal(p.n, 4);
assert.match(p.errors[0], /prepend 1 to 3/);
assert.equal(p.up.lvl, 'prefer');
assert.equal(p.prep.cog, 2);
ev("S.te.script='prefer transit level tree';compute()");
assert.ok(use('cog') < 1e-6 && use('lvl') > 0, 'local-pref sends everything to the preferred upstream');
const tot = use('lvl');
ev("S.te.script='prepend transit level tree 2';compute()");
assert.ok(use('lvl') < tot * 0.5 && use('cog') > 0, 'prepending moves traffic off, but not all of it');
assert.ok(Math.abs(use('lvl') + use('cog') - tot) < 0.5, 'nothing is lost');
// Congest the city, then protect business customers: they keep their service, home users take the hit.
ev("S.biz.push({id:uid(),city:'fra',city2:null,reqs:[],name:'Test DIA',type:'dia',bw:5,rate:600,mood:100,since:0});S.pops.fra.bb.d*=40;S.te.script='';compute()");
const plain = ev("bizSf(S.biz[S.biz.length-1])");
assert.ok(plain < 0.95, `the city is congested (${plain})`);
ev("S.te.script='protect customers';compute()");
assert.ok(ev("bizSf(S.biz[S.biz.length-1])") >= 0.95, 'protected customer stays happy (95%+ served)');
assert.ok(ev("sfOf(R,'fra')") <= plain + 0.01, 'the city as a whole is not better off');
const draft = ev('teOptimize()');
assert.match(draft, /spill at 85%/);
assert.match(draft, /protect customers/);
assert.match(draft, /prefer transit cogentle/);
assert.match(draft, /peers at DE-KICKS/);
assert.equal(ev('teParse(teOptimize()).errors.length'), 0, 'the draft is a valid script');
ev("S.te.script='';ACT.teEdit();ACT.teOpt()");
assert.match(ev("document.getElementById('teSrc').value"), /Suggested by the optimizer/);
assert.deepEqual(errors, []);
});
test('#27 new networks get a random name, and "Another one" never repeats it', () => {
const { ev, errors } = load();
assert.ok(ev("NETWORK_NAMES.every(n=>n.length<=24)&&new Set(NETWORK_NAMES).size===NETWORK_NAMES.length"));