diff --git a/CHANGELOG.md b/CHANGELOG.md index 738b54e..a22a7d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,20 +6,24 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The game no longer freezes while it routes each day's traffic on big networks. A background thread of the game does the routing, so the map, panels and buttons keep responding while days go by; what the day brings is exactly what it was before. Clicks that change your network still route right away. + +## [2.4.0] — 2026-11-01 + +- Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again. +- Doitsche Telekomm and Tangerine Telecom are now Tier 1s, as in real life (#194). In new games, going transit-free means a PNI with both of them too; games you already started keep the Tier 1s they were playing for. Doitsche now sells transit at the highest price in Europe and still charges for peering, and like the other Tier 1s, Tangerine now starts its PNIs at 100G. +- Cache boxes now share router ports through an aggregation switch: one port carries as many 100G boxes as its speed holds, so 32 fit on a 3.2T port (#252). Each site gets its own. +- Pick a standard POP: in any POP's Infra tab, make its routers the standard, and every new POP gets that model and number of routers right away, while it is still empty (#240). +- Big networks run faster: routing skips traffic it has already placed, the map skips links off screen without working out their shape, and the Networks tab and the zoomed-in map draw faster. Where traffic goes does not change. - A network the game once failed to load is no longer stuck as damaged: the next version of the game tries it again, and its menu has a Try again button. Before, it could only be exported or deleted, even after the cause was fixed. - Save files of very large networks import again: the limit went from 8 MB to 64 MB. -- Big networks run faster: routing skips traffic it has already placed, the map skips links off screen without working out their shape, and the Networks tab and the zoomed-in map draw faster. Where traffic goes does not change. - 400G cache boxes: a POP whose routers have 400G or faster ports now gets 400G boxes, at $1,000 a month instead of $400 for 100G, so big caches need fewer boxes and cost less per Gbps. Boxes you already have stay as they are. -- Pick a standard POP: in any POP's Infra tab, make its routers the standard, and every new POP gets that model and number of routers right away, while it is still empty (#240). - Clarovision now peers only over paid PNIs, like the real carrier, and free only with networks at customer level 11 or above (#213). A PNI you already have with it starts paying the fee. -- Cache boxes now share router ports through an aggregation switch: one port carries as many 100G boxes as its speed holds, so 32 fit on a 3.2T port (#252). Each site gets its own. - Opening a link from a list now moves the map to it, zoomed so the whole line fits beside the open panel. - Traffic for a carrier now leaves through that carrier's own transit port at the same POP, instead of being shared with every other transit port there. Networks that buy transit from the carrier get the same treatment, and a new switch on each transit port, Carry here, pulls that traffic across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win, and Prefer only does so at the POP where you set it. -- Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again. - When every ship of a region's club is out, a subsea cut waits for the first one back. A private charter of the quickest free ship anywhere jumps the queue for $1M plus $200 per km it sails; the NOC intern's rush-repair order can pay it within its budget. - Building your own subsea cable now shows the survey, permits and cable factory first, then a lay ship laying about 150 km a day. Crews can no longer speed up a cable at sea: book a second lay ship before laying starts instead, for $3M plus $150k a day, and it lays from the other end to halve that part. - Tap a cable ship on the map to see its name, its club and what it is doing. -- Doitsche Telekomm and Tangerine Telecom are now Tier 1s, as in real life (#194). In new games, going transit-free means a PNI with both of them too; games you already started keep the Tier 1s they were playing for. Doitsche now sells transit at the highest price in Europe and still charges for peering, and like the other Tier 1s, Tangerine now starts its PNIs at 100G. ## [2.3.0] — 2026-10-31 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 469afbc..d3b7cad 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -141,6 +141,29 @@ link) is only put together for a link when something reads it. Served share per city (`sfOf`) drives eyeball revenue and customer mood. +## Routing in a worker + +During play, each day's `compute()` runs off the main thread (`src/game/80-simulation/28-route-worker.js`), so a big +network does not freeze the page once a day. + +- **Built from the page itself.** The worker is the page's own inline game script (`document.currentScript.textContent`) + run again from a Blob URL, after a short prelude of inert stand-ins for `document`, storage and the other DOM globals, + and the player's dictionary. Nothing is fetched: GitHub Pages still serves one page, and a release cannot mismatch. + In the worker `RW_IN` is true and `boot()` never runs; the catalogs are rebuilt by the same top-level code. +- **The day split.** `dayTick()` is `dayPre()` (the world moves on), `compute()`, `dayPost()` (bills, moods, offers, + goals). In play, `frame()` calls `rwDay()` instead: `dayPre()`, then S and what routing reads of yesterday's R + (`R.load`, `R.l2route`, `R.efg`) are posted, and the next day waits until R comes back and `dayPost()` has run. So a day + sees exactly the routing it would have had in one go: same results, same random numbers. Half a day is never saved. +- **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays + transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. +- **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's + answer is stale: it is dropped and the day ends with the action's R. +- **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a + post that fails or a worker that errors take the synchronous path (`rwKill()` routes the day in flight on the page). +- **Still on the main thread**, because the caller reads R right away: actions (`after()`), loading a game, failures and + events that fire during a day, standing orders, the chaos monkey, RouteScript what-ifs, the link panel's cut check and + automatic offers. + ## Actions and rendering - Player actions live in `ACT`. Buttons render as `btn(label, act, args, cls, disabled)` diff --git a/package-lock.json b/package-lock.json index 27ac0d2..63a1bf4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "2.3.0", + "version": "2.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "2.3.0", + "version": "2.4.0", "license": "MIT", "devDependencies": { "jsdom": "24.1.3", diff --git a/package.json b/package.json index de5c794..4de598b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "2.3.0", + "version": "2.4.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", diff --git a/src/game/80-simulation/28-route-worker.js b/src/game/80-simulation/28-route-worker.js index e1f45a9..ec8fdc9 100644 --- a/src/game/80-simulation/28-route-worker.js +++ b/src/game/80-simulation/28-route-worker.js @@ -30,7 +30,7 @@ function rwDay(){const d=dayPre();if(d===false)return;const w=rwStart(); if(!w){compute();dayPost(d);rwDayDone();return;} const t=performance.now(),seq=++RW.seq; // The worker also needs what compute() reads from yesterday's R: link loads, and the scenic circuits' paths. - try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:R.efg||null});}catch(e){console.error('[tubes] route worker post',e);rwKill();compute();dayPost(d);rwDayDone();return;} + try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)});}catch(e){console.error('[tubes] route worker post',e);rwKill();compute();dayPost(d);rwDayDone();return;} const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,d,gen:RW.gen,t:t1};} function rwDone(m){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now(); if(m.err){console.error('[tubes] route worker',m.err);compute();} @@ -38,22 +38,19 @@ function rwDone(m){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const const t1=performance.now(),st=RW.stat;st.n++;st.apply+=t1-t;st.wait+=t-j.t;st.work+=m.ms||0; try{dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();} function rwDayDone(){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}} -/* R as plain data. R.ef is lazy getters over typed arrays (sent as the raw pieces, the arrays moved, not copied); - R.fl's flows point at exit lists with functions in them; an attack record points at its attack in S. */ +/* R as plain data. R.ef and R.fl are lazy getters, sent as the pieces they are built from (R.efp, R.flc, see efBuild() + and flDefine() in 30-compute.js), their typed arrays moved, not copied. Exits become their ids (all R.fl reads), and an + attack record names its attack in S by id. */ +const FL_COLS=['FREM','FCI','FNJ','FCA','FBZ','FGT','FGI','FGP','FGH','FTI','FII']; function rwPack(R){const o={};for(const k in R)o[k]=k==='ef'?0:k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k]; - const p=R.efp,F=rwFlPack(R.fl||[]);o.fl=F;return {o,p,tr:[p.ACN.buffer,p.ACD.buffer,F.num.buffer,F.idx.buffer]};} -/* Flows as columns (tens of thousands of objects cost more to clone than routing saves): only what the PNI list - reads (38-pni-value.js), turned back into objects the first time something asks for R.fl. */ -function rwFlPack(fl){const n=fl.length,num=new Float64Array(n*5),idx=new Int32Array(n*5),ids=[],idOf=new Map(),id=x=>{if(x==null)return -1;let k=idOf.get(x);if(k===undefined){idOf.set(x,k=ids.length);ids.push(x);}return k;}; - for(let i=0;ifl||(fl=rwFlUnpack(F))}); + const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>({id:e.id}))},tr=[p.ACN.buffer,p.ACD.buffer];for(const k of FL_COLS)tr.push(c[k].buffer); + return {o,p:{...p,flc:c},tr};} +function rwUnpack(o,p){o.ef={};efBuild(o,p.L,p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc); const as=ddosAll(S,false);for(const m of o.ddos){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();}return o;} +// Yesterday's egress sums for scenic routing, as plain data (EgSums is a class; a clone would lose its get()). +const rwEfgOut=efg=>{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[k].t;return o;}; +const rwEfgIn=o=>{const efg={};for(const k in o)efg[k]=new EgSums(o[k]);return efg;}; // In the worker: route the state it was sent, answer with R. -function rwServe(m){try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};if(m.efg)Object.defineProperty(R,'efg',{value:m.efg}); +function rwServe(m){try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)}); const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);postMessage({seq:m.seq,R:o,ef:p,ms},tr);} catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 75168e7..5c4cfdd 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -2,12 +2,23 @@ const LABS=new Map();function labOf(s,k,v){const key=s+'|'+v;let o=LABS.get(key);if(o===undefined)LABS.set(key,o=tr(s,{[k]:v}));return o;} // Who carries a network reached only through a cone (kept out of compute(), whose size the JIT is sensitive to). function coneBy(L,id){let by=null;for(const e of L){if(e.k==='p')return e.net;if(!by&&e.k==='ix'&&e.dir)by=ANC[id].find(u=>e.dir.has(u))||null;}return by||1;} -/* R.ef from what routing added up per edge (L: [link id, edge index, egress map, network keys, source cities]). Also - rebuilds it from a worker's answer (35-route-worker.js), which sends these plain pieces: getters do not cross. */ -function efBuild(R2,L,ACN,ACD,NKN,NC,NN){const efg={};for(const [id,i,g,n,d] of L){let rec=null;efg[id]=g; - Object.defineProperty(R2.ef,id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,v] of g)rec.eg[k]=v; - for(const j of n)rec.net[j{const a=new A(c);if(o)a.set(o);return a;}; + FLB.rem=g(Float64Array,FLB.rem);FLB.ci=g(Int32Array,FLB.ci);FLB.nj=g(Int32Array,FLB.nj);FLB.ca=g(Uint8Array,FLB.ca);FLB.bz=g(Uint8Array,FLB.bz);FLB.cap=c;} +// R.efg[link]: what each egress put on that link, read by scenic routing the next day (t.g gives each egress its slot in t.v). +class EgSums{constructor(t){this.t=t;}get(k){const s=this.t.g.get(k);return s===undefined?undefined:this.t.v[s];}} +/* R.ef and R.efg from what routing added up per edge (L: [link id, edge index, its sums t]), and R.fl from the flow + columns (c). Also how a route worker's answer is put back together (28-route-worker.js): getters do not cross + threads, so it sends these plain pieces (R.efp, R.flc) and the page rebuilds the same lazy R. */ +function efBuild(R2,L,ACN,ACD,NKN,NC,NN){const efg={};for(const [id,i,t] of L){let rec=null;efg[id]=new EgSums(t); + Object.defineProperty(R2.ef,id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,s] of t.g)rec.eg[k]=t.v[s]; + for(const j of t.n)rec.net[je.ok(net)). const okBy={};for(const id of NET_IDS)okBy[id]=[]; - const ekN={};for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} + const okAdd=(e,n)=>{const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}; + // TSL: a slot per transit port id, for what it carries to each network (R.tNet, added up in TNA). + const ekN={},TSL=new Map();for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. - for(const e of E){e.J=0;e.byC=null;e.desc=null;e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}} + for(const e of E){e.J=0;e.byC=null;e.desc=null;e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;e.ts=-1;if(e.k==='t'){let t=TSL.get(e.id);if(t===undefined)TSL.set(e.id,t=TSL.size);e.ts=t;} + // Index loops or forEach (same order): for…of here made an iterator result per exit and network. + const ns=e.nets||NET_IDS;if(Array.isArray(ns)){for(let q=0;qokAdd(e,n));} for(const n of NETS){let any=false,nt=false;for(const e of okBy[n.id])if(e.rank>0){any=true;if(e.k!=='t'){nt=true;break;}}R2.reachable[n.id]=any;if(any)R2.reach+=NSH[n.id];if(nt){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id]; // Reached without transit only through the customers of networks you peer with (#85). R.cone[id]: the peer that // carries it, the first PNI's network or else the nearest upstream that is a member of an exchange you are on. if(!okBy[n.id].some(e=>(e.k==='p'||e.k==='ix')&&!coneOf(e,n.id)))R2.cone[n.id]=coneBy(okBy[n.id],n.id);}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); - // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). - const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j],f={c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j,gt:0,gi:0,gp:0,gh:0,ti:null,ii:null,br:null};flows.push(f);return f;}; + /* Flows are columns, not objects (tens of thousands of them on a big network): flow F starts in city FCI[F] for network + index FNJ[F] and has FREM[F] left to place. Gathered in FLB here, then copied into this call's own columns below. */ + FLB.n=0;const NN=NETS.length,CNB=[],NCN=NETS.map(n=>!!n.cn),flow=(ci,j,rem,cache,bz)=>{const k=FLB.n;if(k===FLB.cap)flbGrow();FLB.rem[k]=rem;FLB.ci[k]=ci;FLB.nj[k]=j;FLB.ca[k]=cache?1:0;FLB.bz[k]=bz?1:0;FLB.n=k+1;}; // Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give). const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}} // Traffic shares by network index, and their sums, for each share table (and with Russia's throttle). @@ -72,17 +88,21 @@ function compute(){RW.gen++; const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?sa[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; for(let j=0;jday?ev.pmtud:null,kr=CITY[c].kr; for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; // With `protect customers`, the business part first, then the rest (no arrays: this runs per city and network). const bf=d0>0?biz/d0:0,sp=!!(TRX&&TRX.protect&&bf>0),cn2=cacheNets.has(n.id); - for(let q=0;q<(sp?2:1);q++){const x=sp?(q?a*(1-bf):a*bf):a,bz=sp&&!q;if(x<=0)continue;if(cn2){flow(c,ci,cn,j,x*0.85,true,false,bz);flow(c,ci,cn,j,x*0.15,false,false,bz);} - else flow(c,ci,cn,j,x,false,false,bz);}} + for(let q=0;q<(sp?2:1);q++){const x=sp?(q?a*(1-bf):a*bf):a,bz=sp&&!q;if(x<=0)continue;if(cn2){flow(ci,j,x*0.85,true,bz);flow(ci,j,x*0.15,false,bz);} + else flow(ci,j,x,false,bz);}} R2.bizDem[c]=biz*d/(d0||1);R2.bizSrv[c]=0; } if(Object.keys(S.pops).length)for(let j=0;j=1;if(CORE)for(const c of pops){const i=CIDX[c];PASS[i]=corePass(c);OUT[i]=inCore(c)?0:1;} const nodeTake=(i,a)=>{NRES[i]-=a;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;}; + const TNA=new Float64Array(TSL.size*NN),TNS=new Uint8Array(TSL.size*NN),TNK=[],TORD=[]; const NKN=NN+2,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[]; - const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),n:[],d:[]};EL.push(l);}t.g.set(eg,(t.g.get(eg)||0)+a); + // t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum). + const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=a; let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;}; R2.l2route={};R2.l2split={}; /* compute() reads only S, except here: scenic circuits remember yesterday's path in R.l2route and R.efg (deliberate @@ -163,61 +185,65 @@ function compute(){RW.gen++; const DIR=directSetup(E,NC),PREFC=DIR.prefc,dirOf=DIR.dirOf,DSEL=new Map(); const RANKS=TR?[0,0.5,1,2,CONE_RANK,2.9,2.92,2.93,2.94,2.95,3,3.5,4,4.4,4.5,4.6]:[0,1,2,CONE_RANK,2.92,2.93,2.94,2.95,3,4]; // With `protect customers`, business flows take every rank first; home users get what is left. - const PASSES=TR&&TR.protect?[x=>x.bz,x=>!x.bz]:null; + // Passes by FBZ: 0 every flow, 1 business only, 2 the rest. + const PASSES=TR&&TR.protect?[1,2]:[0]; // Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order. // Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order. // With several islands (POPs no backbone joins), each list is split by island: a flow only scans exits it can reach. const idx=L=>{L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}; // Networks with the same exits at a rank share one list (LIST, by content), so what one flow learns serves them all. const LIST=new Map();for(let i=0;ie.xi).join(','),o=LIST.get(key);if(o){m[r]=o;continue;} let V=L;if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);V={cs};}else idx(L);LIST.set(key,V);m[r]=V;}} // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. - let f=null,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[]; + // F: its index; fci, fnj: its city and network index. + let F=0,fci=0,fnj=0,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[]; // An exit the flow can still try: not visited yet, not full when the flow started, reachable, and not on a saturated path. const usable=e=>e.vis!==vis&&e.useda.hp-b.hp||Dv[a.ci]-Dv[b.ci]; - // Push up to `want` along one path to exit e; returns what fitted. Capacity only shrinks while routing, so a + // Push up to `want` along one path to exit e; returns what fitted. Index loops: for…of allocates an iterator until optimised. Capacity only shrinks while routing, so a // path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing // (most tries are into paths that filled up earlier). const push=(e,P,want,keep=0)=>{if(P.dead)return 0;const path=P.path,ni=P.ni;let amt=want; - for(const l of path){const r=l.res;if(r<=1e-6){P.dead=1;return 0;}amt=Math.min(amt,r-l.cap*keep);} + const PN=path.length;for(let k=0;kx.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);} - SRV[f.ci]+=ok;R2.served+=ok;if(f.bz)R2.bizSrv[f.c]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok;} + SRV[ci]+=ok;R2.served+=ok;if(bz)R2.bizSrv[CITIES[ci].id]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const k=e.ts*NN+nr;if(!TNS[k]){TNS[k]=1;if(!TNK[e.ts]){TNK[e.ts]=[];TORD.push(e);}TNK[e.ts].push(nr);}TNA[k]+=ok;} // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays, // Korean users notice any exit far away, transit or not, and much sooner. - if(path.length&&(e.k==='t'||snd&&CITIES[f.ci].kr)){let ms=P.ms;if(ms===undefined){ms=0;for(const l of path)ms+=l.lat;P.ms=ms;}const rtt=2*ms,kl=snd&&CITIES[f.ci].kr; - if(rtt>(kl?KR_LAT_OK:LAT_OK)){LATP[f.ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,f.ci,e.ci);}P.fg+=ok;}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok; + if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr)){let ms=P.ms;if(ms===undefined){ms=0;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)){LATP[ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[nr]||(NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok; // Where each flow left (the PNI list asks what a PNI here would take over, #175). - if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(f.ci);if(v){v[0]+=ok;if(f.bz)v[1]+=ok;}else m.set(f.ci,[ok,f.bz?ok:0]);} - if(e.k==='t'){f.gt+=ok;f.ti=e.id;}else if(e.k==='ix'){f.gi+=ok;f.ii=e.id;}else if(e.k==='p'){if(e.net===f.n&&e.city===f.c)f.gh+=ok;else f.gp+=ok;}} + if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);} + if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}} return amt; }; // Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths // with free capacity, as long as they are no more than twice as long. const send=(e,want)=>{ - let room=Math.min(want,f.rem,e.cap-e.used);if(room<=1e-6)return; - const P=PP[e.ci]||(PP[e.ci]=walkI(Pv,f.ci,e.ci));if(!P.dead)room-=push(e,P,room,TE&&SPILL<1?1-SPILL:0); - if(TE&&room>1e-6&&f.rem>1e-6&&e.used1e-6;k++){const P=altPath(f.ci,e.ci,Dv[e.ci]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;} + let room=Math.min(want,FREM[F],e.cap-e.used);if(room<=1e-6)return; + const P=PP[e.ci]||(PP[e.ci]=walkI(Pv,fci,e.ci));if(!P.dead)room-=push(e,P,room,TE&&SPILL<1?1-SPILL:0); + if(TE&&room>1e-6&&FREM[F]>1e-6&&e.used1e-6;k++){const P=altPath(fci,e.ci,Dv[e.ci]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;} }; // Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over // them by free capacity (like several transits in one city), then top up in order if one fills. // The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order). // Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes). const gone=e=>{if(TE)return false;const P=PP[e.ci];return !!P&&P.dead===1;}; + // Every exit of a remembered group still has room (a loop, not every(): no closure per flow). NOG: no group. + const allRoom=c=>{for(let k=0;k{for(let k=i0;k1){let tot=0;for(let k=i0;k1e-6)for(let k=i0;k1){let tot=0;for(let k=i0;k1e-6)for(let k=i0;k{const n=a.length;if(n>24){a.sort(byDist);return;}for(let i=1;i=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}}; @@ -226,32 +252,31 @@ function compute(){RW.gen++; // networks that have an exit there, and nothing from a POP where Prefer has the say; a port that is not set to carry only takes // its own POP's traffic. Kept in a function of its own so the loop below stays as it was: the JIT is sensitive to its shape. const directPass=(rank,pass)=>{const DS=DSEL.get(rank),LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1]; - for(let fi=0,FN=AF.length;fi1e-6;){let j=i+1;while(j1e-6;){let j=i+1;while(je.used=e.cap||gone(e)){full++;continue;}const d=Dv[e.ci];if(d===Infinity)continue;const h=e.hp; if(h=lst.length&&full){let k=0;for(let li=0;li1){gc[f.ci]=[];continue;} - if(G.length>1)sortD(G);gc[f.ci]=G.slice();}} + if(bh>1){gc[fci]=NOG;continue;} + if(G.length>1)sortD(G);gc[fci]=G.slice();}} sendGroup(G,0,G.length); - if(f.rem<=1e-6)continue; + if(FREM[F]<=1e-6)continue; REST.length=0;for(let li=0;li1e-6;){ + for(let i=0;i1e-6;){ let j=i+1;while(j1e-6)rem+=f.rem;if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;} + if(DD){let rem=0,jf=0;for(let i=0;i1e-6)rem+=FREM[i];if(JK)for(const k in edges){const e=edges[k];if(e.res<=1e-6&&e.jk)jf+=e.jk;} ddosAfter(DD,{E,R2,squeeze:Math.min(rem,jf), lost:(ci,x,y,e)=>{SRV[ci]-=x;R2.served-=x;const c=CITIES[ci].id;if(y)R2.bizSrv[c]-=y;R2.egT[e.k]-=x;if(e.rank<=2)R2.peered-=x;}});} for(const c of Object.keys(S.pops)){const i=CIDX[c];R2.citySrv[c]=SRV[i]; @@ -288,9 +313,10 @@ function compute(){RW.gen++; for(const o of G.values()){const c=CITIES[o.src].id,cur=R2.latFar[c];if(!cur||o.g>cur.g)R2.latFar[c]={to:CITIES[o.to].id,g:o.g,ms:o.ms,share:SRV[o.src]>0?o.g/SRV[o.src]:0};}} // R.ef is read for the link you inspect: each edge's record is put together the first time it is asked for. Scenic // routing only needs the egress amounts, so R.efg keeps those as they are (not listed, so R reads the same). - efBuild(R2,EL.map(l=>[l.id,l.i,l.tr.g,l.tr.n,l.tr.d]),ACN,ACD,NKN,NC,NN); + efBuild(R2,EL.map(l=>[l.id,l.i,l.tr]),ACN,ACD,NKN,NC,NN); // Active links fill first, by capacity; standby links take what is left over. for(const k in edges){const e=edges[k],ld=e.ld||0,ac=e.cap-e.scap,a=Math.min(ld,ac),sp=ld-a;for(const l of e.links){const c=capOf(l);R2.load[l.id]=l.standby?(e.scap>0?sp*c/e.scap:0):(ac>0?a*c/ac:0);}} + for(const e of TORD){const m=R2.tNet[e.id]={},b=e.ts*NN;for(const j of TNK[e.ts])m[NET_IDS[j]]=TNA[b+j];} R2.peerShare=R2.served>0?R2.peered/R2.served:0; for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;} // money @@ -312,5 +338,7 @@ function compute(){RW.gen++; C.revshare=(S.loans||[]).reduce((a,l)=>a+(BANKS[l.bank].equity||l.bal>0?l.share||0:0),0)*(V.eyeballs+V.business+V.ix); R2.costMo=Object.values(C).reduce((a,b)=>a+b,0); R2.revMo=V.eyeballs+V.business+V.ix+V.grant; - Object.defineProperty(R2,'fl',{value:flows});R=R2;UI.hotMap=hotByCity(); + // R.fl: from this call's own columns, made into objects only when something asks. + flDefine(R2,{NF,FREM,FCI,FNJ,FCA,FBZ,FGT,FGI,FGP,FGH,FTI,FII,E,CNB,NCN}); + R=R2;UI.hotMap=hotByCity(); } diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index d15bc61..096f6d2 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -6,16 +6,16 @@ module.exports = ` // A carrier's own port (dr) is also a plain transit exit. A POP with a Prefer-marked transit port keeps what Prefer // says, and a port not set to carry only takes its own POP's traffic. const PH=new Set(E.filter(x=>x.k==='t'&&x.pref==='high').map(x=>CIDX[x.city])); - const dr=(e,f)=>{if(e.k!=='t'||PH.has(f.ci)||eff(e,f.n)!==3)return 0;const t=directTier(e.net,f.n);return t?DIRECT_RANK[t][e.carry?0:1]:0;}; - for(const pass of PASSES||[null])for(const rank of RANKS){ - for(f of flows){ - if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue; - Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++; - const candidates=E.filter(e=>e.used{if(e.k!=='t'||PH.has(ci)||eff(e,n)!==3)return 0;const t=directTier(e.net,n);return t?DIRECT_RANK[t][e.carry?0:1]:0;}; + for(const pass of PASSES)for(const rank of RANKS){ + for(F=0;Fe.used(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]); - for(let i=0;i1e-6;){ + for(let i=0;i1e-6;){ let j=i+1;while(j{window.__got=m;};"); - ev("{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:R.efg};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}"); + ev("{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}"); ev("R=rwUnpack(structuredClone(__got.R),__got.ef)"); const fromWorker = ev(SIG); ev('R=__R0;S=JSON.parse(__S0);compute()'); diff --git a/tests/routing-reference.test.js b/tests/routing-reference.test.js index 14c5eed..850a21a 100644 --- a/tests/routing-reference.test.js +++ b/tests/routing-reference.test.js @@ -23,7 +23,7 @@ function network(ev) { // Share the model and path sender, but replace indexed exit selection with // the original full scan and stable sort for every flow. const source = ev('compute.toString()'); - const start = source.indexOf(' for(const pass of PASSES||[null])for(const rank of RANKS){'); + const start = source.indexOf(' for(const pass of PASSES)for(const rank of RANKS){'); const end = source.indexOf(' for(const i of NORD)', start); assert.ok(start >= 0 && end > start, 'allocation loop boundaries must exist'); ev(`window.referenceCompute=eval('('+${JSON.stringify(source.slice(0,start)+referenceAllocation+source.slice(end))}+')')`); diff --git a/tests/speed.test.js b/tests/speed.test.js index 2b03e05..b3ac6f4 100644 --- a/tests/speed.test.js +++ b/tests/speed.test.js @@ -272,17 +272,17 @@ test('the map is not drawn while the dashboard covers the whole screen', () => { function plainCompute(ev) { const src = ev('compute.toString()'); let plain = src - .replace('if(!lst.hi&&ALONE[f.ci])', 'if(false)') + .replace('if(!lst.hi&&ALONE[fci])', 'if(false)') .replace('if(!G.length){\n // One scan', 'if(false){\n // One scan') - .replace('for(const n of e.nets||NET_IDS)', 'for(const n of NET_IDS)') + .replace('const ns=e.nets||NET_IDS;', 'const ns=NET_IDS;') .replace('if(P.dead)return 0;', '').replaceAll('if(r<=1e-6){P.dead=1;return 0;}', '') .replace('if(!P.dead)room-=push(', 'room-=push(').replace(/const gone=e=>\{[^\n]*\};/, 'const gone=e=>false;'); // ...and the group split and sorting written the plain way, with array copies, as before they were made allocation-free const sg = plain.indexOf('const ROOM=[],sendGroup='), sd = plain.indexOf('const sortD='); assert.ok(sg > 0 && sd > sg, 'found the group sender and the sort'); plain = plain.slice(0, sg) + `const ROOM=[],sendGroup=(g0,i0=0,i1=g0.length)=>{const g=g0.slice(i0,i1);for(const e of g)e.vis=vis; - if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=f.rem;if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));} - for(const e of g){if(f.rem<=1e-6)break;send(e,f.rem);}};\n ` + plain.slice(sd).replace(/^const sortD=a=>\{[^\n]*\};/, 'const sortD=a=>a.sort(byDist);'); + if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=FREM[F];if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));} + for(const e of g){if(FREM[F]<=1e-6)break;send(e,FREM[F]);}};\n ` + plain.slice(sd).replace(/^const sortD=a=>\{[^\n]*\};/, 'const sortD=a=>a.sort(byDist);'); for (const [a, b] of [[src, plain]]) assert.notEqual(a, b); assert.equal((plain.match(/if\(false\)/g) || []).length, 2, 'both shortcuts were found and switched off'); assert.ok(!plain.includes('e.nets||NET_IDS'), 'the exit index was switched off');