From 13a29c2c2a7562a649e0cb1869d191e79dd20f2d Mon Sep 17 00:00:00 2001 From: Florian Krieger Date: Sun, 25 Oct 2026 15:38:10 +0100 Subject: [PATCH 01/13] Add on-demand single-link redundancy checks --- CHANGELOG.md | 2 ++ site/i18n/it.js | 13 +++++++++++++ site/index.html | 24 +++++++++++++++++++++--- tests/issues.test.js | 17 +++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c36434..bf32aa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. + ## [1.25.2] — 2026-10-25 - Tier 1 networks can lay their own subsea cable (#22). Pick two cities with a diff --git a/site/i18n/it.js b/site/i18n/it.js index 8a0542a..46aeda8 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2248,4 +2248,17 @@ "Replace ten of them and the cable pays for itself in about {n} months.":"Sostituiscine dieci e il cavo si ripaga in circa {n} mesi.", "Cuts still happen, anchors and sharks included, but the repair ship is yours to call.":"I tagli succedono lo stesso, ancore e squali compresi, ma la nave di riparazione la chiami tu.", "Lay the cable {price}":"Posa il cavo {price}", +"This backhoe wins.":"Questa ruspa vince.", +"Connected, but tight.":"Connesso, ma al limite.", +"One backhoe is not enough.":"Una ruspa non basta.", +"Redundancy check":"Verifica della ridondanza", +"No alternate backbone path connects these endpoints if this link fails.":"Se questo collegamento si interrompe, nessun percorso alternativo della dorsale collega questi estremi.", +"An alternate path exists, but current routing and capacity deliver less traffic.":"Esiste un percorso alternativo, ma con routing e capacità attuali viene consegnato meno traffico.", +"With current demand and routing, this link can fail without additional traffic loss.":"Con domanda e routing attuali, questo collegamento può interrompersi senza ulteriori perdite di traffico.", +"Additional traffic lost":"Ulteriore traffico perso", +"Service affected":"Servizio interessato", +"Full links during the test":"Collegamenti saturi durante il test", +"Snapshot only: one selected link fails. Other links on the same cable, trench or fabric stay up. Existing outages and routing rules still apply. No time, money or game state is changed.":"Solo un’istantanea: si interrompe il collegamento selezionato. Gli altri collegamenti sullo stesso cavo, scavo o fabric restano attivi. I guasti e le regole di routing esistenti si applicano comunque. Tempo, denaro e stato della partita non cambiano.", +"What happens if this link fails right now?":"Cosa succede se questo collegamento si interrompe adesso?", +"Check redundancy":"Verifica ridondanza", }; diff --git a/site/index.html b/site/index.html index 44a609b..ab5b4aa 100644 --- a/site/index.html +++ b/site/index.html @@ -427,6 +427,7 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #coach{top:auto !important;bottom:calc(var(--tabbar) + 8px);width:calc(100% - 16px);padding:7px 10px;font-size:13px} body.sheet-open #coach{bottom:calc(var(--tabbar) + 8px + min(62vh,520px))} #modal{align-items:end;padding:0} + #modal.link-check{bottom:var(--tabbar)} #modal .cta{position:sticky;bottom:calc(-16px - env(safe-area-inset-bottom,0px));z-index:1;background:var(--paper);margin:12px -16px 0 !important;padding:10px 16px calc(10px + env(safe-area-inset-bottom,0px));border-top:2px solid var(--line)} .title-art h1{font-size:34px}.title-art svg{width:54px;height:54px} .tagline{font-size:13.5px;margin:8px 0 10px} @@ -2443,6 +2444,7 @@ function checkGoals(){checkBadges(); /* ================= ACTIONS ================= */ function spend(c){if(S.cashNot enough cash.
Wait for revenue, or speed up time.'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;} const ACT={ + linkCheck:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);}, speed:({v})=>{v=+v;if(![0,0.5,1,2,4,8].includes(v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, help:()=>showHelp(), dash:()=>{if(!S)return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();}, @@ -2470,7 +2472,7 @@ const ACT={ tab:({t})=>{UI.tab=t;UI.confirm=null;renderPanel();}, leftTab:({t})=>{UI.left=t;UI.leftOpen=true;renderLeft();}, toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();}, - phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();}, + phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;if($('modal').classList.contains('link-check'))closeModal();haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();}, phonePlay:()=>{haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();}, phoneSpeed:()=>{haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();}, install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;} @@ -3041,9 +3043,25 @@ function vxcPanel(l){ return h; } function prefCtl(kind,id,cur){cur=cur||'normal';return `
${tr('Egress:')}${Object.keys(PREF).map(v=>btn(PREF[v],'setPref',{kind,id,v},cur===v?'pink sm':'ghost sm')).join('')}
`;} +// Trial routing is isolated from the live save, counters and scenic-route memory. +function linkTrial(id){const save=S,live=R,hot=UI.hotMap,cache=TE_CACHE; + try{S=JSON.parse(JSON.stringify(save));const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return null; + compute();const before=R;l.cut=S.day+1;compute(); + const allowed=new Set(Object.keys(S.pops).filter(popUp).concat(remoteCities())),adj={}; + for(const x of S.links)if(!linkDown(x)&&allowed.has(x.a)&&allowed.has(x.b)){(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];for(let i=0;i.01)losses.push({name:CITY[c].name,g});} + for(const b of S.biz)if(BIZ_T[b.type].l2){const g=Math.max(0,(before.l2[b.id]||0)-(R.l2[b.id]||0));if(g>.01)losses.push({name:b.name,g});} + const busy=S.links.filter(x=>x.id!==id&&!linkDown(x)&&capOf(x)>0&&(R.load[x.id]||0)/capOf(x)>=.995).map(x=>({name:CITY[x.a].name+' ⇄ '+CITY[x.b].name,g:R.load[x.id]||0,cap:capOf(x)})); + return {split:!seen.has(l.b),loss:losses.reduce((a,x)=>a+x.g,0),losses,busy,day:S.day}; + }finally{S=save;R=live;UI.hotMap=hot;TE_CACHE=cache;}} +function linkCheckModal(l){const t=linkTrial(l.id);if(!t)return; + const title=t.split?tr('This backhoe wins.'):t.loss>.01?tr('Connected, but tight.'):tr('One backhoe is not enough.'); + openModal(`

${tr('Redundancy check')}

${esc(CITY[l.a].name)} ⇄ ${esc(CITY[l.b].name)} · ${dateStr(t.day)}

${title}

${t.split?tr('No alternate backbone path connects these endpoints if this link fails.'):t.loss>.01?tr('An alternate path exists, but current routing and capacity deliver less traffic.'):tr('With current demand and routing, this link can fail without additional traffic loss.')}

${tr('Additional traffic lost')}${fmtG(t.loss)}
${t.losses.length?`

${tr('Service affected')}

${t.losses.map(x=>`
${esc(x.name)}−${fmtG(x.g)}
`).join('')}`:''}${t.busy.length?`

${tr('Full links during the test')}

${t.busy.slice(0,6).map(x=>`
${esc(x.name)}${fmtG(x.g)} / ${fmtG(x.cap)}
`).join('')}`:''}

${tr('Snapshot only: one selected link fails. Other links on the same cable, trench or fabric stay up. Existing outages and routing rules still apply. No time, money or game state is changed.')}

${btn(tr('Close'),'closeModal',{},'ghost')}
`,'link-check');} +function linkCheckControl(l){return `

${tr('Redundancy check')}

${tr('What happens if this link fails right now?')}

${btn(tr('Check redundancy'),'linkCheck',{id:l.id},'ghost sm',linkDown(l))}
`;} function trafficSection(l){ const rec=R.ef[edgeKey(l)],n=pairLinks(l.a,l.b).length; - let h=`

${tr("What's on this link")}

`; + let h=linkCheckControl(l)+`

${tr("What's on this link")}

`; if(!rec){return h+`

${tr('No traffic right now.')}

`;} const tot=Object.values(rec.net).reduce((a,b)=>a+b,0)||1; const nets=Object.entries(rec.net).sort((a,b)=>b[1]-a[1]); @@ -3297,7 +3315,7 @@ function toast(html,kind='',actions=[]){ const markLayer=()=>{UI.layerAt=performance.now();}; // Which layers are open: when that changes (a sheet, the dashboard, the bank, a selection), taps in flight are void. function checkLayer(){const q=id=>{const e=$(id);return e?(e.hidden?0:1):0;},sig=[q('modal'),q('dash'),q('bankBox'),UI.leftOpen?1:0,UI.left||'',UI.sel?UI.sel.type+UI.sel.id:'',UI.tab||''].join('|');if(sig!==UI._layer){UI._layer=sig;markLayer();}} -function openModal(html){if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;} +function openModal(html,cls=''){$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;} function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;} const NETWORK_NAMES=[ 'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom', diff --git a/tests/issues.test.js b/tests/issues.test.js index 13b30b8..06bfc03 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -539,3 +539,20 @@ test('#35 your own trench can light another fiber pair once a ROADMaster is full assert.equal(ev('S.links[0].pairs'), 4, 'saves are clamped to four pairs'); assert.deepEqual(errors, []); }); + +test('link redundancy trials distinguish a bridge, a full fallback and a healthy alternate path without changing the game',()=>{ + const {ev,errors}=load(); + ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}];S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0,trench:'main'}];compute();window.state=JSON.stringify(S);window.live=R;window.hot=UI.hotMap;window.cache=TE_CACHE"); + let t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,true);assert.equal(t.loss,80); + assert.equal(ev('JSON.stringify(S)'),ev('state'));assert.equal(ev('R===live&&UI.hotMap===hot&&TE_CACHE===cache'),true); + ev("S.links.push({id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0});compute()"); + t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,70);assert.equal(t.busy.length,2); + ev("S.links[1].tier=1;S.links[2].tier=1;compute()");t=JSON.parse(ev("JSON.stringify(linkTrial('main'))"));assert.equal(t.split,false);assert.equal(t.loss,0); + ev("S.links[1].cut=S.day+5;compute()");assert.equal(ev("linkTrial('main').split"),true,'existing failures are respected');assert.equal(ev("linkTrial('a')"),null,'an already failed link is not tested'); + ev("S.links=S.links.slice(0,1);S.links.push({...S.links[0],id:'parallel'});compute()");assert.equal(ev("linkTrial('main').split"),false,'only the selected link fails even when a trench is shared');assert.equal(ev("linkTrial('main').loss"),0); + ev("S.links[0]={...S.links[0],kind:'df',sys:'roadm',ch:['tp16'],pairs:1,regen:0,ready:0,own:true};compute()");assert.equal(ev("linkTrial('main').loss"),0,'dark fiber is tested as one link'); + ev("window.innerWidth=360;ACT.linkCheck({id:'main'})");assert.match(ev("$('modalCard').textContent"),/One backhoe is not enough/);assert.equal(ev("$('modal').className"),'link-check');ev("ACT.phoneTab({t:'noc'})");assert.equal(ev("$('modal').hidden"),true); + ev("S.links[0]={...S.links[0],kind:'vxc',vt:1,prov:FABS[0].id};compute()");assert.equal(ev("linkTrial('main').loss"),0,'virtual circuits are tested individually'); + ev("window.saveRef=S;window.liveRef=R;window.originalCompute=compute;compute=()=>{throw Error('trial failed')}");assert.throws(()=>ev("linkTrial('main')"),/trial failed/);ev('compute=originalCompute');assert.equal(ev('S===saveRef&&R===liveRef'),true,'even a failed trial restores the live state'); + assert.deepEqual(errors,[]); +}); From af155f27bb504086376a474053dbaca3d3f88ac7 Mon Sep 17 00:00:00 2001 From: clayberF <49653677+clayberF@users.noreply.github.com> Date: Sun, 25 Oct 2026 22:38:19 -0300 Subject: [PATCH 02/13] Calibrate city prices with PeeringDB and Hurricane Electric data CITY_PDB holds, per city, the carrier-neutral facilities and network presences from PeeringDB (within 50 km or same city name) and the ASN count of its country from bgp.he.net, pulled 2026-10-25. - Transit: the regional multiplier is scaled by competition, up to 1.8x where few networks are present. Hubs (1000+ presences) are unchanged, and hand-set markets (Korea, Belgian red tape) keep their price. - POPs: 1.25x to build and run with one or two facilities, 1.5x with none. - Offers: countries with 2000+ ASNs bring extra ISP customers. --- CHANGELOG.md | 2 ++ site/i18n/it.js | 1 + site/i18n/pt.js | 1 + site/index.html | 24 +++++++++++++++++++----- tests/regions.test.js | 16 ++++++++++++++++ 5 files changed, 39 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04b01be..e476617 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Prices now follow how connected each city really is, based on PeeringDB and Hurricane Electric data. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. + ## [1.30.0] — 2026-10-26 - Twelve Pacific islands join the map: Honolulu, Guam, Koror, Majuro, Port Moresby, Honiara, Nouméa, Suva, Nuku’alofa, Apia, Pago Pago and Papeete. The cables across the Pacific now stop where they really land, and a POP on an island splits a long crossing into shorter hops that each carry more: California to Sydney goes from 400G to 1.6T per wave via Honolulu and Suva, Hong Kong and Manila to Los Angeles from 400G to 800G via Guam, and Santiago to Sydney from 400G to 800G via Tahiti. Twelve new cables, among them SEA-US Later, Echo-Chamber and Coral Sea Shanty, link the islands, and the old ones gain island stops. Only islands with a real exchange today get one: Honolulu, Guam, Suva, Nouméa and Honiara. Island telcos from Hawaiian Telecombo to Never Too Atoll join the networks, PacNOG meets in Suva every December, Guam, Port Moresby and Honiara have unreliable power, Tonga’s cable has a volcano for a neighbour, and a new scenario, Stepping Stones, asks you to hop the Pacific at 1.6T. diff --git a/site/i18n/it.js b/site/i18n/it.js index 47d9ec7..4a15669 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2585,4 +2585,5 @@ "The seabed off Tonga slid down a slope and took your {a}–{b} cable with it. The repair ship is coming from Papua New Guinea.":"Il fondale al largo di Tonga è franato giù per un pendio e si è portato via il tuo cavo {a}–{b}. La nave di riparazione arriva dalla Papua Nuova Guinea.", "Tonga hangs on one cable from Fiji. In 2022 an undersea volcano cut it, and the country was offline for weeks.":"Tonga è appesa a un solo cavo dalle Figi. Nel 2022 un vulcano sottomarino l’ha tranciato e il paese è rimasto offline per settimane.", "Tonga’s own telco. Lived through a volcano that cut its only cable, and jokes about it now.":"La telco di Tonga. È sopravvissuta a un vulcano che le ha tranciato l’unico cavo, e ora ci scherza su.", +"Few data centers: POPs {x}×":"Pochi data center: POP {x}×", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index b0f10d6..3d2e1f3 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2585,4 +2585,5 @@ "The seabed off Tonga slid down a slope and took your {a}–{b} cable with it. The repair ship is coming from Papua New Guinea.":"O fundo do mar perto de Tonga deslizou encosta abaixo e levou junto o seu cabo {a}–{b}. O navio de reparo está vindo de Papua-Nova Guiné.", "Tonga hangs on one cable from Fiji. In 2022 an undersea volcano cut it, and the country was offline for weeks.":"Tonga depende de um único cabo vindo de Fiji. Em 2022 um vulcão submarino o cortou, e o país ficou offline por semanas.", "Tonga’s own telco. Lived through a volcano that cut its only cable, and jokes about it now.":"A operadora de Tonga. Sobreviveu a um vulcão que cortou seu único cabo e hoje faz piada disso.", +"Few data centers: POPs {x}×":"Poucos data centers: POPs {x}×", }; diff --git a/site/index.html b/site/index.html index 35f84e6..47d0019 100644 --- a/site/index.html +++ b/site/index.html @@ -599,7 +599,7 @@ const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; const SITE2_N=[tr('The Other Building'),tr('Campus B (the one with parking)'),tr('Across-the-River DC'),tr('The Annex'),tr('Suburban Mega-shed'),tr('The Cheaper One'),tr('Formerly a Shopping Mall'),tr('Bunker Two')]; const siteName=(c,s)=>s==='b'?SITE2_N[hstr(c)%SITE2_N.length]:CITY[c].dc; const BE_TAPE=30000; -const popCost=c=>POP_COST+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); +const popCost=c=>Math.round(POP_COST*(c&&CITY[c]?colo(c):1))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); const CN_LIC=150000, CN_JV_MO=6000; // Scrubbing centers come in tiers by clean bandwidth. Always-on diverts instantly; on-demand is cheaper // but takes a couple of days to engage. A clean-pipe add-on on a transit scrubs upstream, per port. @@ -2125,7 +2125,7 @@ function compute(){ for(const e of E){if(e.k==='t')R2.useT[e.id]=(R2.useT[e.id]||0)+e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;} // money const C=R2.cost,V=R2.rev,pm=S.priceMul; - C.pops=Object.values(S.pops).reduce((a,p)=>a+POP_MO+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0); + C.pops=Object.entries(S.pops).reduce((a,[c,p])=>a+popMo(c)+((p.routers||1)-1)*ROUTER_MO+(p.routers||1)*RG[p.rgen||0].mo+(p.gen?GEN_MO:0),0); C.optical=S.links.filter(l=>l.kind==='df').reduce((a,l)=>a+(l.ready>S.day?0:ampCount(l.km)*AMP_MO*(l.own&&isRdm(l.sys)&&!l.sub?Math.max(1,l.pairs|0):1)+(l.regen|0)*REGEN_MO)+(l.spares?Math.round(150+(l.ch||[]).length*80):0),0); C.links=S.links.reduce((a,l)=>a+(l.mo||0),0); C.nni=(S.nni||[]).reduce((a,x)=>a+NNI[x.tier].mo,0); @@ -2305,7 +2305,19 @@ function spawnSpecial(t){const T=BIZ_T[t],mine=Object.keys(S.pops),lv=S.lvl||1; S.offers.push({id:uid(),city:l.a,city2:l.b,link:l.id,what:tr('a spare fiber pair in your {a}–{b} trench',{a:CITY[l.a].name,b:CITY[l.b].name}),name:nm(),type:t,bw:1,rate:Math.round(dfLeaseMo(l.km)*0.9),reqs:[],exp:S.day+30});} } function cnOk(){return S.cnLic&&S.cnLic.state==='ok';} -function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.tape)return 1.5;return C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;} +/* Real-world calibration, pulled 2026-10-25 (Pacific islands 2026-10-26). Per city: [carrier-neutral facilities, network presences across them, + ASNs registered in its country]. Facilities and presences are PeeringDB facilities within 50 km or in the same city + (peeringdb.com/api/fac, net_count summed); ASNs per country are from bgp.he.net/report/world. */ +const CITY_PDB={sea:[37,539,33300],sjc:[57,1048,33300],dal:[59,969,33300],chi:[64,809,33300],ash:[86,1010,33300],nyc:[96,1322,33300],mia:[27,553,33300],sao:[70,1875,9693],lon:[100,2588,4027],ams:[69,2731,1827],fra:[56,2450,3705],par:[77,1528,2249],mrs:[8,273,2249],tor:[46,509,2595],bru:[33,328,443],oos:[5,22,443],bet:[16,174,152],mtl:[35,283,2595],kcy:[22,313,33300],cal:[15,127,2595],van:[13,214,2595],ott:[6,21,2595],lax:[44,939,33300],mex:[18,122,814],rek:[15,51,93],dub:[21,277,350],osl:[20,209,448],cph:[30,290,529],hel:[23,232,427],beg:[7,49,227],sof:[15,451,889],dxb:[8,135,231],mos:[49,632,6683],akl:[27,398,755],per:[12,248,3196],jkt:[98,3015,4108],mnl:[17,352,750],ber:[22,351,3705],ham:[26,228,3705],muc:[22,230,3705],zrh:[38,535,1209],nbo:[9,283,274],cai:[5,28,97],stg:[18,63,3705],sto:[31,539,1011],bcn:[13,159,1341],mad:[31,578,1341],lag:[13,279,304],jnb:[14,561,879],bom:[59,1050,6412],sin:[58,1271,782],hkg:[57,1107,1514],icn:[37,201,1197],pek:[10,15,6717],sha:[11,27,6717],tok:[58,917,1330],syd:[40,979,3196],for:[16,362,9693],rio:[33,577,9693],bsb:[14,108,9693],bhz:[13,40,9693],cwb:[11,79,9693],poa:[22,120,9693],aju:[4,3,9693],bel:[3,7,9693],bvb:[3,6,9693],cac:[4,6,9693],cpv:[4,12,9693],cpq:[19,65,9693],cgr:[4,4,9693],cau:[2,2,9693],cgb:[4,5,9693],cxj:[2,3,9693],fec:[5,4,9693],fln:[5,23,9693],igu:[5,26,124],gyn:[5,28,9693],jpa:[4,18,9693],ljd:[1,2,9693],ldb:[3,7,9693],mcp:[2,0,9693],mcz:[1,5,9693],mao:[7,15,9693],mgf:[4,9,9693],nat:[1,3,9693],pmw:[3,8,9693],pvh:[3,4,9693],rao:[6,3,9693],rec:[6,31,9693],rbr:[0,0,9693],ssa:[13,44,9693],ria:[2,2,9693],sjp:[2,4,9693],slz:[1,6,9693],the:[2,1,9693],vix:[6,30,9693],mvd:[1,2,53],asu:[3,8,124],cor:[2,29,1357],lpb:[1,2,71],uio:[9,16,287],mde:[2,18,598],ccs:[6,32,296],gua:[5,16,103],sjo:[8,6,128],qro:[11,144,814],mty:[5,27,814],gdl:[4,22,814],bue:[28,372,1357],scl:[36,274,450],lim:[12,156,267],bog:[16,195,598],pan:[8,26,158],del:[31,479,6412],maa:[20,374,6412],blr:[14,104,6412],hyd:[17,152,6412],tpe:[15,274,500],auh:[4,1,231],fuj:[1,49,231],cpt:[6,267,879],dkr:[2,4,23],abj:[5,11,32],acc:[7,78,124],dla:[3,14,34],fih:[7,19,57],lad:[8,27,79],cas:[2,2,39],alg:[0,0,16],tun:[2,0,30],jib:[3,19,5],add:[2,3,10],mba:[4,176,274],dar:[9,67,124],kla:[2,18,71],kgl:[5,14,34],mpm:[7,20,36],dur:[4,137,879],wdh:[1,2,22],lun:[4,3,24],hre:[1,0,37],gbe:[1,2,39],mel:[20,395,3196],bne:[21,277,3196],drw:[3,15,3196],osa:[19,229,1330],kul:[20,210,434],bkk:[32,397,675],sgn:[6,36,1068],khi:[7,15,488],dac:[30,107,2105],cbo:[1,0,33],waw:[25,855,2743],prg:[24,336,775],vie:[30,377,860],bud:[6,146,369],buh:[23,289,1424],tll:[7,80,256],ist:[28,334,1290],kyv:[33,506,2342],jed:[5,25,220],ruh:[8,29,220],doh:[6,29,31],mil:[29,728,1534],rom:[12,213,1534],pmo:[3,46,1534],lis:[9,129,187],ath:[6,108,307],atn:[42,589,33300],den:[28,310,33300],phx:[26,279,33300],bos:[31,209,33300],hou:[21,173,33300],slc:[22,202,33300],man:[29,353,4027],edi:[4,46,4027],bde:[0,0,4027],svg:[2,14,448],hnl:[7,33,33300],gum:[6,28,11],ror:[0,0,4],maj:[0,0,12],pom:[2,0,46],hir:[1,0,11],nou:[2,2,19],suv:[0,0,23],tbu:[0,0,5],apw:[0,0,11],ppg:[0,0,2],ppt:[0,0,6]}; +// Few networks in the building means few transit sellers to haggle with: up to 1.8× where almost nobody is present. +// Hand-set markets (Korea, Belgian red tape) keep their own price. +const txComp=c=>{const q=CITY_PDB[c];return q?clamp((1000/Math.max(q[1],10))**0.15,1,1.8):1;}; +// No neutral data center means building your own room: POPs cost more to build and to run. +const colo=c=>{const q=CITY_PDB[c];return !q?1:q[0]===0?1.5:q[0]<=2?1.25:1;}; +const popMo=c=>Math.round(POP_MO*colo(c)); +// Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. +const asnDense=c=>{const q=CITY_PDB[c];return !!q&&q[2]>=2000;}; +function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.tape)return 1.5;const base=C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;return Math.round(base*txComp(c)*10)/10;} const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae; const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain); const borderPair=(a,b)=>!!CITY[a].cc&&!!CITY[b].cc&&CITY[a].cc!==CITY[b].cc; @@ -2730,6 +2742,7 @@ function spawnOffer(){ if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if(lv>=4&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('pairs'); if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); + const dense=mine.filter(asnDense);if(lv>=2&&dense.length)types.push('isp'); const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');} const t=pick(types),T=BIZ_T[t]; if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} @@ -2744,6 +2757,7 @@ function spawnOffer(){ let name=list.length?pick(list):(T.names?pick(T.names):'Startup #'+Math.floor(Math.random()*999)); S.usedNames.push(name); if(t==='provedor')city=pick(br); + if(t==='isp'&&dense.length&&Math.random()<0.5)city=pick(dense); if(t==='hft'){const fin=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash'],mf=mine.filter(c=>fin.includes(c));city=mf.length?pick(mf):pick(mine);city2=pick(fin.filter(c=>c!==city));} const rate=T.l2?Math.round((150+kmBetween(city,city2)*0.08)*T.km):T.rate; if(T.div&&!reqCan('diverse',{city,city2}))return; @@ -3314,12 +3328,12 @@ function renderPanel(){checkLayer(); function cityPanel(c){ const C=CITY[c],p=S.pops[c],ix=ixName(c),down=p&&p.down>S.day; let h=`
${REG[C.reg]} · ${esc(C.dc)}

${C.name}

-
${tr('{g} of eyeballs',{g:fmtG(eyeP(c))})}${regionMult(c)>1?`${tr('Transit {x}× pricier',{x:regionMult(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('Underserved: users grow 60% faster')+'':''}${ix?`${tr('IX: {ix}',{ix:esc(ix)})}`:''}${p?`${tr('Your POP')}`:''}${down?`DOWN`:''}
+
${tr('{g} of eyeballs',{g:fmtG(eyeP(c))})}${regionMult(c)>1?`${tr('Transit {x}× pricier',{x:regionMult(c)})}`:''}${colo(c)>1?`${tr('Few data centers: POPs {x}×',{x:colo(c)})}`:''}${C.reg==='AS'&&!C.cn?''+tr('Underserved: users grow 60% faster')+'':''}${ix?`${tr('IX: {ix}',{ix:esc(ix)})}`:''}${p?`${tr('Your POP')}`:''}${down?`DOWN`:''}
`; if(!p){ h+=`
${C.note?`

${esc(C.note)}

`:''} ${C.cn?chinaSection(c):''}${C.cn&&!cnOk()?'':`

${tr('Open a POP here')}

${tr('A POP (point of presence) is your router in a rack here. Then connect it: lay fiber from one of your POPs, or buy transit right here.')}

- ${C.ru?`

${tr('Includes the mandatory government box in your rack: {cost} + {mo}/mo. It comes with its own listener.',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${btn(tr('Build POP {cost} + {mo}/mo',{cost:fmt$(popCost(c)),mo:fmt$(POP_MO)}),'buildPop',{city:c},'pink big',S.cash${tr('Includes the mandatory government box in your rack: {cost} + {mo}/mo. It comes with its own listener.',{cost:fmt$(RU_BOX),mo:fmt$(RU_BOX_MO)})}

`:''}${btn(tr('Build POP {cost} + {mo}/mo',{cost:fmt$(popCost(c)),mo:fmt$(popMo(c))}),'buildPop',{city:c},'pink big',S.cash${tr('Or drag from one of your routers to this city to lay fiber and build the POP in one go.')}

`}`; h+=offersHere(c); const trs=NETS.filter(n=>n.price&&n.pops.includes(c)); diff --git a/tests/regions.test.js b/tests/regions.test.js index 74a906a..5a3d8f8 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -634,5 +634,21 @@ test('Pacific islands: real landings, real exchanges only, and island hops carry assert.ok(ev('!!S.pops.hnl') && ev('S.lvl') >= 4); assert.equal(ev('scnProg().items.length'), 3); ev('cam.z=0.5;draw(0);cam.z=2;draw(0)'); + +test('prices follow real connectivity: thin markets cost more, hubs stay put', () => { + const { ev, errors } = load(); + start(ev); + assert.ok(ev('Object.keys(CITY_PDB).length') === ev('CITIES.length'), 'every city has real-world data'); + for (const c of ['fra', 'ams', 'lon', 'nyc']) assert.equal(ev(`txComp('${c}')`), 1, `${c} is a hub`); + assert.equal(ev("regionMult('sao')"), 1.6, 'São Paulo keeps the South American price'); + assert.ok(ev("regionMult('rbr')") > ev("regionMult('sao')") * 1.5, 'Rio Branco has few sellers'); + assert.ok(ev("txComp('rbr')") <= 1.8); + assert.equal(ev("colo('rbr')"), 1.5, 'no neutral data center'); + assert.equal(ev("popCost('rbr')"), ev('POP_COST') * 1.5); + assert.equal(ev("popMo('fra')"), ev('POP_MO')); + ev("ACT.buildPop({city:'rbr'});compute()"); + assert.ok(ev('R.cost.pops') >= ev("popMo('rbr')"), 'running cost uses the city rent'); + ev("selectCity('rbr')"); + assert.equal(ev('asnDense("sao")&&asnDense("nyc")&&!asnDense("kgl")'), true); assert.deepEqual(errors, []); }); From 6de56f79ebc7fa3eef1de62c55b1da80e70d8766 Mon Sep 17 00:00:00 2001 From: clayberF <49653677+clayberF@users.noreply.github.com> Date: Mon, 26 Oct 2026 10:00:53 -0300 Subject: [PATCH 03/13] Calibration: drop a redundant guard and a one-caller helper --- site/index.html | 7 +++---- tests/regions.test.js | 4 +++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/site/index.html b/site/index.html index 47d0019..dcf523b 100644 --- a/site/index.html +++ b/site/index.html @@ -599,7 +599,7 @@ const SITE2_COST=45000,SITE2_MO=3000,TE_COST=60000,TE_MO=4000; const SITE2_N=[tr('The Other Building'),tr('Campus B (the one with parking)'),tr('Across-the-River DC'),tr('The Annex'),tr('Suburban Mega-shed'),tr('The Cheaper One'),tr('Formerly a Shopping Mall'),tr('Bunker Two')]; const siteName=(c,s)=>s==='b'?SITE2_N[hstr(c)%SITE2_N.length]:CITY[c].dc; const BE_TAPE=30000; -const popCost=c=>Math.round(POP_COST*(c&&CITY[c]?colo(c):1))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); +const popCost=c=>Math.round(POP_COST*colo(c))+(c&&CITY[c]&&CITY[c].tape?BE_TAPE:0)+(c&&CITY[c]&&CITY[c].ru?RU_BOX:0)+(c&&CITY[c]&&CITY[c].uae?UAE_LIC:0)+(c&&CITY[c]&&CITY[c].saudi?KSA_LIC:0); const CN_LIC=150000, CN_JV_MO=6000; // Scrubbing centers come in tiers by clean bandwidth. Always-on diverts instantly; on-demand is cheaper // but takes a couple of days to engage. A clean-pipe add-on on a transit scrubs upstream, per port. @@ -2315,8 +2315,6 @@ const txComp=c=>{const q=CITY_PDB[c];return q?clamp((1000/Math.max(q[1],10))**0. // No neutral data center means building your own room: POPs cost more to build and to run. const colo=c=>{const q=CITY_PDB[c];return !q?1:q[0]===0?1.5:q[0]<=2?1.25:1;}; const popMo=c=>Math.round(POP_MO*colo(c)); -// Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. -const asnDense=c=>{const q=CITY_PDB[c];return !!q&&q[2]>=2000;}; function regionMult(c){const C=CITY[c];if(!C||C.cn)return 1;if(C.kr)return KR_TRANSIT;if(C.tape)return 1.5;const base=C.reg==='AS'?2.5:C.reg==='AF'?2:C.reg==='OC'?1.8:C.reg==='SA'?1.6:1;return Math.round(base*txComp(c)*10)/10;} const uaePair=(a,b)=>!!CITY[a].uae&&!!CITY[b].uae; const rainPair=(a,b)=>!!(CITY[a].rain||CITY[b].rain); @@ -2742,7 +2740,8 @@ function spawnOffer(){ if(lv>=3&&MEGA.some(m=>mine.includes(m.c)))types.push('ingest');if(lv>=4&&MEGA.some(m=>mine.includes(m.c)))types.push('aiwan','aiwan','mtrain');if(lv>=4&&S.links.some(l=>l.kind==='df'&&l.own&&l.ready<=S.day))types.push('pairs'); if(lv>=5)types.push('esport');if(lv>=6&&mine.length>=2)types.push('sov','sov');if(lv>=8)types.push('cgame','cgame');if(lv>=9)types.push('metav','metav');if(lv>=11&&MEGA.some(m=>mine.includes(m.c)))types.push('agi');if(lv>=13&&mine.length>=2)types.push('mars'); const br=mine.filter(c=>CITY[c].br);if(br.length)types.push('provedor','provedor','provedor'); - const dense=mine.filter(asnDense);if(lv>=2&&dense.length)types.push('isp'); + // Countries with thousands of ASNs (Brazil's provedores, US regionals) are full of small ISPs shopping for transit. + const dense=mine.filter(c=>(CITY_PDB[c]||[])[2]>=2000);if(lv>=2&&dense.length)types.push('isp'); const fabC=mine.filter(c=>FABS.some(f=>f.cities.includes(c)));if(lv>=2&&fabC.length){types.push('fabip','fabip');if(mine.length>=2)types.push('fabl2');} const t=pick(types),T=BIZ_T[t]; if(T.event||T.sdwan||T.fiber||T.mega){spawnSpecial(t);return;} diff --git a/tests/regions.test.js b/tests/regions.test.js index 5a3d8f8..41bc080 100644 --- a/tests/regions.test.js +++ b/tests/regions.test.js @@ -634,6 +634,8 @@ test('Pacific islands: real landings, real exchanges only, and island hops carry assert.ok(ev('!!S.pops.hnl') && ev('S.lvl') >= 4); assert.equal(ev('scnProg().items.length'), 3); ev('cam.z=0.5;draw(0);cam.z=2;draw(0)'); + assert.deepEqual(errors, []); +}); test('prices follow real connectivity: thin markets cost more, hubs stay put', () => { const { ev, errors } = load(); @@ -649,6 +651,6 @@ test('prices follow real connectivity: thin markets cost more, hubs stay put', ( ev("ACT.buildPop({city:'rbr'});compute()"); assert.ok(ev('R.cost.pops') >= ev("popMo('rbr')"), 'running cost uses the city rent'); ev("selectCity('rbr')"); - assert.equal(ev('asnDense("sao")&&asnDense("nyc")&&!asnDense("kgl")'), true); + assert.ok(ev("CITY_PDB.sao[2]>=2000&&CITY_PDB.nyc[2]>=2000&&CITY_PDB.kgl[2]<2000"), 'Brazil and the US are dense in ASNs, Rwanda is not'); assert.deepEqual(errors, []); }); From 8a25ebdb95bccf8d744256f666ddbe2a9731e962 Mon Sep 17 00:00:00 2001 From: Marvin Date: Mon, 26 Oct 2026 20:55:12 +0100 Subject: [PATCH 04/13] Custom routing metric for links MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A link's routing metric could only be one of four presets (Prefer, Normal, Avoid, Backup only). Links now also get a Custom option, closer to how real networks tune IGP metrics: - Multiplier mode scales the distance cost, (km + 60) × 0.1 to 100. - Cost mode sets an exact cost, 1 to 65535 like an OSPF metric. The preset buttons stay plain. Picking Custom explains how a link's cost is worked out and lists what each preset comes to on that link. Choosing Custom starts from the current preset and switching modes keeps the effective cost, so nothing moves until the player changes the value. Like the presets, it applies to every link between the two cities. The cost formula lives in one helper, linkW(), used by compute() and the traceroute paths. Custom links store mk/mv, which sanitize() repairs and clamps; old saves load unchanged. The link panel skips its daily re-render while the number field has focus, and Enter applies the value. Tests cover routing equivalence with the presets, rerouting by cost, mode switching, input clamping, saves, and the panel at desktop and phone width. French, Italian and Portuguese for the new strings. Perf on the big network: no change beyond noise, routing identical to main. --- CHANGELOG.md | 2 + site/i18n/fr.js | 11 ++++- site/i18n/it.js | 11 ++++- site/i18n/pt.js | 11 ++++- site/index.html | 34 +++++++++++---- tests/game.test.js | 102 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 161 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 648e743..fe661d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. + ## [1.31.0] — 2026-10-26 - Series of Tubes now speaks French. The game follows your browser's language the first time, and you can switch to Français under Settings or on the title screen. diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 1b4c2ba..0bb9742 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1604,7 +1604,6 @@ "Going to customers in":"Vers les clients de", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Plus gros contributeur : {egress} à {city}. Passe-le en « Secours seul », donne aux clients une sortie plus proche (peering, cache, transit local) ou augmente la métrique de ce lien.", "Routing metric":"Métrique de routage", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"Tes routeurs choisissent le chemin le moins coûteux. Augmente la métrique pour pousser le trafic vers d’autres chemins. « Secours seul » le laisse au repos tant que le reste fonctionne. S’applique à tous les liens entre ces deux villes.", "Behind the Great Firewall":"Derrière le Grand Pare-feu", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"La Chine continentale joue selon ses propres règles. {list} et d’autres services étrangers y sont bloqués, donc les utilisateurs atteignent surtout des réseaux chinois. Le trafic qui passe la frontière perd environ {pct} en filtrage et congestion, sauf s’il emprunte une route premium : du transit CN-Too ou un circuit transfrontalier premium (tous deux vendus uniquement à Hong Kong), ou un PNI avec un réseau chinois. Le revenu par utilisateur est plus faible ici.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Les réseaux étrangers ont besoin d’une coentreprise locale et d’une licence d’opérateur pour construire ici.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"via un courtier en capacité", "List it with a capacity broker they keep 10%":"La confier à un courtier en capacité il garde 10 %", "Nothing spare to sell on this fiber right now.":"Rien à vendre sur cette fibre pour l’instant.", +"Custom":"Perso", +"Multiplier":"Multiplicateur", +"Cost":"Coût", +"Set":"Appliquer", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Coût sur ce lien : {w}. Autorisé : de {lo} à {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"Tes routeurs choisissent le chemin le moins coûteux. Augmente la métrique pour pousser le trafic vers d’autres chemins. « Secours seul » le laisse au repos tant que le reste fonctionne. Choisis Perso pour fixer ton propre multiplicateur ou coût. S’applique à tous les liens entre ces deux villes.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"Le coût d’un lien, c’est sa longueur en km plus 60, fois un multiplicateur. Le trafic prend le chemin au coût total le plus bas.", +"Presets on this link: {list}.":"Préréglages sur ce lien : {list}.", +"Cost: the exact number, whatever the distance.":"Coût : le nombre exact, quelle que soit la distance.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Multiplicateur : il multiplie le coût de la distance, donc un lien plus long coûte toujours plus.", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 6bf8565..fdc589d 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1603,7 +1603,6 @@ "Going to customers in":"Diretto ai clienti a", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Fonte principale: {egress} a {city}. Impostala su “Solo backup”, dai ai clienti un’uscita più vicina (peering, una cache, transit locale) o alza la metrica di questo link.", "Routing metric":"Metrica di routing", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"I tuoi router scelgono il percorso a costo minore. Alza la metrica per spingere il traffico su altri percorsi. “Solo backup” lo lascia a riposo finché il resto funziona. Vale per tutti i link tra queste due città.", "Behind the Great Firewall":"Dietro il Great Firewall", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"La Cina continentale gioca con regole tutte sue. {list} e altri servizi stranieri qui sono bloccati, quindi gli utenti raggiungono soprattutto reti cinesi. Il traffico che attraversa il confine perde circa il {pct} tra filtri e congestione, a meno che non viaggi su una rotta premium: transit CN-Too o un circuito transfrontaliero premium (entrambi venduti solo a Hong Kong), oppure un PNI con una rete cinese. Qui i ricavi per utente sono più bassi.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Per costruire infrastrutture qui, le reti straniere hanno bisogno di una joint venture locale e di una licenza operativa.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"tramite un broker di capacità", "List it with a capacity broker they keep 10%":"Mettila in vendita con un broker di capacità trattiene il 10%", "Nothing spare to sell on this fiber right now.":"Per ora non c’è niente da vendere su questa fibra.", +"Custom":"Personalizzata", +"Multiplier":"Moltiplicatore", +"Cost":"Costo", +"Set":"Imposta", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Costo su questo link: {w}. Ammessi: da {lo} a {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"I tuoi router scelgono il percorso a costo minore. Alza la metrica per spingere il traffico su altri percorsi. “Solo backup” lo lascia a riposo finché il resto funziona. Scegli Personalizzata per impostare il tuo moltiplicatore o costo. Vale per tutti i link tra queste due città.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"Il costo di un link è la sua lunghezza in km più 60, per un moltiplicatore. Il traffico prende il percorso col costo totale più basso.", +"Presets on this link: {list}.":"Preset su questo link: {list}.", +"Cost: the exact number, whatever the distance.":"Costo: il numero esatto, a prescindere dalla distanza.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Moltiplicatore: scala il costo della distanza, così un link più lungo costa comunque di più.", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9c443f5..9f4950d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1602,7 +1602,6 @@ "Going to customers in":"Indo para clientes em", "Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.":"Maior fonte: {egress} em {city}. Coloque em “Só backup”, dê aos clientes uma saída mais próxima (peering, um cache, transit local) ou aumente a métrica deste link.", "Routing metric":"Métrica de roteamento", -"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.":"Seus routers escolhem o caminho de menor custo. Aumente a métrica para empurrar o tráfego para outros caminhos. “Só backup” deixa o link ocioso a menos que nada mais funcione. Vale para todos os links entre essas duas cidades.", "Behind the Great Firewall":"Atrás do Great Firewall", "Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.":"A China continental joga com regras próprias. {list} e outros serviços estrangeiros são bloqueados aqui, então os usuários acessam principalmente redes chinesas. O tráfego que cruza a fronteira perde cerca de {pct} com filtragem e congestionamento, a menos que vá por uma rota premium: transit CN-Too ou um circuito transfronteiriço premium (ambos vendidos só em Hong Kong), ou um PNI com uma rede chinesa. A receita por usuário aqui é menor.", "Foreign networks need a local joint venture and an operating license to build infrastructure here.":"Redes estrangeiras precisam de uma joint venture local e de uma licença de operação para construir infraestrutura aqui.", @@ -2631,4 +2630,14 @@ "via a capacity broker":"por um corretor de capacidade", "List it with a capacity broker they keep 10%":"Anunciar com um corretor de capacidade ele fica com 10%", "Nothing spare to sell on this fiber right now.":"Nada sobrando para vender nesta fibra por enquanto.", +"Custom":"Personalizada", +"Multiplier":"Multiplicador", +"Cost":"Custo", +"Set":"Aplicar", +"Cost on this link: {w}. Allowed: {lo} to {hi}.":"Custo neste link: {w}. Permitido: de {lo} a {hi}.", +"Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.":"Seus routers escolhem o caminho de menor custo. Aumente a métrica para empurrar o tráfego para outros caminhos. “Só backup” deixa o link ocioso a menos que nada mais funcione. Escolha Personalizada para definir seu próprio multiplicador ou custo. Vale para todos os links entre essas duas cidades.", +"A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.":"O custo de um link é seu comprimento em km mais 60, vezes um multiplicador. O tráfego segue o caminho de menor custo total.", +"Presets on this link: {list}.":"Predefinições neste link: {list}.", +"Cost: the exact number, whatever the distance.":"Custo: o número exato, seja qual for a distância.", +"Multiplier: scales the distance cost, so a longer link still costs more.":"Multiplicador: multiplica o custo da distância, então um link mais longo continua custando mais.", }; diff --git a/site/index.html b/site/index.html index 9334e32..a125165 100644 --- a/site/index.html +++ b/site/index.html @@ -315,6 +315,7 @@ label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-t input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft)} .network-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px} .network-name input.t{flex:1 1 240px;width:auto;min-width:0} +.metric-in{display:flex;gap:6px;align-items:center;margin-top:6px}.metric-in input.t{flex:1 1 120px;width:auto;min-width:0;font-size:16px;padding:4px 10px} .plug{display:flex;gap:12px;align-items:center;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;margin:10px 0 4px;background:var(--soft);box-shadow:0 3px 0 var(--ink);color:var(--ink);text-decoration:none} .plug:hover{background:#FFF6D6}.plug .pi{font-size:30px;line-height:1}.plug b{font-family:var(--display);font-size:16px}.plug .meta{display:block;margin-top:2px}.plug .go{margin-left:auto;font-weight:900;white-space:nowrap} .starts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} @@ -719,6 +720,10 @@ const NNI=[{n:'10G',g:10,mo:500},{n:'100G',g:100,mo:1200}]; const VXC=[{n:'10G',g:10,m:1},{n:'50G',g:50,m:2.4},{n:'100G',g:100,m:3.6}]; const vxcMo=(km,sub,t)=>Math.round((150+km*0.12)*VXC[t].m*(sub?2:1)); const MET={prefer:{l:tr('Prefer'),f:0.5},normal:{l:tr('Normal'),f:1},avoid:{l:tr('Avoid'),f:4},backup:{l:tr('Backup only'),f:60}}; +// Custom metrics: a multiplier on the distance cost (f) or an absolute IGP cost (w), capped like an OSPF metric. +const MET_LIM={f:[0.1,100],w:[1,65535]}; +const clampM=(k,v)=>{const [lo,hi]=MET_LIM[k];v=Math.min(hi,Math.max(lo,v));return k==='w'?Math.round(v):Math.round(v*100)/100;}; +const linkW=l=>l.metric==='custom'?(l.mk==='w'?l.mv:(l.km+60)*l.mv):(l.km+60)*MET[l.metric||'normal'].f; const PREF={high:tr('Prefer'),normal:tr('Normal'),low:tr('Backup only')}; const edgeKey=l=>l.aString(t).toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'x'; function trPaths(src){const live=S.links.filter(l=>!linkDown(l)),rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),adj={}; - for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=(l.km+60)*MET[l.metric||'normal'].f;(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} + for(const l of live){if(!ok(l.a)||!ok(l.b))continue;const w=linkW(l);(adj[l.a]=adj[l.a]||[]).push([l.b,l,w]);(adj[l.b]=adj[l.b]||[]).push([l.a,l,w]);} const dist={[src]:0},prev={},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]{if(dist[dst]===undefined)return null;const out=[];let v=dst;while(v!==src){const l=prev[v];out.unshift({l,from:l.a===v?l.b:l.a,to:v});v=l.a===v?l.b:l.a;}return out;};return {dist,path};} function trExits(net){const day=S.day,ev=S.ev,leak=ev.leak&&ev.leak.until>day?ev.leak.net:null,out=[]; @@ -1924,7 +1929,7 @@ function compute(){ const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]); const edges={},TRX=teRules(),live=[];let NE=0;R2.bizDem={};R2.bizSrv={}; for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.ae.w,wLat=e=>e.lat+0.05; @@ -2202,7 +2207,7 @@ function sanitize(s){ for(const c of Object.keys(s.pops)){const p=s.pops[c];if(!isCity(c)||!p||typeof p!=='object'){delete s.pops[c];continue;}p.routers=int(p.routers,1,RMAX,1);if(p.rupDay!==undefined)p.rupDay=num(p.rupDay,-1);if(p.rgen!==undefined)p.rgen=int(p.rgen,0,RG.length-1,0);p.down=num(p.down,0);if(p.bb&&typeof p.bb==='object')p.bb.d=num(p.bb.d,0);else p.bb=null;} if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; const tier=v=>int(v,0,PORT.length-1,0),lag=v=>int(v,1,LAG_MAX,1),sid=v=>String(v==null?uid():v).slice(0,40); - s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric&&!own(MET,l.metric))l.metric='normal';return l;}); + s.links=s.links.filter(l=>l&&isCity(l.a)&&isCity(l.b)&&l.a!==l.b).map(l=>{l.id=sid(l.id);l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.pairs!==undefined)l.pairs=Math.min(l.sub?SUB_PAIRS_MAX:s.lvl>=PAIRS_LV?PAIRS_BIG:PAIRS_MAX,Math.max(1,Math.floor(+l.pairs)||1));if(l.kind!=='df'&&l.kind!=='vxc')l.kind='wave';if(l.kind==='wave')l.tier=int(l.tier,0,LT.length-1,0);if(l.cable&&!own(CAB,l.cable))l.cable=null;if(l.kind==='vxc'&&!own(VXC,l.vt))l.vt=0;if(l.kind==='df'){if(!own(DF_SYS,l.sys))l.sys='lite';l.ch=Array.isArray(l.ch)?l.ch.filter(o=>own(OPT,o)):[];l.ready=num(l.ready,0);for(const k of Object.keys(SUB_UPGRADES)){const f='sub'+k;if(l[f]!==undefined){if(l.own&&l.sub&&Number.isFinite(l[f])&&l[f]>=0)l[f]=Math.round(l[f]);else delete l[f];}}if(l.paid!==undefined){if(l.own&&l.sub&&Number.isFinite(l.paid)&&l.paid>=0)l.paid=Math.round(l.paid);else delete l.paid;}if(l.own&&l.sub&&!own(SEA_DESIGNS,l.seaDesign))l.seaDesign='standard';l.regen=int(l.regen,0,REGEN_MAX,0);}const deg=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null;if(l.loss)l.loss=deg(l.loss);if(l.metric==='custom'){if(l.mk!=='w')l.mk='f';l.mv=clampM(l.mk,num(l.mv,l.mk==='w'?l.km+60:1));}else{if(l.metric&&!own(MET,l.metric))l.metric='normal';delete l.mk;delete l.mv;}return l;}); const degO=v=>v&&typeof v==='object'?{until:num(v.until,0),f:Math.min(1,Math.max(0,num(v.f,1)))}:null; s.transit=s.transit.filter(t=>t&&isCity(t.city)&&isNet(t.net)).map(t=>(t.lacp=degO(t.lacp),t.site=['a','b','ab'].includes(t.site)?t.site:'a',t.id=sid(t.id),t.tier=tier(t.tier),t.n=lag(t.n),t.down=num(t.down,0),t.clean=!!t.clean,t)); s.pni=s.pni.filter(x=>x&&isCity(x.city)&&isNet(x.net)).map(x=>(x.lacp=degO(x.lacp),x.site=['a','b','ab'].includes(x.site)?x.site:'a',x.id=sid(x.id),x.tier=tier(x.tier),x.n=lag(x.n),x.sacrif=!!x.sacrif,x)); @@ -3039,7 +3044,13 @@ const ACT={ upVxc:({id,t})=>{t=+t;const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='vxc'||!VXC[t]||t<=l.vt)return;const extra=VXC[t].g-VXC[l.vt].g;for(const c of [l.a,l.b]){const pt=nniPort(c,l.prov);if(pt&&nniUsed(c,l.prov)+extra>NNI[pt.tier].g){toast(tr('Fabric port in {city} is full.',{city:CITY[c].name}),'bad');sfx('err');return;}}const mo=vxcMo(l.km,l.sub,t);if(!spend(mo))return;l.vt=t;l.mo=mo;after();}, cancelVxc:({id})=>{if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.links=S.links.filter(l=>l.id!==id);const rem=remoteCities();for(const c in S.ixp){if(!S.pops[ixCity(c)]&&!rem.includes(ixCity(c))){delete S.ixp[c];delete S.rs[c];for(const k in S.peers)if(k.endsWith('@'+c))delete S.peers[k];}}UI.sel=null;UI.confirm=null;after();}, setPref:({kind,id,v})=>{if(!own(PREF,v))return;if(kind!=='t'&&kind!=='p'&&!(isIx(id)&&S.ixp[id]!==undefined))return;if(kind==='t'){const t=S.transit.find(x=>x.id===id);if(t)t.pref=v;}else if(kind==='p'){const x=S.pni.find(y=>y.id===id);if(x)x.pref=v;}else{S.ixPref=S.ixPref||{};S.ixPref[id]=v;}sfx('click');after();}, - setMetric:({id,v})=>{if(!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return;for(const x of pairLinks(l.a,l.b))x.metric=v;sfx('click');after();}, + setMetric:({id,v})=>{if(v!=='custom'&&!own(MET,v))return;const l=S.links.find(x=>x.id===id);if(!l)return; + // Switching to custom starts from the current preset's factor, so nothing moves until the player edits it. + for(const x of pairLinks(l.a,l.b)){if(v==='custom'){if(x.metric!=='custom'){x.mk='f';x.mv=MET[x.metric||'normal'].f;}}else{delete x.mk;delete x.mv;}x.metric=v;}sfx('click');after();}, + metricMode:({id,k})=>{if(k!=='f'&&k!=='w')return;const l=S.links.find(x=>x.id===id);if(!l||l.metric!=='custom')return; + for(const x of pairLinks(l.a,l.b))if(x.metric==='custom'&&x.mk!==k){const w=linkW(x);x.mk=k;x.mv=clampM(k,k==='w'?w:w/(x.km+60));}sfx('click');after();}, + metricSet:({id})=>{const l=S.links.find(x=>x.id===id),t=$('metIn');if(!l||l.metric!=='custom'||!t)return;const v=parseFloat(String(t.value).replace(',','.'));if(!Number.isFinite(v)){sfx('err');return;} + t.blur();for(const x of pairLinks(l.a,l.b))if(x.metric==='custom'){x.mk=l.mk;x.mv=clampM(l.mk,v);}sfx('click');after();}, goEgress:({city,k})=>{ACT.focusCity({city});UI.tab=k==='t'?'up':k==='l2'?'cust':k==='nni'?'links':'peer';renderPanel();}, custGo:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b)return;$('dash').hidden=true;ACT.focusCity({city:b.city});UI.tab='cust';renderPanel();}, listMore:({k})=>{if(k!=='conn'&&k!=='cust')return;UI.listN=UI.listN||{};UI.listN[k]=listN(k)+LIST_PAGE;renderDash();}, @@ -3373,6 +3384,8 @@ function renderPanel(){checkLayer(); const P=$('panel'); if(!S||!UI.sel){P.hidden=true;return;} P.hidden=false; + // Don't wipe a half-typed custom metric on the daily re-render. + const fe=document.activeElement;if(fe&&fe.id==='metIn'&&UI.sel.type!=='city'&&fe.dataset.id===UI.sel.id)return; const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0; const html=UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;morph($('panelBody'),html); const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st; @@ -3563,8 +3576,15 @@ function trafficSection(l){ if(u>=0.8&&egs.length){const d=R.egDesc[egs[0][0]];h+=`

${tr("Biggest feeder: {egress} in {city}. Set it to “Backup only”, give the customers a closer egress (peering, a cache, local transit), or raise this link's metric.",{egress:esc(d.lab),city:CITY[d.city].name})}

`;} return h+`
`; } -function metricSection(l){const cur=l.metric||'normal'; - return `

${tr('Routing metric')}

${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Applies to every link between these two cities.')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},cur===k?'pink sm':'ghost sm')).join('')}
`;} +function metricSection(l){const cur=l.metric||'normal',base=l.km+60,sel=k=>cur===k?'pink sm':'ghost sm'; + let h=`

${tr('Routing metric')}

${tr('Your routers pick the lowest-cost path. Raise the metric to push traffic onto other paths. “Backup only” keeps it idle unless nothing else works. Pick Custom to set your own multiplier or cost. Applies to every link between these two cities.')}

${Object.keys(MET).map(k=>btn(MET[k].l,'setMetric',{id:l.id,v:k},sel(k))).join('')}${btn(tr('Custom'),'setMetric',{id:l.id,v:'custom'},sel('custom'))}
`; + if(cur==='custom'){const k=l.mk,[lo,hi]=MET_LIM[k],md=m=>k===m?'pink sm':'ghost sm'; + const pre=Object.keys(MET).map(m=>`${MET[m].l} ×${MET[m].f} = ${Math.round(base*MET[m].f)}`).join(', '); + h+=`

${tr('A link’s cost is its length in km plus 60, times a multiplier. Traffic takes the path with the lowest total cost.')} ${tr('Presets on this link: {list}.',{list:pre})}

+
${btn(tr('Multiplier'),'metricMode',{id:l.id,k:'f'},md('f'))}${btn(tr('Cost'),'metricMode',{id:l.id,k:'w'},md('w'))}
+
${btn(tr('Set'),'metricSet',{id:l.id},'pink sm')}
+

${k==='w'?tr('Cost: the exact number, whatever the distance.'):tr('Multiplier: scales the distance cost, so a longer link still costs more.')} ${tr('Cost on this link: {w}. Allowed: {lo} to {hi}.',{w:Math.round(linkW(l)),lo:k==='w'?lo:'×'+lo,hi:k==='w'?hi:'×'+hi})}

`;} + return h+'
';} function chinaSection(c){const st=S.cnLic?S.cnLic.state:'none',loss=S.ev.gfw>S.day?0.35:0.2; let h=`

${tr('Behind the Great Firewall')}

${tr('Mainland China plays by its own rules. {list} and other foreign services are blocked here, so users mostly reach Chinese networks. Traffic crossing the border loses about {pct} to filtering and congestion, unless it rides a premium route: CN-Too transit or a premium cross-border circuit (both sold only in Hong Kong), or a PNI with a Chinese network. Revenue per user is lower here.',{list:CN_BLOCKED.slice(0,4).map(esc).join(', '),pct:pct(loss)})}

`; if(st==='none')h+=`

${tr('Foreign networks need a local joint venture and an operating license to build infrastructure here.')}

${btn(tr('Apply for a license {price} + {mo}/mo · ~45 days',{price:fmt$(CN_LIC),mo:fmt$(CN_JV_MO)}),'applyCn',{},'pink',S.cash{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false}); -addEventListener('keydown',e=>{if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); +addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); /* ---------- click delegation ---------- */ let pressing=false; diff --git a/tests/game.test.js b/tests/game.test.js index 6bbdadc..1502f83 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -405,3 +405,105 @@ test('#117 several scrubbing centers: nearest first, spill to the next, and far assert.equal(ev("S.scrubs.some(x=>x.city==='lon')"), false); assert.deepEqual(errors, []); }); + +// Custom routing metrics: a fra–ams–par triangle where the direct fra–par link is normally shortest. +const triangle = (ev) => { + ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + ev("for(const c of ['ams','par'])ACT.buildPop({city:c});const L=(a,b)=>{UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();};L('fra','ams');L('ams','par');L('fra','par');compute()"); + ev("window.FP=S.links.find(l=>(l.a==='fra'&&l.b==='par')||(l.a==='par'&&l.b==='fra')).id;window.hops=()=>JSON.stringify(trPaths('fra').path('par').map(h=>h.l.id))"); +}; + +test('a custom multiplier routes exactly like the matching preset', () => { + const { ev, errors } = load(); + triangle(ev); + assert.equal(ev("hops()"), JSON.stringify([ev("FP")]), 'direct link wins by default'); + ev("ACT.setMetric({id:FP,v:'avoid'})"); + const avoid = ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"); + ev("ACT.setMetric({id:FP,v:'custom'})"); + const l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.metric, 'custom'); + assert.equal(l.mk, 'f'); + assert.equal(l.mv, 4, 'custom starts from the preset it replaces'); + assert.equal(ev("JSON.stringify({h:hops(),load:R.load,served:R.served})"), avoid); + ev("ACT.setMetric({id:FP,v:'normal'})"); + assert.equal(ev("'mk' in S.links.find(l=>l.id===FP)||'mv' in S.links.find(l=>l.id===FP)"), false, 'presets drop the custom fields'); + assert.deepEqual(errors, []); +}); + +test('an absolute custom cost steers the path, and switching modes keeps the cost', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'})"); + const l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.mk, 'w'); + assert.equal(l.mv, Math.round(l.km + 60), 'switching to cost keeps the effective metric'); + ev("ACT.selLink({id:FP});renderAll();$('metIn').value='65535';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 65535); + assert.ok(!JSON.parse(ev("hops()")).includes(ev("FP")), 'a huge cost sends traffic round via Amsterdam'); + ev("renderAll();$('metIn').value='1';ACT.metricSet({id:FP})"); + assert.equal(ev("hops()"), JSON.stringify([ev("FP")])); + ev("ACT.metricMode({id:FP,k:'f'})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 0.1, 'converted back to a multiplier, clamped to the minimum'); + assert.deepEqual(errors, []); +}); + +test('custom metric input is validated and clamped', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.selLink({id:FP});renderAll()"); + ev("$('metIn').value='';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 1, 'empty input changes nothing'); + ev("renderAll();$('metIn').value='9999';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 100); + ev("renderAll();$('metIn').value='0';ACT.metricSet({id:FP})"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 0.1); + ev("ACT.metricMode({id:FP,k:'x'});ACT.setMetric({id:FP,v:'bogus'})"); + assert.equal(ev("S.links.find(l=>l.id===FP).metric"), 'custom'); + assert.deepEqual(errors, []); +}); + +test('custom metrics survive a save, and broken ones are repaired', () => { + const { ev, errors } = load(); + triangle(ev); + ev("ACT.setMetric({id:FP,v:'custom'});ACT.metricMode({id:FP,k:'w'});S.links.find(l=>l.id===FP).mv=777;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + let l = ev("S.links.find(l=>l.id===FP)"); + assert.deepEqual([l.metric, l.mk, l.mv], ['custom', 'w', 777]); + ev("Object.assign(S.links.find(l=>l.id===FP),{mk:'zz',mv:'lots'});S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + l = ev("S.links.find(l=>l.id===FP)"); + assert.deepEqual([l.metric, l.mk, l.mv], ['custom', 'f', 1]); + ev("Object.assign(S.links.find(l=>l.id===FP),{metric:'custom',mk:'w',mv:1e9});S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev("S.links.find(l=>l.id===FP).mv"), 65535); + // An old save: preset metric, no custom fields at all. + ev("const x=S.links.find(l=>l.id===FP);x.metric='avoid';delete x.mk;delete x.mv;S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + l = ev("S.links.find(l=>l.id===FP)"); + assert.equal(l.metric, 'avoid'); + assert.ok(!('mk' in l) && !('mv' in l)); + assert.equal(JSON.parse(ev("hops()")).length, 2, 'the old save still routes, avoiding the direct link'); + assert.deepEqual(errors, []); +}); + +test('preset buttons stay plain, and Custom explains the numbers, also on phones', () => { + const { ev, dom, errors } = load(); + triangle(ev); + for (const w of [1280, 390]) { + ev(`window.innerWidth=${w};ACT.setMetric({id:FP,v:'normal'});ACT.selLink({id:FP});renderAll()`); + const doc = dom.window.document; + const btns = [...doc.querySelectorAll('#panel [data-act="setMetric"]')]; + assert.equal(btns.length, 5); + const km = ev("S.links.find(l=>l.id===FP).km"); + assert.deepEqual(btns.map(b => b.textContent), ['Prefer', 'Normal', 'Avoid', 'Backup only', 'Custom']); + assert.equal(doc.getElementById('metIn'), null); + assert.doesNotMatch(doc.getElementById('panel').textContent, /times a multiplier/); + ev("ACT.setMetric({id:FP,v:'custom'})"); + assert.ok(doc.getElementById('metIn'), `custom editor at ${w}px`); + assert.ok(doc.querySelector('#panel [data-act="metricMode"]')); + const txt = doc.getElementById('panel').textContent; + assert.match(txt, /times a multiplier/); + assert.match(txt, new RegExp(`Normal ×1 = ${Math.round(km + 60)}, Avoid ×4 = ${Math.round((km + 60) * 4)}`)); + assert.match(txt, /Multiplier: scales the distance cost/); + assert.match(txt, /Cost on this link/); + ev("ACT.metricMode({id:FP,k:'w'})"); + assert.match(doc.getElementById('panel').textContent, /Cost: the exact number/); + } + assert.deepEqual(errors, []); +}); From 744b769000792679b7bdf145e5d302b16dfc70c1 Mon Sep 17 00:00:00 2001 From: Filip Hruska Date: Tue, 27 Oct 2026 10:13:07 +0000 Subject: [PATCH 05/13] Rework DDoS generation, mitigation accounting and NOC reporting Scale normal attacks with network demand, level and gaming exposure, with randomized sizes, durations, overlapping attacks and distributed ingress. Set average sizes to three times the non-gaming baseline at one gaming customer and eight times at fifty. Keep Flood Season escalating after its challenge ends. Add gaming-specific vectors, Memcached amplification and ACK floods. Account for upstream scrubbing, Flowspec and shared scrubbing capacity in sequence. Show precise mitigation totals and one destination-based scrubbing detour in existing live attack cards. Keep each source-to-scrubbing route distinct in link traffic breakdowns, including the source label, Open button and map highlight. Include deterministic tests, old-save migration and translations. --- CHANGELOG.md | 28 ++ site/i18n/fr.js | 29 +- site/i18n/it.js | 29 +- site/i18n/pt.js | 29 +- site/index.html | 265 ++++++++----- tests/game.test.js | 520 ++++++++++++++++++++++++++ tests/helpers/reference-allocation.js | 4 +- tests/modes.test.js | 26 +- tests/routing-reference.test.js | 1 + tests/services.test.js | 24 ++ 10 files changed, 823 insertions(+), 132 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5d320..df9f47c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,34 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels, Open buttons or map highlights. + +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. Local scrubbing adds no backbone-haul line, and distributed ingress no longer produces unrelated or repeated latency messages. + +- The NOC no longer shows the generic attack-rate note for networks without gaming customers. + +- Gaming customers now scale normal-mode DDoS sizes from three times the no-gaming average with one customer to eight times with 50. Adding more gamers continues to increase attack sizes, while frequency still rises gradually toward seven attacks per week. Flood Season keeps its existing escalation. + +- Normal-mode DDoS attacks now vary much more in size, with a 2% chance of a much larger flood. The long-run average still scales with demand, customer level and gaming customers; Flood Season keeps its existing size distribution and escalation. + +- Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them. + +- Live attacks now show how much traffic Flowspec actually drops at the ingress routers. Routers without TCAM no longer claim to filter attacks, mixed router capabilities are called out, and Flowspec drops are counted separately from other edge filters. + +- Normal networks without gaming customers now average half a DDoS attack per week, with attacks ten times smaller than the ordinary baseline. Gaming customers gradually raise attack sizes and the expected rate toward seven attacks per week as your level and customer count grow. The size calculation accounts for the smaller RackNet and TeamSpooked floods so signing a gamer increases the overall average size. Flood Season keeps its separate escalation. + +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec, and their size stays within one third of the ordinary attack range at your current scale. + +- Gaming customers bring larger, longer and more frequent DDoS attacks as your level and customer count grow, with overlapping floods, at most 14 starts in any seven days and durations up to seven days. Attacks arrive across transit and peering ports in different regions, following normal traffic shares. Attack bandwidth grows with the whole network, with no fixed bandwidth ceiling. + +- Flood Season keeps sending larger, more frequent attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off. + +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through in its existing status lines. Bandwidth uses the usual Gbps and Tbps units, with no duplicate summary. “After upstream scrubbing” appears only while upstream scrubbing is active. Scrubbing lines show the city, current use and compact capacity, such as “Scrubbing in Frankfurt: 30.2 Gbps / 100G”. + +- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. + +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter needs other defences. + - Pick a peering policy in the peering inbox: Open to all, Selective or Closed. Open accepts every request and keeps the route servers; Selective gets fewer requests but you answer them yourself and request peers at each exchange, without route servers; Closed gets no requests, and customers hear you are hard to reach. The inbox also gets a button to raise all max-prefix limits at once. - Brazil is slimmer: 15 small cities that sat right next to bigger ones are gone from new games, leaving 25 in Brazil. A small city no longer crowds a bigger one in the same country unless it is a cable landing or a capital. Saved games keep their POPs in those cities, and the Order and Progress scenario now asks for 15 IX.brrr ports instead of 20. ## [1.33.0] — 2026-10-27 diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c06021c..7fcfb8f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -923,10 +923,7 @@ "Live attack: {city}":"Attaque en cours : {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · {n} j restants", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"Blackholé : les déchets ont disparu, et {city} aussi. L’attaque a obtenu ce qu’elle voulait.", -"Reaching your network: {g}":"Ce qui atteint ton réseau : {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing à la demande en cours de redirection, actif dans {n} j", -"{tier} scrubbing in {city} is cleaning it":"Le scrubbing {tier} à {city} le nettoie", -"{net} is scrubbing it upstream (clean-pipe)":"{net} le nettoie en amont (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contenu sur ton PNI sacrificiel {net}", "IX blackhole on ✓":"Blackhole IX actif ✓", "IX blackhole ~half honour it":"Blackhole IX ~la moitié le respecte", @@ -935,10 +932,7 @@ "Sacrificial choke ✓":"Goulot sacrificiel ✓", "Make sacrificial contains floods · ½ capacity":"Rendre sacrificiel contient les floods · ½ capacité", "No scrubbing center":"Pas de centre de scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"Flowspec sur ton {model} élimine le trafic {vec} en bordure", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"Flowspec sur ton {model} rogne le trafic {vec}, mais sa TCAM est petite", -"Your {model} here has no Flowspec TCAM":"Ton {model} ici n’a pas de TCAM Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec ne peut pas arrêter un {vec} (couche applicative)", +"Flowspec cannot catch {vec}":"Flowspec ne peut pas arrêter {vec}", "Stop blackholing":"Arrêter le blackholing", "Blackhole the target (RTBH)":"Blackholer la cible (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2604,8 +2598,6 @@ "Attack hauled to scrubbing in {city}":"Attaque acheminée vers le scrubbing de {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Veut un centre de scrubbing sur son continent, pour que les attaques ne traversent pas un océan", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Ton backbone ne peut en acheminer que {g} jusqu’à {city} : le reste n’est pas nettoyé", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"Le scrubbing {tier} à {city} le nettoie, acheminé par ton backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"Tes centres de scrubbing sont pleins : {g} passent quand même", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Les attaques vont vers ton centre de scrubbing le plus proche. D’ici, c’est {city}, à {km} km : le flot traverse ton backbone aller et retour, ce qui ajoute de la latence, et ce que tes liens ne peuvent pas porter n’est pas nettoyé. Un centre ici nettoie les attaques sur place.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"les attaques sur {city} sont acheminées vers {to} pour le scrubbing : +{ms} ms", "Scrubbing centers":"Centres de scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"{n} limites max-prefix relevées.
{k} d’entre elles étaient des fuites de routes. Elles sont dans le NOC maintenant.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"{n} limites max-prefix relevées.
Que de la croissance, aucune fuite. Chanceux.", "Off while your peering policy is {pol}":"Désactivé tant que votre politique de peering est {pol}", +"Memcached amplification":"Amplification Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtres en bordure : {g} supprimés", +"{g} is leaking through":"{g} passent encore", +"Attack fully mitigated":"Attaque entièrement neutralisée", +"Scrubbing centers unavailable or at capacity":"Centres de scrubbing indisponibles ou saturés", +"Distributed ingress":"Arrivée distribuée", +", across {n} transit and peering ports":", via {n} ports de transit et de peering", +"No scrubbing needed after edge mitigation":"Aucun scrubbing nécessaire après la protection en bordure", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing à {city} : {used} / {capacity}", +"This attack: {g}":"Cette attaque : {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Trafic de scrubbing acheminé par ton backbone : {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Après le scrubbing en amont : {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Aucun filtrage Flowspec : les routeurs d’entrée n’ont pas de TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec supprime {g} ; certains routeurs d’entrée n’ont pas de TCAM", +"Flowspec dropping: {g}":"Flowspec supprime {g}", +"Gaming attracts attacks":"Le gaming attire les attaques", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index be339b0..ef9450b 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -924,10 +924,7 @@ "Live attack: {city}":"Attacco in corso: {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · {n}g rimasti", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"In buco nero: la spazzatura è sparita, e anche {city}. L’attacco ha ottenuto ciò che voleva.", -"Reaching your network: {g}":"Arriva alla tua rete: {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing on-demand in deviazione, attivo tra {n}g", -"{tier} scrubbing in {city} is cleaning it":"Lo scrubbing {tier} a {city} lo sta pulendo", -"{net} is scrubbing it upstream (clean-pipe)":"{net} lo sta ripulendo a monte (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contenuto sulla tua PNI sacrificale {net}", "IX blackhole on ✓":"Blackhole IX attivo ✓", "IX blackhole ~half honour it":"Blackhole IX ~metà lo rispetta", @@ -936,10 +933,7 @@ "Sacrificial choke ✓":"Strozzatura sacrificale ✓", "Make sacrificial contains floods · ½ capacity":"Rendi sacrificale contiene i flood · ½ capacità", "No scrubbing center":"Nessun centro di scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"Il Flowspec sul tuo {model} sta scartando {vec} all’edge", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"Il Flowspec sul tuo {model} lima {vec}, ma la sua TCAM è piccola", -"Your {model} here has no Flowspec TCAM":"Il tuo {model} qui non ha TCAM per il Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec non può fermare un {vec} (livello applicativo)", +"Flowspec cannot catch {vec}":"Flowspec non può fermare {vec}", "Stop blackholing":"Togli il buco nero", "Blackhole the target (RTBH)":"Metti il bersaglio in buco nero (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2607,8 +2601,6 @@ "Attack hauled to scrubbing in {city}":"Attacco portato allo scrubbing di {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Vuole un centro di scrubbing nel suo continente, così gli attacchi non attraversano un oceano", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Il tuo backbone riesce a portarne solo {g} a {city}: il resto non viene pulito", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"Lo scrubbing {tier} a {city} lo sta pulendo, portato lì sul tuo backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"I tuoi centri di scrubbing sono pieni: {g} passano lo stesso", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Gli attacchi vanno al tuo centro di scrubbing più vicino. Da qui è {city}, a {km} km: il flusso viaggia sul tuo backbone fin lì e ritorno, il che aggiunge latenza, e quello che i tuoi link non riescono a portare non viene pulito. Un centro qui pulisce gli attacchi sul posto.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"gli attacchi su {city} vengono portati a {to} per lo scrubbing: +{ms} ms", "Scrubbing centers":"Centri di scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"Alzati {n} limiti max-prefix.
{k} erano route leak. Ora sono nel NOC.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"Alzati {n} limiti max-prefix.
Tutta crescita, nessun leak. Fortuna.", "Off while your peering policy is {pol}":"Spento finché la tua politica di peering è {pol}", +"Memcached amplification":"Amplificazione Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtri al bordo: {g} scartati", +"{g} is leaking through":"{g} superano le difese", +"Attack fully mitigated":"Attacco completamente mitigato", +"Scrubbing centers unavailable or at capacity":"Centri di scrubbing non disponibili o al completo", +"Distributed ingress":"Ingresso distribuito", +", across {n} transit and peering ports":", su {n} porte di transit e peering", +"No scrubbing needed after edge mitigation":"Nessuno scrubbing necessario dopo la mitigazione al bordo", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing a {city}: {used} / {capacity}", +"This attack: {g}":"Questo attacco: {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Traffico di scrubbing trasportato sul tuo backbone: {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Dopo lo scrubbing a monte: {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Nessun filtraggio Flowspec: i router di ingresso non hanno TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec scarta {g}; alcuni router di ingresso non hanno TCAM", +"Flowspec dropping: {g}":"Flowspec scarta {g}", +"Gaming attracts attacks":"Il gaming attira attacchi", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 215579b..9479de2 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -924,10 +924,7 @@ "Live attack: {city}":"Ataque ao vivo: {city}", "{size} · {vec}{entry} · {n}d left":"{size} · {vec}{entry} · faltam {n}d", "Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.":"Em blackhole: o lixo sumiu, e {city} também. O ataque conseguiu o que queria.", -"Reaching your network: {g}":"Chegando na sua rede: {g}", "On-demand scrubbing diverting, live in {n}d":"Scrubbing on-demand desviando, ativo em {n}d", -"{tier} scrubbing in {city} is cleaning it":"O scrubbing {tier} em {city} está limpando", -"{net} is scrubbing it upstream (clean-pipe)":"{net} está limpando upstream (clean-pipe)", "Contained on your sacrificial {net} PNI":"Contido no seu PNI sacrificial com {net}", "IX blackhole on ✓":"Blackhole IX ativo ✓", "IX blackhole ~half honour it":"Blackhole IX ~metade respeita", @@ -936,10 +933,7 @@ "Sacrificial choke ✓":"Gargalo sacrificial ✓", "Make sacrificial contains floods · ½ capacity":"Tornar sacrificial contém floods · ½ capacidade", "No scrubbing center":"Sem centro de scrubbing", -"Flowspec on your {model} is dropping {vec} at the edge":"O Flowspec no seu {model} está descartando {vec} na borda", -"Flowspec on your {model} trims {vec}, but its TCAM is small":"O Flowspec no seu {model} reduz {vec}, mas a TCAM é pequena", -"Your {model} here has no Flowspec TCAM":"Seu {model} aqui não tem TCAM para Flowspec", -"Flowspec cannot catch an {vec} (application layer)":"Flowspec não pega um {vec} (camada de aplicação)", +"Flowspec cannot catch {vec}":"Flowspec não consegue filtrar {vec}", "Stop blackholing":"Parar blackhole", "Blackhole the target (RTBH)":"Blackhole no alvo (RTBH)", "HackBack 3000™ $20k":"HackBack 3000™ $20k", @@ -2607,8 +2601,6 @@ "Attack hauled to scrubbing in {city}":"Ataque levado ao scrubbing em {city}", "Wants a scrubbing center on its own continent, so attacks are not hauled across an ocean":"Quer um centro de scrubbing no próprio continente, para que os ataques não atravessem um oceano", "Your backbone can only haul {g} of it to {city}: the rest is not scrubbed":"Seu backbone só consegue levar {g} até {city}: o resto não é limpo", -"{tier} scrubbing in {city} is cleaning it, hauled over your backbone (+{ms} ms)":"O scrubbing {tier} em {city} está limpando, levado pelo seu backbone (+{ms} ms)", -"Your scrubbing centers are full: {g} leaks past":"Seus centros de scrubbing estão cheios: {g} passam direto", "Attacks go to your nearest scrubbing center. From here that is {city}, {km} km away: the flood rides your backbone there and back, which adds latency, and whatever your links cannot carry is not scrubbed. A center here cleans attacks on the spot.":"Os ataques vão para o seu centro de scrubbing mais próximo. Daqui é {city}, a {km} km: a enxurrada viaja pelo seu backbone até lá e volta, o que aumenta a latência, e o que seus links não conseguem levar não é limpo. Um centro aqui limpa os ataques na hora.", "attacks on {city} are hauled to {to} for scrubbing: +{ms} ms":"os ataques em {city} são levados a {to} para scrubbing: +{ms} ms", "Scrubbing centers":"Centros de scrubbing", @@ -2941,4 +2933,23 @@ "Raised {n} max-prefix limits.
{k} of them were route leaks. They are in the NOC now.":"{n} limites de max-prefix aumentados.
{k} deles eram vazamentos de rotas. Estão no NOC agora.", "Raised {n} max-prefix limits.
All growth, no leaks. Lucky.":"{n} limites de max-prefix aumentados.
Tudo crescimento, nenhum vazamento. Sorte.", "Off while your peering policy is {pol}":"Desligado enquanto sua política de peering for {pol}", +"Memcached amplification":"Amplificação Memcached", +"ACK flood":"Flood ACK", +"Edge filters dropping: {g}":"Filtros de borda descartando: {g}", +"{g} is leaking through":"{g} estão passando", +"Attack fully mitigated":"Ataque totalmente mitigado", +"Scrubbing centers unavailable or at capacity":"Centros de scrubbing indisponíveis ou lotados", +"Distributed ingress":"Entrada distribuída", +", across {n} transit and peering ports":", por {n} portas de transit e peering", +"No scrubbing needed after edge mitigation":"Scrubbing desnecessário após a mitigação na borda", +"RackNet":"RackNet", +"TeamSpooked":"TeamSpooked", +"Scrubbing in {city}: {used} / {capacity}":"Scrubbing em {city}: {used} / {capacity}", +"This attack: {g}":"Este ataque: {g}", +"Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)":"Tráfego de scrubbing levado pelo seu backbone: {city} → {to} (+{ms} ms)", +"After upstream scrubbing: {g}":"Após o scrubbing upstream: {g}", +"No Flowspec filtering: ingress routers have no TCAM":"Sem filtragem Flowspec: os roteadores de entrada não têm TCAM", +"Flowspec dropping: {g}; some ingress routers have no TCAM":"Flowspec descarta {g}; alguns roteadores de entrada não têm TCAM", +"Flowspec dropping: {g}":"Flowspec descarta {g}", +"Gaming attracts attacks":"Gaming atrai ataques", }; diff --git a/site/index.html b/site/index.html index c003a61..b9c7a6f 100644 --- a/site/index.html +++ b/site/index.html @@ -637,9 +637,13 @@ const FS_RES=[1,0.4,0.15]; const DDOS_VEC={ dns:{n:tr('DNS reflection'),fs:true}, ntp:{n:tr('NTP amplification'),fs:true}, + memcached:{n:tr('Memcached amplification'),fs:true}, + ack:{n:tr('ACK flood'),fs:false}, cldap:{n:tr('CLDAP flood'),fs:true}, syn:{n:tr('SYN flood'),fs:true}, http:{n:tr('HTTP flood'),fs:false}, + racknet:{n:tr('RackNet'),fs:false,gaming:true}, + teamspooked:{n:tr('TeamSpooked'),fs:false,gaming:true}, }; const MYIX_COST=80000, MYIX_MO=3000, MYIX_FEE=1500, START_CASH=200000; // Your own exchange's switching fabric. Bigger fabrics carry more and attract more members. @@ -1441,7 +1445,7 @@ const initials=n=>n.name.replace(/[^A-Za-z ]/g,'').split(' ').filter(Boolean).ma /* ================= BUSINESSES ================= */ const BIZ_T={ dia:{l:tr('Enterprise DIA'),opts:[1,2,5,10],rate:600}, - game:{l:tr('Game servers'),opts:[5,10,20,40],rate:120}, + game:{l:tr('Game servers'),gaming:true,opts:[5,10,20,40],rate:120}, host:{l:tr('Hosting'),opts:[10,20,40,80],rate:60}, isp:{l:tr('Downstream ISP (buys transit)'),opts:[100,200,400,800],rate:15,lv:2}, l2vpn:{l:tr('L2VPN circuit'),opts:[1,10,40,100],rate:0,l2:true,km:1,lv:1}, @@ -1466,7 +1470,7 @@ const BIZ_T={ pairs:{l:tr('Hundreds of fiber pairs'),opts:[1],rate:0,fiber:true,mega:true,lv:4,names:['A Hyperscaler Who Shall Not Be Named','Planet-Scale AI WAN Team','The Fiber-Hungry Giant','Project Very Long Glass']}, esport:{l:tr('Esports world final'),opts:[400,800,1600,3200],rate:0,event:true,lv:5,names:['League of Lag Finals','Counter-Ping Major','Fortnightly World Cup','Dota Two Many Viewers','Rocket Leak Championship','Street Frighter Evo']}, sov:{l:tr('Sovereign cloud region'),opts:[400,800,1600],rate:0,l2:true,div:true,km:0.6,lv:6,names:['Gaia-Ex Sovereign Cloud','Bundeswolke (Very Secure)','Le Cloud Souverain','Datenschutz Deluxe','Your Data Stays Here, Probably','A Cloud With a Flag on It','Data Residency Is a State of Mind']}, - cgame:{l:tr('Cloud gaming platform'),opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, + cgame:{l:tr('Cloud gaming platform'),gaming:true,opts:[800,1600,3200],rate:45,lv:8,names:['Stadia-ium (Back Again)','GeForce Later','Ping Station Now','Luna-tick Gaming','Shadow of a Doubt Cloud PC','Input Lag Arcade','Bufferbloat Bros. Streaming']}, metav:{l:tr('Metaverse platform'),opts:[1600,3200,6400],rate:35,lv:9,names:['Meh-taverse','Second Second Life','Horizon Worlds Apart','The Oasis (Ready Player Done)','Legs Finally Shipped Inc.','Decentra-landlocked']}, agi:{l:tr('AGI lab (allegedly)'),opts:[12800,25600],rate:0,l2:true,div:true,mega:true,km:0.4,lv:11,names:['Almost General Intelligence Inc.','Superintelligence Pending','The Lab That Said Two More Years','Paperclip Maximizer Labs','Deep Thought Two','Benevolent Overlord Research']}, mars:{l:tr('Mars mission ground station'),opts:[100,200,400],rate:0,l2:true,lat:true,km:4,lv:13,names:['Red Planet Relay','Ares Ground Segment','Olympus Mons Uplink','Mars or Bust Mission Control','Interplanetary Ping Society','Light-Minute Logistics','RFC 1149 Avian Carriers (Mars Division)']}, @@ -1794,7 +1798,7 @@ function scenarioModal(){const wk=weekly(),h=scnHof();let best=null;try{best=JSO function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, ltv:2,t1v:2,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{}, - done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; + done:{},inc:[],ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; } /* ================= HELPERS ================= */ @@ -2133,7 +2137,7 @@ function teOptimize(){const L=[tr('# Suggested by the optimizer from live traffi return L.join('\n');} // Ready-made RouteScripts, filled in from the live network. Players load them from the help; the AI button picks them too. const teUps=()=>[...new Set(S.transit.map(t=>t.net))].map(n=>({n,p:Math.min(...S.transit.filter(t=>t.net===n).map(t=>NET[n].price*regionMult(t.city)))})).sort((a,b)=>a.p-b.p); -const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>!!(S.ev.ddos&&S.ev.ddos.until>S.day); +const teNm=n=>NET[n].name.toLowerCase(),teAtk=()=>ddosAll().length>0; const teSad=()=>S.biz.some(b=>!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&!BIZ_T[b.type].event&&sfOf(R,b.city)<0.95); const TE_RECIPES=[ {id:'shield',n:N_('Shields Up'),d:N_('For a DDoS: drop the junk at the edge and keep business customers first. It costs a little real traffic, so remove it when the attack is over.'),fit:()=>teAtk()?9:0.3, @@ -2235,18 +2239,18 @@ function compute(){ // ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank. // okBy[net] lists the exits that reach it in E's order, like E.filter(e=>e.ok(net)). const okBy={};for(const id of NET_IDS)okBy[id]=[]; - const ekN={};for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} + R2.ingressPorts={};const ekN={};for(const e of E){e.ek=e.k+':'+e.id;if(e.k!=='c'){const p=R2.ingressPorts[e.ek]||(R2.ingressPorts[e.ek]={k:e.k,id:e.id,city:e.city,lab:e.lab,cap:0,traffic:0});p.cap+=e.cap;}ekN[e.ek]=(ekN[e.ek]||0)+1;} // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}} for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];if(okBy[n.id].some(e=>e.rank>0&&e.k!=='t')){R2.nt[n.id]=1;R2.reachNT+=NSH[n.id];}} const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net)); const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1); // Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index). - const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j];flows.push({c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j});}; + const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk,bz=false)=>{const n=NETS[j],f={c,n:n.id,rem,cache,junk,bz,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j};flows.push(f);return f;}; // Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give). const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}} // Traffic shares by network index, and their sums, for each share table (and with Russia's throttle). - const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),HAUL=[];R2.haul=[]; + const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN),loc=scnRule('local'),scrubRoom={},atkBy={},junkGroups=[],bhCities=new Set(ddosAll().filter(a=>a.bh).map(a=>a.city));R2.haul=[];R2.ddos=[];for(const a of ddosAll())for(const part of ddosSlices(a))(atkBy[part.city]||(atkBy[part.city]=[])).push(part); for(const c of Object.keys(S.pops)){ const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz; // Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not @@ -2255,26 +2259,18 @@ function compute(){ const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),lf=loc?NETS.reduce((t,n,j)=>t+(R2.reachable[n.id]?sa[j]*thr(n.id):0),0)/(tt[0]||1):1,d=d0*tt[0]/(tt[1]||1)*lf; R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d; for(let j=0;jday?ev.ddos:null; - const rtbh=!!(atk&&atk.bh), edge=!!(atk&&TRX&&TRX.blackhole&&!rtbh); + const attacks=atkBy[c]||[],rtbh=bhCities.has(c),edge=!!(attacks.length&&TRX&&TRX.blackhole&&!rtbh); let dd=0; - if(atk&&!rtbh){let mult=1;const en=atk.entry||{}; - if(DDOS_VEC[atk.vec]&&DDOS_VEC[atk.vec].fs){const cap=fsAt(atk.city);if(cap)mult=Math.min(mult,FS_RES[cap]);} - if(en.k==='t'){const t=S.transit.find(x=>x.id===en.id);if(t&&t.clean)mult=Math.min(mult,0.1);} - if(atk.ixbh&&hasIxAt(atk.city))mult=Math.min(mult,0.5); - if(edge)mult=0; - // Scrubbing is used when it beats the edge tools; floods for a center in another city are hauled after the circuits below. - const sp=edge?null:scrubPlan(atk); - if(sp&&scrubIdeal(sp)x.id===en.id);if(p&&p.sacrif)dd=Math.min(dd,liveCap(pniG(p),p.city,p.site,p.n)*0.9);}} + for(const atk of attacks){const m=ddosMitigation(atk,{},bhCities.has((atk.parent||atk).city),false);R2.ddos.push(m);dd+=m.leak; + const group={m,flows:[]};junkGroups.push(group); + if(atk.entries?.length){for(const q of m.ingress){const f=flow(c,ci,cn,0,q.g,false,true);f.pin=q.entry.k+':'+q.entry.id;group.flows.push({f,share:m.leak>0?q.g/m.leak:0});}} + else for(let j=0;jm.attack.city===c))m.offline=true;continue;} const bh=rtbh||edge; - if(dd>0)for(let j=0;jn+a.gbps,0)+d*0.1;if(rtbh)R2.teBlack+=attacks.reduce((n,a)=>n+a.gbps,0)+d; R2.cityBlocked=R2.cityBlocked||{}; const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr; for(let j=0;jday&&n.id==='fbk'?0.8:1);if(a<=0)continue; @@ -2337,18 +2333,28 @@ function compute(){ if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}} /* A flood for a scrubbing center elsewhere rides the backbone there, with the victim's own traffic (#117). What the links cannot carry is not scrubbed and lands on the city after all. */ - for(const H of HAUL){const A=H.c,B=H.to,Ai=CIDX[A],Bi=CIDX[B];let h=0,ms=null; - if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]0?H.a*take/want:0;ms=path.reduce((x,e)=>x+e.lat,0)*2; - const ek='scrub:'+B;R2.egDesc[ek]={lab:labOf(N_('Attack hauled to scrubbing in {city}'),'city',CITY[B].name),city:A,k:'l2'}; - for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}} - R2.haul.push({city:A,to:B,tier:H.tier,a:H.a,h,ms});const left=(H.a-h)*0.85;if(left>1e-6)for(let j=0;j0?scrubPlan(atk,m.leak,scrubRoom,(x,want)=>{const B=x.city,Bi=CIDX[B];if(A===B)return want;let h=0,ms=null; + if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][Bi]0?want*take/total:0;ms=path.reduce((n,e)=>n+e.lat,0)*2; + // Sources sharing a center need separate labels in link breakdowns and map highlights. + const ek='scrub:'+A+'>'+B;R2.egDesc[ek]={lab:labOf(N_('Attack hauled to scrubbing in {city}'),'city',CITY[B].name),city:A,k:'l2'}; + for(const i of ni)if(HAS[i])nodeTake(i,take);for(const l of path){l.res-=take;l.ld+=take;carry(l,ek,NN,Ai,take);}} + R2.haul.push({city:A,to:B,tier:x.tier||0,a:want,h,ms,attack:atk.id});return h;}):null; + if(m.sp){m.leak=m.sp.leak; + // The card describes the victim's nearest center, separately from distributed ingress hauling above. + const c=(atk.parent||atk).city;let near=scrubNear.get(c);if(near===undefined){near=null; + for(const x of S.scrubs)if(popUp(x.city)&&SPD[c]&&SPD[c][CIDX[x.city]]n+e.lat,0);if(!near||ms{const key=src*NC+dst,c0=teCache.get(key); if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0; const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3),dst); if(D[dst]===Infinity||D[dst]>2*base+60){teCache.set(key,false);return null;} const Q=walkI(P,src,dst);teCache.set(key,Q);return Q;}; + const ingressE={};for(const e of E)(ingressE[e.ek]||(ingressE[e.ek]=[])).push(e); const base=e=>e.pref==='low'?4:e.rank; // LOCAL_PREF on an upstream moves it ahead of or behind the other transits, never ahead of peering (#96). const eff=(e,n)=>{let r=base(e);if(TR){if(e.k==='t'&&TR.up[e.net])r=TR.up[e.net]==='prefer'?2.9:3.5;if(e.prep)r=4.4;if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;}; @@ -2374,7 +2380,7 @@ function compute(){ const ek=e.ek,nr=f.nr,ci=f.ci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc;e.told=true;} for(const l of path){l.res-=amt;l.ld+=amt;carry(l,ek,nr,ci,amt);} e.used+=amt;f.rem-=amt; - if(!f.junk){let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn; + if(!f.junk){if(e.k!=='c')R2.ingressPorts[ek].traffic+=amt;let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn; if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);} SRV[f.ci]+=ok;R2.served+=ok;if(f.bz)R2.bizSrv[f.c]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok; // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then @@ -2406,8 +2412,9 @@ function compute(){ // Index loops in here: plain for…of allocates an iterator per loop until V8 has optimised compute(). for(let fi=0,FN=flows.length;fix&&typeof x==='object'&&isCity(x.city)&&s.pops[x.city]&&!seen.has(x.city)&&seen.add(x.city)).map(x=>({city:x.city,tier:int(x.tier,0,SCRUB_TIERS.length-1,0)}));} s.scrubMode=s.scrubMode==='ondemand'?'ondemand':'always'; - if(s.ev&&s.ev.ddos){const a=s.ev.ddos; - if(!a||typeof a!=='object'||!isCity(a.city)||!own(DDOS_VEC,a.vec))delete s.ev.ddos; - else{a.gbps=num(a.gbps,2);a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=num(a.start,s.day); - if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}}} + // Keep the legacy primary attack so old saves and imports remain compatible; additional floods overlap it. + const repairAttack=a=>{if(!a||typeof a!=='object'||!isCity(a.city)||!s.pops[a.city]||!own(DDOS_VEC,a.vec))return null; + a.id=sid(a.id);a.gbps=Math.max(0,num(a.gbps,2));a.until=num(a.until,s.day);a.bh=!!a.bh;a.ixbh=!!a.ixbh;a.start=Math.max(0,Math.min(s.day,num(a.start,s.day)));a.until=Math.min(a.until,a.start+7); + if(Array.isArray(a.entries)){a.entries=a.entries.filter(en=>en&&['t','ix','p'].includes(en.k)&&isCity(en.city)&&typeof en.id==='string'&&Number.isFinite(+en.share)&&+en.share>0).slice(0,3000).map(en=>({k:en.k,id:en.id.slice(0,40),city:en.city,lab:String(en.lab||'').slice(0,60),share:+en.share}));const sum=a.entries.reduce((n,en)=>n+en.share,0);if(Number.isFinite(sum)&&sum>0)for(const en of a.entries)en.share/=sum;else delete a.entries;}else delete a.entries; + a.sla=Array.isArray(a.sla)?a.sla.filter(x=>typeof x==='string').slice(0,s.biz.length):[]; + if(!a.entry||typeof a.entry!=='object')a.entry={k:'edge',lab:''};else{a.entry.lab=String(a.entry.lab||'').slice(0,60);a.entry.id=a.entry.id==null?undefined:String(a.entry.id).slice(0,40);}return a;}; + const attacks=[s.ev.ddos,...(Array.isArray(s.ev.ddosMore)?s.ev.ddosMore:[])].map(repairAttack).filter(Boolean).slice(0,14); + if(attacks.length)s.ev.ddos=attacks[0];else delete s.ev.ddos;s.ev.ddosMore=attacks.slice(1); + s.ddosStarts=(Array.isArray(s.ddosStarts)?s.ddosStarts:attacks.map(a=>a.start)).filter(d=>typeof d==='number'||typeof d==='string').map(Number).filter(d=>Number.isFinite(d)&&d>s.day-7&&d<=s.day).sort((a,b)=>a-b).slice(-14); s.auV=s.auV===1?1:0;if(s.auNews!==true)delete s.auNews; if(s.te){if(typeof s.te!=='object')s.te=null;else{s.te.on=!!s.te.on;s.te.script=typeof s.te.script==='string'?s.te.script.slice(0,4000):'';}} return s;} @@ -2623,6 +2635,7 @@ function bizSfOf(r,c){const d=r.bizDem&&r.bizDem[c];return teRules()&&teRules(). function bCities(o){return o.sites?o.sites.slice():[o.city,o.city2].filter(Boolean);} function bHas(o){return bCities(o).every(c=>S.pops[c]);} function eventLive(b){return BIZ_T[b.type].event&&S.day>=b.start&&S.day⚠️ ${tr('Gaming attracts attacks')}`:'';} function bTerms(o){const T=BIZ_T[o.type]; if(T.event){const live=S.day>=o.start;return tr('{bw} extra for {d} days, {when} · pays {fee} when it is over',{bw:fmtG(o.bw),d:o.dur,when:live?tr('day {n} of {d}',{n:S.day-o.start+1,d:o.dur}):tr('starting in {n}d',{n:o.start-S.day}),fee:fmt$(o.fee)});} if(T.sdwan)return tr('{n} sites: {list} · {bw} per site · {price}/mo',{n:o.sites.length,list:o.sites.map(c=>CITY[c].name).join(', '),bw:fmtG(o.bw),price:fmt$(o.bw*o.rate)}); @@ -2753,59 +2766,83 @@ function lagsN(){const o=[];for(const t of S.transit)if((t.n||1)>=2&&!(t.down>S. for(const p of S.pni)if((p.n||1)>=2)o.push({k:'p',id:p.id,o:p,n:p.n,lab:tr('PNI LAG with {name} in {city}',{name:NET[p.net].name,city:CITY[p.city].name})}); for(const x in S.ixp){const n=(S.ixn||{})[x]||1;if(n>=2&&!S.myIx[x])o.push({k:'ix',id:x,n,lab:ixNamesCity(x)?tr('{ix} LAG',{ix:ixName(x)}):tr('{ix} LAG in {city}',{ix:ixName(x),city:CITY[ixCity(x)].name})});}return o;} // Where the junk comes in: one of the city's live uplinks, or just "the edge" if it has none yet. +// The primary slot remains compatible with older saves; every system uses the full live set. +function ddosAll(s=S,live=true){return [s.ev.ddos,...(s.ev.ddosMore||[])].filter(a=>a&&(!live||a.until>s.day));} +const ddosFind=id=>ddosAll().find(a=>id===undefined||a.id===id); +function ddosDrop(a){const left=ddosAll(S,false).filter(x=>x!==a);S.ev.ddos=left[0]||null;S.ev.ddosMore=left.slice(1);} +function ddosExpire(){for(const a of ddosAll(S,false))if(a.until<=S.day||!S.pops[a.city]){ddosDone(a);ddosDrop(a);}} +function ddosEntries(){const ports=Object.values(R.ingressPorts||{}).filter(p=>p.cap>0),busy=ports.some(p=>p.traffic>1e-6),weight=p=>busy?p.traffic:p.cap,total=ports.reduce((n,p)=>n+weight(p),0); + return total>0?ports.filter(p=>weight(p)>0).map(p=>({k:p.k,id:p.id,city:p.city,lab:p.lab,share:weight(p)/total})):[];} +function ddosSlices(a){if(!a.entries?.length)return [a];const groups={}; + for(const en of a.entries){const c=S.pops[en.city]?en.city:a.city;(groups[c]||(groups[c]=[])).push(en);} + return Object.entries(groups).map(([city,entries])=>({...a,parent:a,city,entries,gbps:a.gbps*entries.reduce((n,en)=>n+en.share,0)}));} +const ddosCities=a=>[...new Set([a.city,...(a.entries||[]).map(en=>en.city)])].filter(c=>S.pops[c]); +const ddosHasIx=a=>ddosCities(a).some(hasIxAt); +const ddosSf=a=>Math.min(1,...ddosCities(a).map(c=>sfOf(R,c))); +function ddosReport(a){const ms=(R.ddos||[]).filter(m=>m.attack===a||m.attack.parent===a);if(!ms.length)return ddosMitigation(a); + const parts={};for(const m of ms)for(const x of m.sp?.parts||[]){const q=parts[x.city]||(parts[x.city]={city:x.city,tier:x.tier,a:0,cleaned:0});q.a+=x.a;q.cleaned+=x.cleaned;} + return {attack:a,blackhole:ms.some(m=>m.blackhole),upstream:ms.some(m=>m.upstream),reaching:ms.reduce((n,m)=>n+m.reaching,0),flowspec:ms.reduce((n,m)=>n+m.flowspec,0),fsMissing:ms.some(m=>m.fsMissing),filtered:ms.reduce((n,m)=>n+m.filtered,0),sp:Object.keys(parts).length?{parts:Object.values(parts)}:null,near:ms.find(m=>m.near)?.near||null,leak:ms.reduce((n,m)=>n+m.leak,0)};} function ddosEntry(c){const o=[]; for(const t of S.transit)if(t.city===c&&!(t.down>S.day))o.push({k:'t',id:t.id,lab:tr('{net} transit',{net:NET[t.net].name})}); for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined)o.push({k:'ix',id:x,lab:tr('{ix} peering',{ix:ixName(x)})}); for(const p of S.pni)if(p.city===c)o.push({k:'p',id:p.id,lab:tr('PNI with {net}',{net:NET[p.net].name})}); return o.length?pick(o):{k:'edge',lab:''};} -// Flowspec capability of the router in a city: 0 none, 1 basic, 2 full. The flood is filtered where the -// victim POP's own router has the TCAM for it. +// Flowspec capability at each ingress POP: 0 none, 1 basic, 2 full. const fsAt=c=>{const p=S.pops[c];return p?(RG[p.rgen||0].fs||0):0;}; -// Scrubbing residual for an attack: clean up to the center's capacity (to 15%), overflow leaks. On-demand +// Scrubbing removes attack traffic up to the center's capacity; overflow leaks. On-demand // does nothing for the first couple of days while traffic is being diverted. -function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start||S.day))>=SCRUB_DELAY);} +function scrubEngaged(atk){return hasScrub()&&(S.scrubMode==='always'||(S.day-(atk.start??S.day))>=SCRUB_DELAY);} // Several centers (#117): the flood goes to the nearest working one, and what it cannot take spills to the next. // A center in another city only helps if the backbone can carry the flood there; routing works that out. -const scrubFar=c=>{const a=S.ev&&S.ev.ddos;return a&&a.until>S.day&&a.city===c&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null;}; -function scrubPlan(atk){if(!scrubEngaged(atk))return null;const c=atk.city;let g=atk.gbps||0;const parts=[]; - for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const a=Math.min(g,SCRUB_TIERS[x.tier||0].g);parts.push({city:x.city,tier:x.tier||0,a});g-=a;} +const scrubFar=c=>ddosAll().some(a=>ddosCities(a).includes(c))&&(R.haul||[]).find(q=>q.city===c&&q.ms!==null&&q.ms>=SCRUB_FAR_MS)||null; +function scrubPlan(atk,g=atk.gbps||0,room={},take=null){if(!scrubEngaged(atk))return null;const c=atk.city;const parts=[]; + for(const x of S.scrubs.filter(x=>popUp(x.city)&&(x.city===c||pathExists(c,x.city))).sort((a,b)=>(a.city===c?0:kmBetween(c,a.city))-(b.city===c?0:kmBetween(c,b.city)))){if(g<=0)break;const cap=SCRUB_TIERS[x.tier||0].g,a=Math.min(g,room[x.city]??cap);if(a<=0)continue;const cleaned=take?take(x,a):a;room[x.city]=(room[x.city]??cap)-cleaned;parts.push({city:x.city,tier:x.tier||0,a,cleaned});g-=cleaned;} return parts.length?{parts,leak:g}:null;} -// What still lands on the city if every haul gets through: 15% of what is scrubbed, plus whatever no center can take. -const scrubIdeal=p=>p?p.parts.reduce((s,x)=>s+x.a*0.15,0)+p.leak:Infinity; +// One accounting pipeline for routing and the NOC: upstream -> edge -> scrubbing -> leakage. +function ddosMitigation(a,room={},blackhole=a.bh,plan=true){const entries=a.entries?.length?a.entries:[{...(a.entry||{}),share:1}],total=entries.reduce((n,en)=>n+en.share,0),ingress=[]; + let upstream=false,reaching=0,g=0,flowspec=0,fsMissing=false; + for(const en of entries){const t=en.k==='t'?S.transit.find(x=>x.id===en.id):null,p=en.k==='p'?S.pni.find(x=>x.id===en.id):null,clean=!!(t&&t.clean); + upstream=upstream||clean;let part=blackhole?0:a.gbps*en.share/total*(clean?0.1:1);reaching+=part; + if(DDOS_VEC[a.vec]?.fs){const cap=fsAt(S.pops[en.city]?en.city:a.city),before=part;part*=FS_RES[cap];flowspec+=before-part;if(cap===0&&before>0)fsMissing=true;} + if(a.ixbh&&hasIxAt(a.city))part*=0.5; + if(p&&p.sacrif)part=Math.min(part,liveCap(pniG(p),p.city,p.site,p.n)*0.9); + if(teRules()?.blackhole&&!blackhole)part=0; + g+=part;ingress.push({entry:en,g:part});} + const filtered=reaching-g,sp=plan&&g>0?scrubPlan(a,g,room):null; + return {attack:a,blackhole,upstream,reaching,flowspec,fsMissing,filtered,ingress,sp,leak:sp?sp.leak:g};} // The NOC's live attack view: what is hitting you, what each tool would do about it right now, and the buttons. -function ddosPanel(){ - const a=S&&S.ev&&S.ev.ddos;if(!a||a.until<=S.day||!S.pops[a.city])return ''; - const V=DDOS_VEC[a.vec]||{n:'?',fs:false},cap=fsAt(a.city),model=RG[(S.pops[a.city].rgen||0)].n,en=a.entry||{}; - const cleanT=en.k==='t'?S.transit.find(x=>x.id===en.id):null, sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null; - let mult=1; - if(V.fs&&cap)mult=Math.min(mult,FS_RES[cap]); - if(cleanT&&cleanT.clean)mult=Math.min(mult,0.1); - if(a.ixbh&&hasIxAt(a.city))mult=Math.min(mult,0.5); - const sp=scrubPlan(a),useS=!!sp&&scrubIdeal(sp)(R.haul||[]).find(q=>q.city===a.city&&q.to===x.city); - let land=a.bh?0:useS?sp.parts.reduce((t,x)=>{const q=x.city===a.city?null:hl(x);return t+x.a*0.15+(q?(q.a-q.h)*0.85:0);},sp.leak):a.gbps*mult; - if(sacP&&sacP.sacrif)land=Math.min(land,liveCap(PORT[sacP.tier].g,sacP.city,sacP.site,sacP.n)*0.9); - land=Math.round(land); - const fsLine=!V.fs?'— '+tr('Flowspec cannot catch an {vec} (application layer)',{vec:esc(V.n)}) - :cap>=2?'✓ '+tr('Flowspec on your {model} is dropping {vec} at the edge',{model:esc(model),vec:esc(V.n)}) - :cap===1?'~ '+tr('Flowspec on your {model} trims {vec}, but its TCAM is small',{model:esc(model),vec:esc(V.n)}) - :'— '+tr('Your {model} here has no Flowspec TCAM',{model:esc(model)}); - const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=x.city===a.city?null:hl(x); - return q&&q.hS.pops[a.city]).map(ddosOne).join(''):'';} +function ddosOne(a){ + const V=DDOS_VEC[a.vec]||{n:'?',fs:false},en=a.entry||{}; + const sacP=en.k==='p'?S.pni.find(x=>x.id===en.id):null; + const m=ddosReport(a),sp=m.sp,hl=x=>{const qs=(R.haul||[]).filter(q=>q.to===x.city&&q.attack===a.id);return qs.length?{a:qs.reduce((n,q)=>n+q.a,0),h:qs.reduce((n,q)=>n+q.h,0)}:null;}; + const landLine=m.blackhole?'~ '+tr('Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.',{city:esc(CITY[a.city].name)}) + :m.upstream?'✓ '+tr('After upstream scrubbing: {g}',{g:fmtG(m.reaching)}):''; + const fsLine=!V.fs?'— '+tr('Flowspec cannot catch {vec}',{vec:esc(V.n)}) + :m.flowspec<=1e-6?'— '+tr('No Flowspec filtering: ingress routers have no TCAM') + :m.fsMissing?'~ '+tr('Flowspec dropping: {g}; some ingress routers have no TCAM',{g:fmtG(m.flowspec)}) + :'✓ '+tr('Flowspec dropping: {g}',{g:fmtG(m.flowspec)}); + const used=c=>(R.ddos||[m]).reduce((n,q)=>n+(q.sp?.parts||[]).filter(x=>x.city===c).reduce((t,x)=>t+x.cleaned,0),0); + const scrOne=x=>{const T=SCRUB_TIERS[x.tier],q=hl(x),total=used(x.city); + return (x.cleaned>1e-6?'✓ ':'~ ')+tr('Scrubbing in {city}: {used} / {capacity}',{city:esc(CITY[x.city].name),used:fmtG(total),capacity:T.n}) + +(total>x.cleaned+1e-6?' · '+tr('This attack: {g}',{g:fmtG(x.cleaned)}):'') + +(q&&q.h~ '+tr('Your backbone can only haul {g} of it to {city}: the rest is not scrubbed',{g:fmtG(q.h),city:esc(CITY[x.city].name)}):'');}; const scrLine=!hasScrub()?'— '+tr('No scrubbing center') - :!scrubEngaged(a)?'… '+tr('On-demand scrubbing diverting, live in {n}d',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start||S.day)))}) - :!sp?'— '+tr('No scrubbing center') - :sp.parts.map(scrOne).join('
')+(sp.leak>0.5?'
~ '+tr('Your scrubbing centers are full: {g} leaks past',{g:fmtG(sp.leak)}):''); - const entryLine=cleanT&&cleanT.clean?'✓ '+tr('{net} is scrubbing it upstream (clean-pipe)',{net:esc(NET[cleanT.net].name)}) - :sacP&&sacP.sacrif?'✓ '+tr('Contained on your sacrificial {net} PNI',{net:esc(NET[sacP.net].name)}):''; + :!scrubEngaged(a)?'… '+tr('On-demand scrubbing diverting, live in {n}d',{n:Math.max(1,SCRUB_DELAY-(S.day-(a.start??S.day)))}) + :!sp?'— '+(m.leak<=1e-6?tr('No scrubbing needed after edge mitigation'):tr('Scrubbing centers unavailable or at capacity')) + :sp.parts.map(scrOne).join('
'); + const haulLine=m.near&&m.near.ms>0&&sp?.parts.some(x=>x.cleaned>1e-6)?'✓ '+tr('Scrubbing traffic hauled over your backbone: {city} → {to} (+{ms} ms)',{city:esc(CITY[a.city].name),to:esc(CITY[m.near.city].name),ms:m.near.ms.toFixed(1)}):''; + const entryLine=sacP&&sacP.sacrif?'✓ '+tr('Contained on your sacrificial {net} PNI',{net:esc(NET[sacP.net].name)}):''; let h=`
🚨 ${tr('Live attack: {city}',{city:esc(CITY[a.city].name)})}
${tr('{size} · {vec}{entry} · {n}d left',{size:fmtG(a.gbps),vec:esc(V.n),entry:a.entry&&a.entry.lab?' · '+esc(a.entry.lab):'',n:a.until-S.day})}
-
${a.bh?tr('Blackholed: the junk is gone, and so is {city}. The attack got what it wanted.',{city:esc(CITY[a.city].name)}):tr('Reaching your network: {g}',{g:fmtG(land)})}
+ ${landLine?`
${landLine}
`:''} + ${m.blackhole?'':`
${fsLine}
${entryLine?`
${entryLine}
`:''} + ${m.filtered-m.flowspec>1e-6?`
✓ ${tr('Edge filters dropping: {g}',{g:fmtG(m.filtered-m.flowspec)})}
`:''}
${scrLine}
-
${fsLine}
${entryLine?`\n
${entryLine}
`:''} -
${a.bh?btn(tr('Stop blackholing'),'unrtbh',{},'ghost sm'):btn(tr('Blackhole the target (RTBH)'),'rtbh',{},'red sm')}${hasIxAt(a.city)&&!a.bh?btn(a.ixbh?tr('IX blackhole on ✓'):tr('IX blackhole ~half honour it'),'ixbh',{},a.ixbh?'green sm':'sm'):''}${btn(tr('HackBack 3000™ $20k'),'hackback',{},'sm',S.cash<20000)}
+ ${haulLine?`
${haulLine}
`:''} +
${m.leak>1e-6?'~ '+tr('{g} is leaking through',{g:fmtG(m.leak)}):'✓ '+tr('Attack fully mitigated')}
`} +
${m.blackhole?btn(tr('Stop blackholing'),'unrtbh',{id:a.id},'ghost sm'):btn(tr('Blackhole the target (RTBH)'),'rtbh',{id:a.id},'red sm')}${ddosHasIx(a)&&!m.blackhole?btn(a.ixbh?tr('IX blackhole on ✓'):tr('IX blackhole ~half honour it'),'ixbh',{id:a.id},a.ixbh?'green sm':'sm'):''}${btn(tr('HackBack 3000™ $20k'),'hackback',{id:a.id},'sm',S.cash<20000)}

${tr('RTBH is free and instant, but it drops everything to the victim, attack and customer alike. An IX blackhole keeps the customer up but only about half the members honour it. HackBack 3000™ by Skynot AI sometimes ends it, and sometimes flattens an innocent and earns you a fine.')}

`; return h;} function fireFailure(){ @@ -2817,7 +2854,7 @@ function fireFailure(){ if(S.transit.some(t=>!(t.down>S.day)))opts.push(['transit',3]); if(Object.keys(S.ixp).length)opts.push(['ixloop',2]); if(S.transit.length&&S.day>60)opts.push(['leak',2]); - if(S.day>40&&!scnRule('ddos'))opts.push(['ddos',2]); // Flood Season brings its own + // DDoS has its own schedule, so other incidents cannot bypass the weekly limit. if(fabsUsed.length)opts.push(['fabric',1.5]); const lit=S.links.filter(l=>l.kind==='df'&&dfCap(l)>0&&!linkDown(l));if(lit.length)opts.push(['amp',1.5+lit.length*0.3],['optic',1.5+lit.length*0.3]); opts.push(['funny',4]); @@ -2921,27 +2958,49 @@ function fireFailure(){ else{const paused=pref('pauseIncident')&&autoPause();toast(`${incTitle(type)}
${esc(last.msg)}${paused?`
${tr('Game paused.')}`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('Rush repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));} sfx('alert'); } -// A DDoS attack: mostly short, modest spikes; now and then a "botnet of toasters" monster into the terabits. -// In Flood Season (scenario rule ddos) they come more often, a third are monsters, and they grow over the year. -function ddosAttack(){const type='ddos',fl=scnRule('ddos'),grow=fl?1+S.day/180:1;if(S.ev.ddos&&S.ev.ddos.until>S.day)ddosDone(S.ev.ddos); - const c=pick(Object.keys(S.pops)),vec=pick(Object.keys(DDOS_VEC)),V=DDOS_VEC[vec]; - const monster=Math.random()<(fl?0.33:0.15),base=Math.max(R.cityDem[c]||0,4); - const gbps=Math.round((monster?800+Math.random()*2600:2+Math.random()*Math.max(18,base*0.9))*grow); - const dur=2+Math.floor(Math.random()*4),entry=ddosEntry(c); - S.ev.ddos={city:c,vec,gbps,until:S.day+dur,entry,bh:false,start:S.day}; +const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0); +const ddosVectors=()=>Object.keys(DDOS_VEC).filter(k=>!DDOS_VEC[k].gaming||gamingCount()>0); +// Expected starts per week in normal play; the rolling 14-start limit is a separate ceiling. +// Spread gaming exposure over dozens of customers, including the first, rather than switching baselines. +const ddosRate=()=>0.5+6.5*(1-Math.exp(-gamingCount()/50*(1+Math.max(1,S.lvl||1)/LEVELS.length))); +const ddosPressure=()=>1-Math.exp(-(.01+Math.max(0,(S.lvl||1)-1)/12+gamingCount()/10+(scnRule('ddos')?.2+S.day/365:0))); +// Normalize the vector mix so smaller gaming-only floods do not lower the advertised overall mean. +function ddosSizeMean(){const stage=Math.max(1,S.lvl||1)/LEVELS.length,games=gamingCount(),fl=scnRule('ddos'); + const base=Math.max(10,(R.demand||0)*4/3*stage,fl?1400:0); + if(fl)return base*(1+0.2*games/(games+10))*(1+S.day/365); + // Relative to no gaming: 3x at one customer, 8x at 50, approaching the existing 12x balance. + const mean=base*(games?1.2-0.9*Math.pow(4/9,(games-1)/49):0.1),vectors=ddosVectors(),weight=vectors.reduce((n,k)=>n+(DDOS_VEC[k].gaming?1/3:1),0)/vectors.length; + return mean/weight;} +// Normal rolls: 98% uniform 0.2–2, 2% uniform 8–12. Their mean is 1.278, so spikes do not inflate the balance. +const ddosSizeMax=()=>ddosSizeMean()*(scnRule('ddos')?1.5:12/1.278); +function ddosSize(vec){const fl=scnRule('ddos'),r=Math.random(),roll=fl?1/3+r*2/3:(r<.98?.2+1.8*r/.98:8+4*(r-.98)/.02)/12; + const raw=ddosSizeMax()*(DDOS_VEC[vec].gaming?1/3:1)*roll; + return fl?Math.max(2,Math.floor(raw)):Math.max(0.001,Math.floor(raw*1000)/1000);} +function ddosTick(){if(S.mode==='sandbox')return;if(scnRule('ddos')){let next=+S.scn.nextDdos||3,n=0; + while(S.day>=next&&n++<2){ddosAttack(false);next+=floodGap();}S.scn.nextDdos=next40||gamingCount())for(let i=0;i<2;i++)if(Math.random()d>S.day-7&&d<=S.day);if(S.ddosStarts.length>=14||!Object.keys(S.pops).length)return;S.ddosStarts.push(S.day); + const c=pick(Object.keys(S.pops)),vec=pick(ddosVectors()),V=DDOS_VEC[vec]; + const gbps=ddosSize(vec); + const dur=1+Math.floor(Math.random()*(1+6*ddosPressure())),entry=ddosEntry(c); + const entries=ddosEntries(),a={id:uid(),city:c,vec,gbps,until:S.day+dur,entry:entries.length>1?{k:'distributed',lab:tr('Distributed ingress')}:entries[0]||entry,entries,bh:false,start:S.day}; + if(!S.ev.ddos)S.ev.ddos=a;else(S.ev.ddosMore||(S.ev.ddosMore=[])).push(a); const soaked=(V.fs&&fsAt(c))||hasScrub(); - const how=entry&&entry.lab?tr(', in via {e}',{e:entry.lab}):''; + const how=entries.length>1?tr(', across {n} transit and peering ports',{n:entries.length}):entry&&entry.lab?tr(', in via {e}',{e:entry.lab}):''; const msg=tr('A {size} {vec} attack is hitting {city}{how}.',{size:fmtG(gbps),vec:V.n,city:CITY[c].name,how})+' '+(soaked?tr('Your mitigation is eating most of it.'):tr('Junk traffic is eating your capacity. Open the NOC to fight back.')); - if(fl)S.ev.ddos.who=pick(FLOOD_WHO); - addInc({type,ref:c,until:S.day+dur,msg:fl?msg+' '+tr('Attacker: {who}.',{who:tr(S.ev.ddos.who)}):msg,cost:0}); + if(fl)a.who=pick(FLOOD_WHO); + addInc({type,ref:c,atk:a.id,until:S.day+dur,msg:fl?msg+' '+tr('Attacker: {who}.',{who:tr(a.who)}):msg,cost:0}); if(soaked){S.stats.survived++;S.stats.ddosHeld=(S.stats.ddosHeld||0)+1;if(gbps>=1000)S.stats.ddosMonster=(S.stats.ddosMonster||0)+1;} - compute(); - toast(`${incTitle('ddos')}: ${esc(CITY[c].name)}
${esc(msg)}${fl?`
${esc(tr('Attacker: {who}.',{who:tr(S.ev.ddos.who)}))}`:''}`,soaked?'goal':'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c}); + if(recompute){compute();a.worst=ddosSf(a);} + toast(`${incTitle('ddos')}: ${esc(CITY[c].name)}
${esc(msg)}${fl?`
${esc(tr('Attacker: {who}.',{who:tr(a.who)}))}`:''}`,soaked?'goal':'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}],{a:'city',v:c}); sfx('alert');} // When an attack is over: was it held? Held means the city under attack got at least 97% of its traffic every day. -function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=sfOf(R,a.city);const ok=(a.worst===undefined?1:a.worst)>=0.97; +function ddosDone(a){if(!a||a.done)return;a.done=1;if(a.worst===undefined&&S.pops[a.city])a.worst=ddosSf(a);const ok=(a.worst===undefined?1:a.worst)>=0.97; if(ok){S.stats.ddosOk=(S.stats.ddosOk||0)+1;if(a.gbps>=1000)S.stats.ddosOkBig=(S.stats.ddosOkBig||0)+1;}else S.stats.ddosLost=(S.stats.ddosLost||0)+1; if(scnRule('ddos')){const who=tr(a.who||FLOOD_WHO[0]);toast(ok?tr('Flood held: {g}.
{who} gave up and went back to mining crypto.',{g:fmtG(a.gbps),who:who.charAt(0).toUpperCase()+who.slice(1)}):tr('That one got through: {g}.
{city} sank to {p}. Somewhere, {who} is very proud of itself.',{g:fmtG(a.gbps),city:CITY[a.city]?CITY[a.city].name:tr('Your network'),p:pct(a.worst||0),who}),ok?'goal':'bad');}} +const floodGap=()=>Math.max(0.05,(3+Math.random()*5)/(Math.sqrt(1+S.day/180)*(1+gamingCount()/10+Math.max(0,(S.lvl||1)-1)/12))); const FLOOD_WHO=[N_('a botnet of 40,000 smart toasters'),N_('every unpatched baby monitor in Europe'),N_('a gaming clan that lost one match'),N_('a fridge that achieved sentience and chose violence'),N_('a crypto bro shorting your stock'),N_('a teenager with a stolen credit card and a grudge'),N_('a rival ISP’s “stress test”'),N_('ten thousand smart light bulbs, blinking in unison'),N_('a printer. Just one printer. Nobody knows how'),N_('a botnet run from a cloud you also host'),N_('somebody who did not like your network name'),N_('the internet-connected kettles of a whole country')]; function incTitle(t){return {ring:tr('Metro ring cut'),site:tr('Site outage'),cut:tr('Fiber cut'),crash:tr('Router crash'),power:tr('Power outage'),transit:tr('Upstream outage'),ixloop:tr('IX meltdown'),leak:tr('Route leak'),ddos:tr('DDoS attack'),fabric:tr('Fabric outage'),depeer:tr('Peering spat'),fatwave:tr('Fat-fingered wave'),label:tr('Patch panel mishap'),mtu:tr('MTU mismatch'),krroute:tr('Rerouted via Hong Kong'),ctrlplane:tr('Control plane meltdown'),lacp:tr('LACP trouble'),loss:tr('Packet loss'),pmtud:tr('PMTUD black hole'),oops:tr('Oops'),cleaner:tr('Vacuum incident'),maxpfx:tr('Max-prefix meltdown'),prepend:tr('Prepend-ageddon'),rpki:tr('RPKI invalid'),amp:tr('Amplifier failure'),roadmff:tr('Fat-fingered ROADM'),optic:tr('Dead optic'),maint:tr('Maintenance window'),ac:tr('Cooling failure'),hijack:tr('BGP hijack'),shutdown:tr('Government shutdown'),redsea:tr('Geopolitical cable cut')}[t]||tr('Incident');} const LINKCUT_TR=['cut','redsea'],LINKCUT_ID=['fatwave','label'],POPDOWN=['crash','power','oops','cleaner','maint','shutdown'],IXDOWN=['ixloop','maxpfx'],TDOWN=['transit','prepend'],LINKEQ=['mtu','amp','roadmff','optic']; @@ -2956,7 +3015,7 @@ function clearInc(i){ else if(TDOWN.includes(T)){const t=S.transit.find(x=>x.id===i.ref);if(t)t.down=remainUntil(x=>TDOWN.includes(x.type)&&x.ref===i.ref);} else if(T==='rpki'||T==='hijack'){if(!S.inc.some(x=>x.type==='rpki'||x.type==='hijack'))S.ev.rpki=null;} else if(T==='leak'){S.ev.leak=null;} - else if(T==='ddos'){const a=S.ev.ddos;if(a&&a.city===i.ref&&(a.start===undefined||a.start===i.start)){ddosDone(a);S.ev.ddos=null;}} + else if(T==='ddos'){const a=ddosAll(S,false).find(a=>i.atk?a.id===i.atk:a.city===i.ref&&(a.start===undefined||a.start===i.start));if(a){ddosDone(a);ddosDrop(a);}} else if(T==='fabric'){if(S.ev.fab)S.ev.fab[i.ref]=remainUntil(x=>x.type==='fabric'&&x.ref===i.ref);} else if(T==='mtu'){const l=S.links.find(x=>x.id===i.ref);if(l)l.deg=remainUntil(x=>x.type==='mtu'&&x.ref===i.ref);} else if(T==='loss'){const l=S.links.find(x=>x.id===i.ref);if(l&&!S.inc.some(x=>x.type==='loss'&&x.ref===i.ref))l.loss=null;} @@ -3034,8 +3093,9 @@ function dayTick(){ 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('You are no longer Tier 1.
Because {why}. Your Tier 1 badge stays; win the status back to show it again.',{why:t1Why()}),'bad');S.t1Now=t1;} if(S.grace&&S.grace.until===d){toast(tr('The courtesy route has ended.
New networks you have not connected to are now only reachable through your own peering and transit.'),'bad',[{l:tr('Open NOC'),act:'leftTab',args:{t:'noc'}}]);} - {const a=S.ev.ddos;if(a&&a.until>d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,sfOf(R,a.city));} - if(scnRule('ddos')&&!(S.scn.done||S.scn.failed)&&d>=(+S.scn.nextDdos||3)&&!(S.ev.ddos&&S.ev.ddos.until>d)){ddosAttack();S.scn.nextDdos=d+3+Math.floor(Math.random()*5);} + for(const a of ddosAll(S,false))if(a.until>=d&&R&&S.pops[a.city])a.worst=Math.min(a.worst===undefined?1:a.worst,ddosSf(a)); + ddosExpire(); + ddosTick(); if(R&&R.demand>0)S.stats.clean=R.served/R.demand>=0.995?(S.stats.clean||0)+1:0; if(S.scn&&S.scn.id==='redsea')S.stats.asiaRun=asiaG()>=RS_G?(S.stats.asiaRun||0)+1:0; if(S.ev.php===d)toast(tr('The internet is back.
Half of it, anyway. Everything was patched in a hurry and nobody learned anything.'),'good'); @@ -3050,6 +3110,7 @@ function dayTick(){ if(sf>=0.9){const g=(CITY[c].be&&!(p.boost>d)?0.35:1)*0.025*(scnRule('boom')?1.5:1)*(p.boost>d?2:1)*sf*(0.7+0.6*(R.peerShare||0))*(CITY[c].reg==='AS'&&!CITY[c].cn?1.6:1);p.bb.d+=g*p.bb.d*(1-p.bb.d/P);} else p.bb.d=Math.max(Math.min(3,P),p.bb.d*(1-(0.9-sf)*0.04));} compute(); + for(const a of ddosAll())a.worst=Math.min(a.worst??1,ddosSf(a)); for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} S.cash+=(R.revMo-R.costMo)/30; S.stats.peak=Math.max(S.stats.peak,R.served); @@ -3059,9 +3120,9 @@ function dayTick(){ if(l.ready===d){toast(`${l.own?tr('Your fiber is finished: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('Dark fiber handed over: {a}–{b}',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('Channels are lighting up now.'):tr('It is dark. Add optics to light it up.')}`,'goal',[{l:tr('Open'),act:'selLink',args:{id:l.id}}]);sfx('coin');} if(l.own&&l.ready>d&&Math.random()<0.012){const extra=10+Math.floor(Math.random()*40);setCableReady(l,l.ready+extra);toast(tr('Construction delay: +{n} days
{why} ({a}–{b})',{n:extra,why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('Archaeologists found a Roman bathhouse on your route.'),tr('A protected hamster species lives along the right-of-way.'),tr('The railway changed its mind about the easement.'),tr('The drilling crew hit a granite boulder the size of a bus.'),tr('A town council wants a public hearing. About the color of the manhole covers.'),tr('Somebody else’s gas main was exactly where the map said it was not.'),tr('The permit office lost your permit. And then the replacement.')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} // DDoS protection SLA: if a protected customer's own city is hit and still goes down, you pay out (once per attack). - if(S.ev.ddos&&S.ev.ddos.until>d){const a=S.ev.ddos; - for(const b of S.biz)if(b.type==='scrub'&&b.city===a.city&&b.slaFor!==a.start&&sfOf(R,b.city)<0.85){ - b.slaFor=a.start;S.cash-=SLA_PEN;b.mood=Math.max(0,b.mood-18);S.stats.sla=(S.stats.sla||0)+1; + for(const a of ddosAll()){ + for(const b of S.biz)if(b.type==='scrub'&&ddosCities(a).includes(b.city)&&!(a.sla||[]).includes(b.id)&&(a.id||b.slaFor!==a.start)&&sfOf(R,b.city)<0.85){ + (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('SLA breach: {name}.
The attack on {city} got through and your protected customer went down. You owe {pen} in SLA credits.',{name:esc(b.name),city:CITY[a.city].name,pen:fmt$(SLA_PEN)}),'bad');sfx('err');}} // businesses mood for(const b of S.biz.slice()){if(eventTick(b,d))continue;b.pm=b.mood;const sf=bizSf(b),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); @@ -3425,10 +3486,10 @@ const ACT={ rmScrub:({city})=>{if(!S.scrubs.some(x=>x.city===city))return;if(UI.confirm!=='scrub:'+city){UI.confirm='scrub:'+city;renderAll();return;}S.scrubs=S.scrubs.filter(x=>x.city!==city);if(!hasScrub())S.scrubMode='always';UI.confirm=null;after();}, cleanPipe:({id})=>{const t=S.transit.find(x=>x.id===id);if(!t)return;t.clean=!t.clean;toast(t.clean?tr('Clean-pipe add-on enabled on {net}.
They scrub a flood before it reaches your port here, for {mo}/mo.',{net:NET[t.net].name,mo:fmt$(cleanMo(t))}):tr('Clean-pipe add-on removed from {net}.',{net:NET[t.net].name}),t.clean?'good':'');after();}, sacrif:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p)return;p.sacrif=!p.sacrif;toast(p.sacrif?tr('{net} PNI is now a sacrificial choke point.
A flood from there dies on the small port instead of inside your network, but legit traffic over it runs at half capacity.',{net:NET[p.net].name}):tr('{net} PNI is back to normal.',{net:NET[p.net].name}),p.sacrif?'good':'');after();}, - ixbh:()=>{const a=S.ev.ddos;if(!a){toast(tr('No attack to blackhole right now.'),'');return;}if(!hasIxAt(a.city)){toast(tr('No IX in {city} to announce a blackhole to.',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('IX blackhole announced in {city}.
About half the members honour the /32 and drop the junk. The customer stays up.',{city:CITY[a.city].name}):tr('IX blackhole withdrawn.'),a.ixbh?'good':'');sfx('alert');after();}, - rtbh:()=>{const a=S.ev.ddos;if(!a){toast(tr('No attack to blackhole right now.'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('RTBH announced.
You blackholed the target in {city}. The flood stops, and so does everyone there.',{city:CITY[a.city].name}),'bad');sfx('alert');after();}, - unrtbh:()=>{const a=S.ev.ddos;if(!a||!a.bh)return;a.bh=false;toast(tr('Blackhole withdrawn.
{city} is reachable again. Brace for the junk.',{city:CITY[a.city].name}),'');after();}, - hackback:()=>{const a=S.ev.ddos;if(!a||a.until<=S.day){toast(tr('Nothing to hack back right now.'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; + ixbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('No attack to blackhole right now.'),'');return;}if(!ddosHasIx(a)){toast(tr('No IX in {city} to announce a blackhole to.',{city:CITY[a.city].name}),'bad');sfx('err');return;}a.ixbh=!a.ixbh;toast(a.ixbh?tr('IX blackhole announced in {city}.
About half the members honour the /32 and drop the junk. The customer stays up.',{city:ddosCities(a).filter(hasIxAt).map(c=>CITY[c].name).join(', ')}):tr('IX blackhole withdrawn.'),a.ixbh?'good':'');sfx('alert');after();}, + rtbh:({id}={})=>{const a=ddosFind(id);if(!a){toast(tr('No attack to blackhole right now.'),'');return;}a.bh=true;S.stats.rtbh=(S.stats.rtbh||0)+1;toast(tr('RTBH announced.
You blackholed the target in {city}. The flood stops, and so does everyone there.',{city:CITY[a.city].name}),'bad');sfx('alert');after();}, + unrtbh:({id}={})=>{const a=ddosFind(id);if(!a)return;for(const x of ddosAll())if(x.city===a.city)x.bh=false;toast(tr('Blackhole withdrawn.
{city} is reachable again. Brace for the junk.',{city:CITY[a.city].name}),'');after();}, + hackback:({id}={})=>{const a=ddosFind(id);if(!a||a.until<=S.day){toast(tr('Nothing to hack back right now.'),'');return;}if(!spend(20000))return;S.stats.hackback=(S.stats.hackback||0)+1; if(Math.random()<0.35){a.until=S.day;a.bh=false;S.stats.hackWin=(S.stats.hackWin||0)+1;toast(tr('HackBack 3000™ strikes back!
Skynot AI traced the botnet and politely bricked it. The attack on {city} stops cold.',{city:CITY[a.city].name}),'goal');sfx('coin');} else{const fine=15000+Math.floor(Math.random()*35000);S.cash-=fine;S.stats.vigilante=(S.stats.vigilante||0)+1; toast(tr('HackBack 3000™ hit the wrong target.
{who} A regulator sends you a {fine} fine, and the attack rolls on.',{who:pick([tr("Skynot AI flattened a grandma's internet-connected fridge."),tr('You counter-flooded a hospital in a country you cannot pronounce.'),tr('The botnet was already someone else’s botnet. They are furious.')]),fine:fmt$(fine)}),'bad');sfx('err');} @@ -3697,7 +3758,7 @@ function renderLeft(){checkLayer(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('Customer level {lv}: {name}',{lv,name:LEVELS[lv-1].n})}
${nx?tr('Next: {req} unlocks {what}',{req:nx.req,what:lc1(nx.unlock)}):tr('Every customer type is unlocked. Go get those terabits.')}
`;} if(!S.offers.length)h+=`

${tr('No open offers right now. Businesses look for networks with POPs in their city. New ones pop up every few weeks.')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); - h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('{n} special requirement','{n} special requirements',o.reqs.length)}`:''}
${reqList(o)} + h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('{n} special requirement','{n} special requirements',o.reqs.length)}`:''}
${bRisk(o)}${reqList(o)}
${has?btn(tr('Accept'),'accept',{id:o.id},'green sm'):btn(tr('Go there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('Decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('Needs a POP in {cities}',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('Open NOC dashboard'),'dash',{},'pink')}${btn(tr('Connections'),'connOpen',{},'')}${btn(tr('Traceroute'),'trace',{},'')}
`; @@ -3781,7 +3842,7 @@ function cityPanel(c){ h+=`

${tr('Business customers')}

`; const bz=S.biz.filter(b=>bCities(b).includes(c)); if(!bz.length)h+=`

${tr('No businesses yet. Offers pop up as $ bubbles on the map.')}

`; - for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('carrying {g} per site',{g:fmtG(R.l2[b.id]||0)}):tr('carrying {g}',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('fiber is down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('serving {v}',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('needs a scrubbing center')+'':''}${S.day-(b.since||0)<15?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('Really drop?'):tr('Drop'),'dropBiz',{id:b.id},'ghost sm')}
`; + for(const b of bz)h+=`
${esc(b.name)}
${esc(BIZ_T[b.type].l)}${b.city2?` ${CITY[b.city].name} ⇄ ${CITY[b.city2].name}`:''} · ${bTerms(b)}${BIZ_T[b.type].l2?` · ${b.sites?tr('carrying {g} per site',{g:fmtG(R.l2[b.id]||0)}):tr('carrying {g}',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('fiber is down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('serving {v}',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('needs a scrubbing center')+'':''}${S.day-(b.since||0)<15?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('Really drop?'):tr('Drop'),'dropBiz',{id:b.id},'ghost sm')}
`; h+=`
`+offersHere(c); }else if(UI.tab==='up'){ h+=portNote(c)+latNote(c); @@ -3973,7 +4034,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('Offers here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('Needs your own scrubbing center (Infra tab).')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('Offers here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('{n}d left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('They need the full internet. Your reach is {pct}.',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('Needs your own scrubbing center (Infra tab).')}
`:''}${bRisk(o)}${reqList(o)}${bHas(o)?'':`
${tr('Needs a POP in {cities} too.',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('Accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('No'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} @@ -4031,8 +4092,8 @@ const SCN_PROG={stg:()=>[{l:tr('Reach'),v:R.reach,max:0.45,txt:`${pct(R.reach)} darien:()=>[...['bog','lim','scl','sao'].map(c=>pChk(tr('POP in {city}',{city:CITY[c].name}),!!S.pops[c])),pSrv(150)], gangnam:()=>[pReach(),pSrv(200)], fttb:()=>[...AU_BB.map(c=>pChk(tr('Broadband in {city}',{city:CITY[c].name}),!!(S.pops[c]&&S.pops[c].bb))),{l:tr('Cables overseas'),v:Math.min(2,auExits()),max:2,txt:`${auExits()} / 2`}], - flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,a=S.ev.ddos&&S.ev.ddos.until>S.day?S.ev.ddos:null; - return [{l:tr('Floods held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('Terabit floods held'),v:big,max:5,txt:`${big} / 5`},{l:tr('Floods that got through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(a?[{l:tr('Under attack now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`}]:[]);},baltic:()=>[{l:tr('Days in a row with 99.5% served'),v:S.stats.clean||0,max:90,txt:tr('{n} of {m}',{n:S.stats.clean||0,m:90})}]}; + flood:()=>{const ok=S.stats.ddosOk||0,big=S.stats.ddosOkBig||0,attacks=ddosAll(); + return [{l:tr('Floods held'),v:ok,max:20,txt:`${ok} / 20`},{l:tr('Terabit floods held'),v:big,max:5,txt:`${big} / 5`},{l:tr('Floods that got through'),v:0,max:0,txt:String(S.stats.ddosLost||0)}].concat(attacks.map(a=>({l:tr('Under attack now'),v:0,max:0,txt:`${fmtG(a.gbps)} · ${CITY[a.city].name} · ${pct(a.worst===undefined?1:a.worst)}`})));},baltic:()=>[{l:tr('Days in a row with 99.5% served'),v:S.stats.clean||0,max:90,txt:tr('{n} of {m}',{n:S.stats.clean||0,m:90})}]}; function scnProg(){const sc=S&&S.scn;if(!sc)return null; if(sc.id==='weekly')return {goal:tr('Serve as much traffic as you can in one year.'),items:[{l:tr('Your score: peak traffic'),v:0,max:0,txt:fmtG(S.stats.peak||0)}],f:Math.min(1,S.day/sc.days)}; const def=SCN.find(x=>x.id===sc.id),fn=SCN_PROG[sc.id];if(!def)return null;let items=[];try{items=fn?fn():[];}catch(e){items=[];} @@ -4110,7 +4171,7 @@ function custSection(){const F=UI.kf||{};let h=`
b.pm===undefined||Math.abs(b.mood-b.pm)<0.05?'':b.mood>b.pm?' ▲':' ▼'; const sorts=[['mood',tr('Happiness')],['mo',tr('Per month')],['name',tr('Name')],['city',tr('Where')]]; h+=`
${sorts.map(([k,l])=>btn(l+(sk===k?(dir>0?' ▲':' ▼'):''),'custSort',{k},sk===k?'pink sm':'ghost sm')).join('')}
`; - h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); + h+=rows.slice(0,listN('cust')).map(b=>{const why=bizWhy(b),grace=S.day-(b.since||0)<15;return `
${esc(b.name)} ${esc(BIZ_T[b.type].l)}
${esc(where(b))} · ${BIZ_T[b.type].event?esc(bTerms(b)):tr('{price}/mo',{price:fmt$(bizMo(b))})}${grace?` · ${tr('provisioning, {n}d grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${why.length?`
${why.map(esc).join(' · ')}
`:''}
${tr('Happiness {p}%',{p:Math.round(b.mood)})}${trend(b)}
${btn(tr('Open'),'custGo',{id:b.id},'ghost sm')}
`;}).join(''); return h+listMore('cust',rows.length,n=>trn('+{n} more customer','+{n} more customers',n))+`
`;} /* ---------- connections overview (#31, #33, #38) ---------- Every transit port, PNI, IX port, cache and fabric port in one list, filterable by type, city and diff --git a/tests/game.test.js b/tests/game.test.js index e6d0d16..1047b19 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -2,6 +2,15 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load, seed } = require('./harness'); +test('daily DDoS spawns share one routing calculation and score their first active day', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.day=50;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();window.__compute=compute;window.__random=Math.random;window.__computes=0;compute=()=>{window.__computes++;window.__compute()};Math.random=()=>0;dayTick();compute=window.__compute;Math.random=window.__random"); + assert.equal(ev('ddosAll().length'), 2, 'both daily spawn opportunities were used'); + assert.equal(ev('window.__computes'), 1, 'daily spawns do not reroute the whole network individually'); + assert.ok(ev('ddosAll().every(a=>a.worst===ddosSf(a))'), 'first-day service is recorded after routing'); + assert.deepEqual(errors, []); +}); + test('page boots to the title screen without errors', () => { const { ev, errors } = load(); assert.equal(ev("document.getElementById('modal').hidden"), false); @@ -197,6 +206,52 @@ test('Flowspec is a router-model capability, and each tool answers a flood', () assert.deepEqual(errors, []); }); +test('a distributed SYN flood reports actual Flowspec drops and sends only the remainder to scrubbing', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.scrubs=[{city:'fra',tier:0}];S.scrubMode='always';S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'edge',city:'fra',share:1}]};compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2); + assert.match(ev('ddosPanel()'), /— No Flowspec filtering: ingress routers have no TCAM/); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 30\.2 Gbps \/ 100G/); + assert.doesNotMatch(ev('ddosPanel()'), /✓ Flowspec|After upstream scrubbing|Reaching your network/); + for (const [router, dropped, scrubbed] of [[1,18.12,12.08], [3,25.67,4.53]]) { + ev(`S.pops.fra.rgen=${router};compute()`); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-dropped)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned')-scrubbed)<1e-9); + assert.match(ev('ddosPanel()'), new RegExp('✓ Flowspec dropping: '+dropped.toFixed(1).replace('.', '\\.')+' Gbps')); + assert.match(ev('ddosPanel()'), new RegExp('Scrubbing in Frankfurt: '+scrubbed.toFixed(1).replace('.', '\\.')+' Gbps / 100G')); + assert.doesNotMatch(ev('ddosPanel()'), /no TCAM|Edge filters dropping/); + } + ev("S.ev.ddos.vec='ack';compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).flowspec'), 0); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts[0].cleaned'), 30.2); + assert.match(ev('ddosPanel()'), /— Flowspec cannot catch ACK flood/); + assert.deepEqual(errors, []); +}); + +test('Flowspec accounts for each ingress router, upstream cleaning and other edge filters separately', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.pops.nyc.rgen=3;S.transit=[{id:'tf',city:'fra',net:'cog',tier:1},{id:'tn',city:'nyc',net:'cog',tier:1}];S.scrubs=[{city:'fra',tier:0},{city:'nyc',tier:0}];S.ev.ddos={id:'syn',city:'fra',vec:'syn',gbps:30.2,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.5},{k:'t',id:'tn',city:'nyc',share:0.5}]};compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-12.835)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)')-17.365)<1e-9); + assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 12\.8 Gbps; some ingress routers have no TCAM/); + assert.match(ev('ddosPanel()'), /Scrubbing in Frankfurt: 15\.1 Gbps \/ 100G/); + assert.match(ev('ddosPanel()'), /Scrubbing in New York: 2\.3 Gbps \/ 100G/); + assert.equal(ev('ddosMitigation(S.ev.ddos).flowspec'), ev('ddosReport(S.ev.ddos).flowspec'), 'uncached reports also filter at the ingress instead of the target'); + ev('S.transit[1].clean=true;compute()'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).reaching')-16.61)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-1.2835)<1e-9); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 16\.6 Gbps/); + assert.match(ev('ddosPanel()'), /~ Flowspec dropping: 1\.3 Gbps/); + ev("S.pops.fra.rgen=3;S.ixp={fra:1,nyc:1};S.ev.ddos.ixbh=true;compute()"); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-14.1185)<1e-9); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).flowspec')-1.24575)<1e-9); + assert.match(ev('ddosPanel()'), /✓ Flowspec dropping: 14\.1 Gbps/); + assert.match(ev('ddosPanel()'), /✓ Edge filters dropping: 1\.2 Gbps/); + assert.ok(ev('Math.abs(ddosReport(S.ev.ddos).reaching-ddosReport(S.ev.ddos).filtered-ddosReport(S.ev.ddos).sp.parts.reduce((n,x)=>n+x.cleaned,0)-ddosReport(S.ev.ddos).leak)<1e-9')); + assert.deepEqual(errors, []); +}); + test('RTBH blackholes the victim, and HackBack 3000 is a gamble', () => { const { ev } = load(); ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=120;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"); @@ -478,3 +533,468 @@ test('the broadband panel shows what homes in that city really pay, not the base assert.ok(ev("cityPanel('del')").includes(rev + '/mo'), `revenue line matches what the month pays (${rev})`); assert.deepEqual(errors, []); }); + + +test('Memcached amplification and ACK flood are available without gaming customers and respect Flowspec', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});RG[0].fs=2"); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('DDOS_VEC.memcached.fs'), true); + assert.equal(ev('DDOS_VEC.ack.fs'), false); + ev("S.ev.ddos={city:'fra',vec:'ack',gbps:300,until:S.day+3,start:S.day};compute()"); + const ack = ev('R.served'); + assert.match(ev('ddosPanel()'), /ACK flood/); + assert.doesNotMatch(ev('ddosPanel()'), /application layer/); + ev("S.ev.ddos.vec='memcached';compute()"); + assert.ok(ev('R.served') > ack, 'Flowspec filters Memcached but cannot filter ACK'); + for (const vec of ['memcached', 'ack']) { + ev(`const old=Math.random;Math.random=()=>(${['dns','ntp','memcached','ack'].indexOf(vec)}+0.1)/ddosVectors().length;ddosAttack();Math.random=old`); + assert.equal(ev('ddosAll().at(-1).vec'), vec, 'the generator can select each new vector'); + } + assert.deepEqual(errors, []); +}); + + +test('DDoS accounting conserves attack bandwidth through upstream, edge and local scrubbing', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.bb.d=100;S.scrubs=[{city:'fra',tier:1}];S.transit[0].clean=true;S.ev.ddos={city:'fra',vec:'http',gbps:1842,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute()"); + assert.ok(Math.abs(ev('R.ddos[0].reaching') - 184.2) < 1e-9); + assert.equal(ev('R.ddos[0].sp.parts[0].cleaned'), ev('R.ddos[0].reaching')); + assert.equal(ev('R.ddos[0].leak'), 0, 'the 1T center cleans the upstream remainder'); + assert.doesNotMatch(ev('ddosPanel()'), /842 Gbps of attack traffic leaks/); + ev('S.transit[0].clean=false;compute()'); + assert.equal(ev('R.ddos[0].reaching'), 1842); + assert.equal(ev('R.ddos[0].leak'), 842); + for (const setup of ["S.transit[0].clean=true", "RG[0].fs=2;S.ev.ddos.vec='dns'", "S.scrubs=[]"]) { + ev(setup+';compute()'); + assert.ok(ev('Math.abs(R.ddos[0].reaching-R.ddos[0].filtered-(R.ddos[0].sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0)-R.ddos[0].leak)<1e-9')); + assert.ok(ev('R.ddos[0].leak<=R.ddos[0].reaching')); + } + // On-demand diversion must also work for an attack which began on day zero. + ev("S.scrubs=[{city:'fra',tier:1}];S.scrubMode='ondemand';S.day=2;compute()"); + assert.equal(ev('R.ddos[0].leak'), 0); + assert.deepEqual(errors, []); +}); + + +test('the NOC integrates DDoS mitigation totals into each live attack card without duplicate summaries on phones', () => { + const { ev, errors, dom } = load(); + ev('ACT.start({})'); + Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true }); + ev("S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.transit[0].clean=true;S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={city:'fra',vec:'http',gbps:3840,until:5,start:0,entry:{k:'t',id:S.transit[0].id}};compute();UI.left='noc';UI.leftOpen=true;renderLeft()"); + const card = () => dom.window.document.querySelector('[data-act="rtbh"], [data-act="unrtbh"]').closest('.inc'); + const text = () => card().textContent; + assert.match(card().querySelector('.nm').textContent, /🚨 Live attack: Frankfurt/); + assert.equal(dom.window.document.querySelector('.ddos-stats'), null, 'use the existing attack card'); + assert.doesNotMatch(text(), /DDoS mitigation status|Attack size:|3840 Gbps|This attack:/); + assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'the attack size appears once'); + assert.match(text(), /✓ After upstream scrubbing: 384 Gbps/); + assert.equal(text().match(/After upstream scrubbing/g).length, 1, 'show the upstream remainder once'); + assert.doesNotMatch(text(), /Reaching your network|reaching your network|Upstream scrubbing active/); + assert.match(text(), /✓ Scrubbing in Frankfurt: 384 Gbps \/ 1T/); + assert.match(text(), /✓ Attack fully mitigated/); + ev('S.transit[0].clean=false;compute();renderLeft()'); + assert.doesNotMatch(text(), /After upstream scrubbing|Reaching your network/); + assert.equal(text().match(/3\.84 Tbps/g).length, 1, 'inactive upstream scrubbing does not repeat the attack size'); + assert.match(text(), /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T/); + assert.match(text(), /~ 2\.84 Tbps is leaking through/); + assert.equal(text().match(/leaking through/g).length, 1, 'show the mitigation outcome once'); + assert.doesNotMatch(text(), /Upstream scrubbing|Attack fully mitigated|leaks past mitigation/); + ev("S.transit[0].clean=true;S.pops.fra.rgen=3;S.ev.ddos.vec='dns';compute();renderLeft()"); + assert.match(text(), /✓ Flowspec dropping: 326 Gbps/); + assert.doesNotMatch(text(), /Edge filters dropping/); + assert.match(text(), /✓ Scrubbing in Frankfurt: 57\.6 Gbps \/ 1T/); + assert.match(text(), /✓ Attack fully mitigated/); + ev('ACT.rtbh();renderLeft()'); + assert.match(text(), /~ Blackholed: the junk is gone, and so is Frankfurt/); + assert.equal(text().match(/Blackholed:/g).length, 1); + assert.doesNotMatch(text(), /After upstream scrubbing|reaching your network|scrubbing in Frankfurt|Attack fully mitigated|leaking through/i); + assert.ok(card().querySelector('[data-act="unrtbh"]'), 'the existing controls stay in the card'); + assert.deepEqual(errors, []); +}); + +test('overlapping floods share scrubbing capacity, have separate controls, and finish independently', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:700,start:0,until:3};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:700,start:0,until:5}];compute();UI.left='noc';UI.leftOpen=true;renderLeft()"); + assert.equal(ev('R.ddos.length'), 2); + assert.equal(ev('R.ddos.reduce((n,m)=>n+(m.sp?.parts.reduce((v,x)=>v+x.cleaned,0)||0),0)'), 1000); + assert.equal(ev('R.ddos.reduce((n,m)=>n+m.leak,0)'), 400, 'one center cannot spend its capacity twice'); + const cards = [...dom.window.document.querySelectorAll('[data-act="rtbh"]')].map(b=>b.closest('.inc')); + assert.equal(cards.length, 2); + assert.match(cards[1].textContent, /✓ Scrubbing in Frankfurt: 1\.00 Tbps \/ 1T · This attack: 300 Gbps/); + ev("ACT.rtbh({id:'two'})"); + assert.equal(ev("S.ev.ddos.bh||false"), false, 'the selected attack gets the control'); + assert.equal(ev('S.ev.ddosMore[0].bh'), true); + assert.ok(ev('R.ddos.every(m=>m.leak===0)'), 'blackholing a target city drops every flood to it'); + ev("ACT.unrtbh({id:'one'});const old=Math.random;Math.random=()=>0.1;ACT.hackback({id:'two'});Math.random=old"); + assert.equal(ev('ddosAll().length'), 1, 'hack-back ends only the selected attack'); + ev('S.day=3;ddosExpire();compute()'); + assert.equal(ev('ddosAll().length'), 0); + assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2, 'both attacks scored once'); + ev('ddosExpire()'); + assert.equal(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)'), 2); + assert.deepEqual(errors, []); +}); + +test('overlapping DDoS saves round trip and legacy attacks migrate safely', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.ev.ddos={city:'fra',vec:'dns',gbps:'80',until:7,start:0};delete S.ev.ddosMore;delete S.ddosStarts;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('ddosAll().length'), 1); + assert.equal(ev('S.ev.ddos.gbps'), 80); + assert.equal(ev('S.ev.ddosMore.length'), 0); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]); + ev("S.ev.ddosMore=[{id:'overlap',city:'fra',vec:'ack',gbps:50,until:5,start:0,sla:['customer']},null,{city:'bad',vec:'dns'}, {city:'fra',vec:'unknown'}];S.ddosStarts=[0,'bad',Infinity,-9,99];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('ddosAll().length'), 2); + assert.equal(ev('S.ev.ddosMore[0].id'), 'overlap'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosStarts)')), [0]); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('R.ddos.length'), 2); + assert.deepEqual(errors, []); +}); + +test('simultaneous attacks each bill their protected customer only once', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=200;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.biz=[{id:'protected',name:'Shield',city:'fra',type:'scrub',bw:5,rate:900,mood:100,since:0,reqs:[]}];S.ev.ddos={id:'one',city:'fra',vec:'http',gbps:6000,start:0,until:7};S.ev.ddosMore=[{id:'two',city:'fra',vec:'http',gbps:6000,start:0,until:7}];compute();dayTick()"); + assert.equal(ev('S.stats.sla'), 2, 'same-day attacks have separate SLA identities'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));dayTick()'); + assert.equal(ev('S.stats.sla'), 2, 'reloading does not pay the same credits twice'); + assert.deepEqual(errors, []); +}); + +test('DDoS frequency rises with level and signed gaming customers, with a rolling weekly ceiling', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.day=50;S.lvl=1;S.biz=[]"); + const base = ev('ddosRate()'); + assert.equal(base, 0.5); + ev('S.lvl=13'); + assert.equal(ev('ddosRate()'), base, 'level alone does not increase the non-gaming rate'); + ev("S.biz=[{type:'game',city:'fra'}];S.lvl=1"); + const early = ev('ddosRate()'); + ev('S.lvl=13'); + const level = ev('ddosRate()'); + ev("S.biz=Array.from({length:20},(_,i)=>({type:i%2?'cgame':'game',city:'fra'}))"); + const gaming = ev('ddosRate()'); + assert.ok(base < early && early < level && level < gaming && gaming <= 7); + ev("S.offers=Array.from({length:50},()=>({type:'game'}));S.biz=[];S.lvl=1"); + assert.equal(ev('ddosRate()'), base, 'unsigned offers do not attract attacks'); + // Force every random spawn opportunity, then verify each rolling seven-day window. + ev('window.__starts=[];window.__oldRandom=Math.random;Math.random=()=>0'); + for (let day = 50; day < 66; day++) { + ev(`S.day=${day};ddosTick();window.__starts.push(...ddosAll().filter(a=>a.start===S.day).map(a=>a.start))`); + assert.ok(ev('S.ddosStarts.length') <= 14); + } + ev('Math.random=window.__oldRandom'); + const starts = JSON.parse(ev('JSON.stringify(window.__starts)')); + for (let day = 50; day < 66; day++) assert.ok(starts.filter(d=>d>day-7&&d<=day).length <= 14); + assert.ok(starts.length > 14, 'the allowance renews as starts leave the rolling window'); + ev('for(let i=0;i<30;i++)ddosAttack()'); + assert.equal(ev('S.ddosStarts.length'), 14, 'manual and incident starts cannot bypass the cap'); + assert.deepEqual(errors, []); +}); + +test('DDoS sizes use a smaller non-gaming baseline and preserve unbounded Flood Season scaling', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.lvl=13;R.demand=150000;S.biz=[]'); + assert.equal(ev('ddosSizeMean()'), 20000); + ev("S.scn={id:'flood',rules:{ddos:true}};S.day=365"); + assert.equal(ev('ddosSizeMean()'), 400000); + ev('S.day=730'); + assert.equal(ev('ddosSizeMean()'), 600000, 'Flood Season keeps growing after completion'); + ev('S.scn=null;R.demand=300000'); + assert.equal(ev('ddosSizeMean()'), 40000, 'larger networks can draw still larger attacks'); + ev('S.lvl=1'); + const early = ev('ddosSizeMax()'); + ev('S.lvl=13'); + const late = ev('ddosSizeMax()'); + ev("S.biz=[{type:'game',city:'fra'}]"); + assert.ok(early < late && late < ev('ddosSizeMax()')); + // Fixed quantiles show longer durations as both level and gaming exposure rise. + ev('window.__oldRandom=Math.random;Math.random=()=>0.95;S.lvl=1;S.biz=[];ddosAttack();window.__earlyDur=ddosAll().at(-1).until-S.day;S.lvl=13;S.biz=Array.from({length:40},()=>({type:\'game\',city:\'fra\',bw:0,rate:0}));ddosAttack();Math.random=window.__oldRandom'); + assert.ok(ev('ddosAll().at(-1).until-S.day') > ev('window.__earlyDur')); + assert.equal(ev('ddosAll().at(-1).until-S.day'), 7); + assert.deepEqual(errors, []); +}); + +test('distributed attacks follow normal transit and peering traffic across regions', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:c==='fra'?100:300}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}];S.pni=[{id:'pf',city:'fra',net:'ggl',tier:1}];S.ixp={nyc:1};S.rs={nyc:true};compute();window.__normal=JSON.stringify(R.ingressPorts);ddosAttack()"); + const normal = JSON.parse(ev('window.__normal')); + const entries = JSON.parse(ev('JSON.stringify(ddosAll()[0].entries)')); + const total = Object.values(normal).reduce((n,p)=>n+p.traffic,0); + assert.ok(entries.some(p=>p.k==='t') && entries.some(p=>p.k==='p') && entries.some(p=>p.k==='ix')); + assert.deepEqual([...new Set(entries.map(p=>p.city))].sort(), ['fra','nyc']); + for (const en of entries) assert.ok(Math.abs(en.share-normal[en.k+':'+en.id].traffic/total)<1e-9); + assert.ok(Math.abs(entries.reduce((n,en)=>n+en.share,0)-1)<1e-9); + assert.match(ev('ddosPanel()'), /Live attack:/); + assert.doesNotMatch(ev('ddosPanel()'), /ports: .*regions:/, 'keep regional detail out of the live attack card'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('S.ev.ddos.entries.length'), entries.length, 'distributed shares survive a save round trip'); + assert.deepEqual(errors, []); +}); + +test('distributed ingress applies upstream scrubbing only to its own port and uses regional centers', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc']){S.pops[c].rgen=3;S.pops[c].bb={d:100}}S.transit=[{id:'tf',city:'fra',net:'cog',tier:2,clean:true},{id:'tn',city:'nyc',net:'cog',tier:2}];S.scrubs=[{city:'fra',tier:0}];S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'tf',city:'fra',share:0.25},{k:'t',id:'tn',city:'nyc',share:0.75}]};compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 775); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 750); + assert.equal(ev('R.useT.tn'), 400, 'the uncleaned flood fills its own ingress port'); + assert.ok(ev('R.useT.tf') < 200, 'it cannot spill into the cleaned port'); + assert.match(ev('ddosPanel()'), /✓ After upstream scrubbing: 775 Gbps/); + assert.match(ev('ddosPanel()'), /~ 750 Gbps is leaking through/); + ev("S.scrubs.push({city:'nyc',tier:1});compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in Frankfurt: 25\.0 Gbps \/ 100G/); + assert.match(ev('ddosPanel()'), /✓ Scrubbing in New York: 750 Gbps \/ 1T/); + assert.deepEqual(errors, []); +}); + +test('scrubbing hauls retain their real source on each link when several cities use one center', () => { + const { ev, errors, dom } = load(); + ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['prg','ber'])ACT.buildPop({city:c}); + for(const c in S.pops)S.pops[c].rgen=3; + S.links=[{id:'fp1',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100}, + {id:'fp2',a:'fra',b:'prg',kind:'wave',tier:2,km:409,mo:100}, + {id:'fb',a:'fra',b:'ber',kind:'wave',tier:2,km:420,mo:100}, + {id:'pb',a:'prg',b:'ber',kind:'wave',tier:2,km:280,mo:100}]; + S.transit=[{id:'tp',city:'prg',net:'cog',tier:2},{id:'tb',city:'ber',net:'cog',tier:2}]; + S.scrubs=[{city:'fra',tier:1}]; + S.ev.ddos={id:'spread',city:'ber',vec:'ack',gbps:100,start:0,until:7, + entries:[{k:'t',id:'tp',city:'prg',share:.5},{k:'t',id:'tb',city:'ber',share:.5}]};compute()`); + const sources = id => JSON.parse(ev(`JSON.stringify(Object.entries(R.ef[edgeKey(S.links.find(l=>l.id==='${id}'))].eg) + .filter(([key])=>key.startsWith('scrub:')).map(([key,g])=>({city:R.egDesc[key].city,g})).sort((a,b)=>a.city.localeCompare(b.city)))`)); + assert.equal(ev('R.load.pb||0'), 0, 'Berlin does not feed the Prague link'); + assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']); + assert.deepEqual(sources('fb').map(x=>x.city), ['ber']); + assert.ok(sources('fp1')[0].g>0 && sources('fb')[0].g>0); + assert.ok(Math.abs(sources('fp1')[0].g-ev('R.load.fp1+R.load.fp2'))<1e-9, 'the grouped record covers both parallel links exactly'); + ev("selectLink('fp1');draw(0)"); + const row = [...dom.window.document.querySelectorAll('#panelBody .row')].find(x=>x.querySelector('.nm')?.textContent==='Attack hauled to scrubbing in Frankfurt'); + assert.ok(row); + assert.match(row.querySelector('.meta').textContent, /^Prague · /); + assert.equal(JSON.parse(row.querySelector('[data-act="goEgress"]').dataset.args).city, 'prg'); + assert.deepEqual(JSON.parse(ev('JSON.stringify([...UI.feed])')), ['prg'], 'the map highlights the same source as the inspected link'); + row.querySelector('[data-act="goEgress"]').click(); + assert.equal(ev('UI.sel.id'), 'prg', 'Open goes to the actual source city'); + // Reordering ingress and adding an overlapping flood must not change the attribution. + ev("S.ev.ddos.entries.reverse();S.ev.ddosMore=[{...S.ev.ddos,id:'overlap',gbps:20,entries:S.ev.ddos.entries.slice().reverse()}];compute()"); + assert.deepEqual(sources('fp1').map(x=>x.city), ['prg']); + assert.deepEqual(sources('fb').map(x=>x.city), ['ber']); + // When Berlin's direct link fails, its haul really does join Prague's route. + ev('S.links.find(l=>l.id==="fb").cut=S.day+1;compute()'); + assert.ok(ev('R.load.pb')>0); + assert.deepEqual(sources('fp1').map(x=>x.city), ['ber','prg']); + assert.deepEqual(sources('pb').map(x=>x.city), ['ber']); + assert.ok(Math.abs(sources('fp1').reduce((n,x)=>n+x.g,0)-ev('R.load.fp1+R.load.fp2'))<1e-9, 'shared-path totals still equal the actual link load'); + assert.deepEqual(errors, []); +}); + +function setupScrubLatency(ev) { + ev(`ACT.start({});S.cash=1e9;S.lvl=6;for(const c of ['par','nyc','ams'])ACT.buildPop({city:c}); + for(const c in S.pops)S.pops[c].rgen=RG.findIndex(g=>g.fs===1); + S.links=[{id:'pf',a:'par',b:'fra',kind:'wave',tier:3,km:620/1.3,mo:100}, + {id:'fn',a:'fra',b:'nyc',kind:'wave',tier:3,km:6000,mo:100}, + {id:'fa',a:'fra',b:'ams',kind:'wave',tier:3,km:200,mo:100}]; + S.transit=[{id:'tf',city:'fra',net:'cog',tier:2},{id:'tn',city:'nyc',net:'cog',tier:2}]; + S.scrubs=[{city:'fra',tier:0},{city:'par',tier:0}]; + S.ev.ddos={id:'par-flood',city:'par',vec:'dns',gbps:33.8,start:0,until:7, + entries:[{k:'t',id:'tf',city:'fra',share:0.65},{k:'t',id:'tn',city:'nyc',share:0.35}]};compute()`); +} + +test('distributed ingress does not give a locally protected victim a remote scrubbing latency', () => { + const { ev, errors, dom } = load(); + setupScrubLatency(ev); + assert.ok(ev("R.haul.some(q=>q.city==='nyc'&&q.to==='par'&&q.ms>60)"), 'the remote ingress still travels to its scrubbing center'); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'both centers clean the distributed flood'); + assert.ok(Math.abs(ev('ddosReport(S.ev.ddos).flowspec')-20.28)<1e-9); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 0); + Object.defineProperty(dom.window, 'innerWidth', { value: 360, configurable: true }); + ev("UI.left='noc';UI.leftOpen=true;renderLeft()"); + const text = dom.window.document.getElementById('left').textContent; + assert.match(text, /Live attack: Paris/); + assert.match(text, /Scrubbing in Frankfurt: 8\.8 Gbps/); + assert.match(text, /Scrubbing in Paris: 4\.7 Gbps/); + assert.doesNotMatch(text, /Scrubbing traffic hauled over your backbone|\+\d+(\.\d+)? ms/); + // A local center is still nearest when it is full and other centers take overflow. + ev("S.ev.ddos.vec='ack';S.ev.ddos.gbps=300;compute()"); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + assert.deepEqual(errors, []); +}); + +test('each attack shows only the nearest scrubbing detour using precise one-way link latency', () => { + const { ev, errors } = load(); + setupScrubLatency(ev); + ev("for(const c in S.pops)S.pops[c].rgen=3;S.scrubs=[{city:'fra',tier:0},{city:'ams',tier:0}];S.ev.ddos.vec='ack';S.ev.ddos.gbps=230;compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).sp.parts.length'), 2, 'capacity spills between centers'); + const card = ev('ddosOne(S.ev.ddos)'); + assert.equal((card.match(/Scrubbing traffic hauled over your backbone/g)||[]).length, 1); + assert.match(card, /✓ Scrubbing traffic hauled over your backbone: Paris → Frankfurt \(\+3\.1 ms\)/); + // An overlapping attack has its own victim and nearest center. + ev("S.ev.ddosMore=[{id:'other',city:'ams',vec:'ack',gbps:10,start:0,until:7,entries:[{k:'t',id:'tn',city:'nyc',share:1}]}];compute()"); + assert.doesNotMatch(ev('ddosOne(S.ev.ddosMore[0])'), /Scrubbing traffic hauled over your backbone/); + assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Frankfurt \(\+3\.1 ms\)/); + // Ignore a failed nearby center and use the live path to Amsterdam. + ev("S.pops.fra.down=10;S.links.push({id:'pa',a:'par',b:'ams',kind:'wave',tier:3,km:2000,mo:100});S.ev.ddos.entries=[{k:'edge',city:'par',share:1}];compute()"); + assert.match(ev('ddosOne(S.ev.ddos)'), /Paris → Amsterdam \(\+13\.0 ms\)/); + ev('S.ev.ddos.bh=true;compute()'); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + ev('S.ev.ddos.bh=false;S.scrubMode="ondemand";compute()'); + assert.doesNotMatch(ev('ddosOne(S.ev.ddos)'), /Scrubbing traffic hauled over your backbone/); + assert.deepEqual(errors, []); +}); + +test('a constrained remote haul leaves scrubbing capacity for the next overlapping flood', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});for(const c of ['fra','nyc'])S.pops[c].rgen=3;S.links=[{id:'thin',a:'nyc',b:'fra',kind:'wave',tier:1,km:6000,mo:100}];S.scrubs=[{city:'fra',tier:1}];S.ev.ddos={id:'far',city:'nyc',vec:'http',gbps:600,start:0,until:7};S.ev.ddosMore=[{id:'near',city:'fra',vec:'http',gbps:900,start:0,until:7}];compute()"); + const clean = JSON.parse(ev('JSON.stringify(R.ddos.map(m=>({id:m.attack.id,clean:m.sp?.parts.reduce((n,x)=>n+x.cleaned,0)||0,leak:m.leak})))')); + assert.equal(clean.find(m=>m.id==='near').clean, 900); + assert.ok(clean.find(m=>m.id==='far').clean <= 100); + assert.ok(clean.reduce((n,m)=>n+m.clean,0) <= 1000); + for (const m of clean) assert.equal(m.clean+m.leak, m.id==='near'?900:600); + assert.deepEqual(errors, []); +}); + +test('distributed attack statistics survive an ingress outage and corrupted saved shares', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;ACT.buildPop({city:'nyc'});S.ev.ddos={id:'spread',city:'fra',vec:'http',gbps:1000,start:0,until:7,entries:[{k:'t',id:'a',city:'fra',share:0.25},{k:'t',id:'b',city:'nyc',share:0.75}]};S.pops.nyc.down=5;compute()"); + assert.equal(ev('ddosReport(S.ev.ddos).reaching'), 1000); + assert.equal(ev('ddosReport(S.ev.ddos).leak'), 1000); + ev("S.ev.ddos.entries.push({k:'t',id:'bad',city:'unknown',share:5},{k:'t',id:'bad2',city:'fra',share:-1});S=migrate(JSON.parse(JSON.stringify(S)));compute()"); + assert.equal(ev('S.ev.ddos.entries.length'), 2); + assert.equal(ev('S.ev.ddos.entries.reduce((n,en)=>n+en.share,0)'), 1); + assert.deepEqual(errors, []); +}); + +test('RackNet and TeamSpooked require signed gaming customers, bypass Flowspec, and stay within a third of the current size range', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=13;S.pops.fra.bb={d:150000};ACT.buyTransit({city:'fra',net:'cog',tier:2});compute()"); + assert.equal(ev("ddosVectors().includes('racknet')||ddosVectors().includes('teamspooked')"), false); + ev("S.offers=[{type:'game'}]"); + assert.equal(ev("ddosVectors().includes('racknet')"), false, 'an unsigned offer does not introduce gaming attacks'); + ev("S.biz=[{type:'game',id:'gamer',name:'Gamer',city:'fra',bw:0,rate:0}];compute()"); + for (const vec of ['racknet','teamspooked']) { + assert.equal(ev(`DDOS_VEC.${vec}.fs`), false); + const sizeMax = ev('ddosSizeMax()/3'); + ev(`const old=Math.random;let n=0;Math.random=()=>n++===1?(ddosVectors().indexOf('${vec}')+0.5)/ddosVectors().length:0.999999;ddosAttack();Math.random=old`); + assert.equal(ev('ddosAll().at(-1).vec'), vec); + assert.ok(ev('ddosAll().at(-1).gbps') <= sizeMax); + assert.ok(ev('ddosAll().at(-1).gbps') > sizeMax*(1-0.00002), 'the upper randomized quantile approaches the one-third limit, including rare spikes'); + } + ev("S.biz[0].type='cgame'"); + assert.equal(ev("ddosVectors().includes('teamspooked')"), true, 'cloud gaming also attracts these vectors'); + ev('S.biz=[]'); + assert.equal(ev("ddosVectors().includes('teamspooked')"), false); + assert.equal(ev('ddosAll().length'), 2, 'existing attacks finish naturally after the gaming customer leaves'); + assert.deepEqual(errors, []); +}); + +test('normal DDoS starts average half an attack per week without gaming and never exceed a seven-per-week expected rate', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.day=50'); + const checks = JSON.parse(ev(` + const oldAttack=ddosAttack,oldRandom=Math.random,out=[]; + try { + for(const [level,games] of [[1,0],[13,0],[1,1],[13,1],[13,10],[13,1000]]){ + S.lvl=level;S.biz=Array.from({length:games},()=>({type:'game'})); + let starts=0,draw=0;ddosAttack=()=>{starts++};Math.random=()=>((draw++)+0.5)/14000; + for(let day=0;day<7000;day++)ddosTick(); + out.push({level,games,expected:ddosRate(),observed:starts/1000}); + } + } finally {ddosAttack=oldAttack;Math.random=oldRandom;} + JSON.stringify(out) + `)); + for(const row of checks){ + assert.ok(Math.abs(row.observed-row.expected)<=0.0011, JSON.stringify(row)); + if(row.games===0)assert.equal(row.observed,0.5); + else assert.ok(row.expected>0.5&&row.expected<=7); + } + assert.ok(checks[3].expected>checks[2].expected, 'level increases gaming frequency'); + assert.ok(checks[4].expected>checks[3].expected, 'more gaming customers increase frequency'); + assert.ok(checks[3].expected<0.8, 'one gaming customer does not suddenly add several attacks per week, even at the last level'); + assert.deepEqual(errors, []); +}); + +test('normal attack sizes match the one- and fifty-gamer targets while frequency rises gradually', () => { + const { ev, errors } = load(); + ev('ACT.start({})'); + const samples = JSON.parse(ev(` + const oldRandom=Math.random,out=[]; + try { + for(const [level,demand] of [[1,0],[3,1850],[LEVELS.length,LV_REQ.at(-1).pk]]){ + const counts=[]; + for(const games of [0,1,2,5,10,20,50,100,1000]){ + S.lvl=level;S.biz=Array.from({length:games},(_,i)=>({id:'g'+i,type:i%2?'cgame':'game',city:'fra',bw:0,rate:0})); + const vectors=ddosVectors();let sum=0; + for(let i=0;idraw++===1?(i+0.5)/vectors.length:roll; + ddosAttack(false);sum+=weight*S.ev.ddos.gbps; + } + counts.push({games,mean:sum/vectors.length,rate:ddosRate()}); + } + out.push({level,demand,counts}); + } + } finally {Math.random=oldRandom;} + JSON.stringify(out) + `)); + for(const row of samples){ + const [plain,first]=row.counts,fifty=row.counts.find(c=>c.games===50),hundred=row.counts.find(c=>c.games===100),many=row.counts.at(-1); + assert.ok(Math.abs(first.mean-plain.mean*3)<0.003, 'the first gamer triples the overall mean, allowing only bandwidth rounding: '+JSON.stringify(row)); + assert.ok(Math.abs(fifty.mean-plain.mean*8)<0.01, 'fifty gamers bring eightfold sizes, allowing only bandwidth rounding'); + assert.ok(hundred.mean>first.mean*3, 'growth continues across dozens of gaming customers'); + assert.ok(hundred.mean>plain.mean*10 && hundred.mean6 && many.rate<=7); + for(let i=1;irow.counts[i-1].mean, 'each sampled count increases actual spawned attack sizes'); + assert.ok(row.counts[i].rate>row.counts[i-1].rate, 'each sampled count increases frequency'); + } + } + assert.ok(Math.abs(samples[0].counts[0].mean-1)<0.001, 'the minimum-demand baseline still permits small attacks'); + assert.ok(Math.abs(samples[1].counts[0].mean-740/13)<0.001, 'the 1.85 Tbps non-gaming example keeps its average'); + assert.ok(Math.abs(samples[2].counts[0].mean-samples[2].demand*4/3/10)<0.001); + assert.deepEqual(errors, []); +}); + +test('normal attack sizes cover a broad ordinary range and a two-percent large tail without raising the mean', () => { + const { ev, errors } = load(); + ev('ACT.start({});S.lvl=3;S.biz=[];R.demand=1850'); + const distribution = JSON.parse(ev(` + const oldRandom=Math.random,ordinary=[],large=[];let sum=0; + try { + for(let i=0;i<10000;i++){ + Math.random=()=>(i+0.5)/10000; + const g=ddosSize('syn');sum+=g;(g>100?large:ordinary).push(g); + } + } finally {Math.random=oldRandom;} + JSON.stringify({ordinary:{n:ordinary.length,min:Math.min(...ordinary),max:Math.max(...ordinary)}, + large:{n:large.length,min:Math.min(...large),max:Math.max(...large),near500:large.some(g=>g>=490&&g<=510)},mean:sum/10000}) + `)); + assert.equal(distribution.ordinary.n, 9800); + assert.equal(distribution.large.n, 200); + assert.ok(distribution.ordinary.min>=8.9 && distribution.ordinary.min<10); + assert.ok(distribution.ordinary.max>85 && distribution.ordinary.max<=89.1); + assert.ok(distribution.ordinary.max/distribution.ordinary.min>9.9); + assert.ok(distribution.large.min>=356 && distribution.large.max<=535); + assert.ok(distribution.large.near500, 'the example network can occasionally face a roughly 500 Gbps flood'); + assert.ok(Math.abs(distribution.mean-740/13)<0.001, 'the rare tail preserves the previous 56.923 Gbps average'); + // Verify that real spawns use both bands, not just the standalone sampler. + for (const [roll,minimum,maximum] of [[0.49,8.9,89.1],[0.99,356,535]]) { + ev(`S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];R.demand=1850;const old=Math.random;let n=0;Math.random=()=>{const i=n++;return i===1?(ddosVectors().indexOf('syn')+0.5)/ddosVectors().length:i===2?${roll}:0.5};try{ddosAttack()}finally{Math.random=old}`); + assert.equal(ev('S.ev.ddos.vec'), 'syn'); + assert.ok(ev('S.ev.ddos.gbps')>=minimum && ev('S.ev.ddos.gbps')<=maximum); + } + assert.deepEqual(errors, []); +}); + +test('Flood Season retains its existing size quantiles and escalation when normal attacks gain rare spikes', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.scn={id:'flood',rules:{ddos:true}};S.lvl=3;S.biz=[];R.demand=1850"); + for (const [day,expected] of [[0,[700,1400,2099]],[365,[1400,2800,4199]],[730,[2100,4200,6299]]]) { + ev(`S.day=${day}`); + const actual = JSON.parse(ev("const old=Math.random;let sizes;try{sizes=[0,0.5,0.999999].map(r=>{Math.random=()=>r;return ddosSize('syn')})}finally{Math.random=old}JSON.stringify(sizes)")); + assert.deepEqual(actual, expected); + } + assert.deepEqual(errors, []); +}); diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index a5c557c..52e6af4 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -5,8 +5,8 @@ module.exports = ` for(f of flows){ if(f.rem<=1e-6||(rank===0&&!f.cache)||(pass&&!pass(f)))continue; Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++; - const candidates=E.filter(e=>e.usede.used(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]); for(let i=0;i1e-6;){ let j=i+1;while(j= 3, 'starts with bigger gear unlocked'); // a few weeks in: several attacks start on their own schedule let n = 0; - for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('!!(S.ev.ddos&&S.ev.ddos.start===S.day)')) n++; } + for (let i = 0; i < 40; i++) { ev('dayTick()'); if (ev('ddosAll().some(a=>a.start===S.day)')) n++; } assert.ok(n >= 4, `attacks keep coming (${n} in 40 days)`); assert.ok(ev('(S.stats.ddosOk||0)+(S.stats.ddosLost||0)') >= 3, 'finished attacks are scored'); // scoring: held only if service stayed at 97%+ @@ -468,3 +468,27 @@ test('RouteScript: help, ready-made scripts and the AI button', () => { ev("UI.dtab='overview';renderAll()"); assert.deepEqual(errors, []); }); + + +test('Flood Season keeps attacking and escalating after both success and timeout', () => { + for (const outcome of ['done', 'failed']) { + const { ev, errors, dom } = load(); + ev("ACT.startScn({id:'flood',sure:1});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9"); + if (outcome === 'done') ev('S.stats.ddosOk=20;S.stats.ddosOkBig=5;S.day=100'); + else ev('S.day=365'); + ev('scnTick(S.day)'); + assert.ok(ev(`!!S.scn.${outcome}`)); + assert.ok([...dom.window.document.querySelectorAll('#modal [data-act="closeModal"]')].some(b=>b.textContent==='Keep playing')); + ev('ACT.closeModal();S.scn.nextDdos=S.day+1;dayTick()'); + assert.equal(ev('S.ev.ddos.start'), ev('S.day'), 'Keep playing still spawns attacks'); + const before = ev('S.day'); + ev('S.scn.nextDdos=S.day+1;S.day+=8;dayTick()'); + assert.ok(ev('ddosAll().at(-1).start') > before, 'subsequent attacks keep coming'); + const gaps = JSON.parse(ev('const old=Math.random;Math.random=()=>0.5;S.day=0;const early=floodGap();S.day=1000;const late=floodGap();Math.random=old;JSON.stringify([early,late])')); + assert.ok(gaps[1] < gaps[0], 'frequency keeps increasing with scenario age'); + const sizes = JSON.parse(ev('const old=Math.random;Math.random=()=>0.9;S.day=0;ddosAttack();const early=ddosAll().at(-1).gbps;S.day=1000;ddosAttack();const late=ddosAll().at(-1).gbps;Math.random=old;JSON.stringify([early,late])')); + assert.ok(sizes[1] > sizes[0], 'intensity keeps increasing with scenario age'); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); diff --git a/tests/routing-reference.test.js b/tests/routing-reference.test.js index 8742007..8a239ad 100644 --- a/tests/routing-reference.test.js +++ b/tests/routing-reference.test.js @@ -38,6 +38,7 @@ test('indexed routing matches the simple allocation loop across network changes' "S.te.script='prefer transit Cogentle\\nprepend transit Cogentle 2\\nprotect customers'", "S.ev.rpki={nets:['ggl','nfx'],until:S.day+3};S.ev.depeer=S.day+3", "S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}", + "S.ev.ddos.entries=[{k:'t',id:'transit0',city:'fra',share:.4},{k:'t',id:'transit4',city:'nyc',share:.6}]", "S.links[0].eqDown=S.day+2;S.links[1].cut=S.day+2;S.links[2].loss={until:S.day+2,f:0.5}", "S.links[4].chFail={until:S.day+2,o:'tp16'};S.links[6].ch.push('zr4');S.links[8].regen=2", "S.day+=4;S.pni.splice(0,20);S.caches.splice(0,10);S.transit[0].pref='high'", diff --git a/tests/services.test.js b/tests/services.test.js index 5379cdc..9ba8bc5 100644 --- a/tests/services.test.js +++ b/tests/services.test.js @@ -9,6 +9,30 @@ function network(ev) { ev("const L=(a,b,t,v)=>{UI.via=v||null;openLinkModal(a,b);ACT.buildLink({tier:t});};L('fra','ams',3);L('fra','par',3);L('ams','lon',2,'uly');closeModal()"); } +test('gaming offers and signed customers show their DDoS risk in Deals, city panels and customer lists', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});S.cash=1e9;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.offers=['game','cgame','host'].map(type=>({id:type,city:'fra',name:type,bw:5,rate:100,reqs:[],exp:S.day+30,type}));UI.left='deals';UI.leftOpen=true;renderLeft()"); + const notes = (root, action) => { + const buttons = [...root.querySelectorAll(`[data-act="${action}"]`)]; + assert.equal(buttons.length, 3); + for (const button of buttons) { + const id = JSON.parse(button.dataset.args).id; + const count = (button.closest('.row').textContent.match(/Gaming attracts attacks/g)||[]).length; + assert.equal(count, id==='game'||id==='cgame'?1:0, `risk note for ${id}`); + } + }; + assert.equal(ev('gamingCount()'), 0, 'offers disclose future risk before signing'); + notes(dom.window.document.getElementById('leftBody'), 'accept'); + ev("selectCity('fra');ACT.tab({t:'cust'})"); + notes(dom.window.document.getElementById('panelBody'), 'accept'); + ev("for(const id of ['game','cgame','host'])ACT.accept({id});UI.tab='cust';renderPanel()"); + assert.equal(ev('gamingCount()'), 2, 'the note uses the same customer classification as the attack calculation'); + notes(dom.window.document.getElementById('panelBody'), 'dropBiz'); + ev('ACT.custOpen({})'); + notes(dom.window.document.getElementById('custSec'), 'custGo'); + assert.deepEqual(errors, []); +}); + test('event networks pay in full when the crowd is served, nothing up front', () => { const { ev, errors } = load(); seed(ev, 4); From 925e7c1798eb335aa2b85ea157f68f1d6507c160 Mon Sep 17 00:00:00 2001 From: Filip Hruska Date: Tue, 27 Oct 2026 10:15:33 +0000 Subject: [PATCH 06/13] rewrite changelog --- CHANGELOG.md | 31 +++++++------------------------ 1 file changed, 7 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index df9f47c..0294568 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,36 +6,19 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels, Open buttons or map highlights. - -- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. Local scrubbing adds no backbone-haul line, and distributed ingress no longer produces unrelated or repeated latency messages. - -- The NOC no longer shows the generic attack-rate note for networks without gaming customers. - -- Gaming customers now scale normal-mode DDoS sizes from three times the no-gaming average with one customer to eight times with 50. Adding more gamers continues to increase attack sizes, while frequency still rises gradually toward seven attacks per week. Flood Season keeps its existing escalation. - -- Normal-mode DDoS attacks now vary much more in size, with a 2% chance of a much larger flood. The long-run average still scales with demand, customer level and gaming customers; Flood Season keeps its existing size distribution and escalation. - +- Attacks are now more common and dynamic in nature to bring some more excitement. +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels. +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency. - Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them. - - Live attacks now show how much traffic Flowspec actually drops at the ingress routers. Routers without TCAM no longer claim to filter attacks, mixed router capabilities are called out, and Flowspec drops are counted separately from other edge filters. - -- Normal networks without gaming customers now average half a DDoS attack per week, with attacks ten times smaller than the ordinary baseline. Gaming customers gradually raise attack sizes and the expected rate toward seven attacks per week as your level and customer count grow. The size calculation accounts for the smaller RackNet and TeamSpooked floods so signing a gamer increases the overall average size. Flood Season keeps its separate escalation. - -- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec, and their size stays within one third of the ordinary attack range at your current scale. - -- Gaming customers bring larger, longer and more frequent DDoS attacks as your level and customer count grow, with overlapping floods, at most 14 starts in any seven days and durations up to seven days. Attacks arrive across transit and peering ports in different regions, following normal traffic shares. Attack bandwidth grows with the whole network, with no fixed bandwidth ceiling. - +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation. - Flood Season keeps sending larger, more frequent attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off. - -- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through in its existing status lines. Bandwidth uses the usual Gbps and Tbps units, with no duplicate summary. “After upstream scrubbing” appears only while upstream scrubbing is active. Scrubbing lines show the city, current use and compact capacity, such as “Scrubbing in Frankfurt: 30.2 Gbps / 100G”. - +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through. - DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center. - -- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter needs other defences. - +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation. - Pick a peering policy in the peering inbox: Open to all, Selective or Closed. Open accepts every request and keeps the route servers; Selective gets fewer requests but you answer them yourself and request peers at each exchange, without route servers; Closed gets no requests, and customers hear you are hard to reach. The inbox also gets a button to raise all max-prefix limits at once. - Brazil is slimmer: 15 small cities that sat right next to bigger ones are gone from new games, leaving 25 in Brazil. A small city no longer crowds a bigger one in the same country unless it is a cable landing or a capital. Saved games keep their POPs in those cities, and the Order and Progress scenario now asks for 15 IX.brrr ports instead of 20. + ## [1.33.0] — 2026-10-27 - Australia arrives: start in Sydney on hard mode. Expensive transit, a national network that keeps 45% of every broadband bill, real Australian exchanges and carriers, Adelaide, Canberra, Hobart and the South Island of New Zealand, new cables, very Australian outages and a new scenario, Fibre to the Basement. Older saves with Australian POPs are told once what changed. From 66ae4be72d5bfaa8a47dfef372ed3ca5beca395a Mon Sep 17 00:00:00 2001 From: LookedPath <2457111+LookedPath@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:30:20 +0000 Subject: [PATCH 07/13] Add editable optic counts to fiber link panels --- CHANGELOG.md | 2 + site/i18n/es.js | 4 ++ site/i18n/fr.js | 4 ++ site/i18n/it.js | 4 ++ site/i18n/pt.js | 4 ++ src/game/90-actions/88-optic-counts.js | 27 +++++++++ src/game/93-ui/70-link-panels.js | 2 +- src/game/93-ui/75-optic-counts.js | 20 +++++++ src/i18n/en.js | 4 ++ src/styles/35-optic-counts.css | 4 ++ tests/optic-counts.test.js | 81 ++++++++++++++++++++++++++ 11 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 src/game/90-actions/88-optic-counts.js create mode 100644 src/game/93-ui/75-optic-counts.js create mode 100644 src/styles/35-optic-counts.css create mode 100644 tests/optic-counts.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 3465c68..5a1b699 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. + - Yellow progress bars are slim again, like the green and red ones, instead of padded boxes. - São Paulo's exchange is now called IX.brrr São Paulo, like every other Brazilian exchange (#166). - Sponsor a conference: some peering meetings sell sponsorships, and while the glow lasts more customers from that region come knocking (#168). diff --git a/site/i18n/es.js b/site/i18n/es.js index f7dea85..23f66b0 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"hace {n} min","other":"hace {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Nada en los últimos 10 minutos.", "notifications.show_all_n":"Mostrar las {n}", +"optic_counts.apply_price":"Aplicar · {price}", +"optic_counts.count_for_model":"Número de canales {model}", +"optic_counts.only_n_channels_free":"Solo quedan {n} canales libres en esta fibra.", +"optic_counts.target_count":"Cantidad deseada", "own_cable.a_and_b":"{a} y {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Una flota pesquera está faenando justo donde necesitas tender.", "own_cable.a_leased_wave_wave_on_this":"Una onda {wave} alquilada en esta ruta cuesta {price}/mes.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4342c28..d9a31c3 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"il y a {n} min","other":"il y a {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Rien ces 10 dernières minutes.", "notifications.show_all_n":"Tout afficher ({n})", +"optic_counts.apply_price":"Appliquer · {price}", +"optic_counts.count_for_model":"Nombre de canaux {model}", +"optic_counts.only_n_channels_free":"Il ne reste que {n} canaux libres sur cette fibre.", +"optic_counts.target_count":"Quantité souhaitée", "own_cable.a_and_b":"{a} et {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Une flotte de chalutiers drague pile là où tu dois poser.", "own_cable.a_leased_wave_wave_on_this":"Une longueur d’onde {wave} louée sur ce parcours coûte {price}/mois.", diff --git a/site/i18n/it.js b/site/i18n/it.js index db5ff27..1054518 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"{n} min fa","other":"{n} min fa"}, "notifications.nothing_in_the_last_10_minutes":"Niente negli ultimi 10 minuti.", "notifications.show_all_n":"Mostra tutte e {n}", +"optic_counts.apply_price":"Applica · {price}", +"optic_counts.count_for_model":"Numero di canali {model}", +"optic_counts.only_n_channels_free":"Su questa fibra sono liberi solo {n} canali.", +"optic_counts.target_count":"Quantità desiderata", "own_cable.a_and_b":"{a} e {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Una flotta di pescherecci sta strascicando proprio dove devi posare.", "own_cable.a_leased_wave_wave_on_this":"Una wave da {wave} in affitto su questa tratta costa {price}/mese.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index b474374..f0f4baf 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2348,6 +2348,10 @@ "notifications.n_min_ago":{"one":"há {n} min","other":"há {n} min"}, "notifications.nothing_in_the_last_10_minutes":"Nada nos últimos 10 minutos.", "notifications.show_all_n":"Mostrar todas as {n}", +"optic_counts.apply_price":"Aplicar · {price}", +"optic_counts.count_for_model":"Número de canais {model}", +"optic_counts.only_n_channels_free":"Só há {n} canais livres nesta fibra.", +"optic_counts.target_count":"Quantidade desejada", "own_cable.a_and_b":"{a} e {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"Uma frota pesqueira está arrastando redes bem onde você precisa lançar.", "own_cable.a_leased_wave_wave_on_this":"Uma wave de {wave} alugada nesta rota custa {price}/mês.", diff --git a/src/game/90-actions/88-optic-counts.js b/src/game/90-actions/88-optic-counts.js new file mode 100644 index 0000000..62d1e91 --- /dev/null +++ b/src/game/90-actions/88-optic-counts.js @@ -0,0 +1,27 @@ +// Quote the whole change before spending: shelf optics still need regen cards. +function opticCountCost(l,o,n){ + const add=Math.max(0,n-(l.ch||[]).filter(k=>k===o).length),sp=Math.min(add,spareN(o)),r=REGEN_CH*(l.regen|0),c=optCost(o); + return sp*Math.round(c*r)+(add-sp)*Math.round(c*(1+r)); +} +Object.assign(ACT,{ + setChCount:({id,o,n})=>{ + const l=S.links.find(x=>x.id===id); + if(!l||l.kind!=='df'||!own(OPT,o)||!Number.isSafeInteger(n)||n<0||n>chMax(l))return; + const old=(l.ch||[]).filter(k=>k===o).length,d=n-old; + if(!d)return; + if(d>0){ + const why=chWhy(l,o); + if(why){toast(tr('fiber_and_hardware.can_t_add_optic_why',{optic:OPT[o].n,why:esc(why)}),'bad');sfx('err');return;} + const free=chMax(l)-(l.ch||[]).length-soldSlots(l); + if(d>free){toast(tr('optic_counts.only_n_channels_free',{n:free}),'bad');sfx('err');return;} + if(!portGate(l.a,d)||!portGate(l.b,d)||!spend(opticCountCost(l,o,n)))return; + const sp=Math.min(d,spareN(o));if(sp)S.spares[o]-=sp; + (l.ch=l.ch||[]).push(...Array(d).fill(o)); + }else{ + let left=-d;l.ch=l.ch.filter(k=>k!==o||left--<=0); + S.spares=S.spares||{};S.spares[o]=(S.spares[o]||0)-d; + } + if(UI.opticCounts)delete UI.opticCounts[JSON.stringify([id,o])]; + after(); + }, +}); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 19b6eb7..e37ea26 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -81,7 +81,7 @@ function dfPanel(l){ if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); const md=optMode(k,l),cc=chCost(l,k),sp=spareN(k); - h+=`
${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${!l.sub&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+ ${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+ ${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash`;} + h+=`
${O.n} ${optModes(k,l).map(([g,r])=>tr('link_panels.g_to_km_km',{g:fmtG(g),km:r.toLocaleString()})).join(' · ')}
${esc(O.blurb)}${n?` · ${tr('link_panels.n_lit',{n})}`:''}${sp?` · ${trn('link_panels.n_spare_on_the_shelf',sp)}`:''}
${md&&!md.full?`
⚠️ ${tr('link_panels.runs_at_g_per_channel_on',{g:fmtG(md.g)})} ${!l.sub&®enNeed(k,l)>(l.regen|0)?trn('link_panels.n_regen_site_would_bring_it',regenNeed(k,l),{g:fmtG(O.g)}):''}
`:''}${why?`
${esc(why)}
`:''}${opticCountControl(l,k,n)}
${n?btn('−','rmCh',{id:l.id,o:k},'ghost sm'):''}${btn(sp?`+ ${cc?tr('link_panels.spare_price',{price:fmt$(cc)}):tr('common.spare')}`:`+ ${fmt$(cc)}`,'addCh',{id:l.id,o:k},'sm',!!why||S.cash`;} {const st=Object.keys(OPT).filter(k=>spareN(k)>0);h+=`

${tr('link_panels.unplugged_optics_go_on_the_spares')}

`; {const used=[...new Set(l.ch||[])].filter(k=>OPT[k]&&OPT[k].lvl<=lvl());if(used.length)h+=`
${used.map(k=>btn(tr('link_panels.stock_a_spare_optic_price',{optic:OPT[k].n,price:fmt$(optCost(k))}),'buySpare',{o:k},'ghost sm',S.cash=64)).join('')}

${tr('link_panels.spares_bought_now_are_already_paid')}

`;}if(st.length)h+=`

${tr('common.spares_shelf')}

`+st.map(k=>`
${spareN(k)} × ${OPT[k].n}
${btn(tr('link_panels.sell_one_price',{price:fmt$(spareValue(k))}),'sellSpare',{o:k},'ghost sm')}
`).join('');} const rg=l.regen|0,rgAdd=REGEN_COST+Math.round((l.ch||[]).reduce((a,c)=>a+optCost(c),0)*REGEN_CH); diff --git a/src/game/93-ui/75-optic-counts.js b/src/game/93-ui/75-optic-counts.js new file mode 100644 index 0000000..35fe1cf --- /dev/null +++ b/src/game/93-ui/75-optic-counts.js @@ -0,0 +1,20 @@ +function opticCountControl(l,o,n){ + const key=JSON.stringify([l.id,o]);let draft=UI.opticCounts&&UI.opticCounts[key]; + if(draft&&draft.base!==n){delete UI.opticCounts[key];draft=null;} + const v=draft?draft.n:n,value=draft?draft.value:n; + const price=Number.isSafeInteger(v)&&v>=0&&v<=chMax(l)?opticCountCost(l,o,v):0; + return `
`; +} +document.addEventListener('input',e=>{ + const f=e.target.closest('form.optic-count');if(!f||!S)return; + const l=S.links.find(x=>x.id===f.dataset.link),o=f.dataset.optic,n=f.elements.count.valueAsNumber; + if(!l||!own(OPT,o))return; + UI.opticCounts=UI.opticCounts||{};UI.opticCounts[JSON.stringify([l.id,o])]={base:(l.ch||[]).filter(k=>k===o).length,n,value:e.target.value}; + e.target.setAttribute('value',e.target.value); + f.querySelector('button').textContent=tr('optic_counts.apply_price',{price:fmt$(Number.isSafeInteger(n)&&n>=0&&n<=chMax(l)?opticCountCost(l,o,n):0)}); +}); +document.addEventListener('submit',e=>{ + const f=e.target.closest('form.optic-count');if(!f)return;e.preventDefault(); + if(!S||!f.reportValidity()||!$('modal').hidden)return; + ACT.setChCount({id:f.dataset.link,o:f.dataset.optic,n:f.elements.count.valueAsNumber}); +}); diff --git a/src/i18n/en.js b/src/i18n/en.js index 86aae1c..2d9cd0b 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2349,6 +2349,10 @@ "notifications.n_min_ago":{"one":"{n} min ago","other":"{n} min ago"}, "notifications.nothing_in_the_last_10_minutes":"Nothing in the last 10 minutes.", "notifications.show_all_n":"Show all {n}", +"optic_counts.apply_price":"Apply · {price}", +"optic_counts.count_for_model":"Number of {model} channels", +"optic_counts.only_n_channels_free":"Only {n} channels are free on this fiber.", +"optic_counts.target_count":"Target count", "own_cable.a_and_b":"{a} and {b}", "own_cable.a_fishing_fleet_is_trawling_exactly":"A fishing fleet is trawling exactly where you need to lay.", "own_cable.a_leased_wave_wave_on_this":"A leased {wave} wave on this route costs {price}/mo.", diff --git a/src/styles/35-optic-counts.css b/src/styles/35-optic-counts.css new file mode 100644 index 0000000..6690821 --- /dev/null +++ b/src/styles/35-optic-counts.css @@ -0,0 +1,4 @@ +.optic-count{display:flex;flex-wrap:wrap;align-items:end;gap:8px;margin-top:8px} +.optic-count label{display:flex;flex-direction:column;gap:3px;font-size:12px;font-weight:800} +.optic-count input.t{width:88px;font-size:16px;min-height:44px} +.optic-count .b{min-height:44px} diff --git a/tests/optic-counts.test.js b/tests/optic-counts.test.js new file mode 100644 index 0000000..1e85f3f --- /dev/null +++ b/tests/optic-counts.test.js @@ -0,0 +1,81 @@ +const test=require('node:test'); +const assert=require('node:assert/strict'); +const {load}=require('./harness'); +function setup(ev,sub=false){ev(`ACT.start({});S.cash=1e9;S.lvl=13;S.day=100;for(const g of GOALS)S.done[g.id]=0; + S.pops.fra.rgen=mainRG(4);S.pops.fra.routers=16;S.pops.ams={...S.pops.fra}; + S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sub:${sub},sys:'roadm',km:400,ch:[],ready:0,day:0,cut:0,mo:1}]; + UI.sel={type:'link',id:'fiber'};renderPanel();`);} +const count=ev=>ev('S.links[0].ch.length'); +for(const sub of [false,true])test(`typed counts buy and remove optics on ${sub?'subsea':'land'} fiber`,()=>{ + const {ev,dom,errors}=load();try{ + setup(ev,sub);const doc=dom.window.document; + const f=doc.querySelector('form.optic-count[data-optic="zr4"]'),input=f.elements.count; + input.focus();input.value='5';input.dispatchEvent(new dom.window.Event('input',{bubbles:true})); + const cost=ev("5*chCost(S.links[0],'zr4')"),cash=ev('S.cash'); + assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`))); + ev('S.day++;renderPanel()'); + assert.equal(doc.activeElement,input,'tick preserves the focused field');assert.equal(input.value,'5'); + assert.ok(f.querySelector('button').textContent.includes(ev(`fmt$(${cost})`))); + f.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true})); + assert.equal(count(ev),5);assert.equal(cash-ev('S.cash'),cost); + ev("ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),2);assert.equal(ev('S.spares.zr4'),3); + const before=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),5);assert.equal(ev('S.cash'),before);assert.equal(ev('S.spares.zr4'),0); + ev("ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(count(ev),0);assert.equal(ev('S.spares.zr4'),5); + assert.deepEqual(errors,[]); + }finally{dom.window.close();} +}); +test('batch price matches individual channel purchases with spares, regen cards and tariffs',()=>{ + const {ev,dom}=load();try{setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20"); + const expected=ev("2*Math.round(optCost('zr4')*REGEN_CH*2)+3*Math.round(optCost('zr4')*(1+REGEN_CH*2))"); + assert.equal(ev("opticCountCost(S.links[0],'zr4',5)"),expected); + const cash=ev('S.cash');ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(cash-ev('S.cash'),expected); + setup(ev);ev("S.links[0].regen=2;S.spares={zr4:2};S.ev.tariff=S.day+20");const cash2=ev('S.cash'); + ev("for(let i=0;i<5;i++)ACT.addCh({id:'fiber',o:'zr4'})");assert.equal(cash2-ev('S.cash'),expected); + }finally{dom.window.close();} +}); +test('unaffordable batches, port limits and invalid input never partially change state',()=>{ + const {ev,dom}=load();try{setup(ev);ev('S.cash=1'); + ev("ACT.setChCount({id:'fiber',o:'zr4',n:5})");assert.equal(count(ev),0);assert.equal(ev('S.cash'),1); + ev('S.cash=1e9;S.pops.ams.routers=1');const max=ev("Math.floor(portsMax('ams')-portsUsed('ams'))"); + ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${max+1}})`);assert.equal(count(ev),0);assert.equal(ev('S.cash'),1e9); + ev('S.pops.ams.routers=16'); + for(const n of ['NaN','Infinity','-1','1.5','65',"'3'"]){ev(`ACT.setChCount({id:'fiber',o:'zr4',n:${n}})`);assert.equal(count(ev),0);} + ev("ACT.setChCount({id:'missing',o:'zr4',n:2});ACT.setChCount({id:'fiber',o:'missing',n:2})");assert.equal(ev('S.cash'),1e9); + }finally{dom.window.close();} +}); +test('channel reservations and reach, line-system, level and router compatibility still apply',()=>{ + const {ev,dom}=load();try{setup(ev); + ev("S.links[0].ch=Array(63).fill('zr8');ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),63); + setup(ev);ev("S.biz.push({type:'wwave',link:'fiber',slots:63});ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.links[0].km=20000;ACT.setChCount({id:'fiber',o:'zr4',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.links[0].sys='lite';ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.lvl=1;S.done={};ACT.setChCount({id:'fiber',o:'tp16',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.pops.ams.rgen=0;ACT.setChCount({id:'fiber',o:'tp32',n:2})");assert.equal(count(ev),0); + setup(ev);ev("S.links[0].ch=['zr4','zr8','zr4'];ACT.setChCount({id:'fiber',o:'zr4',n:0})");assert.equal(ev("JSON.stringify(S.links[0].ch)"),'["zr8"]'); + }finally{dom.window.close();} +}); +test('plus and minus buttons work alongside typed counts',()=>{ + const {ev,dom,errors}=load();try{setup(ev);const doc=dom.window.document; + const plus=()=>[...doc.querySelectorAll('[data-act="addCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4'); + const minus=()=>[...doc.querySelectorAll('[data-act="rmCh"]')].find(b=>JSON.parse(b.dataset.args).o==='zr4'); + const input=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input'); + plus().click();assert.equal(count(ev),1);assert.equal(input().value,'1'); + input().value='4';input().dispatchEvent(new dom.window.Event('input',{bubbles:true})); + input().form.dispatchEvent(new dom.window.Event('submit',{bubbles:true,cancelable:true})); + assert.equal(count(ev),4);minus().click();assert.equal(count(ev),3);assert.equal(input().value,'3'); + plus().click();assert.equal(count(ev),4);assert.equal(input().value,'4');assert.deepEqual(errors,[]); + }finally{dom.window.close();} +}); + +test('draft counts and quotes stay together when reopening a panel or using shortcuts',()=>{ + const {ev,dom}=load();try{setup(ev);const doc=dom.window.document; + const field=()=>doc.querySelector('form.optic-count[data-optic="zr4"] input'); + field().value='5';field().dispatchEvent(new dom.window.Event('input',{bubbles:true})); + ev("UI.sel=null;renderPanel();$('panelBody').innerHTML='';UI.sel={type:'link',id:'fiber'};renderPanel()"); + assert.equal(field().value,'5'); + ev("ACT.addCh({id:'fiber',o:'zr4'});ACT.rmCh({id:'fiber',o:'zr4'})"); + assert.equal(field().value,'0');assert.ok(field().form.querySelector('button').textContent.includes(ev('fmt$(0)'))); + field().value='';field().dispatchEvent(new dom.window.Event('input',{bubbles:true}));ev('S.day++;renderPanel()'); + assert.equal(field().value,'','empty in-progress entry survives a tick'); + }finally{dom.window.close();} +}); From 4932b3f93a786fb29c574a374d9eebf65ceecfec Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 01:44:17 +0100 Subject: [PATCH 08/13] Add bulk PNI ordering across networks and POPs Add two actions to the NOC Traffic tab: - Order PNIs with one network at every shared POP. - Order PNIs with all eligible networks at every shared POP, including long-tail peers. Both actions offer a selectable port size and preview new connections, upgrades, total setup costs, additional monthly charges and blocked sites. Upgrade smaller PNIs while preserving larger connections, pending orders and existing LAG members. Reserve router capacity across the batch and account for pending speed and LAG augments to avoid overbooking ports. Require the full setup budget before placing any orders. Reuse normal peering policies, minimum port sizes and provisioning delays, then recompute and save once for the entire batch. Keep large global previews compact with collapsible network and blocked-connection lists. Translate the new UI into all five supported languages and add tests for single-network and global ordering, capacity, budgets, repeated clicks, save migration, and mobile keyboard interaction. Validation: - Build and translation checks pass. - 308 of 309 tests pass. The existing subsea reach test also fails on origin/main because the Windows locale uses a dot as the thousands separator where the assertion expects a comma. - Chromium desktop and phone checks pass with the supplied save. - Big-network benchmark against origin/main: dashboard tabs take 16.8 -> 17.6 ms on desktop and 77.1 -> 80.7 ms on a simulated phone (median of 15 runs). Routing results are identical, with no slowdowns beyond the benchmark's noise threshold. --- CHANGELOG.md | 2 + site/i18n/es.js | 20 +++ site/i18n/fr.js | 20 +++ site/i18n/it.js | 20 +++ site/i18n/pt.js | 20 +++ src/game/70-rules/35-pni-orders.js | 23 +++ .../90-actions/40-sites-peering-caches.js | 12 +- src/game/94-dashboard/60-dashboard.js | 3 +- src/game/95-modals/35-pni-all.js | 19 +++ src/i18n/en.js | 20 +++ tests/pni-all.test.js | 155 ++++++++++++++++++ tests/pni-global.test.js | 135 +++++++++++++++ 12 files changed, 442 insertions(+), 7 deletions(-) create mode 100644 src/game/70-rules/35-pni-orders.js create mode 100644 src/game/95-modals/35-pni-all.js create mode 100644 tests/pni-all.test.js create mode 100644 tests/pni-global.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0094b5d..40263ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Order PNIs with one network or every network at all shared POPs from the NOC Traffic tab: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. + ## [1.35.0] — 2026-10-27 - Series of Tubes now speaks Spanish. The game follows your browser's language the first time, and you can switch to Spanish under Settings or on the title screen. diff --git a/site/i18n/es.js b/site/i18n/es.js index 16f2a3c..06a16dd 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Probaron un peer remoto una vez. Osciló durante un lanzamiento de producto. Nunca más.", "pitcairn.uk_grant_mo":"Subvención británica {mo}/mes", "pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea", +"pni_all.additional_per_month":"Coste mensual adicional", +"pni_all.all_at_port":"Peering con todas las redes · {port}", +"pni_all.delivery_and_traffic_charges":"Los plazos de entrega varían según la red. También se aplican cargos de peering basados en el tráfico cuando corresponda.", +"pni_all.n_blocked_connections":{"one":"{n} conexión no disponible","other":"{n} conexiones no disponibles"}, +"pni_all.n_blocked_pops":{"one":"{n} POP no disponible","other":"{n} POP no disponibles"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existente o pedido pendiente se mantiene sin cambios.","other":"{n} PNI existentes o pedidos pendientes se mantienen sin cambios."}, +"pni_all.n_networks":{"one":"{n} red","other":"{n} redes"}, +"pni_all.n_of_total_connections":"{n} / {total} conexiones", +"pni_all.n_of_total_pops":"{n} / {total} POP en común", +"pni_all.n_orders_with_net":{"one":"{n} pedido de PNI realizado con {net}. Sin cambios: {kept}; no disponibles: {blocked}.","other":"{n} pedidos de PNI realizados con {net}. Sin cambios: {kept}; no disponibles: {blocked}."}, +"pni_all.new_and_upgrades":"Nuevos: {fresh} · Ampliaciones: {up}", +"pni_all.no_shared_locations":"No hay POP en común disponibles.", +"pni_all.no_shared_pops":"No tienes POP en común con esta red.", +"pni_all.order_missing_and_upgrade_smaller":"Pide los PNI que faltan y amplía los más pequeños en los POP en común. Los PNI mayores y los pedidos pendientes se mantienen sin cambios. Se omiten los POP no disponibles.", +"pni_all.peer_all_networks":"Peering con todas las redes en todos los POP", +"pni_all.peer_at_port":"Peering en todos los POP · {port}", +"pni_all.peer_on_all_pops":"Peering en todos los POP", +"pni_all.pni_size":"Capacidad del PNI", +"pni_all.setup_total":"Coste total de instalación", +"pni_all.traffic_charges_apply":"También se aplican cargos de tráfico de {price} por Gbps.", "pnis.a_new_region_is_coming_online":"Pronto se pondrá en marcha una región nueva. Lleva poniéndose en marcha pronto desde 2019.", "pnis.about_n_days_to_go_nothing":"Faltan unos {n} días. No queda más que esperar, o perseguirlo.", "pnis.augment_with_net_delivered_in_city":"Ampliación con {net} entregada en {city}.
Ahora {port}.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4e674bf..882a336 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Ils ont essayé un peer distant, une fois. Il a flappé pendant un lancement de produit. Plus jamais.", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", +"pni_all.additional_per_month":"Coût mensuel supplémentaire", +"pni_all.all_at_port":"Peering avec tous les réseaux · {port}", +"pni_all.delivery_and_traffic_charges":"Les délais de livraison varient selon le réseau. Des frais de peering liés au trafic s'appliquent aussi lorsque le réseau l'exige.", +"pni_all.n_blocked_connections":{"one":"{n} connexion indisponible","other":"{n} connexions indisponibles"}, +"pni_all.n_blocked_pops":{"one":"{n} POP indisponible","other":"{n} POP indisponibles"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existant ou commande en attente reste inchangé.","other":"{n} PNI existants ou commandes en attente restent inchangés."}, +"pni_all.n_networks":{"one":"{n} réseau","other":"{n} réseaux"}, +"pni_all.n_of_total_connections":"{n} / {total} connexions", +"pni_all.n_of_total_pops":"{n} / {total} POP en commun", +"pni_all.n_orders_with_net":{"one":"{n} commande de PNI passée avec {net}. Inchangés : {kept} ; indisponibles : {blocked}.","other":"{n} commandes de PNI passées avec {net}. Inchangés : {kept} ; indisponibles : {blocked}."}, +"pni_all.new_and_upgrades":"Nouveaux : {fresh} · Augmentations : {up}", +"pni_all.no_shared_locations":"Aucun POP en commun disponible.", +"pni_all.no_shared_pops":"Tu n'as aucun POP en commun avec ce réseau.", +"pni_all.order_missing_and_upgrade_smaller":"Commande les PNI manquants et augmente la capacité des plus petits dans les POP en commun. Les PNI plus grands et les commandes en attente restent inchangés. Les POP indisponibles sont ignorés.", +"pni_all.peer_all_networks":"Peering avec tous les réseaux sur tous les POP", +"pni_all.peer_at_port":"Peering sur tous les POP · {port}", +"pni_all.peer_on_all_pops":"Peering sur tous les POP", +"pni_all.pni_size":"Capacité du PNI", +"pni_all.setup_total":"Coût total d'installation", +"pni_all.traffic_charges_apply":"Des frais de trafic de {price} par Gbps s'appliquent également.", "pnis.a_new_region_is_coming_online":"Une nouvelle région arrive bientôt. Elle arrive bientôt depuis 2019.", "pnis.about_n_days_to_go_nothing":"Encore environ {n} jours. Rien à faire qu’attendre, ou relancer.", "pnis.augment_with_net_delivered_in_city":"Extension avec {net} livrée à {city}.
Désormais {port}.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 83a3693..6ad0307 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Hanno provato un peer remoto, una volta. Ha flappato durante il lancio di un prodotto. Mai più.", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", +"pni_all.additional_per_month":"Costo mensile aggiuntivo", +"pni_all.all_at_port":"Peering con tutte le reti · {port}", +"pni_all.delivery_and_traffic_charges":"I tempi di consegna variano secondo la rete. Si applicano anche costi di peering basati sul traffico, dove previsti.", +"pni_all.n_blocked_connections":{"one":"{n} connessione non disponibile","other":"{n} connessioni non disponibili"}, +"pni_all.n_blocked_pops":{"one":"{n} POP non disponibile","other":"{n} POP non disponibili"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI esistente o ordine in attesa resta invariato.","other":"{n} PNI esistenti o ordini in attesa restano invariati."}, +"pni_all.n_networks":{"one":"{n} rete","other":"{n} reti"}, +"pni_all.n_of_total_connections":"{n} / {total} connessioni", +"pni_all.n_of_total_pops":"{n} / {total} POP in comune", +"pni_all.n_orders_with_net":{"one":"{n} ordine PNI effettuato con {net}. Invariati: {kept}; non disponibili: {blocked}.","other":"{n} ordini PNI effettuati con {net}. Invariati: {kept}; non disponibili: {blocked}."}, +"pni_all.new_and_upgrades":"Nuovi: {fresh} · Upgrade: {up}", +"pni_all.no_shared_locations":"Nessun POP in comune disponibile.", +"pni_all.no_shared_pops":"Non hai POP in comune con questa rete.", +"pni_all.order_missing_and_upgrade_smaller":"Ordina i PNI mancanti e potenzia quelli più piccoli nei POP in comune. I PNI più grandi e gli ordini in attesa restano invariati. I POP non disponibili vengono saltati.", +"pni_all.peer_all_networks":"Peering con tutte le reti su tutti i POP", +"pni_all.peer_at_port":"Peering su tutti i POP · {port}", +"pni_all.peer_on_all_pops":"Peering su tutti i POP", +"pni_all.pni_size":"Capacità PNI", +"pni_all.setup_total":"Costo totale di attivazione", +"pni_all.traffic_charges_apply":"Si applicano anche costi di traffico di {price} per Gbps.", "pnis.a_new_region_is_coming_online":"Una nuova region arriverà presto. Arriva presto dal 2019.", "pnis.about_n_days_to_go_nothing":"Mancano circa {n} giorni. Non resta che aspettare, o sollecitare.", "pnis.augment_with_net_delivered_in_city":"Ampliamento con {net} consegnato a {city}.
Ora {port}.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cd40592..e3fd3ba 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2581,6 +2581,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Tentaram um peer remoto uma vez. Ele flapou durante um lançamento de produto. Nunca mais.", "pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês", "pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online", +"pni_all.additional_per_month":"Custo mensal adicional", +"pni_all.all_at_port":"Peering com todas as redes · {port}", +"pni_all.delivery_and_traffic_charges":"Os prazos de entrega variam conforme a rede. Também se aplicam custos de peering baseados no tráfego, quando exigidos.", +"pni_all.n_blocked_connections":{"one":"{n} ligação indisponível","other":"{n} ligações indisponíveis"}, +"pni_all.n_blocked_pops":{"one":"{n} POP indisponível","other":"{n} POPs indisponíveis"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} PNI existente ou pedido pendente permanece inalterado.","other":"{n} PNIs existentes ou pedidos pendentes permanecem inalterados."}, +"pni_all.n_networks":{"one":"{n} rede","other":"{n} redes"}, +"pni_all.n_of_total_connections":"{n} / {total} ligações", +"pni_all.n_of_total_pops":"{n} / {total} POPs em comum", +"pni_all.n_orders_with_net":{"one":"{n} pedido de PNI feito com {net}. Inalterados: {kept}; indisponíveis: {blocked}.","other":"{n} pedidos de PNI feitos com {net}. Inalterados: {kept}; indisponíveis: {blocked}."}, +"pni_all.new_and_upgrades":"Novos: {fresh} · Upgrades: {up}", +"pni_all.no_shared_locations":"Não há POPs em comum disponíveis.", +"pni_all.no_shared_pops":"Não tens POPs em comum com esta rede.", +"pni_all.order_missing_and_upgrade_smaller":"Pede os PNIs em falta e aumenta os mais pequenos nos POPs em comum. Os PNIs maiores e os pedidos pendentes ficam inalterados. Os POPs indisponíveis são ignorados.", +"pni_all.peer_all_networks":"Peering com todas as redes em todos os POPs", +"pni_all.peer_at_port":"Peering em todos os POPs · {port}", +"pni_all.peer_on_all_pops":"Peering em todos os POPs", +"pni_all.pni_size":"Capacidade do PNI", +"pni_all.setup_total":"Custo total de instalação", +"pni_all.traffic_charges_apply":"Também se aplicam custos de tráfego de {price} por Gbps.", "pnis.a_new_region_is_coming_online":"Uma nova região vai entrar no ar em breve. Ela está entrando no ar em breve desde 2019.", "pnis.about_n_days_to_go_nothing":"Faltam cerca de {n} dias. Não há nada a fazer além de esperar, ou cobrar.", "pnis.augment_with_net_delivered_in_city":"Ampliação com {net} entregue em {city}.
Agora {port}.", diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js new file mode 100644 index 0000000..c364a8e --- /dev/null +++ b/src/game/70-rules/35-pni-orders.js @@ -0,0 +1,23 @@ +/* Single and bulk orders share the same checks, prices and provisioning. */ +function pniQuote(city,net,tier,reserved=0){tier=+tier;const g1=tier===-1;if(g1)tier=0; + if(!S||!S.pops[city]||!isNet(net)||!NET[net].pops.includes(city)||!Number.isInteger(tier)||!PORT[tier]||(g1&&!pniG1(net)))return null; + const ex=S.pni.find(p=>p.city===city&&p.net===net); + if(ex&&(g1||!pniOn(ex)||ex.up||(!(ex.g1&&tier===0)&&tier<=ex.tier)))return null; + const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1),slots=ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier); + let why='';if(!portOk(city,tier))why=tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}); + else{const r=peerOk(net,'pni',city);if(!r.ok)why=tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}); + else if(!g1&&tier0&&portsUsed(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(portsUsed(city)+reserved),m:portsMax(city)});} + return {city,net,tier,g1,ex,cost,slots,why};} +function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net); + if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; + if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); + return lead;} +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; + // 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 n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city); + const q=pniQuote(city,n.id,tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots; + mo+=pniMo({net:n.id,tier:q.tier,g1:q.g1,n:q.ex&&q.ex.n},0)-(q.ex?pniMo(q.ex,0):0);} + return {shared,orders,blocked,kept,cost,mo};} diff --git a/src/game/90-actions/40-sites-peering-caches.js b/src/game/90-actions/40-sites-peering-caches.js index 05783be..cf4da86 100644 --- a/src/game/90-actions/40-sites-peering-caches.js +++ b/src/game/90-actions/40-sites-peering-caches.js @@ -12,13 +12,13 @@ Object.assign(ACT,{ unpeer:({city,net})=>{delete S.peers[net+'@'+city];after();}, peerAll:({city})=>{if(!isIx(city)||S.ixp[city]===undefined)return;const set=ixSessions(city);let n=0;for(const id of ixMembers(city))if(!set.has(id)&&peerOk(id,'ix',city).ok){S.peers[id+'@'+city]=true;n++;}if(!n)return;toast(trn('sites_peering_caches.n_new_session_at_ix_small',n,{ix:esc(ixName(city))}),'good',[],{a:'city',v:ixCity(city)});sfx('build');after();}, tailTog:()=>{UI.tailOpen=!UI.tailOpen;renderLeft();}, - pni:({city,net,tier})=>{tier=+tier;const g1=tier===-1;if(g1){if(!pniG1(net))return;tier=0;}if(!S.pops[city]||!NET[net]||!NET[net].pops.includes(city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const r=peerOk(net,'pni',city);if(!r.ok){toast(tr('sites_peering_caches.net_declined_the_pni_why',{net:esc(NET[net].name),why:esc(r.why)}),'bad');sfx('err');after();return;} - if(!g1&&tierp.city===city&&p.net===net);if(ex&&(g1||!pniOn(ex)||ex.up))return;if(ex&&!(ex.g1&&tier===0)&&tier<=ex.tier)return; - const cost=g1?PNI_G1_COST:(1500+PORT[tier].setup/2)*(ex&&ex.n||1);if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(cost))return;if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1; - // Nothing is instant: a cross-connect takes weeks, and the big networks quote months for a new PNI or an augment. - const lead=pniLead(net);if(ex)ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead}); + pni:({city,net,tier})=>{const q=pniQuote(city,net,tier);if(!q)return;if(q.why){toast(q.why,'bad');sfx('err');after();return;}if(!spend(q.cost))return;const lead=pniPlace(q); toast(tr('sites_peering_caches.pni_with_net_ordered_eta_a',{net:esc(NET[net].name),eta:pniWhen(lead),dc:esc(siteName(city,'a'))}),'good');after();}, + pniAllOpen:({net})=>{pniAllModal(net);}, + pniAllSize:({v})=>{if(!UI.pniAll)return;pniAllModal(UI.pniAll.net,+v);$('modalCard').querySelector('[data-chg="pniAllSize"]')?.focus();}, + pniAll:({net,tier})=>{const b=pniBatch(net,tier);if(!b||!b.orders.length)return;if(!spend(b.cost))return; + for(const q of b.orders)pniPlace(q);UI.pniAll=null;closeModal(); + toast(trn('pni_all.n_orders_with_net',b.orders.length,{net:esc(net===null?tr('common.all_networks'):NET[net].name),kept:b.kept,blocked:b.blocked.length}),'good');after();}, pniChase:({id})=>{const p=S.pni.find(x=>x.id===id);if(!p||(pniOn(p)&&!p.up))return;const r=Math.random(); if(r<0.15){if(p.up)p.up.ready=Math.max(S.day+1,p.up.ready-30);else p.ready=Math.max(S.day+1,p.ready-30);toast(tr('sites_peering_caches.your_account_manager_found_the_order'),'good');} else toast(pick([tr('sites_peering_caches.it_is_with_the_provisioning_team'),tr('sites_peering_caches.we_are_waiting_on_the_colo'),tr('sites_peering_caches.your_ticket_was_merged_into_another'),tr('sites_peering_caches.could_you_resend_the_loa_you'),tr('sites_peering_caches.your_account_manager_is_on_paternity')]));after();}, diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 5bb0282..85e9c64 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -18,8 +18,9 @@ function renderDash(){checkLayer(); {const k=UI.dashSort||'traffic',dir=UI.dashDir||-1,val=x=>k==='name'?x.n.name.toLowerCase():k==='asn'?x.n.asn:k==='type'?x.n.type:k==='cost'?x.cost:k==='lost'?x.lost:x.t;nets.sort((a,b)=>{const A=val(a),B=val(b);return (AB?1:0)*dir||b.t-a.t;});} if(DT==='cust')h+=custSection(); if(DT==='conn')h+=connSection(); + if(DT==='traffic')h+=`
${btn(tr('pni_all.peer_all_networks'),'pniAllOpen',{net:null},'pink sm')}
`; if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} - ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; + ${nets.map(({n,e,t,want})=>{return `${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?`
${btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm')}
`:''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}`;}).join('')}
`; if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8); const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6); diff --git a/src/game/95-modals/35-pni-all.js b/src/game/95-modals/35-pni-all.js new file mode 100644 index 0000000..69f228e --- /dev/null +++ b/src/game/95-modals/35-pni-all.js @@ -0,0 +1,19 @@ +function pniAllModal(net,tier=1){const b=pniBatch(net,tier);if(!b)return;UI.pniAll={net,tier}; + const all=net===null,n=NET[net],port=tier===-1?'1G':PORT[tier].n,up=b.orders.filter(q=>q.ex).length,byNet={}; + if(all)for(const q of b.orders)(byNet[q.net]||(byNet[q.net]=[])).push(q.city); + const controls=`
${btn(all?tr('pni_all.all_at_port',{port}):tr('pni_all.peer_at_port',{port}),'pniAll',{net,tier},'pink',!b.orders.length||S.cash`; + const blocked=b.blocked.map(q=>`

${all?esc(NET[q.net].name)+' · ':''}${esc(CITY[q.city].name)}: ${q.why}

`).join(''); + openModal(`
${all?tr('common.all_networks'):`AS${n.asn} · ${esc(n.name)}`}

${all?tr('pni_all.peer_all_networks'):tr('pni_all.peer_on_all_pops')}

+

${tr('pni_all.order_missing_and_upgrade_smaller')}

+
+
${tr('pni_all.new_and_upgrades',{fresh:b.orders.length-up,up})}${all?tr('pni_all.n_of_total_connections',{n:b.orders.length,total:b.shared.length}):tr('pni_all.n_of_total_pops',{n:b.orders.length,total:b.shared.length})}
+
${tr('pni_all.setup_total')}${fmt$(b.cost)}
+
${tr('pni_all.additional_per_month')}${tr('common.price_mo',{price:fmt$(b.mo)})}
+ ${all?`

${tr('pni_all.delivery_and_traffic_charges')}

`:n.perG?`

${tr('pni_all.traffic_charges_apply',{price:fmt$(n.perG)})}

`:''} + ${S.cash${tr('interface.not_enough_cash_wait_for_revenue')}

`:''} + ${all?controls:''} + ${all&&b.orders.length?`
${trn('pni_all.n_networks',Object.keys(byNet).length)}${Object.entries(byNet).map(([id,cities])=>`
${esc(NET[id].name)}${trn('save.n_pop',cities.length)}

${cities.map(c=>esc(CITY[c].name)).join(' · ')}

`).join('')}
`:b.orders.length?`

${b.orders.map(q=>esc(CITY[q.city].name)).join(' · ')}

${pniEta(net)}

`:''} + ${b.kept?`

${trn('pni_all.n_existing_or_pending_unchanged',b.kept)}

`:''} + ${b.blocked.length?(all?`
${trn('pni_all.n_blocked_connections',b.blocked.length)}${blocked}
`:`

${trn('pni_all.n_blocked_pops',b.blocked.length)}

${blocked}`):''} + ${!b.shared.length?`

${all?tr('pni_all.no_shared_locations'):tr('pni_all.no_shared_pops')}

`:''} + ${all?'':controls}`);} diff --git a/src/i18n/en.js b/src/i18n/en.js index b26cc57..64c4e7f 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2582,6 +2582,26 @@ "peering_policy.tried_a_remote_peer_once_it":"Tried a remote peer once. It flapped during a product launch. Never again.", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", +"pni_all.additional_per_month":"Additional monthly cost", +"pni_all.all_at_port":"Peer all networks · {port}", +"pni_all.delivery_and_traffic_charges":"Delivery times vary by network. Traffic-based peering charges also apply where required.", +"pni_all.n_blocked_connections":{"one":"{n} blocked connection","other":"{n} blocked connections"}, +"pni_all.n_blocked_pops":{"one":"{n} blocked POP","other":"{n} blocked POPs"}, +"pni_all.n_existing_or_pending_unchanged":{"one":"{n} existing PNI or pending order stays unchanged.","other":"{n} existing PNIs or pending orders stay unchanged."}, +"pni_all.n_networks":{"one":"{n} network","other":"{n} networks"}, +"pni_all.n_of_total_connections":"{n} / {total} connections", +"pni_all.n_of_total_pops":"{n} / {total} shared POPs", +"pni_all.n_orders_with_net":{"one":"{n} PNI order placed with {net}. Unchanged: {kept}; blocked: {blocked}.","other":"{n} PNI orders placed with {net}. Unchanged: {kept}; blocked: {blocked}."}, +"pni_all.new_and_upgrades":"New: {fresh} · Upgrades: {up}", +"pni_all.no_shared_locations":"No shared POPs are available.", +"pni_all.no_shared_pops":"You have no POPs in common with this network.", +"pni_all.order_missing_and_upgrade_smaller":"Orders missing PNIs and upgrades smaller ones at your shared POPs. Larger PNIs and pending orders stay unchanged. Unavailable POPs are skipped.", +"pni_all.peer_all_networks":"Peer all networks on all POPs", +"pni_all.peer_at_port":"Peer on all POPs · {port}", +"pni_all.peer_on_all_pops":"Peer on all POPs", +"pni_all.pni_size":"PNI size", +"pni_all.setup_total":"Total setup cost", +"pni_all.traffic_charges_apply":"Traffic charges of {price} per Gbps also apply.", "pnis.a_new_region_is_coming_online":"A new region is coming online soon. It has been coming online soon since 2019.", "pnis.about_n_days_to_go_nothing":"About {n} days to go. Nothing to do but wait, or chase it.", "pnis.augment_with_net_delivered_in_city":"Augment with {net} delivered in {city}.
Now {port}.", diff --git a/tests/pni-all.test.js b/tests/pni-all.test.js new file mode 100644 index 0000000..c6ba3b0 --- /dev/null +++ b/tests/pni-all.test.js @@ -0,0 +1,155 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev, cities = []) { + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0"); + for (const city of cities) ev(`ACT.buildPop({city:'${city}'})`); + ev('for(const p of Object.values(S.pops))p.rgen=RG.length-1;compute()'); +} + +test('bulk PNIs add missing shared POPs and upgrade smaller ports once, preserving existing orders and LAGs', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams', 'lon', 'par', 'nyc', 'sjc', 'sao']); + ev(`S.pni.push( + {id:'small',net:'drz',city:'fra',tier:0,n:2,site:'ab',pref:'high'}, + {id:'big',net:'drz',city:'ams',tier:2}, + {id:'equal',net:'drz',city:'lon',tier:1}, + {id:'pending',net:'drz',city:'par',tier:0,ready:S.day+20}, + {id:'augment',net:'drz',city:'nyc',tier:0,up:{tier:1,n:1,ready:S.day+20}});compute()`); + const before = ev('JSON.stringify(S)'); + assert.deepEqual(JSON.parse(ev("JSON.stringify((b=>({shared:b.shared.length,orders:b.orders.length,kept:b.kept,cost:b.cost,mo:b.mo}))(pniBatch('drz',1)))")), + { shared: 6, orders: 2, kept: 4, cost: 6750, mo: 650 }); + assert.equal(ev('JSON.stringify(S)'), before, 'preview does not change the save'); + const cash = ev('S.cash'); + const existing = JSON.parse(ev("JSON.stringify(S.pni.filter(p=>p.id!=='small'))")); + ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('window.afterCount'), 1, 'one recompute/render/save for the whole batch'); + assert.equal(ev('S.cash'), cash - 6750); + assert.equal(ev('S.pni.length'), 6); + assert.equal(ev("S.pni.filter(p=>p.city==='sao'||p.city==='tok').length"), 0, 'only shared owned POPs'); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(p=>['big','equal','pending','augment'].includes(p.id)))")), existing); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2); + assert.equal(ev("S.pni.find(p=>p.id==='small').site"), 'ab'); + assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high'); + assert.ok(ev("S.pni.find(p=>p.city==='sjc').ready>S.day"), 'new PNIs still take time'); + ev("ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('S.cash'), cash - 6750, 'repeat clicks neither charge nor duplicate'); + assert.equal(ev('window.afterCount'), 1); + ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));S.day=Math.max(...S.pni.map(p=>p.up?p.up.ready:p.ready||0));pniDay(S.day);compute()'); + assert.equal(ev("S.pni.find(p=>p.id==='small').tier"), 1, 'augment survives save migration and delivers'); + assert.equal(ev("S.pni.find(p=>p.city==='sjc').tier"), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('bulk PNIs skip router speed, port capacity and policy restrictions with city-specific reasons', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams', 'lon', 'ash']); + ev(`S.pops.fra.rgen=0;S.pops.ams.rgen=1; + S.caches=Array.from({length:portsMax('ams')},()=>({id:uid(),city:'ams',net:'cfl'})); + while(['ams','lon'].some(c=>snub('msf',c)?.all))S.asn++; + compute();R.demTo.msf=1e4;ACT.pniAllOpen({net:'msf'});ACT.pniAllSize({v:'2'})`); + assert.equal(ev("pniBatch('msf',2).orders.length"), 1); + assert.equal(ev("pniBatch('msf',2).blocked.length"), 3); + const text = dom.window.document.getElementById('modalCard').textContent; + assert.match(text, /Frankfurt.*router can't take a 400G/s); + assert.match(text, /Amsterdam.*No free router ports/s); + assert.match(text, /Ashburn.*capacity|Ashburn.*sold out/s); + const cash = ev('S.cash'); + ev("ACT.pniAll({net:'msf',tier:2})"); + assert.equal(ev('S.pni.length'), 1); + assert.equal(ev('S.pni[0].city'), 'lon'); + assert.equal(ev('S.cash'), cash - 3500); + assert.match(ev("S.log[0].t"), /blocked: 3/); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('insufficient funds refuse the entire eligible batch and execution rechecks a stale preview', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams']); + ev("S.cash=pniBatch('drz',1).cost-1;ACT.pniAllOpen({net:'drz'})"); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + const cash = ev('S.cash'); + ev("ACT.pniAll({net:'drz',tier:1})"); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0); + ev("S.cash=1e8;ACT.pniAllOpen({net:'drz'});delete S.pops.ams;S.pops.fra.rgen=0;ACT.pniAll({net:'drz',tier:2})"); + assert.equal(ev('S.cash'), 1e8); + assert.equal(ev('S.pni.length'), 0, 'deleted POPs and unsupported speeds are rechecked on click'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('bulk PNI actions reject invalid networks, sizes, minimum ports, traffic thresholds and non-shared locations', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev('S.pops.fra.rgen=0'); + const cash = ev('S.cash'); + for (const net of ['missing', '__proto__', 'drz', 'nfx']) { + for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:'${net}',tier:${tier}})`); + } + ev("ACT.pniAll({net:'nfx',tier:0});R.demTo.nfx=0;ACT.pniAll({net:'nfx',tier:1})"); + assert.equal(ev('S.pni.length'), 0); + assert.equal(ev('S.cash'), cash); + ev("delete S.pops.fra;ACT.pniAllOpen({net:'drz'});ACT.pniAll({net:'drz',tier:1})"); + assert.match(dom.window.document.getElementById('modalCard').textContent, /no POPs in common/); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('Doitsche 1G bulk orders and 10G augments keep paid-peering fees and conference delivery rules', () => { + const { dom, ev, errors } = load(); + setup(ev, ['ams']); + ev("S.conf={until:S.day+10,reg:'EU'};Math.random=()=>0.5"); + const cash = ev('S.cash'); + assert.equal(ev("pniBatch('dtk',-1).cost"), 2400); + assert.equal(ev("pniBatch('dtk',-1).mo"), ev('2*(PORT[0].pni/2+NET.dtk.paidFee)')); + ev("ACT.pniAll({net:'dtk',tier:-1})"); + assert.equal(ev('S.cash'), cash - 2400); + assert.equal(ev('S.stats.beerPni'), 1); + assert.equal(ev('S.pni.every(p=>p.g1&&pniG(p)===1&&p.ready===S.day+15)'), true); + ev('S.day+=15;pniDay(S.day);compute()'); + assert.equal(ev("pniBatch('dtk',0).mo"), 200, 'upgrades add port costs, without charging the peering fee twice'); + ev("ACT.pniAll({net:'dtk',tier:0});S.day=Math.max(...S.pni.map(p=>p.up.ready));pniDay(S.day)"); + assert.equal(ev('S.pni.every(p=>!p.g1&&pniG(p)===10)'), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('Traffic row buttons and size selection work by DOM events on phones in every language', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + ev("ACT.launchBB({city:'fra'});ACT.dash();ACT.dashTab({k:'traffic'})"); + const doc = dom.window.document; + const buttons = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')]; + assert.ok(buttons.length > 0, lang); + assert.equal(buttons.some(b => JSON.parse(b.dataset.args).net === '_tail'), false); + const cash = ev('S.cash'); + buttons.find(b => JSON.parse(b.dataset.args).net === 'cfl').click(); + assert.equal(doc.getElementById('modal').hidden, false, lang); + let select = doc.querySelector('#modalCard select'); + assert.equal(select.closest('label').textContent.includes(ev("tr('pni_all.pni_size')")), true, lang); + select.focus(); + select.value = '0'; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + select = doc.querySelector('#modalCard select'); + assert.equal(select.value, '0', lang); + assert.equal(doc.activeElement, select, 'size changes preserve keyboard focus'); + const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); + assert.equal(JSON.parse(submit.dataset.args).tier, 0, lang); + assert.equal(submit.disabled, false, lang); + assert.equal(ev('S.cash'), cash, 'opening or changing the preview spends nothing'); + submit.click(); + assert.equal(doc.getElementById('modal').hidden, true, lang); + assert.equal(ev("S.pni.some(p=>p.net==='cfl'&&p.city==='fra'&&p.tier===0)"), true, lang); + assert.equal(ev('S.cash'), cash - 1750, lang); + assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); diff --git a/tests/pni-global.test.js b/tests/pni-global.test.js new file mode 100644 index 0000000..e175ed2 --- /dev/null +++ b/tests/pni-global.test.js @@ -0,0 +1,135 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=RG.length-1;compute()"); +} + +test('global PNIs cover every eligible network and shared POP, including the long tail, in one transaction', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev(`ACT.buildPop({city:'ams'});S.pops.ams.rgen=RG.length-1; + S.pni.push({id:'small',net:'cfl',city:'fra',tier:0,n:2,site:'ab',pref:'high'}, + {id:'big',net:'drz',city:'ams',tier:2}, + {id:'pending',net:'nfx',city:'fra',tier:1,ready:S.day+30}); + compute();for(const n of NETS)R.demTo[n.id]=1e4`); + const before = ev('JSON.stringify(S)'); + const batch = JSON.parse(ev('JSON.stringify(pniBatch(null,1))')); + assert.equal(ev('JSON.stringify(S)'), before, 'global preview changes no game state'); + assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'fra' && q.ex)); + assert.ok(batch.orders.some(q => q.net === 'cfl' && q.city === 'ams' && !q.ex)); + assert.ok(batch.orders.some(q => ev(`NET['${q.net}'].tail`)), 'small networks are included'); + assert.equal(batch.orders.some(q => q.net === 'drz' && q.city === 'ams'), false, 'no downgrade'); + assert.equal(batch.orders.some(q => q.net === 'nfx' && q.city === 'fra'), false, 'keep pending orders'); + const cash = ev('S.cash'); + ev("const originalAfter=after;window.after=()=>{window.afterCount=(window.afterCount||0)+1;originalAfter()};ACT.pniAll({net:null,tier:1})"); + assert.equal(ev('window.afterCount'), 1); + assert.equal(ev('S.cash'), cash - batch.cost); + assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length); + assert.equal(ev('new Set(S.pni.map(p=>p.net+"@"+p.city)).size'), ev('S.pni.length')); + assert.equal(ev("S.pni.every(p=>S.pops[p.city]&&NET[p.net].pops.includes(p.city))"), true); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.n"), 2, 'LAG members stay together'); + assert.equal(ev("S.pni.find(p=>p.id==='small').pref"), 'high'); + assert.equal(ev("S.pni.find(p=>p.id==='big').tier"), 2); + assert.equal(ev('Object.keys(S.pops).every(c=>portsUsed(c)<=portsMax(c))'), true); + ev('S=migrate(JSON.parse(JSON.stringify(packSave(S))));compute()'); + assert.equal(ev('S.pni.length'), 3 + batch.orders.filter(q => !q.ex).length); + assert.equal(ev("S.pni.find(p=>p.id==='small').up.tier"), 1); + const count = ev('S.pni.length'); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.cash'), cash - batch.cost, 'repeat clicks spend nothing'); + assert.equal(ev('S.pni.length'), count); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('global PNIs share the available router ports, including four 10G breakouts per slot', () => { + for (const [tier, count] of [[1, 1], [0, 4]]) { + const { dom, ev, errors } = load(); + setup(ev); + ev("S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'}));compute()"); + assert.equal(ev(`pniBatch(null,${tier}).orders.length`), count); + assert.ok(ev(`pniBatch(null,${tier}).blocked.some(q=>/No free router ports/.test(q.why))`)); + ev(`ACT.pniAll({net:null,tier:${tier}})`); + assert.equal(ev('S.pni.length'), count); + assert.equal(ev("portsUsed('fra')"), 8); + const cash = ev('S.cash'); + ev(`ACT.pniAll({net:null,tier:${tier}})`); + assert.equal(ev('S.cash'), cash); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('global planning reserves ports for pending speed and LAG augments without mutating the save', () => { + for (const [tier, n] of [[1, 1], [0, 4]]) { + const { dom, ev, errors } = load(); + setup(ev); + ev(`S.pops.fra.rgen=0;S.caches=Array.from({length:7},()=>({id:uid(),city:'fra',net:'cfl'})); + S.pni=[{id:'pending',city:'fra',net:'cfl',tier:0,n:1,up:{tier:${tier},n:${n},ready:S.day+30}}];compute()`); + const state = ev('JSON.stringify(S)'); + assert.equal(ev('pniBatch(null,0).orders.length'), 0); + assert.equal(ev('pniBatch(null,1).orders.length'), 0); + assert.equal(ev('JSON.stringify(S)'), state); + const cash = ev('S.cash'); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.pni.length'), 1); + assert.equal(ev('S.cash'), cash); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('global PNIs require the full budget and reject unsupported sizes and an empty POP list', () => { + const { dom, ev, errors } = load(); + setup(ev); + ev('S.cash=pniBatch(null,1).cost-1;ACT.pniAllOpen({net:null})'); + const cash = ev('S.cash'); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + ev('ACT.pniAll({net:null,tier:1})'); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0, 'no partial purchase'); + for (const tier of [-2, -1, 0.5, 99, NaN, Infinity]) ev(`ACT.pniAll({net:null,tier:${tier}})`); + ev('ACT.pniAll({tier:1});S.pops={};ACT.pniAllOpen({net:null})'); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('S.pni.length'), 0); + assert.match(dom.window.document.getElementById('modalCard').textContent, /No shared POPs/); + assert.equal(dom.window.document.querySelector('#modalCard [data-act="pniAll"]').disabled, true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the global Traffic button preserves scope, keyboard focus and translations on phones', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { dom, ev, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + ev("ACT.dash();ACT.dashTab({k:'traffic'})"); + const doc = dom.window.document; + const button = [...doc.querySelectorAll('#dashCard [data-act="pniAllOpen"]')].find(b => JSON.parse(b.dataset.args).net === null); + assert.ok(button, lang); + button.click(); + assert.equal(doc.querySelector('#modalCard h2').textContent, ev("tr('pni_all.peer_all_networks')"), lang); + const cash = ev('S.cash'); + const select = doc.querySelector('#modalCard select'); + assert.equal([...select.options].some(o => o.value === '-1'), false, '1G is not available for all networks'); + select.focus(); + select.value = '0'; + select.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.equal(doc.activeElement, doc.querySelector('#modalCard select')); + const submit = doc.querySelector('#modalCard [data-act="pniAll"]'); + assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang); + assert.equal(submit.disabled, false, lang); + assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed'); + assert.equal(ev('S.cash'), cash, 'preview does not buy anything'); + assert.doesNotMatch(doc.getElementById('modalCard').textContent, /pni_all\./, lang); + const cost = ev('pniBatch(null,0).cost'); + submit.click(); + assert.equal(doc.getElementById('modal').hidden, true, lang); + assert.equal(ev('S.cash'), cash - cost, lang); + assert.ok(ev('new Set(S.pni.map(p=>p.net)).size') > 1, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); From abe92fe3b13c2493950ac36aeb238bfade0c86d3 Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 02:19:30 +0100 Subject: [PATCH 09/13] Add real-time sales automation and automatic paid repairs Add independent toggles for auto-accept in Deals and auto-pay repairs in NOC. Save both settings and default them off for older or malformed saves. Check sales every five wall-clock seconds regardless of game speed, and show a small countdown on Accept buttons in Deals, city offers and fiber broker offers. Only sign when all requirements, locations, equipment and service capacity are ready. Trial the added demand before accepting it, protect healthy existing customers and account for booked future events. Use the existing paid repair action for affordable active incidents, including slow router reboots. Skip expired incidents, removed equipment, DDoS attacks and repairs that were already rushed. Pause both automations with the game, hidden pages and open dialogs. Translate the controls into all five supported languages and cover timing, countdowns, capacity, budgets, repair payments, persistence, mobile controls and trial rollback with deterministic tests. Chromium checks verify about five real seconds at both 0.5x and 8x game speed and exercise the supplied large save without changing the save file. --- CHANGELOG.md | 3 + site/i18n/es.js | 5 + site/i18n/fr.js | 5 + site/i18n/it.js | 5 + site/i18n/pt.js | 5 + src/game/60-features/80-new-game.js | 2 +- src/game/60-features/90-automation.js | 30 +++ src/game/80-simulation/50-sanitize.js | 1 + src/game/90-actions/50-customers.js | 5 +- src/game/93-ui/40-hud-and-panels.js | 4 +- src/game/93-ui/70-link-panels.js | 4 +- src/game/99-loop.js | 1 + src/i18n/en.js | 5 + tests/automation.test.js | 319 ++++++++++++++++++++++++++ 14 files changed, 388 insertions(+), 6 deletions(-) create mode 100644 src/game/60-features/90-automation.js create mode 100644 tests/automation.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 0094b5d..3f87e28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside each Accept button. +- Toggle auto-pay repairs in the NOC to pay for affordable rush repairs automatically while the game runs. + ## [1.35.0] — 2026-10-27 - Series of Tubes now speaks Spanish. The game follows your browser's language the first time, and you can switch to Spanish under Settings or on the title screen. diff --git a/site/i18n/es.js b/site/i18n/es.js index 16f2a3c..4fd30a4 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Demasiado lejos incluso en su ajuste más lento: aquí un tramo óptico mide {span} km y el alcance es de {max} km. Añade un sitio regenerador (Sistema de línea).", "action_helpers.unlocks_at_customer_level_n":"Se desbloquea en el nivel de cliente {n}.", "actions.your_router_can_t_take_a":"Tu router no admite un puerto de {port}.
Mejóralo en la pestaña Infra.", +"automation.auto_accept_sales":"Ventas automáticas: {state}", +"automation.auto_pay_repairs":"Reparaciones pagadas auto: {state}", +"automation.next_auto_check":"Tiempo hasta la próxima comprobación automática de requisitos.", +"automation.repairs_when_affordable":"Mientras juegas, paga automáticamente las reparaciones urgentes disponibles si hay fondos suficientes.", +"automation.sales_every_five_seconds":"Cada 5 segundos mientras juegas, acepta solo ofertas cuyos requisitos se cumplan y tengan capacidad de servicio disponible.", "badges.a_petabit_a_second":"Un petabit por segundo", "badges.a_secret_badge":"Una insignia secreta", "badges.attend_a_conference":"Asiste a una conferencia.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4e674bf..7280f8a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Trop loin, même au débit le plus lent : ici une portée optique fait {span} km et l’optique va jusqu’à {max} km. Ajoute un site de régénération (Système de ligne).", "action_helpers.unlocks_at_customer_level_n":"Se débloque au niveau client {n}.", "actions.your_router_can_t_take_a":"Ton routeur ne supporte pas de port {port}.
Mets-le à niveau dans l’onglet Infra.", +"automation.auto_accept_sales":"Ventes automatiques : {state}", +"automation.auto_pay_repairs":"Réparations payées auto : {state}", +"automation.next_auto_check":"Temps avant la prochaine vérification automatique des conditions.", +"automation.repairs_when_affordable":"Pendant le jeu, paie automatiquement les réparations urgentes disponibles si les fonds suffisent.", +"automation.sales_every_five_seconds":"Toutes les 5 secondes pendant le jeu, accepte uniquement les offres dont les conditions sont remplies et la capacité de service disponible.", "badges.a_petabit_a_second":"Un pétabit par seconde", "badges.a_secret_badge":"Un badge secret", "badges.attend_a_conference":"Participe à une conférence.", diff --git a/site/i18n/it.js b/site/i18n/it.js index 83a3693..312e1b0 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Troppo lontano anche alla velocità più bassa: qui una tratta ottica è di {span} km e l’ottica arriva a {max} km. Aggiungi un sito di rigenerazione (Sistema di linea).", "action_helpers.unlocks_at_customer_level_n":"Si sblocca al livello cliente {n}.", "actions.your_router_can_t_take_a":"Il tuo router non regge una porta {port}.
Aggiornalo nella scheda Infra.", +"automation.auto_accept_sales":"Vendite automatiche: {state}", +"automation.auto_pay_repairs":"Riparazioni a pagamento auto: {state}", +"automation.next_auto_check":"Tempo fino alla prossima verifica automatica dei requisiti.", +"automation.repairs_when_affordable":"Durante il gioco, paga automaticamente le riparazioni urgenti disponibili se hai abbastanza fondi.", +"automation.sales_every_five_seconds":"Ogni 5 secondi durante il gioco, accetta solo le offerte con requisiti soddisfatti e capacità di servizio disponibile.", "badges.a_petabit_a_second":"Un petabit al secondo", "badges.a_secret_badge":"Un badge segreto", "badges.attend_a_conference":"Partecipa a una conferenza.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cd40592..49b342f 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -12,6 +12,11 @@ "action_helpers.too_far_even_at_its_slowest":"Longe demais até na configuração mais lenta: um span óptico aqui tem {span} km e ela alcança {max} km. Adicione um site de regeneração (Line system).", "action_helpers.unlocks_at_customer_level_n":"Desbloqueia no nível de cliente {n}.", "actions.your_router_can_t_take_a":"Seu router não aguenta uma porta {port}.
Faça upgrade na aba Infra.", +"automation.auto_accept_sales":"Vendas automáticas: {state}", +"automation.auto_pay_repairs":"Reparações pagas auto: {state}", +"automation.next_auto_check":"Tempo até à próxima verificação automática dos requisitos.", +"automation.repairs_when_affordable":"Durante o jogo, paga automaticamente as reparações urgentes disponíveis quando há fundos suficientes.", +"automation.sales_every_five_seconds":"A cada 5 segundos durante o jogo, aceita apenas ofertas com os requisitos cumpridos e capacidade de serviço disponível.", "badges.a_petabit_a_second":"Um petabit por segundo", "badges.a_secret_badge":"Um badge secreto", "badges.attend_a_conference":"Participe de uma conferência.", diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 2fa348b..5ae1c21 100644 --- a/src/game/60-features/80-new-game.js +++ b/src/game/60-features/80-new-game.js @@ -1,6 +1,6 @@ function newGame(name,home){ S={v:1,name,asn:200000+Math.floor(_rand()*15000),home,day:0,cash:START_CASH, - ltv:2,t1v:3,auV:1,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{}, + ltv:2,t1v:3,auV:1,autoSales:false,autoRepair:false,seen:NETS.map(n=>n.id),spares:{},pops:{[home]:{day:0,bb:null,boost:0,down:0,routers:1,gen:false}},links:[],nni:[],transit:[],ixp:{},rs:{},peers:{},pni:[],caches:[],biz:[],offers:[],myIx:{}, done:{},inc:[],ev:{},priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',capDeal:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,inbox:{items:[],down:{},tiny:{},rep:0,bot:false,log:[],seq:0},hw:{}}; } diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js new file mode 100644 index 0000000..e8130b9 --- /dev/null +++ b/src/game/60-features/90-automation.js @@ -0,0 +1,30 @@ +/* Optional operators use the same sales and repair actions as the player. */ +const AUTO_SALES_MS=5000; +function autoSalesSeconds(now=performance.now()){if(!S||!S.autoSales)return null; + const left=UI.autoGame===S&&autoActive()?AUTO_SALES_MS-(now-UI.autoSalesAt):AUTO_SALES_MS; + return Math.max(1,Math.min(AUTO_SALES_MS/1000,Math.ceil(left/1000)));} +function autoAcceptLabel(){return tr('common.accept')+(S.autoSales?` (${autoSalesSeconds()})`:'');} +function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n)return;UI.autoCount=n; + for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n===null?'':`(${n})`;} +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; + const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; + if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null; + if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id; + if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;} + 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}; + // shortcut: future events reserve capacity together; use per-date trials if separate bookings must share capacity. + if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);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(); + 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;}} +function autoActive(){return !!(S&&UI.started&&!S.lost&&UI.speed&&$('modal').hidden&&document.visibilityState==='visible');} +function automationTick(now){if(UI.autoGame!==S){UI.autoGame=S;UI.autoSalesAt=now;} + if(!autoActive()){UI.autoSalesAt=now;return;} + if(S.autoRepair&&S.inc.length){purgeInc();for(const i of S.inc.slice()){if(!autoActive())break; + if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&i.cost<=S.cash&&!(i.slow&&i.rushed))ACT.fixInc({id:i.id});}} + if(!S.autoSales||!autoActive()){UI.autoSalesAt=now;return;}if(now-UI.autoSalesAt{const list=T.names.filter(n=>!S.usedNames.includes(n)),n=list.length?pick(list):pick(T.names);useName(n);return n;}; // A capacity broker finds a buyer at once and keeps 10% of the monthly price. const o=fiberOffer(t,l,nm,0.9);o.broker=true;S.offers.push(o);toast(tr('customers.listed_with_a_capacity_broker_name',{name:esc(o.name),what:esc(o.what)}),'good');sfx('click');after();}, - accept:({id})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} + autoToggle:({k})=>{if(k!=='autoSales'&&k!=='autoRepair')return;S[k]=!S[k];if(k==='autoSales'){UI.autoGame=S;UI.autoSalesAt=performance.now();}sfx('click');after();}, + accept:({id,auto=false})=>{const o=S.offers.find(x=>x.id===id);if(!o)return;const customer=auto?(S.autoSales&&autoOffer(o)):offerCustomer(o);if(!customer)return;if(!bHas(o)){toast(tr('customers.you_need_a_pop_in_every'),'bad');return;} if(o.type==='wwave'){const l=S.links.find(x=>x.id===o.link);if(!l||chMax(l)-(l.ch||[]).length-soldSlots(l)=o.start){toast(tr('customers.too_late_the_event_has_already'),'bad');return;} // A carrier renting more alien waves on a fiber it already rents grows its contract, like a real order for extra waves, @@ -12,7 +13,7 @@ Object.assign(ACT,{ const more=o.type==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===o.link&&b.name===o.name); if(more){const l=S.links.find(x=>x.id===o.link);S.offers=S.offers.filter(x=>x!==o);more.slots=(more.slots||0)+(o.slots||0);more.rate+=o.rate;if(l)more.what=wwWhat(l,more.slots); floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();return;} - S.offers=S.offers.filter(x=>x!==o);S.biz.push({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}); + S.offers=S.offers.filter(x=>x!==o);S.biz.push(customer); floater(CITY[o.city].x,CITY[o.city].y-30,tr('common.signed'),'#16A866');sfx('coin');after();}, decline:({id})=>{S.offers=S.offers.filter(x=>x.id!==id);after();}, dropBiz:({id})=>{const b0=S.biz.find(x=>x.id===id);if(!b0)return;if(BIZ_T[b0.type].event&&S.day>=b0.start){toast(tr('customers.the_event_is_already_running_the'),'bad');sfx('err');return;}if(UI.confirm!==id){UI.confirm=id;renderPanel();return;}S.biz=S.biz.filter(b=>b.id!==id);UI.confirm=null;after();}, diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 2a98394..2f599cf 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -37,16 +37,18 @@ function renderLeft(){checkLayer(); h+=GOALS.map(g=>{const d=S.done[g.id]!==undefined,c=g===cur;return `
${d?'✓':''}
${esc(g.t)}
${c||!d?`
${esc(g.d)}
`:''}${!d&&g.r?`
${tr('hud_and_panels.reward_cash',{cash:fmt$(g.r)})}
`:''}
`;}).join(''); h+=badgeGrid(); }else if(UI.left==='deals'){ + h+=`

${tr('automation.sales_every_five_seconds')}

`; {const st=custStats();if(st.n)h+=`
${tr('common.your_customers')} ${st.n} · ${tr('hud_and_panels.happiness_p',{p:Math.round(st.avg)})}
${st.unhappy?`
${trn('hud_and_panels.n_unhappy_customer_price_mo_at',st.unhappy,{price:fmt$(st.risk)})}
`:''}
${btn(st.unhappy?tr('common.see_who'):tr('common.all_customers'),'custOpen',{sad:st.unhappy?1:0},st.unhappy?'pink sm':'ghost sm')}
`;} h+=confSection(); {const lv=S.lvl||1,nx=LEVELS[lv];h+=`
${tr('hud_and_panels.customer_level_lv_name',{lv,name:LEVELS[lv-1].n})}
${nx?tr('hud_and_panels.next_req_unlocks_what',{req:nx.req,what:lc1(nx.unlock)}):tr('common.every_customer_type_is_unlocked_go')}
`;} if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${reqList(o)} -
${has?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} +
${has?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${btn(tr('common.connections'),'connOpen',{},'')}${btn(tr('common.traceroute'),'trace',{},'')}
`; h+=`

${tr('hud_and_panels.your_network_operations_center_every')}

`; + h+=`

${tr('automation.repairs_when_affordable')}

`; // Incidents come first, the ones you can fix with one click at the top (#63): no scrolling past hot ports to replace an optic. for(const i of S.inc.filter(i=>i.type!=='ddos').sort((a,b)=>(b.cost?1:0)-(a.cost?1:0)||(b.impact||0)-(a.impact||0))){h+=`
${incTitle(i.type)}
${esc(i.msg)}
${trn('hud_and_panels.auto_fix_in_n_day',i.until-S.day)}${i.impact?` · ${tr('hud_and_panels.g_lost',{g:fmtG(i.impact)})}`:''}
${i.cost?`
${btn(`${esc(i.fix||tr('common.rush_repair'))} ${fmt$(i.cost)}`,'fixInc',{id:i.id},'red sm',S.cash`:''}
`;} h+=logSection();UI.logSeen=Date.now(); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 19b6eb7..5cba29a 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -76,7 +76,7 @@ function dfPanel(l){ if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); h+=`

${tr('link_panels.selling_spare_capacity')}

${tr('link_panels.other_carriers_rent_what_you_do')}

${tr('common.free_channels')}${fc} / ${chMax(l)}
${sold.map(b=>`
${esc(b.name)}
${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}
`).join('')} - ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(tr('common.accept'),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}
`;} + ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); @@ -93,7 +93,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(tr('common.accept'),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 7f1b386..70a4e5d 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -10,6 +10,7 @@ function frame(now){ if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} if(S&&!S.lost&&$('modal').hidden&&UI.speed){acc+=dt*UI.speed;let n=0;while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}} + try{automationTick(now);renderAutoCountdown();}catch(e){tickErr(e);} if(UI.speed&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ const t=animOn()?animT:0; if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;} diff --git a/src/i18n/en.js b/src/i18n/en.js index b26cc57..bdc2a00 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -13,6 +13,11 @@ "action_helpers.too_far_even_at_its_slowest":"Too far even at its slowest setting: an optical span here is {span} km and it reaches {max} km. Add a regen site (Line system).", "action_helpers.unlocks_at_customer_level_n":"Unlocks at customer level {n}.", "actions.your_router_can_t_take_a":"Your router can't take a {port} port.
Upgrade it in the Infra tab.", +"automation.auto_accept_sales":"Auto-accept sales: {state}", +"automation.auto_pay_repairs":"Auto-pay repairs: {state}", +"automation.next_auto_check":"Time until the next automatic requirements check.", +"automation.repairs_when_affordable":"While playing, automatically pay for available rush repairs when you can afford them.", +"automation.sales_every_five_seconds":"Every 5 seconds while playing, accept only offers whose requirements and service capacity are ready.", "badges.a_petabit_a_second":"A Petabit a Second", "badges.a_secret_badge":"A secret badge", "badges.attend_a_conference":"Attend a conference.", diff --git a/tests/automation.test.js b/tests/automation.test.js new file mode 100644 index 0000000..b613873 --- /dev/null +++ b/tests/automation.test.js @@ -0,0 +1,319 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});compute()"); +} +function offer(ev, id, extra = {}) { + ev(`S.offers.push(${JSON.stringify({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`); +} + +test('auto-accept waits five real seconds at every game speed and the toggle stops it', () => { + for (const speed of [0.5, 1, 2, 4, 8]) { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'first'); + ev("ACT.autoToggle({k:'autoSales'});UI.autoSalesAt=1000"); + const start = ev('UI.autoSalesAt'); + ev(`UI.speed=${speed};automationTick(${start + 4999})`); + assert.equal(ev('S.biz.length'), 0, speed); + ev(`automationTick(${start + 5000})`); + assert.equal(ev('S.biz[0].id'), 'first', speed); + offer(ev, 'second'); + ev(`automationTick(${start + 9999})`); + assert.equal(ev('S.biz.length'), 1, speed); + ev(`automationTick(${start + 10000})`); + assert.equal(ev('S.biz.length'), 2, speed); + ev("ACT.autoToggle({k:'autoSales'})"); + offer(ev, 'off'); + ev(`automationTick(${start + 20000});ACT.accept({id:'off',auto:true})`); + assert.equal(ev('S.biz.length'), 2, speed); + assert.equal(ev('S.offers[0].id'), 'off', speed); + assert.deepEqual(errors, []); + dom.window.close(); + } +}); + +test('Accept buttons share a real-time countdown in Deals, city offers and fiber broker offers', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + offer(ev, 'waiting', { reqs: ['gen'] }); + ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';UI.leftOpen=true;renderAll()"); + assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0); + ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); + const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')]; + assert.ok(counts().length >= 2, 'Deals and the city panel both show it'); + assert.ok(counts().every(el => el.textContent === '(5)')); + ev('testNow=2001;renderAutoCountdown()'); + assert.ok(counts().every(el => el.textContent === '(4)')); + ev('testNow=3000;UI.speed=8;renderAutoCountdown()'); + assert.ok(counts().every(el => el.textContent === '(3)')); + ev('UI.speed=0.5;renderAll();renderAutoCountdown()'); + assert.ok(counts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); + assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/); + ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})"); + offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' }); + ev("compute();UI.sel={type:'link',id:'fiber'};renderPanel()"); + const broker = dom.window.document.querySelector('#panelBody [data-act="accept"] [data-auto-sales]'); + assert.ok(broker); + assert.equal(broker.textContent, '(3)'); + ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); + assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true); + assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements'); + assert.ok(counts().every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); + ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); + assert.equal(counts().length, 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('auto-accept leaves unready and expired offers alone without failure notifications', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'generator', { reqs: ['gen'] }); + offer(ev, 'missing-pop', { city: 'ams' }); + offer(ev, 'scrub', { type: 'scrub' }); + offer(ev, 'expired', { exp: 0 }); + offer(ev, 'ipv6', { reqs: ['ipv6'] }); + const log = ev('S.log.length'); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('S.offers.length'), 5); + assert.equal(ev('S.log.length'), log, 'no repeated failed manual-action toasts'); + ev('S.pops.fra.gen=true;compute();automationTick(10000)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].id'), 'generator'); + // Manual acceptance keeps its existing sign-now, provision-later behavior. + ev("ACT.accept({id:'scrub'})"); + assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the trial includes new bandwidth and later offers cannot overbook earlier accepted sales', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'one', { bw: 60 }); + offer(ev, 'two', { bw: 60 }); + const state = ev('JSON.stringify(S)'); + ev('window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap'); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + assert.equal(ev('JSON.stringify(S)'), state); + assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.offers[0].id'), 'two'); + assert.ok(ev('bizSf(S.biz[0])') >= 0.95); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('auto-accept checks actual circuits, latency and NNI capacity', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()"); + offer(ev, 'circuit', { type: 'hft', city2: 'ams', bw: 10, latMax: 50, reqs: ['lat'] }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'POPs alone are not a circuit'); + ev("S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.offers[0].latMax=0.1'); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'latency budget must pass'); + ev("S.offers=[];window.fabric=FABS.find(f=>f.cities.includes('fra')).id;ACT.buyNni({city:'fra',prov:fabric,tier:0})"); + const prov = ev('fabric'); + const bandwidth = ev('NNI[0].g * 0.75'); + offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); + offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); + // Transit has enough headroom, so the second rejection is the shared NNI port. + ev("S.transit[0].tier=4;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)"); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.offers[0].id'), 'fabric-two'); + assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g")); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('new circuits do not take service away from healthy signed customers', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});S.transit[0].city='ams';compute()"); + offer(ev, 'existing', { bw: 80 }); + ev("ACT.accept({id:'existing'})"); + offer(ev, 'new-circuit', { type: 'l2vpn', city2: 'ams', bw: 50 }); + assert.equal(ev('bizWhy(S.biz[0]).length'), 0); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + assert.ok(ev('bizSf(S.biz[0])') >= 0.95, 'failed preview leaves the old routing result intact'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('fiber sales check live equipment and free spectrum, and repeated carrier orders still merge', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(14).fill('zr4'),km:450,sub:false,ready:0,cut:0,mo:1}];S.biz=[{id:'old',name:'Same Carrier',type:'wwave',city:'fra',city2:'ams',link:'fiber',bw:1,rate:1000,slots:1,reqs:[],mood:100,since:0}];compute()"); + offer(ev, 'full', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 2 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale'); + ev('S.links[0].eqDown=0;compute();S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].slots'), 2); + assert.equal(ev('S.biz[0].rate'), 1600); + assert.equal(ev('freeCh(S.links[0])'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('capacity pair sales need completed infrastructure and reserve it for the accepted contract', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz[0].link'), 'own'); + assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day'); + offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'the same trench cannot be promised twice'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('future event demand is tested before signing, with booked events reserving headroom', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(5000)'); + assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date'); + assert.equal(ev('R.cityDem.fra'), 0); + offer(ev, 'too-large', { bw: 30 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev('S.offers[0].bw=10'); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + assert.equal(ev('S.biz[0].start'), 10); + assert.equal(ev('R.cityDem.fra'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('failed capacity trials restore game, routing and map state even when compute throws', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + ev("window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap;window.originalCompute=compute;window.compute=()=>{throw new Error('trial failed')}"); + assert.throws(() => ev('autoOffer(S.offers[0])'), /trial failed/); + assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); + ev('window.compute=originalCompute'); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('S.offers.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('auto-pay rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its toggle', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}]; + S.pops.fra.down=8;S.inc=[ + {id:'amp',type:'amp',ref:'fiber',until:10,cost:30000,msg:'Broken amp'}, + {id:'optic',type:'optic',ref:'fiber',until:10,cost:5000,msg:'Broken optic'}, + {id:'slow',type:'crash',ref:'fra',until:8,cost:2000,slow:true,msg:'Slow boot'}, + {id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'}, + {id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'}, + {id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}]; + S.autoRepair=true;UI.autoGame=S;UI.autoSalesAt=0;automationTick(1)`); + assert.equal(ev('S.cash'), 3000); + assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false); + assert.equal(ev('S.links[0].chFail'), null); + assert.equal(ev("S.inc.find(i=>i.id==='slow').rushed"), true); + assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1); + assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0); + assert.equal(ev('S.pops.fra.down'), 1); + ev('automationTick(2)'); + assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment'); + ev('S.cash=40000;automationTick(3)'); + assert.equal(ev('S.cash'), 10000); + assert.equal(ev('S.links[0].eqDown'), 0); + assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false); + ev("ACT.autoToggle({k:'autoRepair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});automationTick(4)"); + assert.equal(ev('S.cash'), 10000); + assert.equal(ev("S.inc.some(i=>i.id==='new')"), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('automation pauses with the game, dialogs, hidden pages and game over', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'paused'); + ev('S.autoSales=true;UI.autoGame=S;UI.autoSalesAt=0;UI.speed=0;automationTick(5000)'); + assert.equal(ev('S.biz.length'), 0); + ev('UI.speed=1;automationTick(9999)'); + assert.equal(ev('S.biz.length'), 0, 'resume starts a fresh five-second wait'); + ev("openModal('

Menu

');automationTick(10000);closeModal()"); + ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'hidden'});automationTick(15000)"); + ev("Object.defineProperty(document,'visibilityState',{configurable:true,value:'visible'});S.lost=true;automationTick(20000);S.lost=false;automationTick(24999)"); + assert.equal(ev('S.biz.length'), 0); + ev('automationTick(25000)'); + assert.equal(ev('S.biz.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the frame loop repairs new incidents without waiting for the sales timer', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev(`S.autoRepair=true;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,mo:1}]; + window.originalDay=dayTick;window.dayTick=()=>{S.links[0].eqDown=10;S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'Broken amp'})}; + window.cashBefore=S.cash;last=0;acc=DAY_MS;frame(16);window.dayTick=originalDay`); + assert.equal(ev('S.cash'), ev('cashBefore-1000')); + assert.equal(ev('S.inc.length'), 0); + assert.equal(ev('S.links[0].eqDown'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('toggles persist, old and malformed saves default off, and the timer resets for another game', () => { + const { ev, dom, errors } = load(); + setup(ev); + assert.equal(ev('S.autoSales||S.autoRepair'), false); + ev("ACT.autoToggle({k:'autoSales'});ACT.autoToggle({k:'autoRepair'});save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')))"); + assert.equal(ev('S.autoSales&&S.autoRepair'), true); + ev("delete S.autoSales;delete S.autoRepair;S=migrate(S)"); + assert.equal(ev('S.autoSales||S.autoRepair'), false); + ev("S.autoSales='true';S.autoRepair=1;S=migrate(S);ACT.autoToggle({k:'cash'})"); + assert.equal(ev('S.autoSales||S.autoRepair'), false); + ev('UI.autoGame=S;UI.autoSalesAt=0;S=migrate(JSON.parse(JSON.stringify(S)));S.autoSales=true;compute()'); + offer(ev, 'imported'); + ev('automationTick(100000)'); + assert.equal(ev('S.biz.length'), 0, 'an imported game does not inherit another game timer'); + ev('automationTick(105000)'); + assert.equal(ev('S.biz.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('both toggle buttons work by keyboard-compatible DOM events on phones in every language', () => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + setup(ev); + dom.window.innerWidth = 360; + for (const [tab, key] of [['deals', 'autoSales'], ['noc', 'autoRepair']]) { + ev(`ACT.leftTab({t:'${tab}'});renderAll()`); + const button = [...dom.window.document.querySelectorAll('#leftBody [data-act="autoToggle"]')].find(b => JSON.parse(b.dataset.args).k === key); + assert.ok(button, lang); + assert.equal(button.getAttribute('aria-pressed'), 'false', lang); + button.focus(); + button.click(); + const updated = dom.window.document.querySelector('#leftBody [data-act="autoToggle"]'); + assert.equal(updated.getAttribute('aria-pressed'), 'true', lang); + assert.equal(ev(`S.${key}`), true, lang); + assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /automation\./, lang); + } + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); From dd82737af8ebbe88bd5130616cbecbd7f5590439 Mon Sep 17 00:00:00 2001 From: logfro Date: Wed, 28 Oct 2026 02:55:12 +0100 Subject: [PATCH 10/13] Show auto-accept countdowns only for ready offers Hide the countdown when an offer has unmet requirements, missing locations, expired terms or insufficient service capacity. Keep manual acceptance available with its existing behavior. Share capacity previews across the Deals, city and fiber views, reuse them between automatic checks, and invalidate them after actions or incidents. Check changing requirements immediately and always perform a fresh full validation before automatically signing a contract. Add regression tests for blocked offers, requirements becoming fulfilled or unfulfilled, capacity changes and preview reuse. All 17 automation tests pass; the full independent branch passes 314 of 315 tests, with only the pre-existing locale-dependent subsea formatting failure remaining. --- CHANGELOG.md | 2 +- src/game/60-features/90-automation.js | 12 +++-- src/game/90-actions/90-action-helpers.js | 2 +- src/game/93-ui/40-hud-and-panels.js | 2 +- src/game/93-ui/70-link-panels.js | 4 +- tests/automation.test.js | 56 +++++++++++++++++++++--- 6 files changed, 64 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f87e28..07cdb6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside each Accept button. +- Toggle auto-accept in Deals to check ready sales every five real seconds, including their requirements and available service capacity, with a countdown beside eligible Accept buttons. - Toggle auto-pay repairs in the NOC to pay for affordable rush repairs automatically while the game runs. ## [1.35.0] — 2026-10-27 diff --git a/src/game/60-features/90-automation.js b/src/game/60-features/90-automation.js index e8130b9..8a2b0e8 100644 --- a/src/game/60-features/90-automation.js +++ b/src/game/60-features/90-automation.js @@ -3,9 +3,15 @@ const AUTO_SALES_MS=5000; function autoSalesSeconds(now=performance.now()){if(!S||!S.autoSales)return null; const left=UI.autoGame===S&&autoActive()?AUTO_SALES_MS-(now-UI.autoSalesAt):AUTO_SALES_MS; return Math.max(1,Math.min(AUTO_SALES_MS/1000,Math.ceil(left/1000)));} -function autoAcceptLabel(){return tr('common.accept')+(S.autoSales?` (${autoSalesSeconds()})`:'');} -function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n)return;UI.autoCount=n; - for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n===null?'':`(${n})`;} +function autoCountdownReady(o){if(!S||!S.autoSales||!o||!(o.exp>S.day)||!bCities(o).every(popUp)||!reqOk(o))return false; + const inc=S.inc.map(i=>i.id).join('|');let c=UI.autoReady; + // Share capacity trials between views and keep them until the next check, action or incident. + if(!c||c.s!==S||c.at!==UI.autoSalesAt||c.inc!==inc||c.event!==S.nextEvent)c=UI.autoReady={s:S,at:UI.autoSalesAt,inc,event:S.nextEvent,offers:new Map()}; + if(!c.offers.has(o))c.offers.set(o,!!autoOffer(o));return c.offers.get(o);} +function autoAcceptLabel(o){return tr('common.accept')+(S.autoSales?` ${autoCountdownReady(o)?`(${autoSalesSeconds()})`:''}`:'');} +function renderAutoCountdown(now=performance.now()){const n=autoSalesSeconds(now);if(UI.autoCount===n&&UI.autoCountResult===R)return;UI.autoCount=n;UI.autoCountResult=R; + const offers=new Map((S?S.offers:[]).map(o=>[o.id,o])); + for(const el of document.querySelectorAll('[data-auto-sales]'))el.textContent=n!==null&&autoCountdownReady(offers.get(el.dataset.autoSales))?`(${n})`:'';} 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; const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null; diff --git a/src/game/90-actions/90-action-helpers.js b/src/game/90-actions/90-action-helpers.js index 67c8055..14e5aad 100644 --- a/src/game/90-actions/90-action-helpers.js +++ b/src/game/90-actions/90-action-helpers.js @@ -20,7 +20,7 @@ function chWhy(l,o){const O=OPT[o];if(O.lvl>lvl())return tr('action_helpers.unlo if((l.ch||[]).length+soldSlots(l)>=chMax(l))return soldSlots(l)?tr('action_helpers.sys_is_full_max_channels_sold',{sys:DF_SYS[l.sys].n,max:chMax(l),sold:soldSlots(l)}):tr('action_helpers.sys_is_full_max_channels',{sys:DF_SYS[l.sys].n,max:chMax(l)}); for(const c of [l.a,l.b]){const p=S.pops[c];if(p&&RG[p.rgen||0].clsinnerWidth>760&&innerWidth<=1200; function selectLink(id){UI.sel={type:'link',id};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;$('panel').classList.remove('full');renderPanel();renderLeft();} function selectCity(c){UI.sel={type:'city',id:c};UI.confirm=null;if(isTablet()||isPhone())UI.leftOpen=false;const P=$('panel');if(P)P.classList.remove('full');if(!S.pops[c])UI.tab='cust';renderPanel();} diff --git a/src/game/93-ui/40-hud-and-panels.js b/src/game/93-ui/40-hud-and-panels.js index 2f599cf..5070f9d 100644 --- a/src/game/93-ui/40-hud-and-panels.js +++ b/src/game/93-ui/40-hud-and-panels.js @@ -44,7 +44,7 @@ function renderLeft(){checkLayer(); if(!S.offers.length)h+=`

${tr('hud_and_panels.no_open_offers_right_now_businesses')}

`; for(const o of S.offers.slice().sort((a,b)=>a.exp-b.exp)){const has=bHas(o); h+=`
${esc(o.name)}
${esc(BIZ_T[o.type].l)} · ${CITY[o.city].name}${o.city2?' ⇄ '+CITY[o.city2].name:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}${(o.reqs||[]).length?` · ${trn('hud_and_panels.n_special_requirement',o.reqs.length)}`:''}
${reqList(o)} -
${has?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} +
${has?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):btn(tr('common.go_there'),'focusCity',{city:bCities(o).find(c=>!S.pops[c])},'ghost sm')}${btn(tr('common.decline'),'decline',{id:o.id},'ghost sm')}
${has?'':`
${tr('hud_and_panels.needs_a_pop_in_cities',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
`;} }else if(UI.left==='noc'){ h+=`
${btn(tr('hud_and_panels.open_noc_dashboard'),'dash',{},'pink')}${btn(tr('common.connections'),'connOpen',{},'')}${btn(tr('common.traceroute'),'trace',{},'')}
`; h+=`

${tr('hud_and_panels.your_network_operations_center_every')}

`; diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 5cba29a..3d15925 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -76,7 +76,7 @@ function dfPanel(l){ if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='dfpair'||b.type==='pairs')),off=S.offers.find(o=>o.link===l.id),fc=freeCh(l); h+=`

${tr('link_panels.selling_spare_capacity')}

${tr('link_panels.other_carriers_rent_what_you_do')}

${tr('common.free_channels')}${fc} / ${chMax(l)}
${sold.map(b=>`
${esc(b.name)}
${esc(b.what||BIZ_T[b.type].l)} · ${tr('common.price_mo',{price:fmt$(b.rate)})}
`).join('')} - ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}
`;} + ${off?`
${esc(off.name)}
${esc(off.what)} · ${tr('common.price_mo',{price:fmt$(off.rate)})} · ${tr('ui.n_d_left',{n:off.exp-S.day})}${off.broker?' · '+tr('link_panels.via_a_capacity_broker'):''}
${btn(autoAcceptLabel(off),'accept',{id:off.id},'pink sm')}
`:fc>=1||pairFree(l)?`
${btn(tr('link_panels.list_it_with_a_capacity_broker'),'advertise',{id:l.id},'sm')}
`:`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`}`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; if(l.own&&l.sub)h+=subUpgradePanel(l); for(const k of Object.keys(OPT)){const O=OPT[k],n=(l.ch||[]).filter(x=>x===k).length,why=chWhy(l,k); @@ -93,7 +93,7 @@ function dfPanel(l){ } function offersHere(c){ const os=S.offers.filter(o=>bCities(o).includes(c));if(!os.length)return ''; - return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; + return `

${tr('common.offers_here')}

${os.map(o=>`
${esc(o.name)}
${esc(BIZ_T[o.type].l)}${o.city2?` ${CITY[o.city].name} ⇄ ${CITY[o.city2].name}`:''} · ${bTerms(o)} · ${tr('ui.n_d_left',{n:o.exp-S.day})}
${R.reach<0.99&&!BIZ_T[o.type].l2?`
${tr('link_panels.they_need_the_full_internet_your',{pct:pct(R.reach)})}
`:''}${o.type==='scrub'&&!hasScrub()?`
${tr('link_panels.needs_your_own_scrubbing_center')}
`:''}${reqList(o)}${bHas(o)?'':`
${tr('link_panels.needs_a_pop_in_cities_too',{cities:bCities(o).filter(x=>!S.pops[x]).map(x=>CITY[x].name).join(', ')})}
`}
${bHas(o)?btn(autoAcceptLabel(o),'accept',{id:o.id},'green sm'):''}${btn(tr('common.no'),'decline',{id:o.id},'ghost sm')}
`).join('')}
`; } function linkPanel(id){ const l=S.links.find(x=>x.id===id);if(!l){UI.sel=null;return '';} diff --git a/tests/automation.test.js b/tests/automation.test.js index b613873..5ae9473 100644 --- a/tests/automation.test.js +++ b/tests/automation.test.js @@ -44,14 +44,16 @@ test('Accept buttons share a real-time countdown in Deals, city offers and fiber assert.equal(dom.window.document.querySelectorAll('[data-auto-sales]').length, 0); ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); const counts = () => [...dom.window.document.querySelectorAll('[data-auto-sales]')]; - assert.ok(counts().length >= 2, 'Deals and the city panel both show it'); - assert.ok(counts().every(el => el.textContent === '(5)')); + const readyCounts = () => counts().filter(el => el.dataset.autoSales === 'ready'); + assert.ok(readyCounts().length >= 2, 'Deals and the city panel both show it'); + assert.ok(readyCounts().every(el => el.textContent === '(5)')); + assert.ok(counts().filter(el => el.dataset.autoSales === 'waiting').every(el => el.textContent === ''), 'unmet requirements have no countdown'); ev('testNow=2001;renderAutoCountdown()'); - assert.ok(counts().every(el => el.textContent === '(4)')); + assert.ok(readyCounts().every(el => el.textContent === '(4)')); ev('testNow=3000;UI.speed=8;renderAutoCountdown()'); - assert.ok(counts().every(el => el.textContent === '(3)')); + assert.ok(readyCounts().every(el => el.textContent === '(3)')); ev('UI.speed=0.5;renderAll();renderAutoCountdown()'); - assert.ok(counts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); + assert.ok(readyCounts().every(el => el.textContent === '(3)'), 'game speed and re-rendering leave the real-time clock alone'); assert.match(dom.window.document.querySelector('#leftBody [data-act="accept"]').textContent, /Accept \(3\)/); ev("ACT.buildPop({city:'ams'});S.links.push({id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:[],own:true,km:450,ready:0,cut:0,mo:1})"); offer(ev, 'broker', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 1, what: 'One wave' }); @@ -62,13 +64,55 @@ test('Accept buttons share a real-time countdown in Deals, city offers and fiber ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); assert.equal(ev("S.biz.some(b=>b.id==='ready')"), true); assert.equal(ev("S.offers.some(o=>o.id==='waiting')"), true, 'the countdown does not bypass requirements'); - assert.ok(counts().every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); + offer(ev, 'next-ready'); + ev('renderAll();renderAutoCountdown()'); + assert.ok(counts().filter(el => el.dataset.autoSales === 'next-ready').every(el => el.textContent === '(5)'), 'the next check starts a fresh countdown'); ev("ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); assert.equal(counts().length, 0); assert.deepEqual(errors, []); dom.window.close(); }); +test('only ready offers get a countdown, including after requirements or capacity change', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + offer(ev, 'needs-generator', { reqs: ['gen'] }); + offer(ev, 'too-big', { bw: 1000 }); + offer(ev, 'expired', { exp: 0 }); + ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});ACT.autoToggle({k:'autoSales'});renderAutoCountdown()"); + const count = id => dom.window.document.querySelector(`#leftBody [data-auto-sales="${id}"]`).textContent; + assert.equal(count('ready'), '(5)'); + assert.equal(count('needs-generator'), ''); + assert.equal(count('too-big'), ''); + assert.equal(count('expired'), ''); + ev('S.pops.fra.gen=true;after()'); + assert.equal(count('needs-generator'), '(5)', 'becoming eligible shows the timer'); + ev('S.pops.fra.gen=false;compute();renderAutoCountdown()'); + assert.equal(count('needs-generator'), '', 'a requirement becoming false hides it immediately'); + ev("S.offers.find(o=>o.id==='too-big').bw=2;after()"); + assert.equal(count('too-big'), '(5)', 'actions invalidate the capacity preview'); + ev('testNow=6000;automationTick(testNow);renderAutoCountdown()'); + assert.equal(ev("S.offers.some(o=>o.id==='needs-generator')"), true, 'acceptance checks requirements again'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('readiness trials are shared between views and are not repeated for every redraw', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + ev("window.testNow=1000;performance.now=()=>testNow;ACT.leftTab({t:'deals'});UI.sel={type:'city',id:'fra'};UI.tab='cust';window.originalAutoOffer=autoOffer;window.trials=0;window.autoOffer=o=>{trials++;return originalAutoOffer(o)};ACT.autoToggle({k:'autoSales'})"); + assert.equal(ev('trials'), 1); + ev('renderAll();compute();renderAll();renderAutoCountdown()'); + assert.equal(ev('trials'), 1, 'ordinary routing refreshes reuse the preview'); + ev('after()'); + assert.equal(ev('trials'), 2, 'a real action refreshes readiness'); + ev('window.autoOffer=originalAutoOffer'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + test('auto-accept leaves unready and expired offers alone without failure notifications', () => { const { ev, dom, errors } = load(); setup(ev); From 2f5a924d6af83781d3678ae7bb4323d023b1663d Mon Sep 17 00:00:00 2001 From: Charles Miller Date: Wed, 28 Oct 2026 09:51:37 +0000 Subject: [PATCH 11/13] Add bulk IX peering and PoP redundancy utilities --- CHANGELOG.md | 2 + site/i18n/es.js | 19 +++ site/i18n/fr.js | 19 +++ site/i18n/it.js | 19 +++ site/i18n/pt.js | 19 +++ src/game/70-rules/95-utilities.js | 15 +++ src/game/90-actions/88-utilities.js | 15 +++ src/game/90-actions/89-game-and-settings.js | 1 + src/game/93-ui/50-city-panel.js | 1 + src/game/93-ui/55-utilities.js | 19 +++ src/i18n/en.js | 19 +++ tests/utilities.test.js | 137 ++++++++++++++++++++ 12 files changed, 285 insertions(+) create mode 100644 src/game/70-rules/95-utilities.js create mode 100644 src/game/90-actions/88-utilities.js create mode 100644 src/game/93-ui/55-utilities.js create mode 100644 tests/utilities.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index fb42726..6cb683f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Utilities join route servers and request eligible peers across every joined IX, and install missing PoP redundancy hardware in one purchase. + ## [1.36.0] — 2026-10-28 - You can put a link on standby, so one of two links between the same cities sits idle as a backup (#122). It carries traffic only when the other links are full or down, so its capacity is never wasted, and the map draws it dashed while it waits. The routing metric still applies to every link between the two cities. diff --git a/site/i18n/es.js b/site/i18n/es.js index 0c9a6df..7235f4c 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"Tus clientes quieren todo internet. Abre la pestaña Tránsito y compra un puerto a un operador.", "tutorial.your_router_is_live_press_launch":"Tu router está activo. Pulsa «Lanzar banda ancha» para vender internet a la gente de tu ciudad.", "ui.n_d_left":"quedan {n} d", +"utilities.hardware_note":"Solo hardware: reparte los servicios entre ambas ubicaciones y comprueba enlaces diversos y la capacidad del router restante para una protección completa ante fallos.", +"utilities.install_missing":"Instalar el hardware que falta", +"utilities.ix_peering":"Peering IX en toda la red", +"utilities.join_route_servers":"Unirse a todos los route servers ({n})", +"utilities.kit_complete":"Todos los componentes del kit están instalados.", +"utilities.kit_cost":"Pago único: {cost} · Coste mensual adicional: {mo}", +"utilities.kit_installed":"Kit de redundancia instalado en {city}.", +"utilities.peer_counts":"{ready} elegibles · {existing} existentes · {blocked} no disponibles", +"utilities.peering_note":"Solicita peers elegibles en cada IX al que te hayas unido. Se omiten las sesiones existentes, incluidos los peers del route server. Los rechazos y umbrales de tráfico siguen vigentes. No se compran puertos ni PNI de pago.", +"utilities.peers_requested":"Se han establecido {n} nuevas sesiones de peering IX.", +"utilities.quote_changed":"El presupuesto ha cambiado. Revisa el nuevo precio e inténtalo de nuevo.", +"utilities.redundancy_kit":"Kit de redundancia del POP", +"utilities.request_all":"Solicitar todos los peers elegibles ({n})", +"utilities.route_server_note":"Los peers de los route servers requieren una política de peering abierta. Las sesiones existentes siguen activas; no se compran puertos.", +"utilities.route_servers_joined":"Te has unido a {n} route servers.", +"utilities.second_site":"Segunda ubicación", +"utilities.title":"Utilidades", +"utilities.two_routers":"Al menos dos routers", +"utilities.view_pop":"Ver POP", }; diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 05ae35c..d4b87c0 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"Tes clients veulent tout Internet. Ouvre l’onglet Transit et achète un port chez un opérateur.", "tutorial.your_router_is_live_press_launch":"Ton routeur est en ligne. Appuie sur « Lancer le haut débit » pour vendre Internet aux habitants de ta ville.", "ui.n_d_left":"encore {n} j", +"utilities.hardware_note":"Matériel uniquement : répartis les services entre les deux sites et vérifie la diversité des liaisons et la capacité du routeur restant pour une protection complète contre les pannes.", +"utilities.install_missing":"Installer le matériel manquant", +"utilities.ix_peering":"Peering IX sur tout le réseau", +"utilities.join_route_servers":"Rejoindre tous les route servers ({n})", +"utilities.kit_complete":"Tous les composants du kit sont installés.", +"utilities.kit_cost":"Coût initial : {cost} · Coût mensuel supplémentaire : {mo}", +"utilities.kit_installed":"Kit de redondance installé à {city}.", +"utilities.peer_counts":"{ready} éligibles · {existing} existants · {blocked} indisponibles", +"utilities.peering_note":"Demande les peers éligibles sur chaque IX rejoint. Les sessions existantes, y compris via le route server, sont ignorées. Les refus et seuils de trafic restent applicables. Aucun port ni PNI payant ne sera acheté.", +"utilities.peers_requested":"{n} nouvelles sessions de peering IX établies.", +"utilities.quote_changed":"Le devis a changé. Vérifie le nouveau prix et réessaie.", +"utilities.redundancy_kit":"Kit de redondance du POP", +"utilities.request_all":"Demander tous les peers éligibles ({n})", +"utilities.route_server_note":"Les peers des route servers nécessitent une politique de peering ouverte. Les sessions existantes restent activées ; aucun port ne sera acheté.", +"utilities.route_servers_joined":"{n} route servers rejoints.", +"utilities.second_site":"Deuxième site", +"utilities.title":"Utilitaires", +"utilities.two_routers":"Au moins deux routeurs", +"utilities.view_pop":"Voir le POP", }; diff --git a/site/i18n/it.js b/site/i18n/it.js index 92ca041..c6beb8c 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"I tuoi clienti vogliono tutta internet. Apri la scheda Transit e compra una porta da un carrier.", "tutorial.your_router_is_live_press_launch":"Il tuo router è acceso. Premi “Lancia la banda larga” per vendere internet alla gente della tua città.", "ui.n_d_left":"ancora {n}g", +"utilities.hardware_note":"Solo hardware: distribuisci i servizi tra le due sedi e verifica percorsi diversi e capacità del router superstite per una protezione completa dai guasti.", +"utilities.install_missing":"Installa l’hardware mancante", +"utilities.ix_peering":"Peering IX su tutta la rete", +"utilities.join_route_servers":"Unisciti a tutti i route server ({n})", +"utilities.kit_complete":"Tutti i componenti del kit sono installati.", +"utilities.kit_cost":"Una tantum: {cost} · Costo mensile aggiuntivo: {mo}", +"utilities.kit_installed":"Kit di ridondanza installato a {city}.", +"utilities.peer_counts":"{ready} idonei · {existing} esistenti · {blocked} non disponibili", +"utilities.peering_note":"Richiedi i peer idonei in ogni IX a cui partecipi. Le sessioni esistenti, inclusi i peer del route server, vengono saltate. Rifiuti e soglie di traffico restano validi. Non vengono acquistate porte o PNI a pagamento.", +"utilities.peers_requested":"Stabilite {n} nuove sessioni di peering IX.", +"utilities.quote_changed":"Il preventivo è cambiato. Controlla il nuovo prezzo e riprova.", +"utilities.redundancy_kit":"Kit di ridondanza del POP", +"utilities.request_all":"Richiedi tutti i peer idonei ({n})", +"utilities.route_server_note":"I peer dei route server richiedono una politica di peering aperta. Le sessioni esistenti restano attive; non vengono acquistate porte.", +"utilities.route_servers_joined":"Collegati {n} route server.", +"utilities.second_site":"Seconda sede", +"utilities.title":"Utilità", +"utilities.two_routers":"Almeno due router", +"utilities.view_pop":"Mostra POP", }; diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 6e219ea..cb05f6d 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3064,4 +3064,23 @@ "tutorial.your_customers_want_the_whole":"Seus clientes querem a internet inteira. Abra a aba Transit e compre uma porta de uma operadora.", "tutorial.your_router_is_live_press_launch":"Seu router está no ar. Aperte “Lançar banda larga” para vender internet ao pessoal da sua cidade.", "ui.n_d_left":"faltam {n}d", +"utilities.hardware_note":"Apenas hardware: distribui os serviços pelos dois locais e verifica ligações diversas e capacidade do router restante para proteção completa contra falhas.", +"utilities.install_missing":"Instalar hardware em falta", +"utilities.ix_peering":"Peering IX em toda a rede", +"utilities.join_route_servers":"Aderir a todos os route servers ({n})", +"utilities.kit_complete":"Todos os componentes do kit estão instalados.", +"utilities.kit_cost":"Custo único: {cost} · Custo mensal adicional: {mo}", +"utilities.kit_installed":"Kit de redundância instalado em {city}.", +"utilities.peer_counts":"{ready} elegíveis · {existing} existentes · {blocked} indisponíveis", +"utilities.peering_note":"Solicita peers elegíveis em todos os IX a que aderiste. As sessões existentes, incluindo peers do route server, são ignoradas. Recusas e limites de tráfego continuam a aplicar-se. Não são compradas portas nem PNI pagos.", +"utilities.peers_requested":"Estabelecidas {n} novas sessões de peering IX.", +"utilities.quote_changed":"O orçamento mudou. Verifica o novo preço e tenta novamente.", +"utilities.redundancy_kit":"Kit de redundância do POP", +"utilities.request_all":"Solicitar todos os peers elegíveis ({n})", +"utilities.route_server_note":"Os peers dos route servers exigem uma política de peering aberta. As sessões existentes continuam ativas; não são compradas portas.", +"utilities.route_servers_joined":"Adesão a {n} route servers concluída.", +"utilities.second_site":"Segundo local", +"utilities.title":"Utilitários", +"utilities.two_routers":"Pelo menos dois routers", +"utilities.view_pop":"Ver POP", }; diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js new file mode 100644 index 0000000..3d99f22 --- /dev/null +++ b/src/game/70-rules/95-utilities.js @@ -0,0 +1,15 @@ +/* Utilities: plan from live state, then apply a whole batch with one recompute. */ +function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} +function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; + const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; + return {gen,site,router,cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), + mo:(gen?GEN_MO:0)+(site?SITE2_MO:0)+(router?routerMo(g):0)};} +function utilityPeers(){if(!S)return [];return Object.keys(S.ixp).filter(isIx).map(ix=>{ + const sessions=ixSessions(ix),requests=[],blocked=[];let existing=0; + for(const id of ixMembers(ix)){ + // Existing but temporarily down sessions must not be repeatedly requested. + if(sessions.has(id)||S.peers[id+'@'+ix]){existing++;continue;} + const chk=peerOk(id,'ix',ix);if(chk.ok)requests.push(id);else blocked.push({id,why:chk.why}); + } + return {ix,requests,blocked,existing}; +});} diff --git a/src/game/90-actions/88-utilities.js b/src/game/90-actions/88-utilities.js new file mode 100644 index 0000000..05b6615 --- /dev/null +++ b/src/game/90-actions/88-utilities.js @@ -0,0 +1,15 @@ +Object.assign(ACT,{ + utilities:({city}={})=>{if(S)utilitiesModal(city);}, + utilityPick:()=>{if(S&&$('utilityCity'))utilitiesModal($('utilityCity').value);}, + utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true; + if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));}, + utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||!q.cost)return; + // Prices can change while a modal is open. Refresh the quote before spending more. + if(q.cost!==+cost){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} + if(!spend(q.cost))return;const p=S.pops[city]; + if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2; + after();const msg=tr('utilities.kit_installed',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + utilityPeers:({city}={})=>{if(!S)return;const rows=utilityPeers();let n=0; + for(const row of rows)for(const id of row.requests){S.peers[id+'@'+row.ix]=true;n++;} + if(n){sfx('build');after();}utilitiesModal(city,tr('utilities.peers_requested',{n}));}, +}); diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 3ec2894..4774cf6 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -23,6 +23,7 @@ Object.assign(ACT,{ ${btn(tr('game_and_settings.scenarios_amp_weekly_challenge'),'scenarios',{},'ghost')} ${btn(tr('common.how_to_play'),'help',{},'ghost')} ${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''} + ${btn(tr('utilities.title'),'utilities',{},'')} ${btn(tr('common.settings'),'settings',{},'ghost')} ${btn(tr('common.start_a_new_network'),'resetAsk',{},'red')} ${chatHtml()}${issueHtml()}`);}, diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index 853d518..71360d8 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -67,6 +67,7 @@ function cityPanel(c){ ${have.length?btn(tr('common.remove'),'rmCache',{id:(have.find(x=>x.site==='b')||have[0]).id},'ghost sm'):''}${btn(have.length?tr('common.box'):tr('common.request'),'cache',{city:c,net:n.id},'sm',!ok)}${S.pops[c].site2&&have.length?(()=>{const nb=have.filter(x=>x.site==='b').length,na=have.length-nb;return `
${tr('city_panel.boxes_a_in_a_b_in',{a:na,b:nb})}${na?btn(tr('city_panel.move_one_to_b'),'cacheSite',{city:c,net:n.id,s:'b'},'ghost sm'):''}${nb?btn(tr('city_panel.move_one_to_a'),'cacheSite',{city:c,net:n.id,s:'a'},'ghost sm'):''}
`;})():''}`;} h+=`
`; }else{ + h+=utilityKitHtml(c); const ls=S.links.filter(l=>l.a===c||l.b===c); const rt=p.routers||1,g=p.rgen||0,G=RG[g],nl=R.nodeLoad[c]||0,nc=R.nodeCap[c]||nodeCap(c),Ni=g===mainRG(G.cls)?mainRG(G.cls+1):-1,N=Ni>=0?RG[Ni]:null,pu=portsUsed(c),pm=portsMax(c); h+=`

${tr('common.routers')}

${tr('city_panel.the_model_sets_your_fastest')}

diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js new file mode 100644 index 0000000..3ed1e15 --- /dev/null +++ b/src/game/93-ui/55-utilities.js @@ -0,0 +1,19 @@ +function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return '';const p=S.pops[city]; + const row=(label,have)=>`
${label}${have?tr('common.installed'):tr('common.none_304f')}
`; + return `

${tr('utilities.redundancy_kit')}

+ ${row(tr('common.backup_generator'),p.gen)}${row(tr('utilities.second_site'),p.site2)}${row(tr('utilities.two_routers'),(p.routers||1)>=2)} + ${q.cost?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.install_missing'),'utilityKit',{city,cost:q.cost,modal},'pink',S.cash`:`

${tr('utilities.kit_complete')}

`} +

${tr('utilities.hardware_note')}

`;} +function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); + city=S.pops[city]?city:UI.sel&&UI.sel.type==='city'&&S.pops[UI.sel.id]?UI.sel.id:S.pops[S.home]?S.home:cities[0]; + const rows=utilityPeers(),n=rows.reduce((v,r)=>v+r.requests.length,0),rs=utilityRouteServers().length; + openModal(`

${tr('utilities.title')}

+ ${message?`

${esc(message)}

`:''} +

${tr('utilities.ix_peering')}

${tr('utilities.peering_note')}

+
${btn(tr('utilities.join_route_servers',{n:rs}),'utilityRouteServers',{city},'pink',!rs)}${btn(tr('utilities.request_all',{n}),'utilityPeers',{city},'',!n)}
+

${tr('utilities.route_server_note')}

+ ${ppol()!=='open'?`

${tr('link_panels.off_while_your_peering_policy_is',{pol:tr(PPOL_N[ppol()])})}

${btn(tr('common.peering_policy'),'inbox',{},'ghost sm')}`:''} + ${rows.map(r=>`
${esc(ixName(r.ix))} · ${tr('utilities.peer_counts',{ready:r.requests.length,existing:r.existing,blocked:r.blocked.length})} + ${r.blocked.map(b=>`

${esc(NET[b.id].name)}: ${esc(b.why)}

`).join('')}
`).join('')}
+ ${cities.length?`
${btn(tr('utilities.view_pop'),'utilityPick',{},'sm')}
${utilityKitHtml(city,true)}`:''}`); +} diff --git a/src/i18n/en.js b/src/i18n/en.js index b8fd360..c25a5c2 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3065,4 +3065,23 @@ "tutorial.your_customers_want_the_whole":"Your customers want the whole internet. Open the Transit tab and buy a port from a carrier.", "tutorial.your_router_is_live_press_launch":"Your router is live. Press “Launch broadband” to sell internet to the people of your city.", "ui.n_d_left":"{n}d left", +"utilities.hardware_note":"Hardware only: assign services across both sites and check diverse links and surviving router capacity for full failover protection.", +"utilities.install_missing":"Install missing hardware", +"utilities.ix_peering":"Network-wide IX peering", +"utilities.join_route_servers":"Join all route servers ({n})", +"utilities.kit_complete":"All kit components are installed.", +"utilities.kit_cost":"One-off: {cost} · Additional monthly cost: {mo}", +"utilities.kit_installed":"Redundancy kit installed in {city}.", +"utilities.peer_counts":"{ready} eligible · {existing} existing · {blocked} unavailable", +"utilities.peering_note":"Request eligible peers at every IX you have joined. Existing sessions, including route-server peers, are skipped. Refusals and traffic thresholds still apply. No ports or paid PNIs are purchased.", +"utilities.peers_requested":"Established {n} new IX peering sessions.", +"utilities.quote_changed":"The quote changed. Review the new price and try again.", +"utilities.redundancy_kit":"PoP redundancy kit", +"utilities.request_all":"Request all eligible peers ({n})", +"utilities.route_server_note":"Route-server peers require an Open peering policy. Existing sessions stay enabled; no ports are bought.", +"utilities.route_servers_joined":"Joined {n} route servers.", +"utilities.second_site":"Second site", +"utilities.title":"Utilities", +"utilities.two_routers":"At least two routers", +"utilities.view_pop":"View PoP", }; diff --git a/tests/utilities.test.js b/tests/utilities.test.js new file mode 100644 index 0000000..1e86ee5 --- /dev/null +++ b/tests/utilities.test.js @@ -0,0 +1,137 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;UI.speed=0;compute()"); + return h; +} + +test('redundancy kit matches normal purchases, including cash, monthly costs and save reload', t => { + const a = setup(t), b = setup(t); + const quote = JSON.parse(a.ev("JSON.stringify(utilityKit('fra'))")); + const cash = a.ev('S.cash'), monthly = a.ev('R.costMo'); + a.ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + b.ev("ACT.addGen({city:'fra'});ACT.addSite({city:'fra'});ACT.addRouter({city:'fra'})"); + for (const expr of ['S.pops.fra', 'R.cost']) + assert.deepEqual(JSON.parse(a.ev(`JSON.stringify(${expr})`)), JSON.parse(b.ev(`JSON.stringify(${expr})`))); + assert.equal(a.ev('S.cash'), cash - quote.cost); + assert.equal(a.ev('S.cash'), b.ev('S.cash')); + assert.equal(a.ev('R.costMo'), monthly + quote.mo); + const before = a.ev('JSON.stringify(S)'); + a.ev("ACT.utilityKit({city:'fra',cost:0})"); + assert.equal(a.ev('JSON.stringify(S)'), before, 'repeat does not buy more hardware'); + a.ev("save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()"); + assert.equal(a.ev('S.pops.fra.gen && S.pops.fra.site2 && S.pops.fra.routers===2'), true); + assert.deepEqual(a.errors, []); + assert.deepEqual(b.errors, []); +}); + +test('kit is all-or-nothing, rejects stale quotes and handles missing PoPs', t => { + const { ev, errors } = setup(t); + ev("window.quote=utilityKit('fra').cost;S.cash=quote-1"); + const before = ev('JSON.stringify(S.pops.fra)'); + ev("ACT.utilityKit({city:'fra',cost:quote})"); + assert.equal(ev('JSON.stringify(S.pops.fra)'), before); + assert.equal(ev('S.cash'), ev('quote-1')); + ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+1,modal:true})"); + assert.equal(ev('JSON.stringify(S.pops.fra)'), before); + assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/); + ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})"); + assert.deepEqual(errors, []); +}); + +test('kit buys only missing components and preserves extra routers and service placement', t => { + const { ev, errors } = setup(t); + ev("S.pops.fra.routers=4;S.pops.fra.gen=true;S.pops.fra.rgen=3;S.transit.push({id:'test',city:'fra',net:'cog',tier:0,site:'a'});compute()"); + const cash = ev('S.cash'); + assert.equal(ev("utilityKit('fra').cost"), ev('SITE2_COST')); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + assert.equal(ev('S.cash'), cash - ev('SITE2_COST')); + assert.equal(ev('S.pops.fra.routers'), 4); + assert.equal(ev('S.pops.fra.rgen'), 3); + assert.equal(ev('S.transit[0].site'), 'a'); + assert.deepEqual(errors, []); +}); + +test('bulk peering covers rival IXs, respects policy and is idempotent', t => { + const { ev, errors } = setup(t); + ev("ACT.buildPop({city:'ams'});ACT.buyIx({city:'fra',tier:0,signed:true});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});ACT.rs({city:'ams'});compute()"); + const expected = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.requests.map(id=>id+'@'+r.ix)))")); + assert.ok(expected.length > 0); + assert.ok(expected.some(k => k.endsWith('@ams~3'))); + const blocked = JSON.parse(ev("JSON.stringify(utilityPeers().flatMap(r=>r.blocked.map(b=>b.id+'@'+r.ix)))")); + assert.ok(blocked.length > 0); + const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), pnis = ev('JSON.stringify(S.pni)'); + ev('ACT.utilityPeers()'); + for (const k of expected) assert.equal(ev(`S.peers[${JSON.stringify(k)}]`), true, k); + for (const k of blocked) assert.equal(ev(`!!S.peers[${JSON.stringify(k)}]`), false, k); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('JSON.stringify(S.ixp)'), ports); + assert.equal(ev('JSON.stringify(S.pni)'), pnis); + const peers = ev('JSON.stringify(S.peers)'); + ev('ACT.utilityPeers()'); + assert.equal(ev('JSON.stringify(S.peers)'), peers); + assert.equal(ev('utilityPeers().reduce((n,r)=>n+r.requests.length,0)'), 0); + assert.deepEqual(errors, []); +}); + +test('bulk peering skips disconnected IXs, route server coverage and existing down sessions', t => { + const { ev, errors } = setup(t); + assert.equal(ev('utilityPeers().length'), 0); + ev("ACT.utilityPeers();ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});S.peers['ggl@fra']=true;compute()"); + assert.equal(ev("utilityPeers()[0].requests.includes('drz')"), false); + assert.equal(ev("utilityPeers()[0].requests.includes('ggl')"), false); + ev("ACT.cancelIx({city:'fra',sure:1,ok:1});ACT.utilityPeers()"); + assert.equal(ev('utilityPeers().length'), 0); + assert.deepEqual(errors, []); +}); + +test('utilities are available from the menu and PoP Infra in every language', t => { + for (const lang of ['en', 'it', 'pt', 'fr', 'es']) { + const { ev, dom, errors } = setup(t, lang === 'en' ? {} : { lang }); + ev('ACT.menu()'); + assert.ok(dom.window.document.querySelector('[data-act="utilities"]'), lang); + ev("selectCity('fra');ACT.tab({t:'links'})"); + assert.ok(dom.window.document.querySelector('#panelBody [data-act="utilityKit"]'), lang); + ev('ACT.utilities()'); + assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra'); + assert.ok(!dom.window.document.querySelector('#modalCard').textContent.includes('utilities.'), lang); + assert.deepEqual(errors, [], lang); + } +}); + +test('join all route servers preserves existing sessions and covers rival and remote IX ports', t => { + const { ev, errors } = setup(t); + ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'});window.fabric=FABS.find(f=>f.cities.includes('fra')&&f.cities.includes('ams')).id;S.links.push({id:'remote',a:'fra',b:'ams',kind:'vxc',prov:fabric,vt:1,km:kmBetween('fra','ams'),sub:false,mo:0,cut:0,day:S.day});ACT.buyIx({city:'ams',tier:0});ACT.buyIx({city:'ams~3',tier:0});compute()"); + assert.equal(ev("isRemote('ams')"), true); + assert.deepEqual(JSON.parse(ev('JSON.stringify(utilityRouteServers().sort())')), ['ams', 'ams~3']); + const cash = ev('S.cash'), ports = ev('JSON.stringify(S.ixp)'), peers = ev('JSON.stringify(S.peers)'); + ev('ACT.utilityRouteServers()'); + assert.equal(ev("S.rs.fra && S.rs.ams && S.rs['ams~3']"), true); + assert.equal(ev("ixSessions('ams').has('drz')"), true); + assert.equal(ev('S.cash'), cash); + assert.equal(ev('JSON.stringify(S.ixp)'), ports); + assert.equal(ev('JSON.stringify(S.peers)'), peers); + const rs = ev('JSON.stringify(S.rs)'); + ev('ACT.utilityRouteServers()'); + assert.equal(ev('JSON.stringify(S.rs)'), rs, 'repeat never toggles a session off'); + assert.equal(ev('utilityRouteServers().length'), 0); + assert.deepEqual(errors, []); +}); + +test('route-server batch leaves peering policy and player-owned exchanges alone', t => { + const { ev, errors } = setup(t); + ev('ACT.utilityRouteServers()'); + assert.equal(ev('Object.keys(S.rs).length'), 0, 'does not join an IX without a port'); + ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.inboxPol({p:'closed'});ACT.utilityRouteServers()"); + assert.equal(ev('ppol()'), 'closed'); + assert.equal(ev('S.rs.fra'), true); + assert.equal(ev("ixSessions('fra').has('drz')"), false, 'does not bypass closed policy'); + assert.match(ev("document.getElementById('modalCard').textContent"), /Off while your peering policy/); + ev("S.myIx.fra={members:[],fab:0};S.rs.fra=false;ACT.utilityRouteServers()"); + assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control'); + assert.deepEqual(errors, []); +}); From 0f1db884c22beca0b7dfe44015e49d2f021a6a71 Mon Sep 17 00:00:00 2001 From: Charles Miller Date: Wed, 28 Oct 2026 10:51:54 +0000 Subject: [PATCH 12/13] Balance PoP caches and request missing caches per site --- CHANGELOG.md | 2 +- site/i18n/es.js | 14 +++- site/i18n/fr.js | 14 +++- site/i18n/it.js | 14 +++- site/i18n/pt.js | 14 +++- src/game/70-rules/95-utilities.js | 11 ++- src/game/90-actions/88-utilities.js | 12 ++- src/game/93-ui/55-utilities.js | 10 ++- src/i18n/en.js | 14 +++- tests/utilities-caches.test.js | 109 ++++++++++++++++++++++++++++ 10 files changed, 187 insertions(+), 27 deletions(-) create mode 100644 tests/utilities-caches.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cb683f..8f40c93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- Utilities join route servers and request eligible peers across every joined IX, and install missing PoP redundancy hardware in one purchase. +- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. ## [1.36.0] — 2026-10-28 diff --git a/site/i18n/es.js b/site/i18n/es.js index 7235f4c..c94e3b2 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"Tus clientes quieren todo internet. Abre la pestaña Tránsito y compra un puerto a un operador.", "tutorial.your_router_is_live_press_launch":"Tu router está activo. Pulsa «Lanzar banda ancha» para vender internet a la gente de tu ciudad.", "ui.n_d_left":"quedan {n} d", -"utilities.hardware_note":"Solo hardware: reparte los servicios entre ambas ubicaciones y comprueba enlaces diversos y la capacidad del router restante para una protección completa ante fallos.", -"utilities.install_missing":"Instalar el hardware que falta", +"utilities.apply_kit":"Aplicar kit de redundancia", +"utilities.cache_moves":"Cachés que mover: {n} (equilibradas por proveedor)", +"utilities.cache_note":"Solicita una caché por proveedor elegible en cada ubicación existente. Se conservan las cachés actuales; los proveedores siguen exigiendo tráfico suficiente.", +"utilities.cache_ports":"Se necesitan {need} puertos libres de router; disponibles: {free}. No se solicita nada hasta que haya espacio para todas.", +"utilities.cache_quote":"{n} cachés nuevas · Hardware gratuito · Coste mensual adicional: {mo}", +"utilities.caches_requested":"Se han instalado {n} cachés en {city}.", "utilities.ix_peering":"Peering IX en toda la red", "utilities.join_route_servers":"Unirse a todos los route servers ({n})", -"utilities.kit_complete":"Todos los componentes del kit están instalados.", +"utilities.kit_applied":"Redundancia actualizada en {city}.", +"utilities.kit_balanced":"Hardware instalado y cachés equilibradas.", "utilities.kit_cost":"Pago único: {cost} · Coste mensual adicional: {mo}", -"utilities.kit_installed":"Kit de redundancia instalado en {city}.", "utilities.peer_counts":"{ready} elegibles · {existing} existentes · {blocked} no disponibles", "utilities.peering_note":"Solicita peers elegibles en cada IX al que te hayas unido. Se omiten las sesiones existentes, incluidos los peers del route server. Los rechazos y umbrales de tráfico siguen vigentes. No se compran puertos ni PNI de pago.", "utilities.peers_requested":"Se han establecido {n} nuevas sesiones de peering IX.", "utilities.quote_changed":"El presupuesto ha cambiado. Revisa el nuevo precio e inténtalo de nuevo.", "utilities.redundancy_kit":"Kit de redundancia del POP", +"utilities.redundancy_note":"Las cachés existentes se equilibran por proveedor. Reparte por separado las conexiones IX, PNI y transit entre ubicaciones y comprueba enlaces diversos y capacidad de reserva de los routers.", "utilities.request_all":"Solicitar todos los peers elegibles ({n})", +"utilities.request_caches":"Solicitar las cachés que faltan ({n})", "utilities.route_server_note":"Los peers de los route servers requieren una política de peering abierta. Las sesiones existentes siguen activas; no se compran puertos.", "utilities.route_servers_joined":"Te has unido a {n} route servers.", "utilities.second_site":"Segunda ubicación", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index d4b87c0..8410879 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"Tes clients veulent tout Internet. Ouvre l’onglet Transit et achète un port chez un opérateur.", "tutorial.your_router_is_live_press_launch":"Ton routeur est en ligne. Appuie sur « Lancer le haut débit » pour vendre Internet aux habitants de ta ville.", "ui.n_d_left":"encore {n} j", -"utilities.hardware_note":"Matériel uniquement : répartis les services entre les deux sites et vérifie la diversité des liaisons et la capacité du routeur restant pour une protection complète contre les pannes.", -"utilities.install_missing":"Installer le matériel manquant", +"utilities.apply_kit":"Appliquer le kit de redondance", +"utilities.cache_moves":"Caches à déplacer : {n} (équilibrés par fournisseur)", +"utilities.cache_note":"Demande un cache par fournisseur éligible sur chaque site existant. Les caches existants sont conservés ; les fournisseurs exigent toujours un trafic suffisant.", +"utilities.cache_ports":"Il faut {need} ports de routeur libres ; {free} disponibles. Aucune demande tant que tous les caches ne peuvent pas être installés.", +"utilities.cache_quote":"{n} nouveaux caches · Matériel gratuit · Coût mensuel supplémentaire : {mo}", +"utilities.caches_requested":"{n} caches installés à {city}.", "utilities.ix_peering":"Peering IX sur tout le réseau", "utilities.join_route_servers":"Rejoindre tous les route servers ({n})", -"utilities.kit_complete":"Tous les composants du kit sont installés.", +"utilities.kit_applied":"Redondance mise à jour à {city}.", +"utilities.kit_balanced":"Matériel installé et caches équilibrés.", "utilities.kit_cost":"Coût initial : {cost} · Coût mensuel supplémentaire : {mo}", -"utilities.kit_installed":"Kit de redondance installé à {city}.", "utilities.peer_counts":"{ready} éligibles · {existing} existants · {blocked} indisponibles", "utilities.peering_note":"Demande les peers éligibles sur chaque IX rejoint. Les sessions existantes, y compris via le route server, sont ignorées. Les refus et seuils de trafic restent applicables. Aucun port ni PNI payant ne sera acheté.", "utilities.peers_requested":"{n} nouvelles sessions de peering IX établies.", "utilities.quote_changed":"Le devis a changé. Vérifie le nouveau prix et réessaie.", "utilities.redundancy_kit":"Kit de redondance du POP", +"utilities.redundancy_note":"Les caches existants sont équilibrés par fournisseur. Répartis séparément les connexions IX, PNI et transit entre les sites et vérifie la diversité des liaisons et la capacité de réserve des routeurs.", "utilities.request_all":"Demander tous les peers éligibles ({n})", +"utilities.request_caches":"Demander les caches manquants ({n})", "utilities.route_server_note":"Les peers des route servers nécessitent une politique de peering ouverte. Les sessions existantes restent activées ; aucun port ne sera acheté.", "utilities.route_servers_joined":"{n} route servers rejoints.", "utilities.second_site":"Deuxième site", diff --git a/site/i18n/it.js b/site/i18n/it.js index c6beb8c..6121288 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"I tuoi clienti vogliono tutta internet. Apri la scheda Transit e compra una porta da un carrier.", "tutorial.your_router_is_live_press_launch":"Il tuo router è acceso. Premi “Lancia la banda larga” per vendere internet alla gente della tua città.", "ui.n_d_left":"ancora {n}g", -"utilities.hardware_note":"Solo hardware: distribuisci i servizi tra le due sedi e verifica percorsi diversi e capacità del router superstite per una protezione completa dai guasti.", -"utilities.install_missing":"Installa l’hardware mancante", +"utilities.apply_kit":"Applica il kit di ridondanza", +"utilities.cache_moves":"Cache da spostare: {n} (bilanciate per fornitore)", +"utilities.cache_note":"Richiedi una cache per ogni fornitore idoneo in ciascuna sede esistente. Le cache esistenti restano; i fornitori richiedono comunque traffico sufficiente.", +"utilities.cache_ports":"Servono {need} porte router libere; disponibili: {free}. Nessuna richiesta finché non ci sarà spazio per tutte le cache.", +"utilities.cache_quote":"{n} nuove cache · Hardware gratuito · Costo mensile aggiuntivo: {mo}", +"utilities.caches_requested":"Installate {n} cache a {city}.", "utilities.ix_peering":"Peering IX su tutta la rete", "utilities.join_route_servers":"Unisciti a tutti i route server ({n})", -"utilities.kit_complete":"Tutti i componenti del kit sono installati.", +"utilities.kit_applied":"Ridondanza aggiornata a {city}.", +"utilities.kit_balanced":"Hardware installato e cache bilanciate.", "utilities.kit_cost":"Una tantum: {cost} · Costo mensile aggiuntivo: {mo}", -"utilities.kit_installed":"Kit di ridondanza installato a {city}.", "utilities.peer_counts":"{ready} idonei · {existing} esistenti · {blocked} non disponibili", "utilities.peering_note":"Richiedi i peer idonei in ogni IX a cui partecipi. Le sessioni esistenti, inclusi i peer del route server, vengono saltate. Rifiuti e soglie di traffico restano validi. Non vengono acquistate porte o PNI a pagamento.", "utilities.peers_requested":"Stabilite {n} nuove sessioni di peering IX.", "utilities.quote_changed":"Il preventivo è cambiato. Controlla il nuovo prezzo e riprova.", "utilities.redundancy_kit":"Kit di ridondanza del POP", +"utilities.redundancy_note":"Le cache esistenti vengono bilanciate per fornitore. Distribuisci separatamente le connessioni IX, PNI e transit tra le sedi e verifica percorsi diversi e capacità di riserva dei router.", "utilities.request_all":"Richiedi tutti i peer idonei ({n})", +"utilities.request_caches":"Richiedi le cache mancanti ({n})", "utilities.route_server_note":"I peer dei route server richiedono una politica di peering aperta. Le sessioni esistenti restano attive; non vengono acquistate porte.", "utilities.route_servers_joined":"Collegati {n} route server.", "utilities.second_site":"Seconda sede", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index cb05f6d..f9407d4 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3064,19 +3064,25 @@ "tutorial.your_customers_want_the_whole":"Seus clientes querem a internet inteira. Abra a aba Transit e compre uma porta de uma operadora.", "tutorial.your_router_is_live_press_launch":"Seu router está no ar. Aperte “Lançar banda larga” para vender internet ao pessoal da sua cidade.", "ui.n_d_left":"faltam {n}d", -"utilities.hardware_note":"Apenas hardware: distribui os serviços pelos dois locais e verifica ligações diversas e capacidade do router restante para proteção completa contra falhas.", -"utilities.install_missing":"Instalar hardware em falta", +"utilities.apply_kit":"Aplicar kit de redundância", +"utilities.cache_moves":"Caches a mover: {n} (equilibradas por fornecedor)", +"utilities.cache_note":"Solicita uma cache por fornecedor elegível em cada local existente. As caches existentes são mantidas; os fornecedores continuam a exigir tráfego suficiente.", +"utilities.cache_ports":"São necessárias {need} portas livres no router; disponíveis: {free}. Nada é solicitado até haver espaço para todas.", +"utilities.cache_quote":"{n} novas caches · Hardware gratuito · Custo mensal adicional: {mo}", +"utilities.caches_requested":"Instaladas {n} caches em {city}.", "utilities.ix_peering":"Peering IX em toda a rede", "utilities.join_route_servers":"Aderir a todos os route servers ({n})", -"utilities.kit_complete":"Todos os componentes do kit estão instalados.", +"utilities.kit_applied":"Redundância atualizada em {city}.", +"utilities.kit_balanced":"Hardware instalado e caches equilibradas.", "utilities.kit_cost":"Custo único: {cost} · Custo mensal adicional: {mo}", -"utilities.kit_installed":"Kit de redundância instalado em {city}.", "utilities.peer_counts":"{ready} elegíveis · {existing} existentes · {blocked} indisponíveis", "utilities.peering_note":"Solicita peers elegíveis em todos os IX a que aderiste. As sessões existentes, incluindo peers do route server, são ignoradas. Recusas e limites de tráfego continuam a aplicar-se. Não são compradas portas nem PNI pagos.", "utilities.peers_requested":"Estabelecidas {n} novas sessões de peering IX.", "utilities.quote_changed":"O orçamento mudou. Verifica o novo preço e tenta novamente.", "utilities.redundancy_kit":"Kit de redundância do POP", +"utilities.redundancy_note":"As caches existentes são equilibradas por fornecedor. Distribui separadamente as ligações IX, PNI e transit pelos locais e verifica ligações diversas e capacidade de reserva dos routers.", "utilities.request_all":"Solicitar todos os peers elegíveis ({n})", +"utilities.request_caches":"Solicitar caches em falta ({n})", "utilities.route_server_note":"Os peers dos route servers exigem uma política de peering aberta. As sessões existentes continuam ativas; não são compradas portas.", "utilities.route_servers_joined":"Adesão a {n} route servers concluída.", "utilities.second_site":"Segundo local", diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index 3d99f22..646f760 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -1,8 +1,17 @@ /* Utilities: plan from live state, then apply a whole batch with one recompute. */ function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} +function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new Map(),moves=[]; + for(const c of S.caches)if(c.city===city){let g=groups.get(c.net);if(!g){g={a:[],b:[]};groups.set(c.net,g);}g[c.site==='b'?'b':'a'].push(c);} + for(const g of groups.values()){const from=g.a.length>g.b.length?'a':'b',to=from==='a'?'b':'a'; + for(const c of g[from].slice(0,Math.floor(Math.abs(g.a.length-g.b.length)/2)))moves.push({id:c.id,site:to});} + return moves;} +function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have=new Set(); + for(const c of S.caches)if(c.city===city)have.add(c.net+'@'+(c.site==='b'?'b':'a')); + for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min)for(const site of sites)if(!have.has(n.id+'@'+site))add.push({net:n.id,site}); + return {add,key:add.map(c=>c.net+'@'+c.site).join(','),mo:add.length*CACHE_MO,free:Math.max(0,portsMax(city)-portsUsed(city))};} function utilityKit(city){const p=S&&S.pops[city];if(!p)return null; const gen=!p.gen,site=!p.site2,router=(p.routers||1)<2,g=p.rgen||0; - return {gen,site,router,cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), + return {gen,site,router,moves:utilityCacheMoves(city),cost:(gen?GEN_COST:0)+(site?SITE2_COST:0)+(router?routerCost(g,1):0), mo:(gen?GEN_MO:0)+(site?SITE2_MO:0)+(router?routerMo(g):0)};} function utilityPeers(){if(!S)return [];return Object.keys(S.ixp).filter(isIx).map(ix=>{ const sessions=ixSessions(ix),requests=[],blocked=[];let existing=0; diff --git a/src/game/90-actions/88-utilities.js b/src/game/90-actions/88-utilities.js index 05b6615..57f818d 100644 --- a/src/game/90-actions/88-utilities.js +++ b/src/game/90-actions/88-utilities.js @@ -3,12 +3,18 @@ Object.assign(ACT,{ utilityPick:()=>{if(S&&$('utilityCity'))utilitiesModal($('utilityCity').value);}, utilityRouteServers:({city}={})=>{if(!S)return;const ids=utilityRouteServers();for(const ix of ids)S.rs[ix]=true; if(ids.length){sfx('build');after();}utilitiesModal(city,tr('utilities.route_servers_joined',{n:ids.length}));}, - utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||!q.cost)return; + utilityKit:({city,cost,modal})=>{const q=utilityKit(city);if(!q||(!q.cost&&!q.moves.length))return; // Prices can change while a modal is open. Refresh the quote before spending more. if(q.cost!==+cost){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} - if(!spend(q.cost))return;const p=S.pops[city]; + if(q.cost&&!spend(q.cost))return;const p=S.pops[city]; if(q.gen)p.gen=true;if(q.site){p.site2=true;p.site2Day=S.day;}if(q.router)p.routers=2; - after();const msg=tr('utilities.kit_installed',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + const moves=new Map(q.moves.map(m=>[m.id,m.site]));for(const c of S.caches)if(moves.has(c.id))c.site=moves.get(c.id); + after();const msg=tr('utilities.kit_applied',{city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, + utilityCaches:({city,quote,modal})=>{const q=utilityCaches(city);if(!q||!q.add.length)return; + if(q.key!==quote){if(modal)utilitiesModal(city,tr('utilities.quote_changed'));else{renderPanel();toast(tr('utilities.quote_changed'));}return;} + if(!portGate(city,q.add.length))return; + for(const c of q.add)S.caches.push({id:uid(),city,net:c.net,site:c.site}); + sfx('build');after();const msg=tr('utilities.caches_requested',{n:q.add.length,city:CITY[city].name});if(modal)utilitiesModal(city,msg);else toast(esc(msg),'good');}, utilityPeers:({city}={})=>{if(!S)return;const rows=utilityPeers();let n=0; for(const row of rows)for(const id of row.requests){S.peers[id+'@'+row.ix]=true;n++;} if(n){sfx('build');after();}utilitiesModal(city,tr('utilities.peers_requested',{n}));}, diff --git a/src/game/93-ui/55-utilities.js b/src/game/93-ui/55-utilities.js index 3ed1e15..2d50105 100644 --- a/src/game/93-ui/55-utilities.js +++ b/src/game/93-ui/55-utilities.js @@ -2,8 +2,14 @@ function utilityKitHtml(city,modal=false){const q=utilityKit(city);if(!q)return const row=(label,have)=>`
${label}${have?tr('common.installed'):tr('common.none_304f')}
`; return `

${tr('utilities.redundancy_kit')}

${row(tr('common.backup_generator'),p.gen)}${row(tr('utilities.second_site'),p.site2)}${row(tr('utilities.two_routers'),(p.routers||1)>=2)} - ${q.cost?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.install_missing'),'utilityKit',{city,cost:q.cost,modal},'pink',S.cash`:`

${tr('utilities.kit_complete')}

`} -

${tr('utilities.hardware_note')}

`;} +

${tr('utilities.cache_moves',{n:q.moves.length})}

+ ${q.cost||q.moves.length?`

${tr('utilities.kit_cost',{cost:fmt$(q.cost),mo:fmt$(q.mo)})}

${btn(tr('utilities.apply_kit'),'utilityKit',{city,cost:q.cost,modal},'pink',q.cost>0&&S.cash`:`

${tr('utilities.kit_balanced')}

`} +

${tr('utilities.redundancy_note')}

${utilityCachesHtml(city,modal)}`;} +function utilityCachesHtml(city,modal=false){const q=utilityCaches(city);if(!q)return ''; + return `

${tr('common.embedded_caches')}

${tr('utilities.cache_note')}

+

${tr('utilities.cache_quote',{n:q.add.length,mo:fmt$(q.mo)})}

+ ${q.free${tr('utilities.cache_ports',{need:q.add.length,free:fmtPorts(q.free)})}

`:''} +
${btn(tr('utilities.request_caches',{n:q.add.length}),'utilityCaches',{city,quote:q.key,modal},'pink',!q.add.length||q.free+1e-9
`;} function utilitiesModal(city,message){if(!S)return;const cities=Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)); city=S.pops[city]?city:UI.sel&&UI.sel.type==='city'&&S.pops[UI.sel.id]?UI.sel.id:S.pops[S.home]?S.home:cities[0]; const rows=utilityPeers(),n=rows.reduce((v,r)=>v+r.requests.length,0),rs=utilityRouteServers().length; diff --git a/src/i18n/en.js b/src/i18n/en.js index c25a5c2..34d1a40 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3065,19 +3065,25 @@ "tutorial.your_customers_want_the_whole":"Your customers want the whole internet. Open the Transit tab and buy a port from a carrier.", "tutorial.your_router_is_live_press_launch":"Your router is live. Press “Launch broadband” to sell internet to the people of your city.", "ui.n_d_left":"{n}d left", -"utilities.hardware_note":"Hardware only: assign services across both sites and check diverse links and surviving router capacity for full failover protection.", -"utilities.install_missing":"Install missing hardware", +"utilities.apply_kit":"Apply redundancy kit", +"utilities.cache_moves":"Cache boxes to move: {n} (balanced per provider)", +"utilities.cache_note":"Request one cache per eligible provider at each existing site. Existing boxes are kept; providers still require sufficient traffic.", +"utilities.cache_ports":"Requires {need} free router ports; {free} available. Nothing is requested until the whole batch fits.", +"utilities.cache_quote":"{n} new cache boxes · Free hardware · Additional monthly cost: {mo}", +"utilities.caches_requested":"Installed {n} cache boxes in {city}.", "utilities.ix_peering":"Network-wide IX peering", "utilities.join_route_servers":"Join all route servers ({n})", -"utilities.kit_complete":"All kit components are installed.", +"utilities.kit_applied":"Redundancy updated in {city}.", +"utilities.kit_balanced":"Hardware installed and caches balanced.", "utilities.kit_cost":"One-off: {cost} · Additional monthly cost: {mo}", -"utilities.kit_installed":"Redundancy kit installed in {city}.", "utilities.peer_counts":"{ready} eligible · {existing} existing · {blocked} unavailable", "utilities.peering_note":"Request eligible peers at every IX you have joined. Existing sessions, including route-server peers, are skipped. Refusals and traffic thresholds still apply. No ports or paid PNIs are purchased.", "utilities.peers_requested":"Established {n} new IX peering sessions.", "utilities.quote_changed":"The quote changed. Review the new price and try again.", "utilities.redundancy_kit":"PoP redundancy kit", +"utilities.redundancy_note":"Existing caches are balanced per provider. Split IX, PNI and transit connections across sites separately, and check diverse links and spare router capacity.", "utilities.request_all":"Request all eligible peers ({n})", +"utilities.request_caches":"Request missing caches ({n})", "utilities.route_server_note":"Route-server peers require an Open peering policy. Existing sessions stay enabled; no ports are bought.", "utilities.route_servers_joined":"Joined {n} route servers.", "utilities.second_site":"Second site", diff --git a/tests/utilities-caches.test.js b/tests/utilities-caches.test.js new file mode 100644 index 0000000..70b212b --- /dev/null +++ b/tests/utilities-caches.test.js @@ -0,0 +1,109 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(t) { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev("ACT.start({});S.cash=1e8;UI.speed=0;for(const g of GOALS)S.done[g.id]=0;compute()"); + return h; +} + +test('kit balances each provider with minimal moves while buying the missing hardware', t => { + const { ev, errors } = setup(t); + ev("for(const [net,n] of [['cfl',4],['ggl',3]])for(let i=0;ic.id).join()'); + const quote = JSON.parse(ev("JSON.stringify(utilityKit('fra'))")); + assert.equal(quote.moves.length, 3); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + assert.equal(ev('S.cash'), before - quote.cost); + assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='cfl'&&c.site==='b').length"), 2); + assert.equal(ev("S.caches.filter(c=>c.city==='fra'&&c.net==='ggl'&&c.site==='b').length"), 1); + assert.equal(ev("S.caches.find(c=>c.id==='elsewhere').site"), 'b'); + assert.equal(ev('S.caches.map(c=>c.id).join()'), ids); + assert.equal(ev("utilityKit('fra').moves.length"), 0); + const stable = ev('JSON.stringify(S.caches)'); + ev("ACT.utilityKit({city:'fra',cost:0})"); + assert.equal(ev('JSON.stringify(S.caches)'), stable); + assert.deepEqual(errors, []); +}); + +test('an already equipped PoP can balance caches for free, even with negative cash', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:3});for(const [net,site] of [['cfl','a'],['ggl','b']])for(let i=0;i<4;i++)S.caches.push({id:net+i,city:'fra',net,site});S.cash=-1;compute();selectCity('fra');ACT.tab({t:'links'})"); + assert.equal(ev("utilityKit('fra').moves.length"), 4, 'overall counts match but provider counts do not'); + assert.equal(ev("document.querySelector('#panelBody [data-act=utilityKit]').disabled"), false); + ev("document.querySelector('#panelBody [data-act=utilityKit]').click()"); + assert.equal(ev('S.cash'), -1); + assert.equal(ev('S.pops.fra.routers'), 3); + for (const net of ['cfl', 'ggl']) + assert.equal(ev(`S.caches.filter(c=>c.net==='${net}'&&c.site==='b').length`), 2); + assert.deepEqual(errors, []); +}); + +test('a rejected kit purchase never moves caches or partially installs hardware', t => { + const { ev, errors } = setup(t); + ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];S.cash=1;compute()"); + const before = ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})'); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});ACT.utilityKit({city:'fra',cost:-1})"); + assert.equal(ev('JSON.stringify({p:S.pops.fra,c:S.caches,cash:S.cash})'), before); + assert.deepEqual(errors, []); +}); + +test('cache batch fills missing provider/site pairs, keeps extra boxes and respects eligibility', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{site2:true,routers:2});S.caches=[{id:'keep1',city:'fra',net:'cfl'},{id:'keep2',city:'fra',net:'cfl',site:'a'}];compute();R.demTo={cfl:NET.cfl.cache.min,ggl:NET.ggl.cache.min-1}"); + const cash = ev('S.cash'), mo = ev('R.cost.caches'); + assert.equal(ev("utilityCaches('fra').add.length"), 1); + ev("ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('S.cash'), cash, 'cache hardware is free'); + assert.equal(ev('R.cost.caches'), mo + ev('CACHE_MO')); + assert.equal(ev("S.caches.filter(c=>c.net==='cfl'&&c.site==='b').length"), 1); + assert.equal(ev("S.caches.filter(c=>c.net==='cfl').length"), 3, 'extra existing A box kept'); + assert.equal(ev("S.caches.some(c=>c.net==='ggl')"), false); + const stable = ev('JSON.stringify(S.caches)'); + ev("R.demTo={cfl:NET.cfl.cache.min};ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('JSON.stringify(S.caches)'), stable); + assert.deepEqual(errors, []); +}); + +test('one-site requests add only A, then a new second site gets exactly its missing boxes', t => { + const { ev, errors } = setup(t); + ev("R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('S.caches.length'), 5); + assert.equal(ev("S.caches.every(c=>c.site==='a')"), true); + ev("ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost});R.demTo=Object.fromEntries(NETS.filter(n=>n.cache).map(n=>[n.id,n.cache.min]));ACT.utilityCaches({city:'fra',quote:utilityCaches('fra').key})"); + assert.equal(ev('S.caches.length'), 10); + assert.equal(ev("NETS.filter(n=>n.cache).every(n=>['a','b'].every(s=>S.caches.filter(c=>c.net===n.id&&c.site===s).length===1))"), true); + ev("save();S=migrate(JSON.parse(localStorage.getItem('sot-save-v1')));compute()"); + assert.equal(ev('S.caches.length'), 10); + assert.equal(ev("S.caches.filter(c=>c.site==='b').length"), 5); + assert.deepEqual(errors, []); +}); + +test('cache requests reject stale eligibility and insufficient port capacity atomically', t => { + const { ev, errors } = setup(t); + ev("S.pops.fra.site2=true;for(let i=0;i<7;i++)S.caches.push({id:'full'+i,city:'fra',net:'nfx'});compute();R.demTo={cfl:NET.cfl.cache.min};window.q=utilityCaches('fra');ACT.utilities()"); + assert.equal(ev('q.free'), 1); + assert.equal(ev('q.add.length'), 2); + assert.equal(ev("document.querySelector('[data-act=utilityCaches]').disabled"), true); + const before = ev('JSON.stringify(S.caches)'); + ev("ACT.utilityCaches({city:'fra',quote:q.key})"); + assert.equal(ev('JSON.stringify(S.caches)'), before); + ev("S.pops.fra.routers=2;R.demTo.ggl=NET.ggl.cache.min;ACT.utilityCaches({city:'fra',quote:q.key,modal:true})"); + assert.equal(ev('JSON.stringify(S.caches)'), before); + assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/); + ev("ACT.utilityCaches({city:'not-a-city',quote:''})"); + assert.deepEqual(errors, []); +}); + +test('balanced caches keep serving when either site fails', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{site2:true,routers:2,rgen:RG.length-1,bb:{d:5000}});S.caches=[{id:'one',city:'fra',net:'ggl'},{id:'two',city:'fra',net:'ggl'}];compute();ACT.utilityKit({city:'fra',cost:utilityKit('fra').cost})"); + for (const site of ['a', 'b']) { + ev(`S.inc=[{id:'site-failure',type:'site',ref:'fra',site:'${site}',until:S.day+2}];compute()`); + assert.ok(ev('Object.values(R.useCache).reduce((a,b)=>a+b,0)') > 0); + assert.equal(ev(`S.caches.filter(c=>(c.site||'a')==='${site}').every(c=>!R.useCache[c.id])`), true); + } + assert.deepEqual(errors, []); +}); From ce83c01f83c7e219cce7b0cc0dad9adec3288744 Mon Sep 17 00:00:00 2001 From: Charles Miller Date: Wed, 28 Oct 2026 10:54:16 +0000 Subject: [PATCH 13/13] Distribute odd cache totals evenly between sites --- src/game/70-rules/95-utilities.js | 7 ++++++- tests/utilities-caches.test.js | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index 646f760..5d759b7 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -2,8 +2,13 @@ function utilityRouteServers(){return S?Object.keys(S.ixp).filter(ix=>isIx(ix)&&!S.myIx[ix]&&!S.rs[ix]):[];} function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new Map(),moves=[]; for(const c of S.caches)if(c.city===city){let g=groups.get(c.net);if(!g){g={a:[],b:[]};groups.set(c.net,g);}g[c.site==='b'?'b':'a'].push(c);} + const move=(g,from,n)=>{const to=from==='a'?'b':'a';for(const c of g[from].splice(0,n)){g[to].push(c);moves.push({id:c.id,site:to});}}; for(const g of groups.values()){const from=g.a.length>g.b.length?'a':'b',to=from==='a'?'b':'a'; - for(const c of g[from].slice(0,Math.floor(Math.abs(g.a.length-g.b.length)/2)))moves.push({id:c.id,site:to});} + move(g,from,Math.floor((g[from].length-g[to].length)/2));} + // Spread odd-provider extras too, so the overall site counts also differ by at most one. + let diff=0;for(const g of groups.values())diff+=g.a.length-g.b.length; + const from=diff>0?'a':'b',to=from==='a'?'b':'a';let left=Math.floor(Math.abs(diff)/2); + for(const g of groups.values())if(left&&g[from].length>g[to].length){move(g,from,1);left--;} return moves;} function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have=new Set(); for(const c of S.caches)if(c.city===city)have.add(c.net+'@'+(c.site==='b'?'b':'a')); diff --git a/tests/utilities-caches.test.js b/tests/utilities-caches.test.js index 70b212b..64840bf 100644 --- a/tests/utilities-caches.test.js +++ b/tests/utilities-caches.test.js @@ -50,6 +50,17 @@ test('a rejected kit purchase never moves caches or partially installs hardware' assert.deepEqual(errors, []); }); +test('odd provider totals are balanced across the whole PoP with the fewest moves', t => { + const { ev, errors } = setup(t); + ev("Object.assign(S.pops.fra,{gen:true,site2:true,routers:2});for(const [net,n] of [['nfx',3],['cfl',1],['ggl',1]])for(let i=0;ic.site==='b').length"), 2); + assert.equal(ev("['nfx','cfl','ggl'].every(net=>Math.abs(S.caches.filter(c=>c.net===net&&c.site==='b').length-S.caches.filter(c=>c.net===net&&c.site!=='b').length)<=1)"), true); + assert.equal(ev("utilityCacheMoves('fra').length"), 0); + assert.deepEqual(errors, []); +}); + test('cache batch fills missing provider/site pairs, keeps extra boxes and respects eligibility', t => { const { ev, errors } = setup(t); ev("Object.assign(S.pops.fra,{site2:true,routers:2});S.caches=[{id:'keep1',city:'fra',net:'cfl'},{id:'keep2',city:'fra',net:'cfl',site:'a'}];compute();R.demTo={cfl:NET.cfl.cache.min,ggl:NET.ggl.cache.min-1}");