Merge pull request #319 from antt0n/perf/intern-and-promises

This commit is contained in:
Frederic Jung 2026-11-08 10:50:48 +00:00
commit 4292cd4c74
No known key found for this signature in database
16 changed files with 371 additions and 65 deletions

View file

@ -9,6 +9,9 @@ All notable changes to this project are documented here. The project follows
- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed.
- A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds.
- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before.
- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before.
- A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before.
- The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before.
## [3.2.0] — 2026-11-07

View file

@ -137,7 +137,9 @@ The day:
Then the NOC intern's standing orders (`opsRun()`, or `opsDay()` in one go), if one is hired: each order clicks the
same `ACT` actions a player would, muted, within its monthly budget, and the shift routes again (a yield) before
decommissioning, which reads today's loads, and at the end, each only if a job changed the network. An order that
throws is paused; the day goes on. The NOC gets one notice a week.
throws is paused; the day goes on. The NOC gets one notice a week. The orders plan for every POP each day, so what
they count is counted for all POPs in one pass (`portsAt()`, `cachePlan()`, `pniFlows()`, `pniBatch()`), never one
pass over the network per POP.
Then the sales desk (`slAutoDay()`), if someone runs sales and the player lets them sign: deals are Sales', never
the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything).
5. Updates customer mood, churn and new offers; IX members join; loans tick.

View file

@ -9,20 +9,29 @@ const cachePerPort=(c,g)=>{const p=S.pops[c];return p?Math.max(1,Math.floor(port
const cacheG=x=>x.g===CACHE_BIG?CACHE_BIG:CACHE_CAP,cacheMo=x=>x.g===CACHE_BIG?CACHE_BIG_MO:CACHE_MO,cachesMo=()=>S.caches.reduce((a,x)=>a+cacheMo(x),0);
const cacheBox=c=>{const p=S.pops[c];return p&&portG(p.rgen||0)>=CACHE_BIG?{g:CACHE_BIG}:{};};
function cachePorts(c,extra=[],g){const n={a:0,b:0};for(const x of S.caches)if(x.city===c)n[x.site==='b'?'b':'a']+=cacheG(x);for(const x of extra)n[x.site==='b'?'b':'a']+=cacheG(x);
const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);}
return cachePortsOf(c,n,g);}
// n: the Gbps of boxes per site.
function cachePortsOf(c,n,g){const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);}
const cachePortsAdd=(c,adds)=>cachePorts(c,adds)-cachePorts(c);
/* A dark fiber channel takes as many router ports at each end as the optic's speed needs (#256): a pluggable sits
in one port, but a 1.6T transponder shelf hands off to an 800G router as two 800G clients. */
const chPorts=(o,c,g)=>{const p=S.pops[c];return p&&OPT[o]?Math.max(1,Math.ceil(OPT[o].g/portG(g===undefined?(p.rgen||0):g)-1e-9)):1;};
function portsUsed(c,g){let u=0;
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);}
function portsUsed(c,g){return portsAt([c],g).get(c);}
/* The router ports in use at each of the cities cs, in one pass over the network: the intern sizes every POP each day,
and a pass per POP was a pass over every link, PNI and cache box for each. Each city's count adds the same things in
the same order as on its own. g: another router model at those cities (what would fit). */
function portsAt(cs,g){const u=new Map(),box=new Map();for(const c of cs){u.set(c,0);box.set(c,{a:0,b:0});}
const add=(c,v)=>{const x=u.get(c);if(x!==undefined)u.set(c,x+v);};
for(const l of S.links){if(l.kind==='vxc')continue;for(const c of l.a===l.b?[l.a]:[l.a,l.b]){if(!u.has(c))continue;
if(l.kind!=='df'){add(c,1);continue;}for(const o of l.ch||[])add(c,chPorts(o,c,g));}}
// A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours.
for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1);
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
if(S.myIx[c])u+=1;
for(const x of S.nni||[])if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
u+=cachePorts(c,[],g);
for(const t of S.transit)if(!t.pz)add(t.city,PORT_SLOT(t.tier)*(t.n||1));
for(const x of S.pni)add(x.city,PORT_SLOT(x.tier)*(x.n||1));
for(const c of u.keys()){for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])add(c,PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1));
if(S.myIx[c])add(c,1);}
for(const x of S.caches){const n=box.get(x.city);if(n)n[x.site==='b'?'b':'a']+=cacheG(x);}
for(const x of S.nni||[])add(x.city,PORT_SLOT(x.tier)*(x.n||1));
for(const c of u.keys())add(c,cachePortsOf(c,box.get(c),g));
return u;}
function portsMax(c,g,rt){const p=S.pops[c];if(!p)return 0;return RG[g===undefined?(p.rgen||0):g].ports*(rt||p.routers||1);}
function portGate(c,add){if(!S.pops[c]||add<=0)return true;const u=portsUsed(c),m=portsMax(c);if(u+add<=m+1e-9)return true;

View file

@ -69,9 +69,13 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1)
let DFC=null;
const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;};
// dfLit: everything the optics carry; dfCap0: what is left for your own traffic once managed waves sold on it (mwG(),
// the capacity market) are carved out.
const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);};
// the capacity market) are carved out. A fiber's channels come in runs of one optic (a big one: a thousand of them):
// optG() once per run, added up in order.
const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0,o=null,x=0;for(const c of ch){if(c!==o){o=c;x=optG(c,l);}g+=x;}const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);};
const dfCap0=l=>Math.max(0,dfLit(l)-mwG(l));
// Whether a fiber carries anything for you (linkDown() asks of every fiber, often): dfCap(l)>0 without adding up every
// channel. An optic out of service, or managed waves sold on it, take the sum.
const dfOn=l=>{if(l.ready>S.day||l.eqDown>S.day)return false;if(l.chFail&&l.chFail.until>S.day||mwG(l)>0)return dfCap(l)>0;let o=null;for(const c of l.ch||[])if(c!==o){o=c;if(optG(c,l)>0)return true;}return false;};
const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1);
// A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears.
const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]});

View file

@ -12,12 +12,12 @@ let BIGEYE=null;const bigEye=()=>BIGEYE||(BIGEYE=CITIES.slice().sort((x,y)=>y.P-
let SPOTC=null;
function spots(){const lv=lvl(),k=S.day+'|'+lv+'|'+S.links.length+'|'+Object.keys(S.pops).length+'|'+charter();if(SPOTC&&SPOTC.s===S&&SPOTC.k===k)return SPOTC.v;const v=spots0(lv);SPOTC={s:S,k,v};return v;}
function spots0(lv){const out=[];if(gatesOpen()||S.scn)return out;const up=t=>BIZ_T[t].lv>lv,mine=Object.keys(S.pops).filter(bizCity);
if(up('hft')){const f=FIN.filter(c=>S.pops[c]);for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],ms=bestLat(a,b);if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)});}}
if(up('hft'))for(const [a,b,ms] of latPairs(FIN.filter(c=>S.pops[c])))if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)});
const dci=['onramp','ai','hyper'].filter(up);
if(dci.length)for(const l of S.links){if(l.kind!=='df'||l.sub||l.ready>S.day||linkDown(l))continue;const g=dfCap(l);
for(const t of dci){const T=BIZ_T[t];if(g>=T.opts[0]*SPOT_DF&&(!T.div||reqCan('diverse',{city:l.a,city2:l.b})))out.push({t,a:l.a,b:l.b,k:'df',n:g});}}
if(up('sov')){const by={};for(const c of mine)(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c);
for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(diversePaths(cs[i],cs[j]))out.push({t:'sov',a:cs[i],b:cs[j],k:'div',n:0});}
const g=divGraph();for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(divOn(g,cs[i],cs[j]))out.push({t:'sov',a:cs[i],b:cs[j],k:'div',n:0});}
if(up('cgame')&&R)for(const c of bigEye())if(S.pops[c]&&S.pops[c].bb&&sfOf(R,c)>=0.95)out.push({t:'cgame',a:c,b:null,k:'eye',n:0});
return out;}
// A spotted customer starts at the smallest size its type comes in; your level makes them bigger and more frequent.
@ -79,10 +79,10 @@ const RG_GLASS=Math.max(...Object.values(OPT).map(o=>o.rg)),rgGlass=g=>broker()&
const latPay=()=>charter()==='boutique'?LAT_PAY:1;
// The fastest a leased wave or fiber gets between two cities: overland, or the quickest cable on the route.
function leasedLat(a,b){let best=isSub(a,b)?Infinity:kmBetween(a,b)*1.25/200;for(const c of cablesFor(a,b))best=Math.min(best,c.km*Math.min(CAB[c.cid].lat||1,1.25)/200);return best;}
const ownGlass=l=>l.kind==='df'&&l.own&&l.ready<=S.day&&dfCap(l)>0;
const ownGlass=l=>l.kind==='df'&&l.own&&dfOn(l);
let SOLC=null;
function solRoutes(){const k=S.day+'|'+S.links.length+'|'+S.links.reduce((n,l)=>n+(l.ch||[]).length,0);if(SOLC&&SOLC.s===S&&SOLC.k===k)return SOLC.v;
const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],o=bestLat(a,b,ownGlass),l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}
const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(const [a,b,o] of latPairs(f,ownGlass)){const l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}
SOLC={s:S,k,v};return v;}
const solCust=()=>S.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].lat&&b.mood>=50&&reqOk(b)).length;
// What each charter promises, as the picker and the agent's docs say it.

View file

@ -143,16 +143,18 @@ const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;retur
// after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there.
const OPS_RUN={
*repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}},
*routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
// Ports in use are counted for every POP at once, after the model swaps: a router added or swapped here changes no other POP's count.
*routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',cs=opsPops('routers'),
load=(c,u)=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),u/Math.max(1,portsMax(c)));
// A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a
// step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there.
if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0;
if(fix&&rgOpen(m)){const pu=portsAt(cs);for(const c of cs.slice().sort((a,b)=>load(b,pu.get(b))-load(a,pu.get(a)))){const p=S.pops[c],g=p.rgen||0;
if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue;
const cost=swapCost(c,m);if(!X.can('routers',cost))continue;
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}
for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue;
const ld=load(c);if(ld<at)continue;
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}}
const pu=portsAt(cs);
for(const c of cs){const p=S.pops[c];if(p.rupDay===S.day)continue;
const ld=load(c,pu.get(c));if(ld<at)continue;
const rt=p.routers||1,g=p.rgen||0,nx=mainRG(RG[g].cls+1);
// A swap with one router is a maintenance window: the intern only swaps where a second router carries the traffic.
// With a chosen model the swaps are the ones above; a busy POP only gets more routers.
@ -184,7 +186,11 @@ const OPS_RUN={
// augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for.
*ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[],
// Router ports that pending PNI augments will take when they land are spoken for.
resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c);
// Both, by city, are worked out once between two jobs (a job may change them; KV is dropped after each), in the order
// the PNIs come, as the sum over them was: the same numbers.
KV={rv:null,pu:new Map()},
resv=c=>{if(!KV.rv){KV.rv=new Map();for(const p of S.pni)if(p.up)KV.rv.set(p.city,(KV.rv.get(p.city)||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)));}return KV.rv.get(c)||0;},
used=c=>{let u=KV.pu.get(c);if(u===undefined)KV.pu.set(c,u=portsUsed(c));return u;},room=c=>portsMax(c)-used(c)+1e-9-resv(c);
// Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took.
for(const p of S.pni){const c=p.city,use=(R.usePni[p.id]||0)*opsAhead(),cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue;
L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(),
@ -200,8 +206,8 @@ const OPS_RUN={
out.push({cost:ixPortMo(x,t)*n(),cap:cap()*lagCap(PORT[t].g,n())/lagCap(g(),n()),w:PORT[t0].n+'→'+PORT[t].n,go:()=>ACT.buyIx({city:x,tier:t})});}return out;}});}
for(const o of L.sort((a,b)=>b.u-a.u))for(let step=0;step<3&&!o.busy()&&o.cap()<N*o.use;step++){
const lag=o.lag(),wantLag=o.n()<2&&o.rt>1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig();
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;}))break;
X.did('ports',o.at+' '+job.w);yield;}},
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;})){KV.rv=null;KV.pu.clear();break;}
KV.rv=null;KV.pu.clear();X.did('ports',o.at+' '+job.w);yield;}},
*optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o);
for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue;
let cap=dfCap(l);const load=((R.load&&R.load[l.id])||0)*opsAhead();
@ -242,20 +248,25 @@ const OPS_RUN={
X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2});
if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;});
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}},
*caches(X){const g=opsP('caches','g');
for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue;
const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
// The boxes sorted by POP once: the boxes racked at one POP change no other POP's plan.
*caches(X){const g=opsP('caches','g'),by=new Map();for(const x of S.caches){const a=by.get(x.city);if(a)a.push(x);else by.set(x.city,[x]);}
for(const c of opsPops('caches')){const add=cachePlan(c,by.get(c)||[]);if(!add||!add.length)continue;
const want=add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);}
yield;}},
// Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192).
ix(X){if(S.day%7&&!opsIs('annie'))return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');}
for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}},
// Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181).
*pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid');
*pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;
// The batch a few networks at a time; if the player acted in between (an action routes), it is made again in one go.
const g0=RW.gen,it=pniBatchRun(null,opsP('pni','tier'));let b;for(;;){const s=it.next();if(s.done){b=s.value;break;}yield;}
if(RW.gen!==g0)b=pniBatch(null,opsP('pni','tier'));if(!b)return;yield;const g=opsP('pni','g'),paid=opsP('pni','paid');
// The traffic a PNI there would take over: what your users at that POP send to the network today over transit, an
// exchange or a PNI elsewhere, the same figure the PNI list shows. Not the city's whole demand: a network's own
// cache boxes in that POP already serve most of it (#244).
const loc=q=>pniVal(q.net,q.city).want;
// pniVal()'s want, without the rest pniVal() prices (the transit it saves, the port): all the order asks (pniWant()).
const lv=new Map(),loc=q=>{let v=lv.get(q);if(v===undefined)lv.set(q,v=pniWant(q.city,q.net));return v;};
// Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift
// let a frame through or waited for a routing, and the batch's quote would order it a second time.
for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
@ -293,8 +304,15 @@ function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l||S.biz.som
return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});}
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first.
function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}}
const was=bz.filter(promiseCheck()),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(promiseCheck());}finally{S.links=all;}}
/* Those promises, asked for many customers on one network: each search is made once and shared (a diversity graph, the
land islands, one latency search per city a customer starts from). Same answers as diversePaths(), terrestrialPath()
and bestLat() asked one by one. */
function promiseCheck(){let dg=null,ti=null,lg=null;const dv=new Map(),ld=new Map();
const div=(a,b)=>{const k=a+'>'+b;let r=dv.get(k);if(r===undefined)dv.set(k,r=divOn(dg||(dg=divGraph()),a,b));return r;};
const land=(a,b)=>{if(a===b)return true;ti=ti||terrIslands();const A=ti.get(a);return A!==undefined&&A===ti.get(b);};
const lat=(a,b)=>{lg=lg||latGraph();if(!ld.has(a))ld.set(a,latRun(lg,a));return latAt(lg,ld.get(a),a,b);};
return b=>(b.reqs||[]).every(k=>k==='diverse'?div(b.city,b.city2):k==='sharks'?land(b.city,b.city2):k==='lat'?lat(b.city,b.city2)<=b.latMax:true);}
// The links between each pair of cities, VXCs left out.
function opsPairs(){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}return by;}
const opsDecomWaits=()=>[...opsPairs().values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'));

View file

@ -1,13 +1,14 @@
/* Single and bulk orders share the same checks, prices and provisioning. */
function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)tier=0;
// at: for a batch, where to look up the PNI there already is and the ports in use, which the batch itself never changes.
function pniQuote(city,net,tier,reserved=0,at=null){tier=+tier;const g1=tier===-1;if(g1)tier=0;
if(!S||!S.pops[city]||!isNet(net)||!NET[net].pops.includes(city)||!Number.isInteger(tier)||!PORT[tier]||(g1&&!pniG1(net)))return null;
const ex=S.pni.find(p=>p.city===city&&p.net===net);
const ex=at?at.ex(city,net):S.pni.find(p=>p.city===city&&p.net===net),used=at?at.used:portsUsed;
if(ex&&(g1||!pniOn(ex)||ex.up||(!(ex.g1&&tier===0)&&tier<=ex.tier)))return null;
const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1),slots=ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier);
let why='';if(!portOk(city,tier))why=tr('actions.your_router_can_t_take_a',{port:PORT[tier].n});
else{const r=peerOk(net,'pni',city);if(!r.ok)why=tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)});
else if(!g1&&tier<pniMin(net))why=tr('sites_peering_caches.net_does_not_do_port_pnis',{net:esc(NET[net].name),port:PORT[tier].n});
else if(slots>0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});}
else if(slots>0&&used(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(used(city)+reserved),m:portsMax(city)});}
return {city,net,tier,g1,ex,cost,slots,why};}
function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
@ -19,12 +20,18 @@ const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots
// A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say).
// Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them.
const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;};
function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null;
function pniBatch(net,tier){const g=pniBatchRun(net,tier);for(;;){const s=g.next();if(s.done)return s.value;}}
// The same batch with a place to let a frame through every few networks: the intern's weekly round (95-standing-orders.js).
function* pniBatchRun(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null;
const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0;
// Asked of every network at every shared POP: the PNIs by POP and network (the first one, as find() would), and the
// ports in use, counted for every POP in one pass the first time a quote needs them.
const exs=new Map();let use=null;for(const p of S.pni){const k=p.city+'|'+p.net;if(!exs.has(k))exs.set(k,p);}
const at={ex:(c,n)=>exs.get(c+'|'+n),used:c=>(use||(use=portsAt(Object.keys(S.pops)))).get(c)};
// Pending augments and earlier orders in this batch already own their future ports.
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+pniUpSlots(p);
for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
let nn=0;for(const n of all?NETS:[NET[net]]){if(++nn%16===0)yield;for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
// Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G.
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots;
mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);}
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0,at);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots;
mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);}}
return {shared,orders,blocked,kept,cost,mo,raised};}

View file

@ -8,12 +8,18 @@ function pniIdx(){if(PNIX&&PNIX.R===R)return PNIX;
const ix={},pn={};
for(const c in S.ixp){const nm=ixName(c);for(const id of ixSessions(c)){const a=ix[id]||(ix[id]=[]);if(!a.includes(nm))a.push(nm);}}
for(const p of S.pni)(pn[p.net]||(pn[p.net]=[])).push(p);
return PNIX={R,fl:{},ix,pn};}
return PNIX={R,fl:{},all:false,ix,pn};}
// One POP's flows by network, added up the first time that POP is asked about.
function pniFlows(c){const X=pniIdx();let m=X.fl[c];if(m)return m;m=X.fl[c]={};
for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;}
return m;}
// Every POP at once, in one pass over the flows: the intern's weekly PNI round asks about all of them, and one POP at a
// time was a pass per POP. The flows are read straight from routing's columns (R.flc), not made into the objects of R.fl
// (tens of thousands on a big network); each POP's sums still add up its flows in their order.
function pniFlows(c){const X=pniIdx();if(!X.all){X.all=true;const F=X.fl,C=R.flc;
const add=(c,n,rem,gt,gi,gp,gh,ti,ii)=>{const m=F[c]||(F[c]={});let o=m[n];if(!o)o=m[n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
o.u+=rem;o.t+=gt;o.ix+=gi;o.p+=gp;o.h+=gh;if(gt)o.T[ti]=(o.T[ti]||0)+gt;if(gi)o.I[ii]=(o.I[ii]||0)+gi;};
if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP,FGH,FTI,FII,E}=C;
for(let i=0;i<NF;i++)add(CITIES[FCI[i]].id,NET_IDS[FNJ[i]],FREM[i],FGT[i],FGI[i],FGP[i],FGH[i],FTI[i]<0?null:E[FTI[i]].id,FII[i]<0?null:E[FII[i]].id);}
else for(const f of R.fl||[])if(!f.junk)add(f.c,f.n,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii);}
return X.fl[c]||(X.fl[c]={});}
// One status, most direct first. c: the POP you are looking at (null: anywhere).
function pniStat(id,c){const X=pniIdx(),ps=X.pn[id]||[],h=c?ps.find(p=>p.city===c):null;
if(h)return {k:'here',p:h};
@ -33,6 +39,16 @@ function pniChip(id,c){const s=pniStat(id,c);let t;
/* What a new PNI with `id` at `c` would carry and save per month. It takes your users' traffic there that now
leaves over transit, an exchange or a PNI elsewhere, or does not leave at all for want of room, up to its port; transit is billed on the 95th percentile,
so the saving is the bill now minus the bill with that much less (commits included). */
/* pniVal()'s want for network n at POP c (what the intern's weekly round sorts by), without the rest pniFlows() keeps
for the PNI list: the same four sums of the same flows in the same order, in columns by (city, network). One pass,
no objects; null when routing left no columns (an old R), then pniFlows() it is. */
function pniWant(c,n){const X=pniIdx();if(X.w===undefined){const C=R.flc;X.w=null;
if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP}=C;let K=1;for(let i=0;i<NF;i++)if(FNJ[i]>=K)K=FNJ[i]+1;
const n4=CITIES.length*K,U=new Float64Array(n4),T=new Float64Array(n4),I=new Float64Array(n4),P=new Float64Array(n4);
for(let i=0;i<NF;i++){const k=FCI[i]*K+FNJ[i];U[k]+=FREM[i];T[k]+=FGT[i];I[k]+=FGI[i];P[k]+=FGP[i];}
X.w={K,U,T,I,P,ni:new Map(NET_IDS.map((id,j)=>[id,j]))};}}
const W=X.w;if(!W){const o=pniFlows(c)[n];return o?o.t+o.ix+o.p+o.u:0;}
const ci=CIDX[c],j=W.ni.get(n);if(ci===undefined||j===undefined||j>=W.K)return 0;const k=ci*W.K+j;return W.T[k]+W.I[k]+W.P[k]+W.U[k];}
function pniVal(id,c){const o=pniFlows(c)[id]||{t:0,ix:0,p:0,h:0,u:0,T:{},I:{}},want=o.t+o.ix+o.p+o.u;
const lo=pniMin(id);let tier=-1;for(let i=lo;i<PORT.length;i++)if(portShown(i)){tier=i;if(PORT[i].g*0.8>=want)break;}
if(tier<0)tier=lo;const g=Math.min(want,PORT[tier].g),gt=Math.min(o.t,g);let saved=0;

View file

@ -15,16 +15,26 @@ function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new
// city cannot even reach, and too few for the ones it uses most.
const cityShTab=c=>cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;
const cityNetSh=(c,id)=>(cityShTab(c)[id]||0)*(id==='ggl'&&ruCity(c)?0.5:1);
function cacheDem(c,id){const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;}
// A city's total share only depends on its table and on the Russian throttle, and the tables never change after load:
// summed once per kind of city, not once per network asked about (that was cities × networks² every shift).
const CSH_SUM=new Map();
function cityShSum(c){const T=cityShTab(c),k=ruCity(c)?1:0;let m=CSH_SUM.get(T);if(!m)CSH_SUM.set(T,m=[null,null]);
if(m[k]===null){let t=0;for(const id in T)t+=cityNetSh(c,id);m[k]=t;}return m[k];}
function cacheDem(c,id){const t=cityShSum(c);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;}
// One box per site first, if the city sends the network anything at all; then more boxes while that demand outgrows them
// (100G each, #248).
function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={};
for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;}
for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&cacheDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0);
// boxes: the city's own boxes in their order, when the caller has them sorted by city already (S.caches otherwise).
function cachePlan(city,boxes=S.caches){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={};
// One pass over the boxes: how many per network and site, and the capacity per network (summed in the same order).
const capN={};for(const c of boxes)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;capN[c.net]=(capN[c.net]||0)+cacheG(c);}
for(const n of NETS){if(!n.cache||!((R.demTo[n.id]||0)>=n.cache.min))continue;const dem=cacheDem(city,n.id);if(!(dem>1e-6))continue;const box=sites.map(st=>have[n.id+'@'+st]||0),a0=add.length;
sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}});
const dem=cacheDem(city,n.id),nb=cacheBox(city);
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
const nb=cacheBox(city);
let cap=(capN[n.id]||0)+(add.length-a0)*cacheG(nb);
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
return add;}
// The plan with its quote: the ports it takes and those free (counting ports walks the whole network), the monthly rent.
function utilityCaches(city){const add=cachePlan(city);if(!add)return null;
return {add,ports:cachePortsAdd(city,add),key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),free:Math.max(0,portsMax(city)-portsUsed(city))};}
function utilityKit(city){const p=S&&S.pops[city];if(!p)return null;
const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0;

View file

@ -2,7 +2,7 @@
// sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day.
const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;};
function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];}
function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);}
function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&!dfOn(l));}
function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);}
function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);}
// Monthly price of one connection; compute() sums these, the connections overview lists them.

View file

@ -25,22 +25,26 @@ const REQS={
TERR names the game and the routing count it was made for: an action between two steps of the day changes a link
only through after(), which routes, so the islands are worked out again; another game, and each question walks. */
let TERR=null;
function terrIslands(){const adj={};for(const l of S.links)if(!linkDown(l)&&!l.sub){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
function terrIslands(){const adj={};for(const l of S.links)if(!l.sub&&!linkDown(l)){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
const m=new Map();let n=0;for(const c in adj){if(m.has(c))continue;const q=[c];m.set(c,n);for(let h=0;h<q.length;h++)for(const v of adj[q[h]])if(!m.has(v)){m.set(v,n);q.push(v);}n++;}return m;}
function terrestrialPath(a,b){if(TERR&&TERR.S===S){if(TERR.gen!==RW.gen||!TERR.m){TERR.gen=RW.gen;TERR.m=terrIslands();}
if(a===b)return true;const A=TERR.m.get(a);return A!==undefined&&A===TERR.m.get(b);}const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
if(a===b)return true;const A=TERR.m.get(a);return A!==undefined&&A===TERR.m.get(b);}const ls=S.links.filter(l=>!l.sub&&!linkDown(l));const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b));
// Some requirements only make sense for some customers: nobody can reach another continent without getting wet.
const reqCan=(k,b)=>!REQS[k].can||REQS[k].can(b);
function reqList(o){return (o.reqs||[]).map(k=>{const ok=REQS[k].ok(o),lab=typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l;return `<div class="meta"><b style="color:${ok?'var(--eye)':'var(--bad)'}">${ok?'✓':'✗'}</b> ${esc(lab)}</div>`;}).join('');}
function diversePaths(a,b){
const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);
return disjointRoutes(a,b,S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)));}
function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));}
/* diversePaths(): a shortest path by hops over the live links (and VXCs to remote cities), then another one that shares
none of its risks. divGraph() numbers the cities and the risks and lists each city's links once, in list order, as
disjointOn() reads them; divOn() asks it, so many pairs on one network (spots0(), opsDecomSafe()) share one graph. The
second search skips the first path's risks rather than rebuilding the graph without them: the same lists in the same
order, so the same answer. */
const srlgOf=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
function divGraph(live){if(!live){const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));}
const ix=new Map(),rk=new Map(),adj=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=adj.length);adj.push([]);}return i;};
for(const l of live){const s=srlgOf(l);let r=rk.get(s);if(r===undefined)rk.set(s,r=rk.size);const u=id(l.a),v=id(l.b);adj[u].push(v,r);adj[v].push(u,r);}return {ix,adj};}
function divOn(g,a,b){if(a===b)return true;const i=g.ix.get(a),j=g.ix.get(b);return i!==undefined&&j!==undefined&&disjointOn(g.adj,i,j);}
function diversePaths(a,b){return divOn(divGraph(),a,b);}
function disjointRoutes(a,b,live){return divOn(divGraph(live),a,b);}
// Check buildable geography, not today's POPs, capacity or outages. Parallel land
// routes can use separate trenches; all segments of one cable share its risk.
let diversityMap=null;

View file

@ -53,7 +53,24 @@ function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let
function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`<p class="note">${landWhy(a,b)}</p>`:'';const wr=waveRoute(a,b,1,false);
const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} <small>${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms</small>`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} <small>${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}</small>`})));
return `<h4 class="sub4">${tr('common.route')}</h4><div class="seg">${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}</div>${wr&&wr.cab?`<p class="note">${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}</p>`:''}`;}
function bestLat(a,b,f){const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},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;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;}
/* bestLat(a,b,f): the lowest one-way latency over the live links (f: only those), +0.05 ms a hop. latGraph() numbers the
cities with a live link (ix) and lists each one's links once, in S.links order, with their latency (off/nb/w). latRun() is
the search itself: the next city is the closest found so far, the first found among equals, and the sums are the same
(d + latency + 0.05), so the same answers. Stopped at b, or run whole (no b): distances by city number, which is what
asking from a for several cities takes (latAt(): solRoutes(), spots0(), opsDecomSafe()). */
function latGraph(f){const ix=new Map(),deg=[],E=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=deg.length);deg.push(0);}return i;};
for(const l of S.links){if(linkDown(l)||f&&!f(l))continue;const u=id(l.a),v=id(l.b);E.push(u,v,linkLat(l));deg[u]++;if(v!==u)deg[v]++;}
const n=deg.length,off=new Int32Array(n+1);for(let i=0;i<n;i++)off[i+1]=off[i]+deg[i];const at=off.slice(0,n),nb=new Int32Array(off[n]),w=new Float64Array(off[n]);
for(let k=0;k<E.length;k+=3){const u=E[k],v=E[k+1];nb[at[u]]=v;w[at[u]++]=E[k+2];if(v!==u){nb[at[v]]=u;w[at[v]++]=E[k+2];}}return {ix,n,off,nb,w};}
function latRun(g,a,b){const s=g.ix.get(a),all=b===undefined;if(s===undefined)return all?null:a===b?0:Infinity;const t=all?-1:g.ix.get(b);if(t===undefined)return Infinity;
const {n,off,nb,w}=g,d=new Float64Array(n).fill(Infinity),seen=new Int32Array(n),done=new Uint8Array(n);let m=1;seen[0]=s;d[s]=0;
for(;;){let u=-1,ud=Infinity;for(let i=0;i<m;i++){const k=seen[i];if(!done[k]&&d[k]<ud){u=k;ud=d[k];}}if(u<0)break;if(u===t)return ud;done[u]=1;
for(let e=off[u];e<off[u+1];e++){const v=nb[e],nd=ud+w[e]+0.05;if(nd<d[v]){if(d[v]===Infinity)seen[m++]=v;d[v]=nd;}}}return all?d:Infinity;}
// From a whole run d out of a: the latency to b.
const latAt=(g,d,a,b)=>{if(a===b)return 0;const k=g.ix.get(b);return d&&k!==undefined?d[k]:Infinity;};
function bestLat(a,b,f){return latRun(latGraph(f),a,b);}
// From each of these cities to the ones after it in the list: [[a,b,ms]…], one search per city.
function latPairs(f,g){const G=latGraph(g),o=[];for(let i=0;i<f.length-1;i++){const d=latRun(G,f[i]);for(let j=i+1;j<f.length;j++)o.push([f[i],f[j],latAt(G,d,f[i],f[j])]);}return o;}
// The lowest one-way latency anything you could build gets between two cities (#273), the way bestLat() adds it up:
// your own fiber over land (×1.1, wherever isSub() allows it), or the route of a cable that lands at both ends (your own cable in the low-latency
// design follows it at 0.9 or better). A sea route that no cable takes needs a survey, so it does not count.

View file

@ -2,7 +2,8 @@
// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so
// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that
// way must be the day dayTick() plays, move for move, R.egDesc left out of the answers that repeat it and R.efg out of
// the posts that would only send the worker its own, and a frame let through in the middle of each day.
// the posts that would only send the worker its own, and a frame let through in the middle of each day. Also: the standing
// orders' cache planner, now linear, plans the same boxes as the old formula.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
@ -210,7 +211,7 @@ test('a customer dropped while a sales trial routes: the trial runs again on the
test("the intern's PNI round never orders again what the player ordered while it waited", (t) => {
// The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile.
const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true;
const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a);
const pb=pniBatchRun;pniBatchRun=function*(...a){const b=yield* pb(...a);window.__b=b;return b;};
window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0;
for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;}
window.__n=S.pni.length-n0;`;
@ -249,3 +250,61 @@ test('an incident repaired while its routing runs: the failure and the monkey st
assert.equal(p.ev('typeof __c.impact'), 'number');
assert.deepEqual(p.errors, []);
});
test('the cache planner plans what the old formula planned, city by city', (t) => {
const h = open(t, 777);
h.ev(SETUP);
// The formula as it was: the total share summed again for every network, the boxes filtered again for each.
h.ev(`window.oldDem=(c,id)=>{const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;};
window.oldPlan=city=>{const p=S.pops[city],sites=p.site2?['a','b']:['a'],add=[],have={};
for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;}
for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&oldDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0);
sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}});
const dem=oldDem(city,n.id),nb=cacheBox(city);
let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb);
while(cap+1e-9<dem){const i=box.indexOf(Math.min(...box));add.push({net:n.id,site:sites[i],...nb});box[i]++;cap+=cacheG(nb);}}
return add;};`);
// Some boxes gone, so there is something to plan; Russia, China and Korea's exit rule have tables of their own.
h.ev("S.caches=S.caches.filter((c,i)=>i%3);S.krExit=true;for(const c of ['mos','pek','icn'])if(!S.pops[c])S.pops[c]={day:0,bb:{d:1},boost:0,down:0,routers:2,gen:true,rgen:0,site2:true};compute();");
const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))'));
let boxes = 0;
for (const c of cities) {
const got = h.ev(`JSON.stringify(utilityCaches('${c}').add)`);
assert.equal(got, h.ev(`JSON.stringify(oldPlan('${c}'))`), c);
boxes += JSON.parse(got).length;
for (const id of JSON.parse(h.ev('JSON.stringify(NETS.map(n=>n.id))'))) if (h.ev(`cacheDem('${c}','${id}')!==oldDem('${c}','${id}')`)) assert.fail(`cacheDem ${c} ${id}`);
}
assert.ok(boxes > 50, `boxes planned: ${boxes}`);
assert.deepEqual(h.errors, []);
});
test('ports counted for every POP at once, and flows summed from the columns, are what each POP counted alone', (t) => {
const h = open(t, 777);
h.ev(SETUP);
// The old ways: one pass over the whole network per POP, and the flows as objects (R.fl).
h.ev(`window.oldPorts=(c,g)=>{let u=0;
for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);}
for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1);
for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1);
for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1);
if(S.myIx[c])u+=1;
u+=cachePorts(c,[],g)+(S.nni||[]).filter(x=>x.city===c).length;return u;};
window.oldFlows=c=>{const m={};for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}};
o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;}return m;};`);
const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))'));
for (const g of ['undefined', '0', 'RG.length-1']) {
const all = JSON.parse(h.ev(`JSON.stringify([...portsAt(Object.keys(S.pops),${g})])`));
assert.deepEqual(all, cities.map((c) => [c, h.ev(`oldPorts('${c}',${g})`)]), `ports, router model ${g}`);
}
assert.ok(h.ev('Object.keys(S.pops).some(c=>portsUsed(c)>10)'));
for (const c of cities) assert.equal(h.ev(`JSON.stringify(pniFlows('${c}'))`), h.ev(`JSON.stringify(oldFlows('${c}'))`), `flows from ${c}`);
assert.ok(h.ev('Object.keys(S.pops).some(c=>Object.keys(pniFlows(c)).length>5)'));
// The intern's weekly PNI round reads only pniVal()'s want, from typed columns (pniWant()): the very same numbers, for
// every network at every POP (and 0 where no flow goes).
const odd = h.ev(`(()=>{const bad=[];let n=0;for(const c in S.pops)for(const id of NET_IDS){const v=pniVal(id,c).want,w=pniWant(c,id);if(v>0)n++;
if(!Object.is(v,w))bad.push(c+'/'+id+' '+v+' '+w);}return JSON.stringify({n,bad:bad.slice(0,5)});})()`);
const r = JSON.parse(odd);
assert.deepEqual(r.bad, [], 'pniWant() is pniVal().want');
assert.ok(r.n > 50, `pairs with traffic: ${r.n}`);
assert.deepEqual(h.errors, []);
});

View file

@ -0,0 +1,69 @@
// A fiber's capacity added up per run of identical optics, "is this fiber lit?" answered without adding it up
// (dfOn(), linkDown()), and latency searches over one list of each city's links (latGraph(), latRun(), latPairs():
// bestLat(), the boutique's routes, latency offers). Same answers as before: the old ways are written out here.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// The fixture's links as the player's own dark fiber (it has none), lit with 2 to 40 channels of one or two optics.
const GLASS = "S.links.forEach((l,i)=>{l.kind='df';l.own=true;l.sys='roadm';l.ready=0;l.regen=3;const o=['zr4','zr8','tp16','tp32'][i%4];l.ch=Array.from({length:2+i%39},(_,j)=>i%5===0&&j%3===0?'zr4':o);delete l.tier;})";
// Before: every channel's optG() added up, and the search that walked every link for every city it reached.
const OLD = `window.oldCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,Math.max(0,g)-mwG(l));};
window.oldLat=(a,b,f)=>{const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},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;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;};`;
// Seeded trouble on the fibers: cuts, a failed optic (named or not, over or not, maybe the only one), equipment down, still building,
// channels taken out or mixed, a subsea upgrade in service, managed waves sold on it (sometimes more than it carries).
const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day;
for(const l of S.links){const r=rnd();if(r<.06)l.cut=D+5;else if(r<.14){if(rnd()<.4)l.ch=l.ch.slice(0,1);l.chFail={o:rnd()<.5&&l.ch.length?l.ch[l.ch.length-1]:rnd()<.5?'tp32':null,until:rnd()<.8?D+3:D-1};}
else if(r<.18)l.eqDown=D+2;else if(r<.22)l.ready=D+4;else if(r<.28)l.ch=l.ch.slice(0,Math.floor(rnd()*3));else if(r<.32)l.ch=l.ch.map((c,i)=>i%2?c:'zr8');
else if(r<.36){l.sub=true;l.km=2000+Math.floor(rnd()*9000);if(rnd()<.5)l.subterminal=D-1;if(rnd()<.5)l.subengineering=D-1;}
if(rnd()<.15)S.biz.push({type:'mwave',link:l.id,slots:1+Math.floor(rnd()*30),g:rnd()<.5?100:400});}})()`;
test('a fiber is lit, and carries, what adding up every channel said', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${GLASS};${OLD}`);
let lit0 = 0, dark = 0;
for (let v = 0; v < 6; v++) {
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(v)};S.day+=${v}`);
const r = JSON.parse(ev(`JSON.stringify(S.links.map(l=>[oldCap(l),dfCap(l),dfOn(l),linkDown(l),l.cut>S.day]))`));
for (const [want, cap, on, down, cut] of r) {
assert.equal(cap, want);
assert.equal(on, want > 0);
assert.equal(down, cut || !(want > 0));
if (on) lit0++; else dark++;
}
}
assert.ok(lit0 > 600 && dark > 30, `lit ${lit0}, dark ${dark}`);
assert.deepEqual(errors, []);
});
test('latency searches give what walking every link gave: bestLat, every pair at once, the boutique\'s routes', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
const P = "Object.keys(S.pops).slice(0,25).concat(FIN.filter(c=>S.pops[c]))";
const check = (f) => JSON.parse(ev(`(()=>{const P=${P},f=${f},bad=[];let n=0;
for(let i=0;i<P.length;i++)for(let j=i+1;j<P.length;j++){const w=oldLat(P[i],P[j],f);if(bestLat(P[i],P[j],f)!==w)bad.push(P[i]+'-'+P[j]);if(isFinite(w))n++;}
for(const [a,b,ms] of latPairs(P,f))if(ms!==oldLat(a,b,f))bad.push('pairs '+a+'-'+b);return JSON.stringify({n,bad:bad.slice(0,5)});})()`));
// Leased waves, then some cut, then the player's own glass in trouble.
let r = check('null');
assert.deepEqual(r.bad, []);
assert.ok(r.n > 150, `pairs with a path: ${r.n}`);
ev("S.links.forEach((l,i)=>{if(i%4===0)l.cut=S.day+3;})");
r = check("l=>l.kind!=='vxc'");
assert.deepEqual(r.bad, []);
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(2)};S.mode='normal';delete S.scn;S.charter='boutique'`);
r = check('ownGlass');
assert.deepEqual(r.bad, []);
assert.ok(r.n > 50, `pairs over own glass: ${r.n}`);
// The boutique's routes: each financial pair, its own glass against the best leased latency. In trouble, then not.
const SOL = `(()=>{const f=FIN.filter(c=>S.pops[c]),v=[];for(let i=0;i<f.length;i++)for(let j=i+1;j<f.length;j++){const a=f[i],b=f[j],o=oldLat(a,b,ownGlass),l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&o<l)v.push({a,b,o,l});}return JSON.stringify(v);})()`;
assert.equal(ev('SOLC=null;JSON.stringify(solRoutes())'), ev(SOL));
ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};S.mode='normal';delete S.scn;S.charter='boutique'`);
const want = ev(SOL);
assert.equal(ev('SOLC=null;JSON.stringify(solRoutes())'), want);
assert.ok(JSON.parse(want).length >= 1, `routes that beat leased: ${want}`);
assert.deepEqual(errors, []);
});

View file

@ -37,7 +37,7 @@ test('Annie peers every day and orders PNIs twice a week; the others weekly', t
ev("S.ops.on.ix=true;S.day=15;opsDay(S.day)");
assert.equal(ev('Object.keys(S.rs).length>0'), want, `${id} on a Tuesday`);
// How often the PNI order looks for networks to order from, over one week.
ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};if(typeof pniBatchRun==='function')pniBatchRun=function*(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}");
assert.equal(ev('__pb'), want ? 2 : 1, `${id}: PNI rounds a week`);
assert.deepEqual(errors, []);
}

View file

@ -0,0 +1,88 @@
// Diverse paths, a land path and a latency budget asked for many pairs on one network: the offers spotted for
// sovereign clouds (spots0()) and the intern's check before taking a wave out (opsDecomSafe()) build one graph per
// network and ask it for every pair (divGraph()/divOn(), promiseCheck()). Same answers as before: the old ways are
// written out here.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
// Before: each question filtered the links again and built both searches' graphs from lists.
const OLD = `window.oldDiv=(a,b)=>{const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));
const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);}
const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}}
if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;};
const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));};
window.oldLand=(a,b)=>{const adj={};for(const l of S.links.filter(l=>!l.sub&&!linkDown(l))){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}
const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;};
window.oldLat=(a,b)=>{const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},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;if(u===b)return ud;done.add(u);for(const l of ls){if(l.a!==u&&l.b!==u)continue;const v=l.a===u?l.b:l.a,nd=ud+linkLat(l)+0.05;if(nd<(dist[v]??Infinity))dist[v]=nd;}}return Infinity;};
window.oldSafe=l=>{const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}};`;
// Seeded trouble: cuts, POPs down, trenches shared by several links, a VXC to a city with no POP.
const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day;
for(const l of S.links)if(rnd()<.1)l.cut=D+3;for(const c in S.pops)if(rnd()<.06)S.pops[c].down=D+2;
const ls=S.links.filter(l=>!l.sub);for(let i=${v};i<ls.length;i+=6)ls[i].trench='shared'+(i%3);
const p=FABS.find(f=>f.cities.some(c=>S.pops[c])&&f.cities.some(c=>!S.pops[c]));if(p&&${v}%2){const a=p.cities.find(c=>S.pops[c]),b=p.cities.find(c=>!S.pops[c]);
S.links.push({id:'vx'+${v},a,b,kind:'vxc',prov:p.id,vt:'1g',km:kmBetween(a,b),sub:isSub(a,b),mo:1,cut:0,day:0});}})()`;
test('diverse paths: one graph for every pair answers like a search per pair, and spots the same sovereign clouds', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
let yes = 0, no = 0;
for (let v = 0; v < 6; v++) {
ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''}`);
const r = JSON.parse(ev(`(()=>{const C=Object.keys(S.pops).filter((c,i)=>i%3===0).concat(S.links.filter(l=>l.kind==='vxc').map(l=>l.b),['nowhere']),g=divGraph(),bad=[];let y=0,n=0;
for(const a of C)for(const b of C){const w=oldDiv(a,b);if(diversePaths(a,b)!==w||divOn(g,a,b)!==w)bad.push(a+'-'+b);w?y++:n++;}
const by={};for(const c of Object.keys(S.pops).filter(bizCity))(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c);const sov=[];
for(const cs of Object.values(by))for(let i=0;i<cs.length;i++)for(let j=i+1;j<cs.length;j++)if(oldDiv(cs[i],cs[j]))sov.push(cs[i]+'-'+cs[j]);
const got=spots0(0).filter(s=>s.t==='sov').map(s=>s.a+'-'+s.b);return JSON.stringify({y,n,bad:bad.slice(0,5),sov,got});})()`));
assert.deepEqual(r.bad, [], `state ${v}`);
assert.deepEqual(r.got, r.sov, `sovereign clouds, state ${v}`);
yes += r.y; no += r.n;
}
assert.ok(yes > 300 && no > 1000, `diverse ${yes}, not ${no}`);
assert.deepEqual(errors, []);
});
test('taking a wave out: the shared check refuses what asking customer by customer refused, for each promise', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`);
// Customers between linked POPs: diverse paths, afraid of sharks, a latency budget just above today's best.
const BIZ = `(()=>{const ls=S.links.filter(l=>S.pops[l.a]&&S.pops[l.b]);let n=0;for(let i=0;i<ls.length;i+=2){const l=ls[i],k=['diverse','sharks','lat'][n%3],b={id:'pc'+n++,city:l.a,city2:l.b,type:'l2',bw:1,reqs:[k]};
if(k==='lat')b.latMax=+(bestLat(l.a,l.b)+0.02).toFixed(2);if(k!=='lat'||isFinite(b.latMax))S.biz.push(b);}})()`;
const refused = { diverse: 0, sharks: 0, lat: 0 };
for (let v = 0; v < 4; v++) {
ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''};${BIZ}`);
// From a few hubs to every POP: several customers of one city, some served and some not.
const hub = JSON.parse(ev(`(()=>{const P=Object.keys(S.pops),H=P.filter((c,i)=>i%25===0);let n=0;for(const a of H)for(const b of P)if(a!==b)for(const k of ['diverse','sharks','lat']){const o={id:'hb'+n++,city:a,city2:b,type:'l2',bw:1,reqs:[k]};
if(k==='lat')o.latMax=n%2?oldLat(a,b):oldLat(a,b)*0.995;S.biz.push(o);}
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true);
const pc=promiseCheck(),bz=S.biz.filter(b=>/^hb/.test(b.id)),w=bz.map(chk);S.biz=S.biz.filter(b=>!/^hb/.test(b.id));
return JSON.stringify({bad:bz.filter((b,i)=>pc(b)!==w[i]).map(b=>b.id).slice(0,5),yes:w.filter(Boolean).length,n:w.length});})()`));
assert.deepEqual(hub.bad, [], `hubs, state ${v}`);
assert.ok(hub.yes > 50 && hub.n - hub.yes > 50, JSON.stringify(hub));
const r = JSON.parse(ev(`(()=>{const bad=[],why=[],all=S.biz;for(const l of S.links.slice(0,60)){const w=oldSafe(l);if(opsDecomSafe(l)!==w)bad.push(l.id);
if(!w)for(const k of ['diverse','sharks','lat']){S.biz=all.filter(b=>/^pc/.test(b.id)&&b.reqs[0]===k);if(!oldSafe(l))why.push(k);S.biz=all;}}
return JSON.stringify({bad,why});})()`));
assert.deepEqual(r.bad, [], `state ${v}`);
for (const k of r.why) refused[k]++;
}
for (const k in refused) assert.ok(refused[k] >= 2, `refused for ${k}: ${JSON.stringify(refused)}`);
assert.deepEqual(errors, []);
});
test('latency searches at the edges: a city with no link, the same city twice, a city nobody reaches', () => {
const { ev, errors } = load({ seed: 3 });
ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();`);
const r = JSON.parse(ev(`(()=>{const lone=CITIES.find(c=>!S.links.some(l=>l.a===c.id||l.b===c.id)).id,p=S.links[0].a,g=latGraph(),d=latRun(g,p);
return JSON.stringify([bestLat(lone,lone),bestLat(p,p),bestLat(lone,p),bestLat(p,lone),latRun(g,lone),latAt(g,d,p,p),latAt(g,d,p,lone),latAt(g,null,lone,p),
latPairs([lone,p,lone]).map(x=>x[2])]);})()`));
assert.deepEqual(r, [0, 0, null, null, null, 0, null, null, [null, 0, null]]);
assert.deepEqual(errors, []);
});