From 9bdc2b70e16fea89304def64a72090588c3c8615 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sun, 1 Nov 2026 15:04:45 +0100 Subject: [PATCH] Prototype: route each game day in a Web Worker built from the page's own script The day is split around its routing (dayPre, compute, dayPost). In play, S goes to a worker started from a Blob URL of the page's inline game script (nothing fetched), the day waits for R and finishes when it arrives. Actions, failures, events and the intern still route synchronously; an action mid-day wins over the worker's stale answer. R crosses as plain data: R.ef as its raw arrays (transferred), flows as columns. Tests and any worker failure keep the synchronous path. --- src/game/80-simulation/28-route-worker.js | 59 +++++++++++++++++++++++ src/game/80-simulation/30-compute.js | 13 +++-- src/game/88-days/10-day-tick.js | 10 ++-- src/game/91-save.js | 2 + src/game/99-loop.js | 9 ++-- tests/route-worker.test.js | 48 ++++++++++++++++++ 6 files changed, 130 insertions(+), 11 deletions(-) create mode 100644 src/game/80-simulation/28-route-worker.js create mode 100644 tests/route-worker.test.js diff --git a/src/game/80-simulation/28-route-worker.js b/src/game/80-simulation/28-route-worker.js new file mode 100644 index 0000000..e1f45a9 --- /dev/null +++ b/src/game/80-simulation/28-route-worker.js @@ -0,0 +1,59 @@ +/* Routing off the main thread (prototype, perf idea 3). The worker is this page's own game script run a second time + from a Blob URL: nothing is fetched, so GitHub Pages still serves one page. In the worker, DOM globals are inert + stand-ins and boot() never runs; the catalogs (cities, networks, cones) are rebuilt from the same code. + Only the day uses it: dayPre(), then S goes to the worker, the day waits (no next day starts) and dayPost() runs + when R is back, so a day sees exactly the routing it would have had in one go. An action in between routes + synchronously as always (compute() bumps RW.gen); then the worker's answer is stale and the action's R stands. + Tests (no Worker in jsdom, __TUBES_TEST__) and any worker failure take the synchronous path. */ +const RW_IN=!!self.__TUBES_WORKER__; +const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null; +const RW={w:null,dead:false,seq:0,gen:0,job:null,stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}}; +function rwOn(){return !RW_IN&&!RW.dead&&!window.__TUBES_TEST__&&!window.__TUBES_SYNC__&&typeof Worker==='function'&&!!RW_EL;} +function rwStart(){if(RW.w)return RW.w; + try{const L=LANG,dict=L!=='en'&&window.I18N[L]?JSON.stringify(window.I18N[L]):'null'; + const pre=`'use strict';self.__TUBES_WORKER__=1;self.window=self; +const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true}); +const _st={getItem:()=>null,setItem(){},removeItem(){},key:()=>null,length:0}; +Object.assign(self,{document:_n,localStorage:_st,sessionStorage:_st,requestAnimationFrame:()=>0,cancelAnimationFrame(){},innerWidth:1280,innerHeight:800,devicePixelRatio:1, + matchMedia:()=>({matches:false,addEventListener(){},addListener(){}}),Image:_n,Audio:_n,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},SOT_LANG:${JSON.stringify(L)},SOT_LANGS:{},I18N:{}}); +if(${dict})self.I18N[${JSON.stringify(L)}]=${dict}; +`; + const url=URL.createObjectURL(new Blob([pre,RW_EL.textContent,'\n;self.onmessage=e=>rwServe(e.data);'],{type:'text/javascript'})); + const w=RW.w=new Worker(url);URL.revokeObjectURL(url); + w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();}; + }catch(e){console.error('[tubes] no route worker',e);rwKill();} + return RW.w;} +// Gone for good this session: the day it was routing is routed here instead. +function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;RW.job=null;if(j){try{compute();dayPost(j.d);}catch(e){tickErr(e);}rwDayDone();}} +// One day in play: the first half here, the routing in the worker, the second half when it answers. +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;} + 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();} + else if(RW.gen===j.gen){R=rwUnpack(m.R,m.ef);UI.hotMap=hotByCity();} + 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. */ +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 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;} +// 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}); + 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 6f3a334..75168e7 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -2,7 +2,13 @@ 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;} -function compute(){ +/* 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[jadj[CIDX[p]]=[]); @@ -282,10 +288,7 @@ function compute(){ 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). - {const efg={};for(const l of EL){const t=l.tr,i=l.i;let rec=null;efg[l.id]=t.g; - Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,v] of t.g)rec.eg[k]=v; - for(const j of t.n)rec.net[j[l.id,l.i,l.tr.g,l.tr.n,l.tr.d]),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);}} R2.peerShare=R2.served>0?R2.peered/R2.served:0; diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index dd909f4..195d1e2 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -1,6 +1,9 @@ /* ---------- daily tick ---------- */ -function dayTick(){ - if(!S||S.lost||!rule('clock'))return; // no clock (puzzles): no days, no bills, nothing fires +/* A day is two halves around its routing: dayPre() (the world moves on), compute(), dayPost() (bills, moods, offers). + In play the routing can run in a worker in between (28-route-worker.js); tests and the fallback run it in one go. */ +function dayTick(){const d=dayPre();if(d===false)return;compute();dayPost(d);} +function dayPre(){ + if(!S||S.lost||!rule('clock'))return false; // no clock (puzzles): no days, no bills, nothing fires S.day++; const d=S.day; dkTick(d);ixPriceWar(d);peeringDeskDay(d);pniDay(d);mergerDay(d); @@ -27,7 +30,8 @@ function dayTick(){ for(const c in S.pops){const p=S.pops[c];if(!p.bb)continue;const sf=sfOf(R,c)*((R.bbF&&R.bbF[c])??1),P=eyeP(c); if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);} else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));} - compute(); + return d;} +function dayPost(d){ ddosNews();ddosTrack(); for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} S.cash+=(R.revMo-R.costMo)/30; diff --git a/src/game/91-save.js b/src/game/91-save.js index 9737d78..49edca6 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -5,6 +5,8 @@ /* A puzzle is never saved: only its stars are, under their own key (sot-puzzles). While one runs, the network it set aside (UI.pzKeep) is the one saved, to its own slot, so closing the tab mid-puzzle loses nothing. */ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot; + // Half a day (its routing still in the worker) is never saved: the day's end saves instead. + if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;} if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return; if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st; if(!force&&failed&&performance.now()-f.at5000)save(); // The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them. if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} - if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} - if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}} + if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0; + // With the route worker one day is in flight at a time; time does not pile up behind it. + if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}} + else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} + if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}} if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ const t=animOn()?animT:0; if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;} @@ -47,4 +50,4 @@ function boot(data){ window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} } -slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); +if(!RW_IN)slotBoot(()=>window.claude?.hot?.ready ? window.claude.hot.ready(boot) : boot(window.claude?.hot?.data ?? {})); diff --git a/tests/route-worker.test.js b/tests/route-worker.test.js new file mode 100644 index 0000000..7a2f7e8 --- /dev/null +++ b/tests/route-worker.test.js @@ -0,0 +1,48 @@ +// The route worker (src/game/80-simulation/28-route-worker.js): jsdom has no Worker, so these check the parts that +// decide whether its answer is the same as routing on the page: R packed, cloned the way postMessage clones it, and +// unpacked gives the same R; a day split around its routing is the same day; tests stay on the synchronous path. +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 BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.close()); + h.dom.window.structuredClone = globalThis.structuredClone; // what postMessage does between the threads + h.ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false;compute();`); return h; }; +// R with its lazy parts (R.ef, R.fl) read out, attacks by id. +const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()"; + +test('R packed, cloned and unpacked is the same R, lazy parts and key order included', (t) => { + const { ev, errors } = big(t); + const want = ev(SIG); + ev("{const {o,p,tr}=rwPack(R);const c=structuredClone({o,p},{transfer:tr});R=rwUnpack(c.o,c.p);UI.hotMap=hotByCity();}"); + assert.equal(ev(SIG), want); + assert.equal(ev('pniFlows(Object.keys(S.pops)[0])!==null'), true, 'the PNI list reads the unpacked flows'); + assert.deepEqual(errors, []); +}); + +test('the worker side routes what it is sent: same R as routing on the page', (t) => { + const { ev, errors } = big(t); + // rwServe() in the page itself stands in for the worker: it posts back what the worker would. + ev("window.__got=null;window.postMessage=(m)=>{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("R=rwUnpack(structuredClone(__got.R),__got.ef)"); + const fromWorker = ev(SIG); + ev('R=__R0;S=JSON.parse(__S0);compute()'); + assert.equal(ev('JSON.stringify(S)'), ev('__S0'), 'routing does not change S'); + assert.equal(ev(SIG), fromWorker); + assert.deepEqual(errors, []); +}); + +test('a day split around its routing is the same day; tests never use the worker', (t) => { + const a = big(t), b = big(t); + for (const h of [a, b]) h.ev('S.nextFail=S.nextEvent=S.day+99;__reseed(4242)'); + a.ev('for(let i=0;i<3;i++)dayTick()'); + b.ev('for(let i=0;i<3;i++){const d=dayPre();compute();dayPost(d);}'); + const st = "JSON.stringify({day:S.day,cash:S.cash,moods:S.biz.map(b=>b.mood),offers:S.offers.length,served:R.served})"; + assert.equal(b.ev(st), a.ev(st)); + assert.equal(a.ev('rwOn()'), false); + assert.deepEqual([...a.errors, ...b.errors], []); +});