diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a20e42..d07d4f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- 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 - New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e7d386..e9ba500 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -134,9 +134,11 @@ 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). + 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. 5. Updates customer mood, churn and new offers; IX members join; loans tick. 6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy. 7. Checks goals, level, badges and scenario end conditions. diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js index 8712607..c7b7789 100644 --- a/src/game/10-catalog/40-ports.js +++ b/src/game/10-catalog/40-ports.js @@ -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; diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 8fd1c7b..8d63b91 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -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]}); diff --git a/src/game/60-features/36-specialist.js b/src/game/60-features/36-specialist.js index f3803d2..c5cb569 100644 --- a/src/game/60-features/36-specialist.js +++ b/src/game/60-features/36-specialist.js @@ -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;iS.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=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;iS.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)&&oS.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. diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 90a2ba1..4071caa 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -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(ldACT.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(ldS.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()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')); diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js index 1e42650..30a7918 100644 --- a/src/game/70-rules/35-pni-orders.js +++ b/src/game/70-rules/35-pni-orders.js @@ -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&&tier0&&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};} diff --git a/src/game/70-rules/38-pni-value.js b/src/game/70-rules/38-pni-value.js index 193e8bc..5d5d22c 100644 --- a/src/game/70-rules/38-pni-value.js +++ b/src/game/70-rules/38-pni-value.js @@ -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;ip.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=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[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=want)break;} if(tier<0)tier=lo;const g=Math.min(want,PORT[tier].g),gt=Math.min(o.t,g);let saved=0; diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index 5e3718c..b007039 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -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-9c.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; diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index b7dae0d..ddf1633 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -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. diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index 8e3aab0..d1e35fb 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -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!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 `
${ok?'✓':'✗'} ${esc(lab)}
`;}).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; diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index 72c8f0f..6e5ee0c 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -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?`

${landWhy(a,b)}

`:'';const wr=waveRoute(a,b,1,false); const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} ${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} ${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'):''}`}))); return `

${tr('common.route')}

${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}
${wr&&wr.cab?`

${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}

`:''}`;} -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]{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{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 { // 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;`; @@ -239,3 +240,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-9i%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, []); +}); diff --git a/tests/fiber-lit-and-latency.test.js b/tests/fiber-lit-and-latency.test.js new file mode 100644 index 0000000..c924927 --- /dev/null +++ b/tests/fiber-lit-and-latency.test.js @@ -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] `(()=>{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 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= 1, `routes that beat leased: ${want}`); + assert.deepEqual(errors, []); +}); diff --git a/tests/intern-personas.test.js b/tests/intern-personas.test.js index f663cf1..e157c96 100644 --- a/tests/intern-personas.test.js +++ b/tests/intern-personas.test.js @@ -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, []); } diff --git a/tests/shared-promise-checks.test.js b/tests/shared-promise-checks.test.js new file mode 100644 index 0000000..9ced4d0 --- /dev/null +++ b/tests/shared-promise-checks.test.js @@ -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]{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};if.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;is.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{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, []); +});