Merge pull request #313: every routing a day needs runs in the route worker, and a long day lets frames through

Conflicts with main resolved: the intern's chosen router model, optical upgrades and personas are generators like the
other orders, with a rest after each job. The optical upgrade's fiber test is a step the day answers, in the route
worker in play (opsDark(), {dark}), like the sales desk's trial; the renewal desk's reroute is a step too (slRenRun()).
This commit is contained in:
Frederic Jung 2026-11-06 22:47:54 +01:00
commit 410eb81544
No known key found for this signature in database
28 changed files with 612 additions and 141 deletions

View file

@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
- France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach.
- 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

View file

@ -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()`; renewal haggles: `S.slAuto.ren`, `slRenDay()`) |
| `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.

View file

@ -24,18 +24,28 @@ 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<w){A.rep=A.wk;logNote(`<b>${esc(tr('sales.desk'))}</b> ${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&&v<A.min){const b0=S.biz.length;ACT.decline({id:o.id});W.x++;if(S.biz.length>b0){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.cash<bizMo(o)))continue;ACT.accept({id:o.id});if(won(o))used.set(k,(used.get(k)||0)+o.bw);continue;}
if(!bCities(o).every(popUp))continue;
if(p==='shark'){if(S.cash<bizMo(o)||(T.event&&!(o.start>d)))continue;ACT.accept({id:o.id});won(o);continue;}
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&&v<A.min){const b0=S.biz.length;ACT.decline({id:o.id});W.x++;if(S.biz.length>b0){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.cash<bizMo(o)))return;ACT.accept({id:o.id});if(won(o))used.set(k,(used.get(k)||0)+o.bw);return;}
if(!bCities(o).every(popUp))return;
if(p==='shark'){if(S.cash<bizMo(o)||(T.event&&!(o.start>d)))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)continue;tries++;ACT.accept({id:o.id,auto:true});if(!won(o))tried.set(o.id,d);}});
if(dirty)compute();}
if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)return;tries++;b=offerTrialOf(o);return true;});
if(!todo)continue;
// o: the offer itself, for a trial the page has to run again on the game as it is by then (dayAgain()).
const got=b?yield {trial:b,hx:offerHealthy(b),o}:null;
// Signed or declined by hand while the trial routed: it is not the desk's.
if(!S.offers.includes(o))continue;
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;}

View file

@ -12,9 +12,11 @@ const SL_REN_WAIT=3;
const slRenOn=()=>!!(S&&S.slAuto&&S.slAuto.ren&&slP());
// The day the desk answers this haggle: a few days after it opened (30 days before the term ends), today at the earliest.
const slRenAt=b=>b.hag.until-30+SL_REN_WAIT;
function slRenDay(d){if(!slRenOn())return;const p=slP();let any=false;
// A step of the day (dayPost()): its yield is the routing after a price changed. slRenDay() is the same all at once.
function slRenDay(d){runNow(slRenRun(d));}
function* slRenRun(d){if(!slRenOn())return;const p=slP();let any=false;
for(const b of S.biz.slice())if(b.hag&&d>=slRenAt(b)&&d<b.hag.until){slRenOne(b,p);any=true;}
if(any)compute();}
if(any)yield;}
// One haggle: returns what happened (for the tests): 'tech', 'mid', 'cave', 'hold', 'walk', 'golf', 'yes', 'fight'.
function slRenOne(b,p){const ask=b.hag.rate,was=b.rate,mid=clMid(b),nerd=SALES_NERDS.includes(b.type),r=clR(b,'sl|'+p);
const v=x=>({name:esc(slCap()),cust:esc(b.name),...x}),bill=rate=>fmt$(clBill(b,rate));

View file

@ -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)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>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;}}

View file

@ -139,17 +139,18 @@ 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'),m=opsP('routers','model'),fix=m!=='next',
*repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}},
*routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',
load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c)));
// A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a
// step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there.
if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0;
if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue;
const cost=swapCost(c,m);if(!X.can('routers',cost))continue;
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m})))X.did('routers',c+' ⇧'+RG[m].pn);}
if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}
for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue;
const ld=load(c);if(ld<at)continue;
const rt=p.routers||1,g=p.rgen||0,nx=mainRG(RG[g].cls+1);
@ -158,8 +159,8 @@ const OPS_RUN={
const swap=!fix&&nx>=0&&rgOpen(nx)&&!modelFits(c,nx)&&(rt>1||popIdle(c)),add=rt<RMAX;
const doSwap=how==='swap'?swap:how==='add'?false:swap&&(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)*opsAhead();if(!(peak>0))continue;
@ -177,11 +178,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.
@ -200,8 +201,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()<N*o.use;step++){
const lag=o.lag(),wantLag=o.n()<2&&o.rt>1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig();
if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;}))break;
X.did('ports',o.at+' '+job.w);}},
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)*opsAhead();
// New fiber gets its first channel; lit fiber gets more while it runs hot.
@ -213,20 +214,20 @@ 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);}}},
optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
cap+=optG(o,l);X.did('optics',l.a+'|'+l.b);yield;}}},
*optup(X){const at=opsP('optup','at')/100,goal=opsP('optup','sys'),swap=opsP('optup','swap');let ups=0,tries=0;
const hot=l=>{const c=dfCap(l);return c>0&&((R.load&&R.load[l.id])||0)*opsAhead()>=c*at;},full=l=>freeCh(l)<=0,u=l=>((R.load&&R.load[l.id])||0)/Math.max(1,dfCap(l));
const ls=S.links.filter(l=>l.kind==='df'&&!l.seat&&l.ready<=S.day&&!(l.eqDown>S.day)&&!(l.cut>S.day)).sort((a,b)=>u(b)-u(a));
for(const l of ls){
// The line system: one step at a time up to the chosen one, or the next one where the fiber is full and hot.
const want=goal==='next'?(full(l)&&hot(l)?sysNext(l):null):SYS_RANK[l.sys]<SYS_RANK[goal]?goal:null;
if(want&&ups<OPTUP_MAX*(opsIs('kevin')?2:1)&&tries<OPTUP_TRY*(opsIs('kevin')?2:1)){const to=sysNext(l),cost=sysUpCost(l);
if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){tries++;const ok=opsDarkOk(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(to&&techOk('sys',to,DF_SYS[to].lvl)&&!(OPTUP_NO.get(l.id)>S.day)&&X.can('optup',cost)){tries++;const ok=yield* opsDark(l,X);if(!ok)OPTUP_NO.set(l.id,S.day+OPTUP_WAIT);
if(ok){const s0=l.sys,top=goal==='next'?to:goal;
for(let k=0;k<2&&sysNext(l)&&SYS_RANK[l.sys]<SYS_RANK[top];k++){const nx=sysNext(l);
if(!techOk('sys',nx,DF_SYS[nx].lvl)||!X.can('optup',sysUpCost(l))||!X.pay('optup',()=>{const s=l.sys;ACT.upSys({id:l.id});return l.sys!==s;}))break;}
// The fiber is dark until tomorrow: its optics wait.
if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);continue;}}}}
if(l.sys!==s0){ups++;X.did('optup',l.a+'|'+l.b+' ⇧'+SYS_TAG[l.sys]);yield;continue;}}}}
// Optics: a full, hot fiber trades its smallest channels for the biggest optic that fits, one at a time. Hitless, and
// the old optics go on the shelf as spares.
if(!swap)continue;
@ -240,32 +241,35 @@ const OPS_RUN={
const was=dfCap(l);
X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2});
if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;});
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));}}},
caches(X){const g=opsP('caches','g');
if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}},
*caches(X){const g=opsP('caches','g');
for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue;
const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9;
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&&!opsIs('annie'))return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');}
for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}},
// Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181).
pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid');
*pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;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);}},
// Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift
// let a frame through or waited for a routing, and the batch's quote would order it a second time.
for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
const q=pniRequote(q0);if(!q)continue;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)<capOf(big)&&!S.biz.some(b=>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)<load*1.25)break;if(!opsDecomSafe(l))continue;cap-=capOf(l);UI.confirm=l.id;X.pay('decom',()=>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)<load*1.25)break;if(!opsDecomSafe(l))continue;cap-=capOf(l);UI.confirm=l.id;X.pay('decom',()=>ACT.rmLink({id:l.id}));if(!S.links.includes(l))X.did('decom',l.a+'|'+l.b);yield;}}},
};
// Line system swaps per shift, and how many fibers a shift may test for one: each test routes the whole network once,
// so a shift costs at most one routing more, and only on a night with a fiber to try. A fiber that failed the test is not tested again for a week
@ -275,23 +279,51 @@ const OPTUP_MAX=1,OPTUP_TRY=1,OPTUP_WAIT=7,OPTUP_NO=new Map(),SYS_RANK={lite:0,r
function opsAround(l){const adj={};for(const x of S.links){if(x===l||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 u=q.pop();if(u===l.b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
// A day without this fiber: does every gigabit still get where it went today, and every circuit stay whole? Today's routing
// is the yardstick (routed again first if this shift already changed the network); R is put back after.
function opsDarkOk(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){compute();X.dirty=false;}
const R0=R,e0=l.eqDown,s0=R0.served,L0=R0.l2||{};
// is the yardstick (routed again first if this shift already changed the network). Both routings are steps the day
// answers (OPS_ROUTE, then {dark}: opsDarkTrial(), in play in the route worker).
const OPS_ROUTE={route:true};
function* opsDark(l,X){if(S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;if(X.dirty){yield OPS_ROUTE;X.dirty=false;}
return !!(yield {dark:l.id,s0:R.served,L0:R.l2||{}});}
// The test itself, on the game it is given: R is put back after.
function opsDarkTrial(y){const l=S.links.find(x=>x.id===y.dark);if(!l)return false;const R0=R,e0=l.eqDown,s0=y.s0,L0=y.L0;
try{l.eqDown=S.day+1;compute();return R.served>=s0-1e-6*Math.max(1,s0)&&Object.keys(L0).every(id=>(R.l2[id]||0)>=L0[id]-1e-6);}
finally{if(e0===undefined)delete l.eqDown;else l.eqDown=e0;R=R0;}}
// The same test overtaken by an action: its checks, and today's routing as the yardstick, as the game is now.
function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l||S.biz.some(b=>b.link===l.id)||!opsAround(l))return false;
return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});}
// A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first.
function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true;
const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true);
const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}}
// 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','optup','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<w){O.rep=O.wk;logNote(`<b>${esc(tr('ops.shift_report',{name:opsName()}))}</b> ${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 bare yield
// is a rest; OPS_ROUTE or a {dark} test is a routing the day answers (v, passed back in).
const step=(k,st,v)=>opsQuiet(()=>{if(ui){UI.sel=ui.sel;UI.confirm=ui.cf;UI.tab=ui.tab;}st.ask=undefined;
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){const s=st.it.next(v);if(s.done)st.done=true;else st.ask=s.value;}}
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};let v;for(;;){step(k,st,v);v=undefined;if(st.done)return;
if(st.ask===OPS_ROUTE)yield;else if(st.ask&&st.ask.dark)v=yield st.ask;else 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.
// Kevin rolls the same dice (so a seeded game plays the same whoever is hired) and catches it before pressing Enter.
@ -301,7 +333,7 @@ function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mo
e.f=f;e.c=c;toast(esc(opsFFLine(e)),'',[{l:tr('ops.ops'),act:'opsOpen',args:{}}]);}}
if(X.up)e.up=Math.round(X.up);if(Math.round(X.mo))e.mo=Math.round(X.mo);
// Stopping at a budget changes nothing a route depends on: no recompute for that.
if(X.dirty)compute();
if(X.dirty)yield;
if(e.r.length||e.f!==undefined){O.log.unshift(e);O.log.length=Math.min(O.log.length,OPS_LOG);}
// The day's detail stays in the Ops sheet; the NOC gets one notice a week (above).
const W=O.wk;for(const [k,n,ws] of e.r){W.n[k]=(W.n[k]||0)+n;const a=W.wh[k]||(W.wh[k]=[]);for(const x of ws)if(a.length<3&&!a.includes(x))a.push(x);}

View file

@ -13,10 +13,16 @@ function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead});
return lead;}
// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free.
const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots(p);return r;};
// A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say).
// Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them.
const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;};
function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null;
const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0;
// Pending augments and earlier orders in this batch already own their future ports.
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+pniUpSlots(p);
for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
// Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G.
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots;

View file

@ -1,13 +1,14 @@
/* Routing off the main thread. The worker is this page's own game script run a second time
from a Blob URL: nothing is fetched, so GitHub Pages still serves one page. In the worker, DOM globals are inert
stand-ins and boot() never runs; the catalogs (cities, networks, cones) are rebuilt from the same code.
Only the day uses it: dayPre(), then S goes to the worker, the day waits (no next day starts) and dayPost() runs
when R is back, so a day sees exactly the routing it would have had in one go. An action in between routes
synchronously as always (compute() bumps RW.gen); then the worker's answer is stale and the action's R stands.
Only the day uses it: the day is a generator (dayRun(), 10-day-tick.js) whose every yield is a routing it needs.
Each one goes to the worker with S, the day waits (no next day starts) and goes on when R is back, so a day sees
exactly the routing it would have had in one go. An action in between routes synchronously as always (compute()
bumps RW.gen); then the worker's answer is stale and the action's R stands.
Tests (no Worker in jsdom, __TUBES_TEST__) and any worker failure take the synchronous path. */
const RW_IN=!!self.__TUBES_WORKER__;
const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null;
const RW={w:null,dead:false,seq:0,gen:0,job:null,stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}};
const RW={w:null,dead:false,seq:0,gen:0,job:null,budget:8,later:f=>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,52 @@ 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=dayAgain(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 or the intern's fiber test'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<RW.budget)continue;rwRest(g);return;}
// A routing, or a test (a sales trial, the intern's fiber test): the worker routes the game it is sent with the offer
// added or the fiber dark, and says yes or no.
const tr=dayAsk(s.value)?s.value:null,here=()=>{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:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{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 again here, checks included, on the game as it is now (dayAgain()).
if(j.tr){if(m.err)console.error('[tubes] route worker',m.err);v=m.err||RW.gen!==j.gen?dayAgain(j.tr):j.tr.dark?!!m.ok: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 +82,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=m.trial.dark?opsDarkTrial(m.trial):!!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)});}}

View file

@ -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<q.length;h++)for(const v of adj[q[h]])if(!m.has(v)){m.set(v,n);q.push(v);}n++;}return m;}
function terrestrialPath(a,b){if(TERR&&TERR.S===S){if(TERR.gen!==RW.gen||!TERR.m){TERR.gen=RW.gen;TERR.m=terrIslands();}
if(a===b)return true;const A=TERR.m.get(a);return A!==undefined&&A===TERR.m.get(b);}const ls=S.links.filter(l=>!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}
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);

View file

@ -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;

View file

@ -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,13 +116,15 @@ 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();
// This failure's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const last=S.inc[S.inc.length-1];
yield;
if(!last)return;
last.impact=Math.max(0,before-R.served);
if(before>1&&last.impact<before*0.03&&type!=='ddos'){S.stats.survived++;toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost&&S.inc.includes(last)?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
sfx('alert');
}
const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0);

View file

@ -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;i<k.n;i++)yield;}
function fireEvent(){
const opts=['viral','price','grant'];
if(S.day>50)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');}

View file

@ -18,25 +18,29 @@ 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(d<M.next)return;if(S.links.filter(l=>l.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;
// The snip's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const i=S.inc[S.inc.length-1];yield;const 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?`<b>🐒 ${incTitle('cut')}</b><br>${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);}}

View file

@ -1,13 +1,33 @@
/* ---------- 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;}};
// The intern's fiber test ({dark}, 95-standing-orders.js) is asked the same way, and answers true or false.
const dayAsk=y=>!!y&&(!!y.trial||!!y.dark);
const dayAnswer=y=>y.dark?opsDarkTrial(y):offerTrial(y.trial,y.hx);
// The same trial overtaken by an action (a customer gone shifts S.biz, so hx no longer points at the right ones):
// its checks, the customer and who is happy, made again on the game as it is now.
const dayAgain=y=>{if(y.dark)return opsDarkAgain(y);const o=y.o;if(!o||!S.offers.includes(o))return null;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;};
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(dayAsk(y))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 +47,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 +69,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 +79,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?`<br><i>${esc(why)}</i>`:'')+(paused?`<br><b>${tr('common.game_paused')}</b>`:''),'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?`<br><i>${esc(why)}</i>`:''),'',[{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);slRenDay(d);
salesDay(d);yield* slRenRun(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.length<myFab(c).max){
const cands=NETS.filter(n=>n.type!=='t1'&&!m.members.includes(n.id)&&(n.pops.includes(c)||n.pops.some(p=>CITY[p].reg===CITY[c].reg)));
@ -74,19 +97,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()<Math.min(5,+S.scn.rules.anchors||1)*n/365){dirty=true;fireFailure('cut');}}
if(cm&&d>=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()<Math.min(5,+S.scn.rules.anchors||1)*n/365){dirty=true;yield* failureRun('cut');}}
if(cm&&d>=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');}

View file

@ -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

241
tests/day-steps.test.js Normal file
View file

@ -0,0 +1,241 @@
// 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, []);
});
// What the player does while a step waits for the worker: the step goes on with the game as it is by then.
const TICK_ERR = "window.__te=[];tickErr=e=>__te.push(String(e&&e.stack||e));";
test('a customer dropped while a sales trial routes: the trial runs again on the customers left', (t) => {
const p = played(t);
p.ev(TICK_ERR);
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()');
for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {
if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; }
// A trial the offer passes, the last customer among the happy ones: that customer goes, and the trial's list of
// who was happy (indices in S.biz) now points one past the end.
if (!found && p.ev('__q.length&&!!__q[0].trial&&!!__q[0].trial.hx&&__q[0].trial.hx.includes(S.biz.length-1)&&!!offerTrial(__q[0].trial.b,__q[0].trial.hx)')) {
found = true; p.ev('__ot=0;const b=S.biz[S.biz.length-1];UI.confirm=b.id;ACT.dropBiz({id:b.id});');
}
p.pump1();
}
}
assert.ok(found, 'the desk trialled an offer');
assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran again on the page');
assert.equal(p.ev('JSON.stringify(__te)'), '[]');
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');
assert.deepEqual(p.errors, []);
});
test("the intern's PNI round never orders again what the player ordered while it waited", (t) => {
// The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile.
const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true;
const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a);
window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0;
for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;}
window.__n=S.pni.length-n0;`;
const key = "S.pni.map(p=>p.city+'|'+p.net)";
const ref = open(t, 777), p = open(t, 777);
ref.ev(SETUP); p.ev(SETUP);
ref.ev(ROUND(false));
assert.ok(ref.ev('__b.orders.length') > 0 && ref.ev('__n') > 0, `the intern orders PNIs: ${ref.ev('__n')} of ${ref.ev('__b.orders.length')}`);
p.ev(ROUND(true));
assert.ok(p.ev('__h') > p.ev('S.pni.length') - p.ev('__n'), 'the player ordered some by hand');
assert.equal(p.ev('S.pni.length'), p.ev('__h'), 'the intern ordered nothing more');
const keys = p.ev(key);
assert.equal(new Set(keys).size, keys.length, 'one PNI per city and network');
assert.deepEqual([...ref.errors, ...p.errors], []);
});
test('an incident repaired while its routing runs: the failure and the monkey still tell its own story', (t) => {
const p = open(t, 777);
p.ev(SETUP);
// On land: a repair clears the incident (at sea it would charter a ship).
p.ev("S.rules.sea='timer';S.inc=[];");
// Repaired before the answer, the only incident there was: nothing left to read as "the last one".
p.ev(`const g=failureRun('cut');g.next();window.__i=S.inc[S.inc.length-1];ACT.fixInc({id:__i.id});g.next();`);
assert.equal(p.ev('S.inc.length'), 0);
assert.equal(p.ev('typeof __i.impact'), 'number', 'its impact is its own');
// An older incident stands: the new one's impact is not pinned on it.
p.ev(`runNow(failureRun('cut'));window.__a=S.inc[S.inc.length-1];__a.impact=-7;
const g2=failureRun('cut');g2.next();window.__b=S.inc[S.inc.length-1];ACT.fixInc({id:__b.id});g2.next();`);
assert.equal(p.ev('__a!==__b&&S.inc.includes(__a)&&!S.inc.includes(__b)'), true);
assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
assert.equal(p.ev('typeof __b.impact'), 'number');
// The monkey's snip, the same way.
p.ev(`S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day,n:0,hurt:0,c:S.home,next:S.day};
const g3=mkSnipRun();g3.next();window.__c=S.inc[S.inc.length-1];ACT.fixInc({id:__c.id});g3.next();`);
assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
assert.equal(p.ev('typeof __c.impact'), 'number');
assert.deepEqual(p.errors, []);
});

View file

@ -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

View file

@ -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()');

View file

@ -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

View file

@ -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();

View file

@ -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");

View file

@ -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');
@ -1316,7 +1316,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/);

View file

@ -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, []);
});

View file

@ -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, []);

View file

@ -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");

View file

@ -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, []);
});

View file

@ -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);

View file

@ -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, []);
});