diff --git a/CHANGELOG.md b/CHANGELOG.md index 783e390..e1c5a6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running. + ## [3.0.0] — 2026-11-06 **Series of Tubes 3.0: Pie in the Sky.** You have wired up the planet with fiber, cables and routers. Now take your network to orbit: start your own rocket company, fill the sky with satellites (we call them pies) and sell internet to everyone your cables will never reach. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 77b2a1e..73b9566 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -34,7 +34,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`) | | `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service | -| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) | +| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `failureRun()`/`fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) | | `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` | | `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers | | `91-save.js`, `92-audio.js` | Save, export and import; sound effects | @@ -103,20 +103,37 @@ Lookup tables built at load: `CITY[id]`, `NET[id]`, `CABLE`, `FAB`, `BIZ_T`, `RE ## The life of a day -`frame()` (requestAnimationFrame) accumulates time; every `DAY_MS × speed` it calls -`dayTick()`, at most four times per frame, each inside a try/catch so one bad tick -never freezes the game. +`frame()` (requestAnimationFrame) accumulates time (`runClock()`); every `DAY_MS × speed` it starts a day, inside a +try/catch so one bad tick never freezes the game. In play the day runs with the route worker (below), one day in flight +at a time: the clock waits for the day, never the other way round, so a machine that cannot keep up at ×8 plays slower +instead of freezing to catch up. Without a worker it calls `dayTick()`, at most four times per frame. -`dayTick()`: +A day is a generator, `dayRun()` (`src/game/88-days/10-day-tick.js`): `dayPreRun()` (the world moves on), then +`dayPost()`, and the intern's shift (`opsRun()`) and the sales desk's (`slAutoRun()`) inside it are generators too. Each +`yield` is a `compute()` the day needs before it goes on: the day's own routing, then a recompute after failures and +events, and after the intern's jobs. `dayTick()` (tests, the fallback) answers each one with `compute()` on the spot +(`dayGo()`); in play the route worker answers them. `yield DAY_REST` is not a routing, only a place where a long day may +let a frame through. Same steps, same random numbers either way: routing draws none. Nothing of a day routes on the page: +a failure (`failureRun()`; `fireFailure()` plays one at once through `runNow()`), a DDoS and Auto-RTBH (`ddosNewsRun()`), +the chaos monkey's snip (`mkSnipRun()`), an event's cut (`eventRun()`: its routing is deferred to the next yield) and the +sales desk's trials (a `{trial}` yield the worker answers with yes or no, `offerTrial()`) are all steps. The intern's +orders are generators too, with a rest after each job. `UI.tick` (what the day itself announces, which quiet +notifications may keep to the NOC log) is set around every step (`dayStep()`), on both sides of the worker. + +The daily mood check asks "a path without subsea" for each customer that wants one: during that loop the land-connected +islands are worked out once (`TERR`, `terrIslands()`), and two cities have a land path when they share one. + +The day: 1. Advances `S.day`, runs scheduled world events (conferences, IX price wars, licences). 2. Runs `compute()` to route today's traffic. 3. Records history for 95th-percentile billing, stats and streaks. -4. Rolls failures (`fireFailure()`) and events (`fireEvent()`) when their timers run out, +4. Rolls failures (`failureRun()`) and events (`fireEvent()`) when their timers run out, and expires incidents. - Then the NOC intern's standing orders (`opsDay()`), if one is hired: each order clicks the same `ACT` - actions a player would, muted, within its monthly budget, and the shift recomputes once at the end, only if - a job changed the network. An order that throws is paused; the day goes on. The NOC gets one notice a week. + 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. Then the sales desk (`slAutoDay()`), if someone runs sales and the player lets them sign: deals are Sales', never the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything). 5. Updates customer mood, churn and new offers; IX members join; loans tick. @@ -179,10 +196,14 @@ network does not freeze the page once a day. 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. +- **The day in steps.** In play, `frame()` calls `rwDay()`, which runs `dayRun()` (see "The life of a day") with + `rwGo()`: the steps run on the page up to a yield, then S and what routing reads of yesterday's R (`R.load`, + `R.l2route`, `R.efg`) are posted, and the day goes on in `rwDone()` when R comes back. The next day waits until the + last step has run. So a day sees exactly the routing it would have had in one go: same results, same random numbers. + At a `DAY_REST`, a day that has run `RW.budget` ms (half a frame, 3 to 8) already goes on after the next frame + (`RW.later`, `rwLater()`), so a phone gets its frames between the steps of a big network's day. Half a day is never + saved; nothing else starts meanwhile. `tests/day-steps.test.js` plays a second page as the worker and compares every + day with `dayTick()`. - **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 @@ -190,8 +211,8 @@ network does not freeze the page once a day. - **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. + RouteScript what-ifs and the link panel's cut check. Everything a day routes (failures, events, DDoS, the chaos monkey, + the intern's shift, the sales desk's trials) is a yield of the day, so it goes to the worker. ## Actions and rendering @@ -294,5 +315,5 @@ assert.deepEqual(errors, []); ``` `ev()` runs code inside the page. To force a specific random failure, patch the -picker, e.g. evaluate `fireFailure` with `.replace('const e=pick(opts);', "const e='x';")`. +picker, e.g. evaluate `failureRun` with a `.replace(…)` and play it with `runNow(…)` (it is a generator). Use `window.__reseed(n)` to reset the random sequence mid-test. diff --git a/src/game/60-features/39-sales-auto.js b/src/game/60-features/39-sales-auto.js index 11f3b81..09497c0 100644 --- a/src/game/60-features/39-sales-auto.js +++ b/src/game/60-features/39-sales-auto.js @@ -24,18 +24,25 @@ function slWeekLine(x,last){const parts=[];if(x.n)parts.push(trn('sales.w_signed const v={name:tr(SALES[x.p].s),list:parts.join(', ')};return last?tr('sales.w_last',v):tr('sales.w_now',v);} // An orbit offer fits where its dish has room for it; used: what this shift already signed on each dish. function slSkyOk(o,used){const L=pieServe(o.city,o.type);if(!L)return null;const k=L.cr+'|'+L.k;return slP()==='shark'||L.left-(used.get(k)||0)>=o.bw?k:null;} -function slAutoDay(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7); +// Like a day, the desk is a generator: a routing trial is a step the day answers (in play, the route worker does). +const slAutoDay=d=>dayGo(slAutoRun(d),(g,v)=>g.next(v)); +function* slAutoRun(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.floor(d/7); // A new week: last week's tally becomes the report, and the one notice of the week. if(!A.wk||A.wk.w!==w){if(slWkAny(A.wk)&&A.wk.w${esc(tr('sales.desk'))} ${esc(slWeekLine(A.rep,true))}`,A.rep.rev>0?'good':'',[],{a:'tab',v:'deals'});}A.wk={w,p,n:0,rev:0,x:0,y:0};} const W=A.wk,used=new Map();W.p=p;let tries=0,dirty=false; const tried=UI.slTried&&UI.slTried.s===S?UI.slTried.m:(UI.slTried={s:S,m:new Map()}).m; const won=o=>{if(S.offers.includes(o))return false;W.n++;W.rev+=Math.round(bizMo(o));dirty=true;return true;}; - opsQuiet(()=>{for(const o of S.offers.slice()){if(!S.offers.includes(o))continue;const T=BIZ_T[o.type];if(!T||!(o.exp>d))continue;const v=T.event?(o.fee||0):bizMo(o); - if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}continue;} - if(!A.on)continue; - if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))continue;ACT.accept({id:o.id});won(o);continue;} - // Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week. - if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)continue;tries++;ACT.accept({id:o.id,auto:true});if(!won(o))tried.set(o.id,d);}}); - if(dirty)compute();} + for(const o of S.offers.slice()){ + // What this offer needs, muted: nothing, or a routing trial (b), which the day answers between the two quiet steps. + let b;const todo=opsQuiet(()=>{if(!S.offers.includes(o))return;const T=BIZ_T[o.type];if(!T||!(o.exp>d))return;const v=T.event?(o.fee||0):bizMo(o); + if(A.min&&vb0){W.y++;W.rev+=Math.round(bizMo(o));dirty=true;}return;} + if(!A.on)return; + if(T.orbit){const k=slSkyOk(o,used);if(!k||(p==='shark'&&S.cashd)))return;ACT.accept({id:o.id});won(o);return;} + // Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week. + if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)return;tries++;b=offerTrialOf(o);return true;}); + if(!todo)continue; + const got=b?yield {trial:b,hx:offerHealthy(b)}:null; + opsQuiet(()=>{OFFER_TRIED={o,b:got};try{ACT.accept({id:o.id,auto:true});}finally{OFFER_TRIED=null;}if(!won(o))tried.set(o.id,d);});} + if(dirty)yield;} diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js index 0bb5dc9..79ef239 100644 --- a/src/game/60-features/90-automation.js +++ b/src/game/60-features/90-automation.js @@ -1,12 +1,24 @@ /* The sales engine of #185: would this offer work if signed now? The sales desk runs it once a day (39-sales-auto.js). It trials the new demand on a copy of the game, so a failed trial leaves the live game untouched. */ function offerCustomer(o){return {id:o.id,city:o.city,city2:o.city2||null,reqs:o.reqs||[],latMax:o.latMax||null,route:BIZ_T[o.type].scenic?'scenic':BIZ_T[o.type].lat?'fast':'normal',name:o.name,type:o.type,bw:o.bw,rate:o.rate,mood:100,since:S.day,sites:o.sites||null,start:o.start,dur:o.dur,fee:o.fee,link:o.link,slots:o.slots||0,what:o.what,prov:o.prov,due:BIZ_T[o.type].cap?S.day+o.win:undefined};} -function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; +// OFFER_TRIED: the answer of a trial the intern's sales order already ran for this offer (the customer, or null). +let OFFER_TRIED=null; +function autoOffer(o){if(OFFER_TRIED&&OFFER_TRIED.o===o)return OFFER_TRIED.b;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;} +// The checks on the live game, and the customer the offer would be: null when there is nothing to trial. +function offerTrialOf(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null; const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null; if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id; if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;} + return b;} +const offerFuture=()=>S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); +// Who is happy today (indices in S.biz), the one thing the trial reads from the live result: null when future events +// make the trial route without the offer first and judge on that. +const offerHealthy=b=>{if(offerFuture())return null;const h=[];S.biz.forEach((x,i)=>{if(!bizWhy(x).length)h.push(i);});return h;}; +/* The trial: the game routed with the customer added, on a copy, S and R put back after. It reads nothing else of the + live result than hx (offerHealthy()), so the route worker can run it on the game it is sent (28-route-worker.js). */ +function offerTrial(b,hx){const T=BIZ_T[b.type],start=b.start; const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day); // Trial the added demand before signing; failed trials leave the live game untouched. try{S={...S,biz:S.biz}; @@ -19,6 +31,6 @@ function autoOffer(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.ra if(!all.some(x=>x.route==='scenic')){if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=all;compute();if(bizWhy(b).length)return null; const bad=fut.filter(x=>bizWhy(x).length);if(!bad.length)return b;S.biz=fut;compute();return bad.every(x=>bizWhy(x).length)?b:null;} compute();} - const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); + const healthy=hx&&!future?hx.map(i=>S.biz[i]):S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute(); return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null; - }finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}} + }finally{S=state;R=result;UI.hotMap=hot;b.start=start;if(T.cap)delete b.live;}} diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index f852910..f95b30f 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -124,10 +124,11 @@ function opsTransitOk(n,c){if(n.id==='cog'&&(scnRule('spat')||S.ev.depeer>S.day) const cheapestTransit=c=>NETS.filter(n=>sellsAt(n,c)&&opsTransitOk(n,c)).sort((a,b)=>transitPerG(a,c,premOnlyAt(a,c))-transitPerG(b,c,premOnlyAt(b,c)))[0]; // 'cheap' and 'have' (Already connected) name no network: quote the cheapest seller (#249). const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;return n&&sellsAt(n,c)&&opsTransitOk(n,c)?n:cheapestTransit(c);}; -// The orders. Each takes the shift and does its jobs through the player's own actions. +// The orders. Each takes the shift and does its jobs through the player's own actions. Most are generators: a yield +// 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');}, - routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'); + *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'); for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; const ld=Math.max((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));if(ld=0&&rgOpen(nx)&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt=4||!add);if(!doSwap&&(how==='swap'||!add))continue; const cost=doSwap?swapCost(c,nx):routerCost(g,rt);if(!X.can('routers',cost))continue; - if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));}}, - transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'); + if(X.pay('routers',()=>doSwap?ACT.upRouter({city:c,g:nx}):ACT.addRouter({city:c})))X.did('routers',c+(doSwap?' ⇧'+RG[nx].pn:' +1'));yield;}}, + *transit(X){if(scnRule('noTransit'))return;const N=opsP('transit','x'); for(const c of opsPops('transit')){let ts=S.transit.filter(t=>t.city===c);if(!ts.length)continue; // Thirty days of 95th-percentile-ish history per port; their peaks summed is a safe (high) estimate of the POP's peak. const peak=ts.reduce((a,t)=>a+(t.hist||[]).reduce((m,v)=>Math.max(m,v),0),0);if(!(peak>0))continue; @@ -154,11 +155,11 @@ const OPS_RUN={ else{const need=N*peak-cap,ok=PORT.map((P,i)=>i).filter(i=>portShown(i)&&portOk(c,i)),i=ok.find(i=>PORT[i].g>=need)??ok.at(-1); if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};}} if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break; - X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);}}}, + X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);yield;}}}, // PNIs and IX ports keep Headroom times today's traffic, hottest first. One port at a POP with several routers gets a // second in a LAG, so it is not the only way out; anything else moves up to the smallest port size that fits. A PNI // augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for. - ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[], + *ports(X){if(ddosAll().length||!X.can('ports',1,0,true))return;const N=opsP('ports','x'),L=[], // Router ports that pending PNI augments will take when they land are spoken for. resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c); // 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. @@ -177,8 +178,8 @@ const OPS_RUN={ 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);}}, - optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o); + 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; // New fiber gets its first channel; lit fiber gets more while it runs hot. @@ -190,45 +191,65 @@ const OPS_RUN={ o=fit.filter(o=>cnt[o]).sort((a,b)=>cnt[b]-cnt[a])[0]||(big&&fit.slice().sort((a,b)=>optG(b,l)-optG(a,l)||gpd(b,l)-gpd(a,l)).find(o=>X.can('optics',opticCountCost(l,o,1),0,true)))||cheap[0];if(!o)break; const n=(cnt[o]||0)+1,cost=opticCountCost(l,o,n),before=(l.ch||[]).length;if(!X.can('optics',cost))break; X.pay('optics',()=>{ACT.setChCount({id:l.id,o,n});return (l.ch||[]).length>before;});if((l.ch||[]).length<=before)break; - cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);}}}, - caches(X){const g=opsP('caches','g'); + cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);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; - 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);}}}, + 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)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)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)return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;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; for(const q 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))){ - if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);}}, + if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}}, // Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102). - decom(X){const keep=opsP('decom','keep'),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);} - // Loads must include what this shift already did (a customer just signed, a repair): recompute first, if anything could go. - if(X.dirty&&[...by.values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave'))){compute();X.dirty=false;} - for(const ls of by.values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; + // Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a + // job changed the network and anything could go (opsDecomWaits()). + *decom(X){const keep=opsP('decom','keep'); + for(const ls of opsPairs().values()){if(ls.length<2)continue;const live=ls.filter(l=>!linkDown(l)),big=live.reduce((a,l)=>!a||capOf(l)>capOf(a)?l:a,null);if(!big)continue; let cap=live.reduce((a,l)=>a+capOf(l),0);const load=ls.reduce((a,l)=>a+((R.load&&R.load[l.id])||0),0); const small=live.filter(l=>l!==big&&l.kind==='wave'&&!l.standby&&!l.premium&&capOf(l)b.link===l.id)).sort((a,b)=>capOf(b)-capOf(a)); // The spare is there for when the big link's trench is cut, so it has to live in another trench. if(keep&&small.length){const tr=l=>l.trench||l.id,i=small.findIndex(l=>tr(l)!==tr(big));small.splice(Math.max(0,i),1);} - for(const l of small.reverse()){if(cap-capOf(l)ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);}}}, + for(const l of small.reverse()){if(cap-capOf(l)ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}}, }; // 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;}} +// 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')); const OPS_ORDER=['repair','routers','transit','ports','optics','caches','ix','pni','decom']; // The shift: once per game day from dayTick, after outages and events have had their turn. -function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} +// One shift. Like a day (dayRun()), it is a generator: each yield is a compute() it needs, answered by the route worker +// in play, so the shift never routes on the page. opsDay() runs it in one go. +function opsDay(d){dayGo(opsRun(d),(g,v)=>g.next(v));} +function* opsRun(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};} // A new week: last week's tally becomes the shift report, and the one NOC notice of the week. const w=Math.floor(d/7);if(!O.wk||O.wk.w!==w){if(opsWkAny(O.wk)&&O.wk.w${esc(tr('ops.shift_report',{name:opsName()}))} ${esc(opsWeekLine(O.rep))}`,'',[],{a:'ops'});}O.wk=opsWkNew(w);} const X=opsShift(); // One order that trips over something (an odd save, a bug) is paused and noted; payday, goals and the save still happen. - opsQuiet(()=>{for(const k of OPS_ORDER)if(O.on[k])try{OPS_RUN[k](X);}catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);}}); + // Each order is a step of the day: a long shift lets the map draw between two (DAY_REST). The interface the orders + // click through (selection, tab, confirmation) goes on from where the last order left it, as in one go; the player's + // own is back in between. + let ui=null; + // One step of an order, muted (opsQuiet()): a plain order all at once, a generator up to its next yield (a rest). + const step=(k,st)=>opsQuiet(()=>{if(ui){UI.sel=ui.sel;UI.confirm=ui.cf;UI.tab=ui.tab;} + try{if(!st.it){const r=OPS_RUN[k](X);if(r&&typeof r.next==='function')st.it=r;else st.done=true;}if(!st.done&&st.it.next().done)st.done=true;} + catch(err){O.on[k]=false;X.dirty=true;X.did('snag',k);console.error('[tubes] standing order failed',k,err);st.done=true;} + ui={sel:UI.sel,cf:UI.confirm,tab:UI.tab};}); + const order=function*(k){const st={it:null,done:false};for(;;){step(k,st);if(st.done)return;yield DAY_REST;}}; + // Every order but the last, decommissioning, which reads today's loads: routed first when a job changed them. + for(const k of OPS_ORDER.slice(0,-1))if(O.on[k]){yield* order(k);yield DAY_REST;} + if(O.on.decom&&X.dirty&&opsDecomWaits()){yield;X.dirty=false;} + ui=null;if(O.on.decom)yield* order('decom'); const e={d,i:O.intern,r:[]};for(const [k,x] of X.r)e.r.push([k,x.n,x.w]);if(X.broke.size)e.r.push(['broke',X.broke.size,[...X.broke]]); // Very rarely, and never under Change Freeze, the intern fat-fingers something harmless. const ff=OPS_FF_RATE[rulePreset()];if(ff&&Object.keys(S.pops).length&&Math.random()rwLater(f),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'; @@ -20,23 +21,51 @@ 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();}; + w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m,t);};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;} +// Gone for good this session: the routing in flight is done here instead, and the day goes on without the worker. +// (A day resting between steps goes on by itself, on the page from then on.) +function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;if(!j||j.rest)return;RW.job=null; + if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAnswer(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);} +// One day in play (dayRun(), 10-day-tick.js): its steps run here, every routing it asks for runs in the worker. +function rwDay(){rwGo(dayRun());} +// Runs the day's steps up to the next routing, posts it, and returns: rwDone() picks the day up when R is back. At a +// DAY_REST, a day that has run RW.budget ms already goes on after the next frame (RW.later), so a phone gets its frames +// between the steps of a big network's day. The day is still in flight meanwhile: no next day starts, nothing saves. +// v: what the step it resumes asked for (a sales trial's answer, dayAnswer()). +function rwGo(g,v){const t0=performance.now();for(;;){let s;try{s=dayStep(g,v);}catch(e){tickErr(e);s={done:true};}v=undefined; + if(s.done){rwDayDone();return;} + if(s.value===DAY_REST){if(performance.now()-t0{if(tr)v=dayAnswer(tr);else compute();}; + const w=rwOn()&&rwStart();if(!w){try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;} 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: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();} + try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg),...(tr?{trial:{b:tr.trial,hx:tr.hx}}:{})});} + catch(e){console.error('[tubes] route worker post',e);rwKill();try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;} + const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,g,gen:RW.gen,t:t1,state:S,tr};return;}} +/* Where a resting day goes on. A frame drawn moments ago leaves time before the next one: the day goes on in a task of + its own, and the browser draws the next frame between two tasks when it is due. Otherwise the day waits for that + frame. (Waiting for a frame every time made a day of many short steps take many frames: a slow phone fell behind.) */ +const RW_CH=typeof MessageChannel==='function'&&!RW_IN?new MessageChannel():null,RW_TQ=[]; +if(RW_CH)RW_CH.port1.onmessage=()=>{const f=RW_TQ.shift();if(f)f();}; +function rwLater(f){if(RW_CH&&performance.now()-(RW.lf||-1e9)<(RW.fms||16)*0.75){RW_TQ.push(f);RW_CH.port2.postMessage(0);} + else requestAnimationFrame(()=>setTimeout(f,0));} +// The day rests: it goes on after the next frame, still in flight meanwhile (no next day, no save). +function rwRest(g,v){const j=RW.job={rest:true,g,state:S};RW.later(()=>{if(RW.job!==j)return;RW.job=null;if(j.state!==S){rwDayDone();return;}rwGo(g,v);});} +function rwDone(m,t0){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;const t=performance.now(); + // Another network was loaded meanwhile: the rest of that day belongs to nobody. + if(j.state!==S){rwDayDone();return;} + let v; + // A sales trial: the customer it signed off, or null. Something routed here meanwhile (an action), or the worker + // failed: the trial runs here, on the game as it is now. + if(j.tr){if(m.err)console.error('[tubes] route worker',m.err);v=m.err||RW.gen!==j.gen?dayAnswer(j.tr):m.ok?j.tr.trial:null;} + else 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();} + // Reading a big answer takes a few ms already: the day goes on after the next frame then, not in the same task. + if(t0!==undefined&&t1-t0>RW.budget/2)rwRest(j.g,v);else rwGo(j.g,v);} 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 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 @@ -52,5 +81,7 @@ const rwEfgOut=efg=>{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[ 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:rwEfgIn(m.efg)}); + // A sales trial (offerTrial()): its answer only. + if(m.trial){const t=performance.now(),ok=!!offerTrial(m.trial.b,m.trial.hx);postMessage({seq:m.seq,ok,ms:performance.now()-t});return;} 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/60-requirements.js b/src/game/80-simulation/60-requirements.js index 65c6e85..f392883 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -19,7 +19,16 @@ const REQS={ skyfull:{only:true,bonus:0,l:()=>tr('requirements.promised_a_full_sky',{p:pct(PIE_PROMISE)}),ok:()=>pieHubs().some(id=>pieCov(id)>=PIE_PROMISE)}, puns:{l:tr('requirements.their_ceo_hates_puns_please_do'),bonus:.05,ok:()=>true}, }; -function terrestrialPath(a,b){const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;} +/* terrestrialPath() asked for many customers at once (the daily mood check, 10-day-tick.js): the islands the live land + links make, worked out the first time one asks (TERR.m: city -> island), and two cities with a land path are two + cities of one island. Walking the links is what costs (a dark fiber's capacity, every one of them), not the question. + 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);} + 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;} 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); diff --git a/src/game/85-incidents/10-incidents-and-ddos.js b/src/game/85-incidents/10-incidents-and-ddos.js index db254dc..f6eb999 100644 --- a/src/game/85-incidents/10-incidents-and-ddos.js +++ b/src/game/85-incidents/10-incidents-and-ddos.js @@ -89,11 +89,13 @@ function ddosAttack(recompute=true){const fl=scnRule('ddos');ddosExpire(); return a;} /* After the day's routing: announce new attacks with what they are doing, pull the plug when Auto-RTBH says so, and teach each lesson once. */ -function ddosNews(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh; +function ddosNews(){runNow(ddosNewsRun());} +// The same as a step of the day: its yield is the routing after Auto-RTBH pulled a plug. +function* ddosNewsRun(){let again=false;const auto=S.ddosAuto&&S.ddosAuto.rtbh; for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue; if(auto&&!a.bh&&m.full>0&&ddosCol(a)>=0.01){a.bh=true;a.sac=1;S.stats.rtbh=(S.stats.rtbh||0)+1;ddosRtbhMood(a);again=true; toast(tr('ddos.auto_rtbh',{who:esc(ddosWho(a))}),'bad',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:a.city});}} - if(again)compute(); + if(again)yield; const T=S.stats.ddT||(S.stats.ddT={}); for(const a of ddosAll()){const m=ddosReport(a);if(!m)continue; if(a.fresh){delete a.fresh;const fl=scnRule('ddos'),col=ddosCol(a),sf=ddosSf(a),bad=col>=0.01||sf<0.97; diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 9266616..610856b 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -2,7 +2,12 @@ const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair(l); // The wet season in the tropical north (November to April): floods close the tracks, so a cut on land takes twice as long to reach. const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); -function fireFailure(only){ +/* failureRun() is a failure as a step of the day (10-day-tick.js): its yield is the routing that tells what it cost, + done by the route worker in play. fireFailure() is the same failure all at once, routed on the spot. */ +function fireFailure(only){runNow(failureRun(only));} +// A step of the day played all at once: every routing it asks for, on the spot (tests, a failure outside a day). +function runNow(g){dayGo(g,(g,v)=>g.next(v));} +function* failureRun(only){ const opts=[]; const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; if(live.length){opts.push(['cut',2+Math.min(6,live.length/2)]);} @@ -111,9 +116,9 @@ function fireFailure(only){ }else if(type==='fabric'){ const f=pick(fabsUsed);S.ev.fab=S.ev.fab||{};S.ev.fab[f]=S.day+2+Math.floor(Math.random()*3); addInc({type,ref:f,until:S.ev.fab[f],msg:tr('failures.fabric_is_having_a_bad_day',{fabric:FAB[f].name}),cost:0}); - }else if(type==='ddos'){ddosAttack();return; + }else if(type==='ddos'){ddosAttack(false);yield;yield* ddosNewsRun();return; } - compute(); + yield; const last=S.inc[S.inc.length-1]; last.impact=Math.max(0,before-R.served); if(before>1&&last.impact${incTitle(type)}
${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));} diff --git a/src/game/85-incidents/30-events.js b/src/game/85-incidents/30-events.js index 829a3af..6c3ec27 100644 --- a/src/game/85-incidents/30-events.js +++ b/src/game/85-incidents/30-events.js @@ -1,3 +1,8 @@ +/* An event that cuts cables or power routes at once, as its last move (evRoute()). As a step of the day (eventRun()) + that routing is the day's next yield instead: nothing reads R in between, so it is the same routing. */ +let EV_DEFER=null; +const evRoute=()=>{if(EV_DEFER)EV_DEFER.n++;else compute();}; +function* eventRun(){const k={n:0};EV_DEFER=k;try{fireEvent();}finally{EV_DEFER=null;}for(let i=0;i50)opts.push('sanction','tariff','hijack','landban','shutdown','redsea','baltic'); @@ -36,16 +41,16 @@ function fireEvent(){ if(e==='shutdown'){const ps=Object.keys(S.pops).filter(c=>c!==S.home);if(!ps.length)return;const c=pick(ps);S.pops[c].down=Math.max(S.pops[c].down||0,S.day+1);addInc({type:'shutdown',ref:c,until:S.day+1,msg:tr('events.regulators_ordered_every_network_in',{city:CITY[c].name}),cost:0});toast(tr('events.ordered_offline_in_city_a_government',{city:CITY[c].name}),'bad');sfx('alert');return;} if(e==='typhoon'){const c=pick(['mnl','ceb','hkg','tok','icn','sha','jkt'].filter(x=>S.pops[x])),p=S.pops[c],nm=pick([tr('common.typhoon_bandwidth'),tr('common.typhoon_latency'),tr('common.typhoon_jitter'),tr('events.typhoon_packet_loss')]); if(p.gen){S.stats.survived++;toast(tr('events.name_hits_city_the_grid_is',{name:nm,city:CITY[c].name}),'good');sfx('alert');return;} - p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');compute();return;} - if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');compute();return;} + p.down=Math.max(p.down||0,S.day+2);addInc({type:'power',ref:c,until:p.down,msg:tr('events.name_knocked_out_power_in_city',{name:nm,city:CITY[c].name}),cost:7000,fix:tr('incidents.rent_a_generator')});toast(tr('events.name_hits_city_power_is_out',{name:nm,city:CITY[c].name}),'bad');sfx('alert');evRoute();return;} + if(e==='runet'){S.ev.runet=S.day+1;toast(tr('events.sovereign_internet_drill_moscow'),'bad');sfx('alert');evRoute();return;} if(e==='baltic'){const BAL=['clion','havf','danice'];const hit=S.links.filter(l=>l.cable&&BAL.includes(l.cable)&&!(l.cut>S.day)); if(!hit.length){toast(tr('events.baltic_cable_damaged_a_cargo_ship'),'goal');return;} const dur=15+Math.floor(Math.random()*15),en=N_('events.a_cargo_ship_dragged_its_anchor');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);} - toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;} + toast(tr('events.baltic_cable_damaged_n_of_your',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;} if(e==='redsea'){const RED=['twoaf','smw6','peace','aae','eig','eassy'];const hit=S.links.filter(l=>l.cable&&RED.includes(l.cable)&&!(l.cut>S.day)); if(!hit.length){toast(tr('events.cables_cut_in_the_red_sea'),'goal');return;} const dur=20+Math.floor(Math.random()*15),en=N_('events.a_ship_drifting_without_power');for(const tk of new Set(hit.map(l=>l.trench||l.id))){S.links.filter(l=>(l.trench||l.id)===tk).forEach(l=>l.cut=Math.max(l.cut||0,S.day+dur));addInc({type:'redsea',ref:tk,until:S.day+dur,msg:tr(en),cost:0},en);} - toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');compute();return;} + toast(tr('events.cables_cut_in_the_red_sea_03e8',{n:hit.length,d:dur}),'bad');sfx('alert');evRoute();return;} if(e==='golden'){S.ev.golden=S.day+7;toast(tr('events.golden_week_demand_in_mainland_china'),'goal');return;} if(e==='gfw'){S.ev.gfw=S.day+10;toast(tr('events.the_border_got_stricter_cross_border'),'bad');sfx('alert');return;} if(e==='viral'){S.ev.viral=S.day+8;toast(tr('events.new_season_of_stranger_pings_just'),'goal');} diff --git a/src/game/85-incidents/40-chaos-monkey.js b/src/game/85-incidents/40-chaos-monkey.js index 6798c37..c878fbb 100644 --- a/src/game/85-incidents/40-chaos-monkey.js +++ b/src/game/85-incidents/40-chaos-monkey.js @@ -18,25 +18,28 @@ const mkBonus=()=>Math.round(Math.min(2e6,Math.max(20000,(R.revMo||0)*0.5))/1000 function mkWeak(l){const trc=l.trench||l.id,adj={}; for(const x of S.links){if(x===l||(x.trench||x.id)===trc||linkDown(x))continue;(adj[x.a]||(adj[x.a]=[])).push(x.b);(adj[x.b]||(adj[x.b]=[])).push(x.a);} const seen=new Set([l.a]),q=[l.a];while(q.length){const c=q.pop();if(c===l.b)return false;for(const n of adj[c]||[])if(!seen.has(n)){seen.add(n);q.push(n);}}return true;} -function mkTick(d){const M=S.monkey;if(!M)return; +function mkTick(d){runNow(mkTickRun(d));} +// The monkey's day as a step of the day: a snip's yield is the routing that tells what it cost. +function* mkTickRun(d){const M=S.monkey;if(!M)return; if(!mkElig()){if(M.on)mkLeave('quiet');return;} // The first visit is spread by the ASN, not the dice, so a game's other luck stays exactly as it was. if(M.next==null)M.next=d+(mkSpicy()?180:270)+(S.asn||0)%120; if(!M.on){if(dl.kind!=='vxc'&&!linkDown(l)).length<3){M.next=d+30;return;}mkArrive(d);return;} if(d>=M.until){mkLeave();return;} - if(d>=M.snip){mkSnip();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} + if(d>=M.snip){yield* mkSnipRun();M.snip=d+(mkSpicy()?rint(9,7):rint(14,11));}} function mkArrive(d){const M=S.monkey,cs=Object.keys(S.pops),len=mkSpicy()?rint(180,61):rint(120,121); S.stats.mkMet=(S.stats.mkMet||0)+1; Object.assign(M,{on:1,start:d,until:d+len,snip:d+3,n:0,hurt:0,c:cs.length?pick(cs):S.home}); toast(tr('chaos_monkey.arrived',{n:len}),'bad',[{l:tr('chaos_monkey.banana',{cost:fmt$(mkBananaCost())}),act:'mkBanana',args:{}}],{a:'tab',v:'noc'});sfx('alert');track('monkey_arrive'); if(typeof mkStart==='function'&&CITY[M.c])mkStart(M.c);} -function mkSnip(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return; +function mkSnip(){runNow(mkSnipRun());} +function* mkSnipRun(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));if(!live.length)return; // Weak spots first: a sample keeps this cheap on big networks. const smp=live.length>40?Array.from({length:40},()=>pick(live)):live,l=pick(smp.flatMap(x=>mkWeak(x)?[x,x,x,x,x]:[x])); const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served; hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a; addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},''); - compute();const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp; + yield;const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp; const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++; toast(felt?`🐒 ${incTitle('cut')}
${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert'); if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}} diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 2f008db..e31d087 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -1,13 +1,28 @@ /* ---------- daily tick ---------- */ -/* 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. */ +/* A day is a few steps around its routing: dayPre() (the world moves on), then dayPost() (bills, moods, offers, the + intern's shift). dayRun() is the whole day as a generator: each yield is a compute() it needs before going on, the + day's own routing first, then a recompute after a failure or after the intern's jobs. dayTick() (tests, the fallback) + answers each with compute() on the spot; in play the route worker answers them (28-route-worker.js), and the page + only runs the steps in between. Same steps, same random numbers either way: routing draws none. (A failure + routes as a step too, failureRun(); an event still routes on the spot: it reads R right away, every few weeks.) */ // UI.tick: what the day itself announces, which quiet notifications may keep to the NOC log. -function dayTick(){UI.tick=true;try{const d=dayPre();if(d===false)return;compute();dayPost(d);}finally{UI.tick=false;}} -function dayPre(){ +// yield DAY_REST: no routing, only a place where the day may let a frame through when it has run long (rwGo()). +const DAY_REST=1; +function* dayRun(){const d=yield* dayPreRun();if(d===false)return;yield;yield* dayPost(d);} +// A step yields undefined (a routing), DAY_REST, or a sales trial ({trial}, 95-standing-orders.js) to answer with the +// customer it signs off or null (dayAnswer()): here at once, in play by the route worker. +const dayStep=(g,v)=>{UI.tick=true;try{return g.next(v);}finally{UI.tick=false;}}; +const dayAnswer=y=>offerTrial(y.trial,y.hx); +function dayGo(g,step=dayStep){let v;for(let s=step(g);!s.done;s=step(g,v)){v=undefined;const y=s.value;if(y===DAY_REST)continue;if(y&&y.trial)v=dayAnswer(y);else compute();}} +function dayTick(){dayGo(dayRun());} +// dayPre(): the world's morning all at once; dayPreRun() the same with a place or two to let a frame through. +function dayPre(){const g=dayPreRun();for(;;){const s=g.next();if(s.done)return s.value;}} +function* dayPreRun(){ 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); + yield DAY_REST; if(!S.phpDone&&d>45&&Math.random()<1/400)elephant(); if(R&&R.teMoved)S.stats.teMax=Math.max(S.stats.teMax||0,R.teMoved); {const t1=!!S.won&&isTier1();if(S.t1Now&&!t1)toast(tr('day_tick.you_are_no_longer_tier_1',{why:t1Why()}),'bad');S.t1Now=t1;} @@ -27,13 +42,14 @@ function dayPre(){ // resolve incidents for(const i of S.inc.slice())if(i.until<=d){const o=incOpen(i),l=o&&o.a==='link'&&S.links.find(x=>x.id===o.v),where=l?CITY[l.a].name+'–'+CITY[l.b].name:o&&o.a==='city'?CITY[o.v].name:'';clearInc(i); toast(where?tr('day_tick.resolved_what_where_is_back_to',{what:incTitle(i.type),where:esc(where)}):tr('day_tick.resolved_what',{what:incTitle(i.type)}),'good',[],o);} + yield DAY_REST; // eyeball growth / churn uses last computed service 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));} return d;} -function dayPost(d){ - ddosNews();ddosTrack(); +function* dayPost(d){ + yield* ddosNewsRun();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)/monLen(d); S.stats.peak=Math.max(S.stats.peak,R.served); @@ -48,7 +64,7 @@ function dayPost(d){ (a.sla||(a.sla=[])).push(b.id);b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; toast(tr('day_tick.sla_breach_name_the_attack_on',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood - const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));for(const b of S.biz.slice()){if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b); + const ids=linkIds(),frr=(coreFrr()&&S.links.some(l=>l.cut)?.5:1)*(rule('moods')==='patient'?.5:1);const bhT=new Set(ddosAll().filter(a=>a.bh).map(a=>a.tgt));let nb=0;TERR={S,gen:RW.gen,m:null};try{for(const b of S.biz.slice()){if(++nb%256===0)yield DAY_REST;if(eventTick(b,d)||capPendTick(b,d))continue;b.pm=b.mood;if(bhT.has(b.id))continue;const sf=bizSf(b,ids),reachOk=BIZ_T[b.type].l2||BIZ_T[b.type].fiber||R.reach>0.99||scnRule('local'),scrubOk=b.type!=='scrub'||(hasScrub()&&!scrubFar(b.city)),divOk=reqOk(b); if(sf>=0.95&&reachOk&&scrubOk&&divOk)b.mood=Math.min(100,b.mood+2); else if(S.day-(b.since||0)<15){} else{const dm=frr*(Math.max(0,0.95-sf)*45+(!reachOk?3:0)+(!scrubOk?4:0)+(!divOk?3:0));b.mood-=BIZ_T[b.type].orbit?Math.min(dm,PIE_PATIENCE):dm; @@ -58,11 +74,13 @@ function dayPost(d){ else if(b.mood<30&&!b.warned){b.warned=b.warn60=true;const why=bizWhy(b)[0],paused=pref('pauseFurious')&&autoPause(); toast(tr('day_tick.name_is_furious_fix_service_in',{name:esc(b.name),city:CITY[b.city].name})+(why?`
${esc(why)}`:'')+(paused?`
${tr('common.game_paused')}`:''),'bad',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}].concat(paused?[resumeAct()]:[]));sfx('err');} else if(b.mood<60&&!b.warn60&&pref('warnUnhappy')){b.warn60=true;const why=bizWhy(b)[0];toast(tr('day_tick.name_is_getting_unhappy_happiness_p',{name:esc(b.name),p:Math.round(b.mood),city:CITY[b.city].name})+(why?`
${esc(why)}`:''),'',[{l:tr('common.show_me'),act:'custGo',args:{id:b.id}}]);}} - if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;} + if(b.mood>60)b.warned=false;if(b.mood>75)b.warn60=false;}}finally{TERR=null;} + yield DAY_REST; // contracts: renewals, growth, haggles and leaving (75-customer-lifecycle.js) clDay(d); // the sales desk: meetings booked, golf played (38-sales-desk.js) salesDay(d); + yield DAY_REST; // own IX members join for(const c in S.myIx){const m=S.myIx[c];if(d>=m.next&&m.members.lengthn.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg))); @@ -74,19 +92,21 @@ function dayPost(d){ S.offers=S.offers.filter(o=>o.exp>d); brTick(); if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);} + yield DAY_REST; // failures & events // Chaos (the rules) scales how often: calm waits about three times as long, spicy comes almost twice as often, none never. let dirty=false;const cm=chaosMul(); // A visiting chaos monkey does the breaking instead (its snips replace these while it is here). - mkTick(d); - if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;fireFailure();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} + yield* mkTickRun(d); + if(cm&&d>=S.nextFail&&!mkOn()){dirty=true;yield* failureRun();const size=S.links.length+Object.keys(S.pops).length;S.nextFail=d+Math.round((Math.max(22,50-size*1.5)+Math.floor(Math.random()*25))*(scnRule('chaos')?0.5:1)/cm);} // Anchors Away: on top of the usual failures, ships drag anchors over each Baltic seabed link (about three cuts a link-year). - if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;fireEvent();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} - if(dirty)compute(); + if(cm&&d>45&&scnRule('anchors')){const n=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l)&&anchorProne(l)).length;if(n&&Math.random()=S.nextEvent){dirty=true;yield* eventRun();S.nextEvent=d+Math.round((45+Math.floor(Math.random()*45))/cm);} + if(dirty)yield; // the sales desk signs and declines deals, when the player lets it (39-sales-auto.js), then the intern's shift sees them - slAutoDay(d); - opsDay(d); + yield* slAutoRun(d); + if(opsHired())yield DAY_REST; + yield* opsRun(d); if(S.pie){pieDay(d);pieTier();} // payday floaters if(cal(d).d===1){for(const c in S.pops){let v=(R.cityEye[c]*sfOf(R,c)*EYE_RATE)+S.biz.filter(b=>b.city===c).reduce((a,b)=>a+b.bw*b.rate,0);v=v-R.cityEye[c]*sfOf(R,c)*EYE_RATE*(1-arpuOf(c));if(v>500)floater(CITY[c].x,CITY[c].y-30,'+'+fmt$(v),'#16A866');}sfx('coin');} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 41f70a8..aadabb0 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -4,6 +4,9 @@ function frame(now){ // Schedule the next frame first: one bad lookup in a day tick must not freeze the whole game. if(!window.__TUBES_TEST__)requestAnimationFrame(frame); const dt=Math.min(250,now-last);last=now; + // A day's steps take half a frame at most before letting one through (rwGo()): 8 ms at 60 Hz, 3 ms on a 240 Hz screen, + // where 8 ms would be two frames lost. The frame time is followed slowly, a long frame counting as two at most. + if(dt>0){RW.fms=RW.fms?RW.fms*0.95+Math.min(dt,RW.fms*2)*0.05:dt;RW.budget=Math.min(8,Math.max(3,RW.fms/2));} if(ANALYTICS.host&&S&&!S.lost&&UI.speed&&document.visibilityState==='visible'){UI.playMs=(UI.playMs||0)+dt;const m=UI.playMs/60000;for(const k of PLAY_MARKS)if(m>=k)track('play_'+k+'m',true);} if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save(); // The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them. @@ -14,12 +17,16 @@ function frame(now){ const t=animOn()?animT:0; if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;} if(DIAG.on)diagFrame(now); + RW.lf=performance.now(); } // dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames // do not (src/agent/, a hidden tab), under the frame's own conditions otherwise. function runClock(dt){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);}}} + // One day in flight at a time (its routing in the worker, or resting between steps): time does not pile up behind it. + // The clock waits for the day, never the other way round: a machine that cannot keep up plays slower, it does not + // freeze to catch up. + if(RW.job){acc=Math.min(acc,DAY_MS);return;} + if(rwOn()){if(!RW.w)rwStart();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;}}} /* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map diff --git a/tests/day-steps.test.js b/tests/day-steps.test.js new file mode 100644 index 0000000..cc31073 --- /dev/null +++ b/tests/day-steps.test.js @@ -0,0 +1,170 @@ +// The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the +// recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so +// a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that +// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day. +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'); +// The big network with an intern running every order, a failure and an event due soon, and its circuits on scenic +// routes, which read yesterday's R.efg. Ids come from Date.now(), +// so the clock stands still in every page. +const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false; + S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true; + S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0; + S.nextFail=S.day+3;S.nextEvent=S.day+5;for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';compute();__reseed(4242);`; +const open = (t, seed) => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; }; +// The page, with a stand-in worker: what it posts waits in a queue until pump() hands it to the other page. +function played(t) { + const page = open(t, 777), wk = open(t, 1); + page.ev(SETUP); + // No time to spare: every DAY_REST waits for the next "frame", which pump() gives it. + page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});'); + wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};'); + // Answers what is waiting, one message at a time; returns how many routings it served. + let rests = 0, trials = 0; + const pump = () => { let n = 0; for (;;) { + if (page.ev('__later.length')) { rests++; page.ev('__later.shift()()'); continue; } + if (!page.ev('__q.length')) break; + if (page.ev('!!__q[0].trial')) trials++; + wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); + page.ev('rwDone(__a)'); n++; } return n; }; + // One message to the worker and its answer back (the trial test steps through a day with it). + const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); }; + return { ...page, pump, pump1, rests: () => rests, trials: () => trials }; +} +// R.egDesc too, key for key and in order. +const STATE = "JSON.stringify({S,R:{served:R.served,demand:R.demand,rev:R.revMo,cost:R.costMo,load:R.load,useT:R.useT,usePni:R.usePni,egDesc:R.egDesc}})"; +// Equal states, or which of their fields differ. +const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = JSON.parse(b), d = []; + for (const o of ['S', 'R']) for (const k of new Set([...Object.keys(A[o]), ...Object.keys(B[o])])) if (JSON.stringify(A[o][k]) !== JSON.stringify(B[o][k])) d.push(`${o}.${k}`); + assert.fail(`${msg}: ${d.join(', ')} differ`); }; + +test('a day whose routings the worker answers is the day dayTick() plays', (t) => { + const ref = open(t, 777), p = played(t); + ref.ev(SETUP); + // The page itself never routes, the failure on day 3 (failureRun()) and the sales desk's trials (offerTrial()) + // included: they are steps like the others, routed by the worker. + p.ev('window.__pc=0;window.__tr=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};'); + let served = 0, extra = 0; + for (let i = 0; i < 12; i++) { + ref.ev('dayTick()'); + p.ev('rwDay()'); + assert.equal(p.ev('!!RW.job'), true, 'the day waits for the worker'); + const n = p.pump(); served += n; if (n > 1) extra++; + assert.equal(p.ev('!!RW.job'), false); + same(p.ev(STATE), ref.ev(STATE), `day ${i + 1}`); + } + // Each day routes once, and some days again after a failure, an event or the intern's jobs: all in the worker. + assert.ok(served > 12 && extra > 0, `routings served: ${served}, days with more than one: ${extra}`); + assert.ok(ref.ev('S.inc.length') > 0 || ref.ev('S.stats.incidents') > 0, 'a failure happened'); + assert.equal(p.ev('__pc'), 0, 'no routing on the page'); + assert.ok(p.trials() > 0, `sales trials the worker ran: ${p.trials()}`); + assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes'); + // A frame through before the intern's shift, after each of the orders on duty (decommissioning aside), and after + // each job of an order (a generator's yields). + const orders = p.ev('OPS_ORDER.slice(0,-1).filter(k=>S.ops.on[k]).length'); + assert.ok(orders > 3, `orders on duty: ${orders}`); + assert.ok(p.rests() > 12 * (1 + orders), `each day let a frame through before the shift, between its orders and its jobs: ${p.rests()}`); + assert.deepEqual([...ref.errors, ...p.errors], []); +}); + +test('a half day is never saved, and a worker lost mid-day finishes it on the page', (t) => { + const ref = open(t, 777), p = played(t); + ref.ev(SETUP); + ref.ev('dayTick()'); + p.ev("window.__saves=0;const s0=save;save=(...a)=>{if(!RW.job)__saves++;return s0(...a);};rwDay()"); + p.ev('save()'); + assert.equal(p.ev('UI.saveDue'), true, 'saving waits for the end of the day'); + p.ev('rwKill()'); + assert.equal(p.ev('RW.job&&RW.job.rest'), true, 'the day goes on on the page, up to its rest'); + assert.equal(p.pump(), 0, 'with no worker left'); + assert.equal(p.ev('!!RW.job'), false, 'the day is over'); + assert.equal(p.ev('UI.saveDue'), false, 'and saved'); + same(p.ev(STATE), ref.ev(STATE), 'the day'); + assert.deepEqual([...ref.errors, ...p.errors], []); +}); + +test('an action while the worker routes stands; another network loaded mid-day gets none of that day', (t) => { + const p = played(t); + p.ev('rwDay()'); + // The action routes on the page as always: the worker's answer is stale, and the day goes on with the action's R. + p.ev('after()'); + assert.equal(p.pump() >= 1, true); + assert.equal(p.ev('!!RW.job'), false); + assert.equal(p.ev('S.day'), p.ev('S.hist[S.hist.length-1].d'), 'the day was finished'); + // A new game while a day is in flight: the old day's steps never touch it. + p.ev('rwDay()'); + const day = p.ev('S.day'); + p.ev(`window.__old=S;S=migrate(JSON.parse(${JSON.stringify(BIG)}));compute();`); + const fresh = p.ev('JSON.stringify(S.hist)'); + p.pump(); + assert.equal(p.ev('JSON.stringify(S.hist)'), fresh); + assert.equal(p.ev('__old.day'), day); + assert.deepEqual(p.errors, []); +}); + +// A sales trial the worker is routing when the player acts (an action routes on the page): its answer was for the game +// as it was, so the trial runs again on the page, on the game as it is now. +test("a sales trial overtaken by the player's action runs again on the page", (t) => { + const p = played(t); + p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};"); + let found = false; + for (let d = 0; d < 20 && !found; d++) { + p.ev('rwDay()'); + // Hand the worker one message at a time until a trial is the one waiting. + for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) { + if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; } + if (!found && p.ev('__q.length&&!!__q[0].trial')) { found = true; p.ev('compute()'); } + p.pump1(); + } + } + assert.ok(found, 'the sales desk trialled an offer'); + assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran on the page'); + assert.deepEqual(p.errors, []); +}); + +// The rest of what used to route on the page in a day: a DDoS that a failure starts (and Auto-RTBH pulling a plug), an +// event that cuts cables or power, and the chaos monkey's snip. Each is a step the worker routes, and the day is still +// the day dayTick() plays. +test('DDoS, cable and power events and the chaos monkey route in the worker too, and the day stays the same', (t) => { + // A visiting monkey does the breaking instead of the failures: failures first, then the monkey. + const MONKEY = 'S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day+1,n:0,hurt:0,c:S.home,next:S.day};'; + const FORCE = `S.ddosAuto={rtbh:true};mkElig=()=>true;S.monkey={on:0,next:S.day+999};S.nextFail=S.day+1;S.nextEvent=S.day+2; + failureRun=eval('('+failureRun.toString().replace('if(only)type=only;',"type=S.day%2?'ddos':'cut';")+')'); + fireEvent=eval('('+fireEvent.toString().replace('const e=pick(opts);',"const e=['redsea','typhoon','baltic','runet'].find(x=>opts.includes(x))||'redsea';")+')');__reseed(99);`; + const ref = open(t, 777), p = played(t); + ref.ev(SETUP); ref.ev(FORCE); p.ev(FORCE); + // The reference routes an event on the spot, the way it always did (no deferred routing). + ref.ev('eventRun=function*(){fireEvent();};'); + ref.ev("window.__dd=0;const da=ddosAttack;ddosAttack=(...a)=>{const r=da(...a);if(r)__dd++;return r;};window.__ev=0;const fe=fireEvent;fireEvent=(...a)=>{__ev++;return fe(...a);};"); + p.ev('window.__pc=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};'); + for (let i = 0; i < 12; i++) { + if (i === 6) for (const h of [ref, p]) h.ev(MONKEY); + for (const h of [ref, p]) h.ev('S.nextFail=S.day+1;S.nextEvent=S.day+1;'); + ref.ev('dayTick()'); + p.ev('rwDay()'); p.pump(); + same(p.ev(STATE), ref.ev(STATE), `day ${i + 1}`); + } + assert.ok(ref.ev('__dd') > 0, `DDoS attacks started: ${ref.ev('__dd')}`); + assert.ok(ref.ev('S.monkey.n') > 0, `the monkey snipped: ${ref.ev('S.monkey.n')}`); + assert.ok(ref.ev('__ev') > 2, `events: ${ref.ev('__ev')}`); + assert.equal(p.ev('__pc'), 0, 'no routing on the page'); + assert.deepEqual([...ref.errors, ...p.errors], []); +}); + +// Quiet notifications keep the day's own news to the NOC log (UI.tick, 95-modals/10-toasts.js). Play goes through the +// worker's steps, not dayTick(): every step of the day is announced as the day's, on both sides of each routing. +test('quiet notifications hold while the worker plays the day', (t) => { + const p = played(t); + p.ev("window.__tc=[];const t0=toast;toast=function(m,k){__tc.push(!!UI.tick);return t0.apply(this,arguments);};"); + for (let i = 0; i < 12; i++) { p.ev('rwDay()'); p.pump(); } + const calls = JSON.parse(p.ev('JSON.stringify(__tc)')); + assert.ok(calls.length > 0, 'the days had news'); + assert.deepEqual(calls.filter((x) => !x), [], 'every toast of the day came with UI.tick set'); + assert.equal(p.ev('UI.tick'), false, 'and it is off between days'); + assert.deepEqual(p.errors, []); +}); diff --git a/tests/frame-pacing.test.js b/tests/frame-pacing.test.js new file mode 100644 index 0000000..3169265 --- /dev/null +++ b/tests/frame-pacing.test.js @@ -0,0 +1,18 @@ +// How long a day may run on the page between two frames (src/game/99-loop.js, rwGo()): half a frame, from 3 to 8 ms. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test("a day's steps follow the screen: half a frame between two, from 3 to 8 ms", () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;"); + const run = (hz, n, extra = '') => ev(`(()=>{for(let i=0;i<${n};i++){window.__now=(window.__now||1000)+1000/${hz};${extra};frame(__now);}return RW.budget;})()`); + assert.equal(run(240, 300), 3, 'a 240 Hz screen'); + const b = run(240, 1, '__now+=250'); + assert.ok(b < 6, `one long frame barely moves it: ${b}`); + assert.equal(run(60, 300), 8, 'a 60 Hz screen'); + assert.ok(Math.abs(run(120, 300) - 1000 / 120 / 2) < 0.1, 'a 120 Hz screen: half its frame'); + assert.deepEqual(errors, []); +}); + +// The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one diff --git a/tests/game.test.js b/tests/game.test.js index c182655..aa21ff1 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -47,17 +47,17 @@ test('every incident and event type fires and clears cleanly', () => { ev("UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.via='grace';openLinkModal('nyc','lon');ACT.buildLink({tier:1});closeModal()"); ev("UI.pending={a:'fra',b:'ams'};UI.lmode='df';UI.dfSys='roadm';ACT.orderDf();UI.lmode='wave';S.pops.fra.rgen=2;S.pops.ams.rgen=2"); ev("const df=S.links.find(l=>l.kind==='df');ACT.addCh({id:df.id,o:'zr4'});df.ready=S.day"); - const failSrc = ev('fireFailure.toString()'); + const failSrc = ev('failureRun.toString()'); const types = ['harmless','fatwave','label','mtu','oops','cleaner','maxpfx','prepend','rpki','amp','roadmff','optic','ac','cut','crash','power','transit','ixloop','leak','ddos']; for (const t of types) { const funny = ['harmless','fatwave','label','mtu','oops','cleaner','maxpfx','prepend','rpki','roadmff','ac'].includes(t); const patched = failSrc - .replace(/^function fireFailure/, 'function') + .replace(/^function\* failureRun/, 'function*') .replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${funny ? 'funny' : t}'))return;opts.splice(0,opts.length,['${funny ? 'funny' : t}',1]);let tot=opts.reduce`) .replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`); ev('window.__ff=' + patched); ev('S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute()'); - ev('__ff()'); + ev('runNow(__ff())'); ev('dayTick()'); } const evSrc = ev('fireEvent.toString()'); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 91e9080..2ac9b47 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -255,7 +255,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => { // [function, what it must read] const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], - ['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'], + ['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'], ['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); // and in play: no chaos and no market means a quiet year diff --git a/tests/gpu-bench.test.js b/tests/gpu-bench.test.js index e27836e..5c8fb85 100644 --- a/tests/gpu-bench.test.js +++ b/tests/gpu-bench.test.js @@ -20,9 +20,10 @@ function open(cfg = {}) { } const wait = (ms) => new Promise((r) => setTimeout(r, ms)); -// A day in flight in the worker when the trial ends: rwDone() would run its dayPost() whenever the answer comes. -const IN_FLIGHT = `window.__old=S;RW.seq=41;RW.job={seq:41,d:201,gen:RW.gen-1,t:0};window.__posts=[]; - dayPost=function(d){__posts.push({d,old:S===__old});};`; +// A day in flight in the worker when the trial ends: rwDone() would go on with its steps (the rest of the day, a +// generator, 10-day-tick.js) whenever the answer comes. This one only notes on which save it ends. +const IN_FLIGHT = `window.__old=S;window.__posts=[];const g=(function*(){yield;__posts.push({d:201,old:S===__old});})();g.next(); + RW.seq=41;RW.job={seq:41,g,gen:RW.gen-1,t:0,state:S};`; test('a late answer from the route worker lands on the trial it belongs to, not the next one', async () => { const { ev, errors } = open(); diff --git a/tests/i18n.test.js b/tests/i18n.test.js index cd780c4..8020414 100644 --- a/tests/i18n.test.js +++ b/tests/i18n.test.js @@ -36,14 +36,14 @@ function tour(ev) { ['route script', 'S.lvl=Math.max(S.lvl,3);S.cash+=1e6;ACT.coreUp();ACT.coreUp();ACT.buyTE();ACT.teEdit();ACT.teExample();ACT.teCheck();closeModal()'], ['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"], ['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src); - const failSrc = ev('fireFailure.toString()'); + const failSrc = ev('failureRun.toString()'); for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) { const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t; - const patched = failSrc.replace(/^function fireFailure/, 'function') + const patched = failSrc.replace(/^function\* failureRun/, 'function*') .replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`) .replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`); - assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'fireFailure still has the hooks this tour forces'); - step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();__ff();dayTick();ACT.leftTab({t:'noc'})`); + assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'failureRun() still has the hooks this tour forces'); + step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();runNow(__ff());dayTick();ACT.leftTab({t:'noc'})`); } // A cable the Baltic event can hit, so the anchor badge does not depend on what the random days built. step('baltic cable', "if(!S.pops.hel)ACT.buildPop({city:'hel'});UI.via='clion';openLinkModal('fra','hel');ACT.buildLink({tier:0});closeModal();UI.via=null"); diff --git a/tests/issues.test.js b/tests/issues.test.js index c59b76d..8036847 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -256,8 +256,8 @@ test('LACP trouble, partial packet loss and PMTUD black holes fire, hurt and cle const { ev, errors } = load(); ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); ev("ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.lagT({id:S.transit[0].id,d:1});ACT.buyIx({city:'ams',tier:1});ACT.lagIx({city:'ams',d:1});S.day=100;compute()"); - const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function').replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce"); - const fire = (t) => { ev('window.__ff=' + src.replace('type=pick(f);}', `type='${t}';}`)); ev('__ff();compute()'); }; + const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*').replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce"); + const fire = (t) => { ev('window.__ff=' + src.replace('type=pick(f);}', `type='${t}';}`)); ev('runNow(__ff());compute()'); }; for (let i = 0; i < 12; i++) { fire('lacp'); } assert.ok(ev("S.inc.some(i=>i.type==='lacp')"), 'LACP incidents fire'); assert.ok(ev("S.transit[0].lacp||S.ev.ixlacp"), 'a LAG is degraded'); @@ -1315,7 +1315,7 @@ test('#134 an exchange named after its city does not repeat the city in messages const labs = JSON.parse(ev("JSON.stringify(lagsN().filter(o=>o.k==='ix').map(o=>o.lab))")); assert.ok(labs.includes('IX.brrr Campinas LAG'), labs.join(' | ')); assert.ok(labs.some(l => / LAG in Frankfurt$/.test(l)), labs.join(' | ')); - ev("S.inc=[];eval('('+fireFailure.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')()"); + ev("S.inc=[];runNow(eval('('+failureRun.toString().replace(\"if(only)type=only;\",\"type='ixloop';\").replace(\"const c=pick(Object.keys(S.ixp));\",\"const c='cpq';\")+')')())"); const msg = ev("S.inc.map(i=>i.msg).join(' ')"); assert.match(msg, /IX\.brrr Campinas/); assert.doesNotMatch(msg, /in Campinas/); diff --git a/tests/land-islands.test.js b/tests/land-islands.test.js new file mode 100644 index 0000000..a52e6a1 --- /dev/null +++ b/tests/land-islands.test.js @@ -0,0 +1,35 @@ +// "Afraid of sharks" (a path that never goes under the sea, 60-requirements.js) asked for every customer in the daily +// mood check: the land islands are worked out once for the check (TERR), and two cities have a land path exactly when +// they are on one island. Same answers as walking the links each time, with links cut, subsea or not, and cities alone. +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'); + +test('land islands answer "a path without subsea" as walking the links does', () => { + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;closeModal();compute();`); + const cmp = () => JSON.parse(ev(`(()=>{const cs=Object.keys(S.pops).concat(['sin','nyc','lon',null,undefined]);let n=0,yes=0;const bad=[]; + for(const a of cs.slice(0,60))for(const b of cs){if(!a)continue;TERR=null;const w=terrestrialPath(a,b);TERR={S,gen:RW.gen,m:null};const i=terrestrialPath(a,b);TERR=null; + n++;if(w)yes++;if(w!==i)bad.push(a+'-'+b);}return JSON.stringify({n,yes,bad:bad.slice(0,5)});})()`)); + let r = cmp(); + assert.deepEqual(r.bad, []); + assert.ok(r.yes > 20 && r.yes < r.n, `pairs with a land path: ${r.yes} of ${r.n}`); + // Cut a third of the land links (an island splits) and the answers still agree. + ev("S.links.forEach((l,i)=>{if(!l.sub&&i%3===0)l.cut=S.day+5;})"); + const r2 = cmp(); + assert.deepEqual(r2.bad, []); + assert.ok(r2.yes < r.yes, `fewer land paths once links are cut: ${r2.yes} < ${r.yes}`); + // Kept for the day, the islands follow an action that routes (RW.gen), and are never used for another game. + ev("TERR={S,gen:RW.gen,m:null};terrestrialPath('fra','ams');window.__m=TERR.m;S.links.forEach(l=>{if(!l.sub)l.cut=0;});compute();"); + assert.equal(ev("terrestrialPath('fra','ams')===(()=>{const t=TERR;TERR=null;const w=terrestrialPath('fra','ams');TERR=t;return w;})()&&TERR.m!==__m"), true, 'made again after routing'); + ev("const S0=S;S={...S,links:[]};window.__r=terrestrialPath('fra','ams');S=S0;TERR=null;"); + assert.equal(ev('__r'), false, 'another game walks its own links'); + // The daily check leaves no islands behind (a later question walks the links of the moment). + ev('S.nextFail=S.nextEvent=S.day+99;dayTick()'); + assert.equal(ev('TERR'), null); + assert.deepEqual(errors, []); +}); diff --git a/tests/peering-desk.test.js b/tests/peering-desk.test.js index 0bb4ad9..515c245 100644 --- a/tests/peering-desk.test.js +++ b/tests/peering-desk.test.js @@ -109,9 +109,9 @@ test('old saves with inbox, max-prefix and Large Peering Model state load and pl test('max-prefix incidents can no longer fire', () => { const { ev, errors } = load(); setup(ev); - assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false); - ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')"); - ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}"); + assert.equal(ev("failureRun.toString().includes('maxpfx')"), false); + ev("S.day=100;const src=failureRun.toString().replace(/^function\* failureRun/,'function*').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')"); + ev("__reseed(7);for(let i=0;i<200;i++){runNow(__ff());S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}"); assert.equal(ev('!!window.__mp'), false); assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined'); assert.deepEqual(errors, []); diff --git a/tests/peering.test.js b/tests/peering.test.js index ab2d0a7..0bfe532 100644 --- a/tests/peering.test.js +++ b/tests/peering.test.js @@ -204,10 +204,10 @@ test('a peer at a rival exchange can de-peer you without stopping the game', () test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => { const { ev, errors } = load(); ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100"); - const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function') + const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*') .replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce"); ev('window.__ff=' + src); - ev('__ff()'); + ev('runNow(__ff())'); assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))")); // a tick that throws is caught, reported once, and the loop keeps going ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0"); diff --git a/tests/regions.test.js b/tests/regions.test.js index b9927fd..88a41a9 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -458,9 +458,9 @@ test('#76 Kansas City, Calgary, Vancouver and Ottawa, with two more Canadian gia assert.equal(ev("NET.tlu.up.every(id=>NET[id].type==='t1')&&NET.rgc.up.every(id=>NET[id].type==='t1')"), true); // a cut on a Canadian link is often a beaver ev("ACT.buildPop({city:'van'});ACT.buildPop({city:'cal'});S.links=[];UI.via=null;openLinkModal('van','cal');ACT.buildLink({tier:1});closeModal()"); - const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function'); + const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*'); ev('window.__ff=' + src.replace('type=pick(f);}', "type='cut';}")); - ev("for(let i=0;i<40&&!(S.stats.f&&S.stats.f.beaver);i++){for(const l of S.links)l.cut=0;S.inc=[];__ff();}"); + ev("for(let i=0;i<40&&!(S.stats.f&&S.stats.f.beaver);i++){for(const l of S.links)l.cut=0;S.inc=[];runNow(__ff());}"); assert.ok(ev("!!(S.stats.f&&S.stats.f.beaver)"), 'a beaver chewed through it'); ev('checkBadges()'); assert.ok(ev("(S.badges||[]).includes('beaver')||!!(S.badge&&S.badge.beaver)||BADGES.find(b=>b.id==='beaver').ok()"), 'Dam It'); @@ -504,13 +504,13 @@ test('#79 Benelux: Brussels red tape, the Flanders duopoly, Oostkamp trawlers an assert.ok(ev("cablesFor('lon','oos').some(c=>c.cid==='clementine')")); ev("ACT.buildPop({city:'lon'});ACT.buildPop({city:'oos'});S.links=[];UI.lmode='wave';UI.via='clementine';openLinkModal('lon','oos');ACT.buildLink({tier:1});closeModal()"); assert.equal(ev("S.links.length&&S.links[0].sub"), true); - const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function'); + const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*'); ev('window.__ff=' + src.replace('type=pick(f);}', "type='cut';}")); - ev("for(let i=0;i<30&&!S.log.some(e=>/trawler|wind-farm/.test(e.t));i++){for(const l of S.links)l.cut=0;S.inc=[];__ff();}"); + ev("for(let i=0;i<30&&!S.log.some(e=>/trawler|wind-farm/.test(e.t));i++){for(const l of S.links)l.cut=0;S.inc=[];runNow(__ff());}"); assert.ok(ev("S.log.some(e=>/trawler|wind-farm/.test(e.t))"), 'a North Sea boat found the cable'); // Bettembourg's chillers run on steam from burning waste wood ev("S.pops={bet:{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}};window.__ac=" + src.replace('type=pick(f);}', "type='ac';}")); - ev("for(let i=0;i<20&&!S.log.some(e=>/waste-wood/.test(e.t));i++){S.pops.bet.hot=0;S.inc=[];__ac();}"); + ev("for(let i=0;i<20&&!S.log.some(e=>/waste-wood/.test(e.t));i++){S.pops.bet.hot=0;S.inc=[];runNow(__ac());}"); assert.ok(ev("S.log.some(e=>/waste-wood/.test(e.t))"), 'the forestry strike'); assert.deepEqual(errors, []); }); @@ -692,18 +692,18 @@ test('Australian failures: cockatoos, kangaroos and emus cut land fiber, and rou ev("ACT.pickStart({city:'syd'});ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0"); ev("ACT.buildPop({city:'mel'});S.links=[];UI.via=null;UI.lmode='wave';openLinkModal('syd','mel');ACT.buildLink({tier:1});closeModal()"); assert.equal(ev('S.links.length'), 1); - const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function'); + const src = ev('failureRun.toString()').replace(/^function\* failureRun/, 'function*'); const AU = /cockatoo|kangaroo|backhoe|emus|Bushfire|copper/; ev('window.__cut=' + src.replace('type=pick(f);}', "type='cut';}")); let seen = false; - for (let i = 0; i < 30 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];__cut()'); seen = AU.test(ev("S.inc.map(x=>x.msg).join(' ')")); } + for (let i = 0; i < 30 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];runNow(__cut())'); seen = AU.test(ev("S.inc.map(x=>x.msg).join(' ')")); } assert.ok(seen, 'an Australian wildlife cut'); seen = false; - for (let i = 0; i < 80 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];__cut()'); seen = /copper/.test(ev("S.inc.map(x=>x.msg).join(' ')")); } + for (let i = 0; i < 80 && !seen; i++) { ev('for(const l of S.links)l.cut=0;S.inc=[];runNow(__cut())'); seen = /copper/.test(ev("S.inc.map(x=>x.msg).join(' ')")); } assert.ok(seen, 'copper thieves who find fiber'); ev('window.__crash=' + src.replace('type=pick(f);}', "type='crash';}")); seen = false; - for (let i = 0; i < 40 && !seen; i++) { ev('for(const c in S.pops){S.pops[c].down=0;S.pops[c].routers=1;}S.inc=[];__crash()'); seen = /Floptus|huntsman/.test(ev("S.inc.map(x=>x.msg).join(' ')")); } + for (let i = 0; i < 40 && !seen; i++) { ev('for(const c in S.pops){S.pops[c].down=0;S.pops[c].routers=1;}S.inc=[];runNow(__crash())'); seen = /Floptus|huntsman/.test(ev("S.inc.map(x=>x.msg).join(' ')")); } assert.ok(seen, 'an Australian router crash'); assert.deepEqual(errors, []); }); diff --git a/tests/route-worker.test.js b/tests/route-worker.test.js index 30256d9..116206a 100644 --- a/tests/route-worker.test.js +++ b/tests/route-worker.test.js @@ -41,7 +41,8 @@ test('a day split around its routing is the same day; tests never use the worker 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);}'); + // Every routing it asks for done by hand (a DAY_REST is only a place to let a frame through, not a routing). + b.ev("for(let i=0;i<3;i++){const g=dayRun();for(let s=g.next();!s.done;s=g.next())if(s.value!==DAY_REST)compute();}"); 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); diff --git a/tests/specialist.test.js b/tests/specialist.test.js index 94e9f42..b3a061a 100644 --- a/tests/specialist.test.js +++ b/tests/specialist.test.js @@ -114,7 +114,7 @@ test('#173 a consortium seat: offer, pay, build, light, cut, save', () => { ev(`ACT.subUpgrade({id:'${l.id}',k:'terminal'})`); assert.equal(ev(`S.links.find(l=>l.id==='${l.id}').subterminal`), undefined, 'the consortium owns the terminals'); // A cut on the cable cuts your share. - ev(`S.links=S.links.filter(l=>l.id==='${l.id}');eval('('+fireFailure.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')()`); + ev(`S.links=S.links.filter(l=>l.id==='${l.id}');runNow(eval('('+failureRun.toString().replace('for(const o of opts){r-=o[1];if(r<=0){type=o[0];break;}}',\"type='cut';\")+')')())`); assert.ok(ev(`linkDown(S.links.find(l=>l.id==='${l.id}'))`), 'the cut takes your pairs down too'); assert.deepEqual(errors, []); });