From 4e6f780c8162b2e2415f8c505c91cb0f15d1ad15 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 10:28:57 +0100 Subject: [PATCH 01/20] No double runs in a release: container test and weekly tests once A version bump's push started docker.yml's test, then auto-release started docker.yml again for the tag, which tests the same code before it publishes: the push skips its test while the version is not tagged. The deploy re-ran the weekly-puzzle tests even when main's weekly files are the tag's own, which CI had just tested: it now runs them only for files that differ (a newer or refitted week) or an untested tag. --- .github/workflows/docker.yml | 23 +++++++++++++++++++++++ .github/workflows/release.yml | 13 +++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 9bcb23a..434307e 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -38,7 +38,30 @@ concurrency: cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} jobs: + # A push that bumps the version is a release on its way: once CI passes, auto-release.yml starts this workflow for + # the tag, which tests the same code before it publishes. Testing the push too would be the same run twice. + gate: + runs-on: ubuntu-latest + outputs: + run: ${{ steps.g.outputs.run }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag || '' }} + persist-credentials: false + - id: g + run: | + tag="v$(jq -r .version package.json)" + if [ "$GITHUB_EVENT_NAME" = push ] && ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + echo "$tag is not tagged yet: the release will test this commit when it publishes." + echo "run=false" >> "$GITHUB_OUTPUT" + else + echo "run=true" >> "$GITHUB_OUTPUT" + fi + test: + needs: gate + if: needs.gate.outputs.run == 'true' runs-on: ubuntu-latest timeout-minutes: 20 steps: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3d2acf5..9c2defa 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -106,9 +106,18 @@ jobs: node scripts/weekly-puzzle.js --check if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi - # The weekly files come from main, not the tag: whatever tested the tag, they are tested against it here. + # The weekly files come from main, not the tag. When they (after fitting) are the tag's own, CI already tested + # them with it; otherwise (a newer week, a refitted one) they are tested against this release here. + - name: Are the weekly files the tag's own? + id: weekly + run: | + if [ -z "$(git status --porcelain -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly)" ]; then + echo "Same weekly files as the tag: tested with it already."; echo "same=true" >> "$GITHUB_OUTPUT" + else + git status --short -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly; echo "same=false" >> "$GITHUB_OUTPUT" + fi - name: Test the weekly puzzles against this release - if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' }} + if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' && (steps.weekly.outputs.same != 'true' || !(inputs.tested || needs.tests.result == 'success')) }} run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null) - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build From fcb726457006093fafd4e8b39ee24b824954b47f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 13:08:11 +0100 Subject: [PATCH 02/20] Traffic badges: a Tbps ladder and an odometer up to a zettabyte Serving 1 Tbps (rare) and 10 Tbps (epic) now earn badges below the old 100 Tbps and 1 Pbps ones. S.vol counts the petabytes a game has carried (a day of 1 Gbps is 10.8 TB), with badges at 1 PB, 100 PB, 1 EB and 1 ZB, and a Carried tile on the dashboard. Old saves start the count from the 180 days of history they keep. The route fuzz takes badges only this checkout has off its page, since an unlock's log line shifts every id after it. --- CHANGELOG.md | 1 + scripts/lib/route-fuzz.js | 7 +++ site/i18n/de.js | 14 ++++++ site/i18n/es.js | 14 ++++++ site/i18n/fr.js | 14 ++++++ site/i18n/it.js | 14 ++++++ site/i18n/pt.js | 14 ++++++ src/agent/30-docs.js | 1 + src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/50-sanitize.js | 2 +- src/game/88-days/10-day-tick.js | 2 +- src/game/88-days/15-traffic-volume.js | 12 ++++++ src/game/88-days/20-badges.js | 7 +++ src/game/94-dashboard/60-dashboard.js | 2 +- src/i18n/en.js | 14 ++++++ tests/traffic-badges.test.js | 62 +++++++++++++++++++++++++++ 16 files changed, 178 insertions(+), 4 deletions(-) create mode 100644 src/game/88-days/15-traffic-volume.js create mode 100644 tests/traffic-badges.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 2380feb..4db3d63 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far. ## [3.1.0] — 2026-11-07 - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index dfca595..efa4c4e 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -64,6 +64,13 @@ const weight = (b) => (BUILD.test(b.act) ? 8 : UIACT.test(b.act) ? 0.3 : 1); opts: moves (count, default 50 to 200 by seed), maxDays per day-move, onMove(i, move) */ function playGame(pages, seed, opts = {}) { const { base, head } = pages; + // A badge only this checkout has would unlock in its game alone, and an unlock writes a log line, which shifts every + // id made after it: the comparison is about routing, so the new badges are taken off this checkout's page. + if (!pages.badges && base !== head) { + const ids = base.ev('JSON.stringify(BADGES.map((b)=>b.id))'); + head.ev(`{const keep=new Set(${ids});for(let i=BADGES.length-1;i>=0;i--)if(!keep.has(BADGES[i].id))BADGES.splice(i,1);}`); + pages.badges = true; + } const r = rng(seed * 2654435761); const both = (fn, ...a) => [base.call(fn, ...a), head.call(fn, ...a)]; const L = base.call('lists'); diff --git a/site/i18n/de.js b/site/i18n/de.js index f3e203d..c61b1a9 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -228,12 +228,16 @@ "badges.run_a_slow_booting_packetoinker":"Betreibe ein langsam bootendes PacketOinker-Chassis.", "badges.run_two_routers_in_one_pop":"Betreibe zwei Router in einem POP.", "badges.serve_100_tbps":"Liefere 100 Tbps aus.", +"badges.serve_10_tbps":"Liefere 10 Tbps aus.", "badges.serve_1_pbps_a_thousand_terabits":"Liefere 1 Pbps aus: tausend Terabit glücklicher Traffic.", +"badges.serve_1_tbps":"Liefere 1 Tbps aus.", "badges.serve_99_5_of_demand_every":"Bediene ein ganzes Jahr lang jeden einzelnen Tag 99,5 % der Nachfrage.", "badges.set_up_a_pni_while_the":"Richte einen PNI ein, solange der Konferenz-Glanz noch anhält.", "badges.survive_100_incidents_without":"Überstehe 100 Störungen ohne Auswirkungen auf Kunden.", "badges.take_a_de_kicks_retention_offer":"Nimm ein Halteangebot von DE-KICKS an.", "badges.take_out_a_loan":"Nimm einen Kredit auf.", +"badges.ten_terabits":"Zehn Terabit", +"badges.terabit_club":"Terabit-Club", "badges.the_long_way_round":"Der lange Weg außenrum", "badges.this_game_earns_fiery_badges":"Dieses Spiel läuft auf BGP um 3 Uhr nachts: Jedes Abzeichen hier wird im Feuer geschmiedet und wertet eins auf, das du schon hast.", "badges.this_game_earns_frosted_badges":"Dieses Spiel läuft im Change Freeze: Abzeichen von hier gibt es gefriergetrocknet.", @@ -243,6 +247,14 @@ "badges.variant_forged_at_3_a_m":"Um 3 Uhr geschmiedet", "badges.variant_freeze_dried":"Gefriergetrocknet", "badges.variant_on_call":"Rufbereitschaft", +"badges.vol_100pb":"Hundert Petabyte", +"badges.vol_100pb_d":"Transportiere in einem Spiel 100 PB Traffic.", +"badges.vol_eb":"Exabyte-Express", +"badges.vol_eb_d":"Transportiere in einem Spiel ein Exabyte Traffic: eine Million Terabyte.", +"badges.vol_pb":"Dein erstes Petabyte", +"badges.vol_pb_d":"Transportiere in einem Spiel ein Petabyte Traffic.", +"badges.vol_zb":"Das Zettabyte-Zeitalter", +"badges.vol_zb_d":"Transportiere in einem Spiel ein Zettabyte, ungefähr so viel wie das ganze Internet um 2016 in einem Jahr.", "badges.weather_a_ddos_with_your_defences":"Überstehe einen DDoS mit einsatzbereiter Abwehr.", "badges.weather_a_multi_terabit_ddos":"Überstehe einen DDoS im Multi-Terabit-Bereich.", "badges.win_without_ever_taking_a_loan":"Gewinne, ohne je einen Kredit aufzunehmen.", @@ -1793,6 +1805,8 @@ "dashboard.all_n":"Alle ({n})", "dashboard.amp_huts_and_spares":"Verstärkerhütten und Ersatzteile", "dashboard.caches_pnis_and_ix":"Caches, PNIs und IX", +"dashboard.carried":"Transportiert", +"dashboard.carried_sub":"insgesamt, dieses Spiel", "dashboard.chart_total":"Gesamt", "dashboard.customers_are_upset":"Kunden sind verärgert", "dashboard.delivered_30_days":"Geliefert, 30 Tage", diff --git a/site/i18n/es.js b/site/i18n/es.js index 4a5cb15..007a5ff 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -226,12 +226,16 @@ "badges.run_a_slow_booting_packetoinker":"Opera un chasis PacketOinker de arranque lento.", "badges.run_two_routers_in_one_pop":"Opera dos routers en un mismo POP.", "badges.serve_100_tbps":"Sirve 100 Tbps.", +"badges.serve_10_tbps":"Sirve 10 Tbps.", "badges.serve_1_pbps_a_thousand_terabits":"Sirve 1 Pbps: mil terabits de tráfico feliz.", +"badges.serve_1_tbps":"Sirve 1 Tbps.", "badges.serve_99_5_of_demand_every":"Sirve el 99,5 % de la demanda cada día durante un año entero.", "badges.set_up_a_pni_while_the":"Monta un PNI mientras dure el brillo de la conferencia.", "badges.survive_100_incidents_without":"Sobrevive a 100 incidentes sin afectar a los clientes.", "badges.take_a_de_kicks_retention_offer":"Acepta una oferta de retención de DE-KICKS.", "badges.take_out_a_loan":"Pide un préstamo.", +"badges.ten_terabits":"Diez terabits", +"badges.terabit_club":"Club del Terabit", "badges.the_long_way_round":"El camino largo", "badges.this_game_earns_fiery_badges":"Esta partida va de BGP a las 3 de la mañana: cada insignia que ganes aquí sale forjada en fuego y mejora la que ya tengas.", "badges.this_game_earns_frosted_badges":"Esta partida está en Change Freeze: las insignias de aquí salen liofilizadas.", @@ -241,6 +245,14 @@ "badges.variant_forged_at_3_a_m":"Forjada a las 3 a. m.", "badges.variant_freeze_dried":"Liofilizada", "badges.variant_on_call":"De guardia", +"badges.vol_100pb":"Cien petabytes", +"badges.vol_100pb_d":"Transporta 100 PB de tráfico en una partida.", +"badges.vol_eb":"Exabyte Exprés", +"badges.vol_eb_d":"Transporta un exabyte de tráfico en una partida: un millón de terabytes.", +"badges.vol_pb":"Tu primer petabyte", +"badges.vol_pb_d":"Transporta un petabyte de tráfico en una partida.", +"badges.vol_zb":"La era del zettabyte", +"badges.vol_zb_d":"Transporta un zettabyte en una partida, más o menos lo que movió todo internet en un año hacia 2016.", "badges.weather_a_ddos_with_your_defences":"Aguanta un DDoS con tus defensas listas.", "badges.weather_a_multi_terabit_ddos":"Aguanta un DDoS de varios terabits.", "badges.win_without_ever_taking_a_loan":"Gana sin pedir nunca un préstamo.", @@ -1791,6 +1803,8 @@ "dashboard.all_n":"Todo ({n})", "dashboard.amp_huts_and_spares":"Casetas de amplificación y repuestos", "dashboard.caches_pnis_and_ix":"cachés, PNIs e IX", +"dashboard.carried":"Transportado", +"dashboard.carried_sub":"en total, esta partida", "dashboard.chart_total":"Total", "dashboard.customers_are_upset":"los clientes están molestos", "dashboard.delivered_30_days":"Entregado, 30 días", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 99ca3df..b79b0fc 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -226,12 +226,16 @@ "badges.run_a_slow_booting_packetoinker":"Fais tourner un châssis PacketOinker qui met des plombes à booter.", "badges.run_two_routers_in_one_pop":"Fais tourner deux routeurs dans un POP.", "badges.serve_100_tbps":"Sers 100 Tbps.", +"badges.serve_10_tbps":"Servez 10 Tbps.", "badges.serve_1_pbps_a_thousand_terabits":"Sers 1 Pbps : mille térabits de trafic heureux.", +"badges.serve_1_tbps":"Servez 1 Tbps.", "badges.serve_99_5_of_demand_every":"Sers 99,5 % de la demande chaque jour, pendant une année entière.", "badges.set_up_a_pni_while_the":"Monte un PNI tant que dure l’euphorie de la conférence.", "badges.survive_100_incidents_without":"Survis à 100 incidents sans impact client.", "badges.take_a_de_kicks_retention_offer":"Accepte une offre de fidélisation DE-KICKS.", "badges.take_out_a_loan":"Contracte un prêt.", +"badges.ten_terabits":"Dix térabits", +"badges.terabit_club":"Club du térabit", "badges.the_long_way_round":"Le grand détour", "badges.this_game_earns_fiery_badges":"Cette partie tourne en BGP à 3 h du matin : chaque badge gagné ici est forgé dans le feu et améliore celui que tu as déjà.", "badges.this_game_earns_frosted_badges":"Cette partie est en Change Freeze : les badges gagnés ici sont lyophilisés.", @@ -241,6 +245,14 @@ "badges.variant_forged_at_3_a_m":"Forgé à 3 h du matin", "badges.variant_freeze_dried":"Lyophilisé", "badges.variant_on_call":"D’astreinte", +"badges.vol_100pb":"Cent pétaoctets", +"badges.vol_100pb_d":"Transportez 100 Po de trafic en une partie.", +"badges.vol_eb":"Exaoctet Express", +"badges.vol_eb_d":"Transportez un exaoctet de trafic en une partie : un million de téraoctets.", +"badges.vol_pb":"Votre premier pétaoctet", +"badges.vol_pb_d":"Transportez un pétaoctet de trafic en une partie.", +"badges.vol_zb":"L'ère du zettaoctet", +"badges.vol_zb_d":"Transportez un zettaoctet en une partie, à peu près ce que tout Internet a transporté en un an vers 2016.", "badges.weather_a_ddos_with_your_defences":"Encaisse un DDoS avec tes défenses prêtes.", "badges.weather_a_multi_terabit_ddos":"Encaisse un DDoS de plusieurs térabits.", "badges.win_without_ever_taking_a_loan":"Gagne sans jamais contracter de prêt.", @@ -1791,6 +1803,8 @@ "dashboard.all_n":"Toutes ({n})", "dashboard.amp_huts_and_spares":"Abris d’amplis et rechanges", "dashboard.caches_pnis_and_ix":"caches, PNI et IX", +"dashboard.carried":"Transporté", +"dashboard.carried_sub":"au total, cette partie", "dashboard.chart_total":"Total", "dashboard.customers_are_upset":"les clients râlent", "dashboard.delivered_30_days":"Livré, 30 jours", diff --git a/site/i18n/it.js b/site/i18n/it.js index 7c15c18..cd12377 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -226,12 +226,16 @@ "badges.run_a_slow_booting_packetoinker":"Usa uno chassis PacketOinker dal boot lentissimo.", "badges.run_two_routers_in_one_pop":"Fai girare due router in un POP.", "badges.serve_100_tbps":"Servi 100 Tbps.", +"badges.serve_10_tbps":"Servi 10 Tbps.", "badges.serve_1_pbps_a_thousand_terabits":"Servi 1 Pbps: mille terabit di traffico felice.", +"badges.serve_1_tbps":"Servi 1 Tbps.", "badges.serve_99_5_of_demand_every":"Servi il 99,5% della domanda ogni singolo giorno per un anno intero.", "badges.set_up_a_pni_while_the":"Attiva un PNI finché dura l’euforia della conferenza.", "badges.survive_100_incidents_without":"Sopravvivi a 100 incidenti senza impatto sui clienti.", "badges.take_a_de_kicks_retention_offer":"Accetta un’offerta di fidelizzazione DE-KICKS.", "badges.take_out_a_loan":"Chiedi un prestito.", +"badges.ten_terabits":"Dieci terabit", +"badges.terabit_club":"Club del terabit", "badges.the_long_way_round":"Il giro lungo", "badges.this_game_earns_fiery_badges":"Questa partita gira con BGP alle 3 di notte: ogni badge che guadagni qui è forgiato nel fuoco e migliora quello che hai già.", "badges.this_game_earns_frosted_badges":"Questa partita è in Change Freeze: i badge che guadagni qui arrivano liofilizzati.", @@ -241,6 +245,14 @@ "badges.variant_forged_at_3_a_m":"Forgiato alle 3 di notte", "badges.variant_freeze_dried":"Liofilizzato", "badges.variant_on_call":"Reperibile", +"badges.vol_100pb":"Cento petabyte", +"badges.vol_100pb_d":"Trasporta 100 PB di traffico in una partita.", +"badges.vol_eb":"Exabyte Express", +"badges.vol_eb_d":"Trasporta un exabyte di traffico in una partita: un milione di terabyte.", +"badges.vol_pb":"Il tuo primo petabyte", +"badges.vol_pb_d":"Trasporta un petabyte di traffico in una partita.", +"badges.vol_zb":"L'era dello zettabyte", +"badges.vol_zb_d":"Trasporta uno zettabyte in una partita, più o meno quanto ha mosso l'intera internet in un anno intorno al 2016.", "badges.weather_a_ddos_with_your_defences":"Reggi un DDoS con le difese pronte.", "badges.weather_a_multi_terabit_ddos":"Reggi un DDoS da più terabit.", "badges.win_without_ever_taking_a_loan":"Vinci senza mai chiedere un prestito.", @@ -1791,6 +1803,8 @@ "dashboard.all_n":"Tutte ({n})", "dashboard.amp_huts_and_spares":"Shelter amplificatori e ricambi", "dashboard.caches_pnis_and_ix":"cache, PNI e IX", +"dashboard.carried":"Trasportato", +"dashboard.carried_sub":"in totale, questa partita", "dashboard.chart_total":"Totale", "dashboard.customers_are_upset":"clienti furiosi", "dashboard.delivered_30_days":"Consegnato, 30 giorni", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 7944a82..bb8e786 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -226,12 +226,16 @@ "badges.run_a_slow_booting_packetoinker":"Rode um chassis PacketOinker de boot lento.", "badges.run_two_routers_in_one_pop":"Rode dois routers em um POP.", "badges.serve_100_tbps":"Atenda 100 Tbps.", +"badges.serve_10_tbps":"Sirva 10 Tbps.", "badges.serve_1_pbps_a_thousand_terabits":"Atenda 1 Pbps: mil terabits de tráfego feliz.", +"badges.serve_1_tbps":"Sirva 1 Tbps.", "badges.serve_99_5_of_demand_every":"Atenda 99,5% da demanda todos os dias por um ano inteiro.", "badges.set_up_a_pni_while_the":"Monte um PNI enquanto dura o clima da conferência.", "badges.survive_100_incidents_without":"Sobreviva a 100 incidentes sem impacto nos clientes.", "badges.take_a_de_kicks_retention_offer":"Aceite uma oferta de retenção da DE-KICKS.", "badges.take_out_a_loan":"Pegue um empréstimo.", +"badges.ten_terabits":"Dez terabits", +"badges.terabit_club":"Clube do Terabit", "badges.the_long_way_round":"A volta longa", "badges.this_game_earns_fiery_badges":"Este jogo roda BGP às 3 da manhã: cada badge que você ganha aqui é forjado no fogo e melhora o que você já tem.", "badges.this_game_earns_frosted_badges":"Este jogo está em Change Freeze: os badges daqui vêm liofilizados.", @@ -241,6 +245,14 @@ "badges.variant_forged_at_3_a_m":"Forjado às 3 da manhã", "badges.variant_freeze_dried":"Liofilizado", "badges.variant_on_call":"De plantão", +"badges.vol_100pb":"Cem petabytes", +"badges.vol_100pb_d":"Transporte 100 PB de tráfego em uma partida.", +"badges.vol_eb":"Exabyte Expresso", +"badges.vol_eb_d":"Transporte um exabyte de tráfego em uma partida: um milhão de terabytes.", +"badges.vol_pb":"Seu primeiro petabyte", +"badges.vol_pb_d":"Transporte um petabyte de tráfego em uma partida.", +"badges.vol_zb":"A era do zettabyte", +"badges.vol_zb_d":"Transporte um zettabyte em uma partida, mais ou menos o que a internet inteira moveu em um ano por volta de 2016.", "badges.weather_a_ddos_with_your_defences":"Aguente um DDoS com as defesas prontas.", "badges.weather_a_multi_terabit_ddos":"Aguente um DDoS de vários terabits.", "badges.win_without_ever_taking_a_loan":"Vença sem nunca pegar um empréstimo.", @@ -1791,6 +1803,8 @@ "dashboard.all_n":"Todos ({n})", "dashboard.amp_huts_and_spares":"Abrigos de amplificador e reservas", "dashboard.caches_pnis_and_ix":"caches, PNIs e IX", +"dashboard.carried":"Transportado", +"dashboard.carried_sub":"no total, nesta partida", "dashboard.chart_total":"Total", "dashboard.customers_are_upset":"clientes furiosos", "dashboard.delivered_30_days":"Entregue, 30 dias", diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 8c41c27..831f97c 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -83,6 +83,7 @@ const API_STATE_DOC={ lost:{type:'boolean',doc:'The bank repossessed the routers.'}, neg:{type:'integer',doc:'Days in the red in a row.'}, hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, + vol:{type:'number',doc:'Traffic carried in this game, in petabytes (each day adds a day of what was served); badges at 1 PB, 100 PB, 1 EB and 1 ZB.'}, scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index c661e15..227dbec 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:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},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:{},pairMet:{}, - done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; + done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 9f3361b..94b2e47 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -111,7 +111,7 @@ function sanitize(s){ {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} specSanitize(s); - pieSanitize(s);pieIncFix(s); + pieSanitize(s);pieIncFix(s);volFix(s); 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;} function migrate(s){sanitize(s); diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 23ab8db..13fd9d8 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -57,7 +57,7 @@ function* dayPost(d){ yield* ddosNewsRun();ddosTrack(); for(const t of S.transit){(t.hist=t.hist||[]).push(R.useT[t.id]||0);if(t.hist.length>30)t.hist.shift();} S.cash+=(R.revMo-R.costMo)/monLen(d); - S.stats.peak=Math.max(S.stats.peak,R.served); + S.stats.peak=Math.max(S.stats.peak,R.served);volDay(); S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift(); {const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('day_tick.customer_level_lv_name_new_customers',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`
${esc(LEVELS[lv-1].q)}`,'goal');}S.lvl=top;sfx('coin');}} for(const l of S.links){if(l.kind!=='df')continue; diff --git a/src/game/88-days/15-traffic-volume.js b/src/game/88-days/15-traffic-volume.js new file mode 100644 index 0000000..e0ae306 --- /dev/null +++ b/src/game/88-days/15-traffic-volume.js @@ -0,0 +1,12 @@ +/* ---------- Traffic carried: the network's odometer ---------- + S.vol counts the petabytes the network has carried in this game: every day adds a day of what it served. R.served + is in Gbps, so a day of 1 Gbps is 86,400 gigabits, 10.8 terabytes, 0.0108 PB. Badges ride on it (20-badges.js), + from the first petabyte to a zettabyte, the whole internet's traffic in a year around 2016. */ +const PB_DAY=86400/8/1e6; +function volDay(){S.vol=(S.vol||0)+(R.served>0?R.served*PB_DAY:0);} +// A volume of traffic, from the petabytes it is stored in: TB, PB, EB, ZB. +const fmtVol=pb=>pb>=1e6?(pb/1e6).toFixed(pb>=1e7?1:2)+' ZB':pb>=1000?(pb/1000).toFixed(pb>=1e4?1:2)+' EB':pb>=1?pb.toFixed(pb>=10?0:1)+' PB':(pb*1000).toFixed(pb>=0.01?0:1)+' TB'; +// Saves: a number of petabytes. A save from before the odometer starts from the days its history still holds (the +// last 180), so an old network gets most of the credit it earned. +function volFix(s){if(typeof s.vol==='number'&&Number.isFinite(s.vol)&&s.vol>=0)return; + s.vol=(Array.isArray(s.hist)?s.hist:[]).reduce((a,h)=>a+(h&&typeof h.srv==='number'&&h.srv>0&&Number.isFinite(h.srv)?h.srv:0),0)*PB_DAY;} diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 0bc8e08..183b039 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -54,8 +54,15 @@ const BADGES=[ {id:'lv13',i:'🌐',t:tr('badges.is_this_the_internet'),d:tr('badges.reach_customer_level_13'),r:'l',ok:()=>(S.lvl||1)>=13}, {id:'gigawatt',i:'⚛️',t:tr('common.gigawatt_landlord'),d:tr('badges.hold_an_ai_wan_a_training'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))}, {id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&S.day<=730}, + {id:'tera',i:'📶',t:tr('badges.terabit_club'),d:tr('badges.serve_1_tbps'),r:'r',ok:()=>R.served>=1000}, + {id:'tera10',i:'🚄',t:tr('badges.ten_terabits'),d:tr('badges.serve_10_tbps'),r:'e',ok:()=>R.served>=10000}, {id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'l',ok:()=>R.served>=100000}, {id:'petabit',i:'🪐',t:tr('badges.a_petabit_a_second'),d:tr('badges.serve_1_pbps_a_thousand_terabits'),r:'l',ok:()=>R.served>=1e6}, + // Traffic carried in total (15-traffic-volume.js): the odometer, in petabytes. + {id:'vol_pb',i:'💾',t:tr('badges.vol_pb'),d:tr('badges.vol_pb_d'),r:'c',ok:()=>(S.vol||0)>=1}, + {id:'vol_100pb',i:'🗄️',t:tr('badges.vol_100pb'),d:tr('badges.vol_100pb_d'),r:'r',ok:()=>(S.vol||0)>=100}, + {id:'vol_eb',i:'🚂',t:tr('badges.vol_eb'),d:tr('badges.vol_eb_d'),r:'e',ok:()=>(S.vol||0)>=1000}, + {id:'vol_zb',i:'🌠',t:tr('badges.vol_zb'),d:tr('badges.vol_zb_d'),r:'l',ok:()=>(S.vol||0)>=1e6}, {id:'llama',i:'🦙',t:tr('common.llama_drama'),d:tr('badges.lose_fiber_to_a_llama_herd'),r:'l',secret:true,ok:()=>!!(st().f||{}).llama}, {id:'hallway',i:'🎤',t:tr('common.hallway_track'),d:tr('badges.attend_a_conference'),r:'r',ok:()=>(st().confs||0)>=1}, {id:'beer',i:'🍺',t:tr('badges.peering_over_beer'),d:tr('badges.set_up_a_pni_while_the'),r:'e',ok:()=>!!st().beerPni}, diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 2703cd9..69bc314 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -6,7 +6,7 @@ function renderDash(){checkLayer(); const net=R.revMo-R.costMo,tot=Object.values(R.egT).reduce((a,b)=>a+b,0)||1; const tile=(l,v,sub)=>`
${l}
${v}
${sub?`
${sub}
`:''}
`; let h=`
AS${S.asn} · ${esc(S.name)} · ${tierLabel()}

${tr('common.noc_dashboard')}

`+dashTabs();const DT=UI.dtab||'overview';if(DT==='overview')h+=` -
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}
+
${tile(tr('common.traffic_now'),fmtG(R.served),tr('dashboard.of_g_wanted',{g:fmtG(R.demand)}))}${tile(tr('common.peak'),fmtG(S.stats.peak))}${tile(tr('dashboard.carried'),fmtVol(S.vol||0),tr('dashboard.carried_sub'))}${tile(tr('dashboard.delivered_30_days'),(up*100).toFixed(1)+'%',up>=0.999?tr('dashboard.five_nines_ish'):up>=0.99?tr('dashboard.two_nines_and_change'):tr('dashboard.customers_are_upset'))}${tile(tr('common.peering_ratio'),pct(R.peerShare||0),tr('dashboard.caches_pnis_and_ix'))}${tile(tr('dashboard.monthly_p_l'),`${net>=0?'+':''}${fmt$(net)}`,tr('dashboard.in_in_out_out',{in:fmt$(R.revMo),out:fmt$(R.costMo)}))}${tile(tr('common.incidents'),S.stats.incidents,tr('dashboard.n_shrugged_off',{n:S.stats.survived}))}

${tr('dashboard.traffic_by_way_out')}

${svgChart(rows,['c','p','ix','t','l2'],[{k:'dem',col:'#1E2640',dash:true}],v=>fmtCap(Math.round(v)),'traffic')}${chartLegend('traffic',k=>k==='dem'?'':' '+pct((R.egT[k]||0)/tot))}

${tr('dashboard.money_per_month')}

${svgChart(rows,[],[{k:'rev',col:'#16A866'},{k:'cost',col:'#FF4D5E'}],v=>fmt$(v),'money')}${chartLegend('money')}

${tr('dashboard.where_the_money_goes')}

${Object.entries(R.cost).filter(([k,v])=>v>0).sort((a,b)=>b[1]-a[1]).map(([k,v])=>`
${{pops:tr('dashboard.pops_and_routers'),links:tr('dashboard.waves_and_fiber'),transit:tr('common.transit'),ix:tr('common.ix_ports'),pni:tr('common.pnis'),caches:tr('common.cache_power'),nni:tr('common.fabric_ports'),optical:tr('dashboard.amp_huts_and_spares'),loans:tr('common.loan_repayments'),revshare:tr('dashboard.investor_revenue_share'),extras:tr('dashboard.licenses_and_scrubbing'),wholesale:tr('dashboard.nearly_broadband_network_wholesale'),levy:tr('dashboard.regional_broadband_levy'),pie:tr('pie.costs_row')}[k]||k}${tr('common.price_mo',{price:fmt$(v)})}
`).join('')}
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 9d3a510..59789da 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -227,12 +227,16 @@ "badges.run_a_slow_booting_packetoinker":"Run a slow-booting PacketOinker chassis.", "badges.run_two_routers_in_one_pop":"Run two routers in one POP.", "badges.serve_100_tbps":"Serve 100 Tbps.", +"badges.serve_10_tbps":"Serve 10 Tbps.", "badges.serve_1_pbps_a_thousand_terabits":"Serve 1 Pbps: a thousand terabits of happy traffic.", +"badges.serve_1_tbps":"Serve 1 Tbps.", "badges.serve_99_5_of_demand_every":"Serve 99.5% of demand every single day for a whole year.", "badges.set_up_a_pni_while_the":"Set up a PNI while the conference glow lasts.", "badges.survive_100_incidents_without":"Survive 100 incidents without customer impact.", "badges.take_a_de_kicks_retention_offer":"Take a DE-KICKS retention offer.", "badges.take_out_a_loan":"Take out a loan.", +"badges.ten_terabits":"Ten Terabits", +"badges.terabit_club":"Terabit Club", "badges.the_long_way_round":"The Long Way Round", "badges.this_game_earns_fiery_badges":"This game runs BGP at 3 a.m.: every badge you earn here is forged in fire, and upgrades one you already have.", "badges.this_game_earns_frosted_badges":"This game runs a Change Freeze: badges you earn here come freeze-dried.", @@ -242,6 +246,14 @@ "badges.variant_forged_at_3_a_m":"Forged at 3 a.m.", "badges.variant_freeze_dried":"Freeze-dried", "badges.variant_on_call":"On-call", +"badges.vol_100pb":"A Hundred Petabytes", +"badges.vol_100pb_d":"Carry 100 PB of traffic in one game.", +"badges.vol_eb":"Exabyte Express", +"badges.vol_eb_d":"Carry an exabyte of traffic in one game: a million terabytes.", +"badges.vol_pb":"Your First Petabyte", +"badges.vol_pb_d":"Carry a petabyte of traffic in one game.", +"badges.vol_zb":"The Zettabyte Era", +"badges.vol_zb_d":"Carry a zettabyte in one game, about what the whole internet moved in a year around 2016.", "badges.weather_a_ddos_with_your_defences":"Weather a DDoS with your defences ready.", "badges.weather_a_multi_terabit_ddos":"Weather a multi-terabit DDoS.", "badges.win_without_ever_taking_a_loan":"Win without ever taking a loan.", @@ -1792,6 +1804,8 @@ "dashboard.all_n":"All ({n})", "dashboard.amp_huts_and_spares":"Amp huts and spares", "dashboard.caches_pnis_and_ix":"caches, PNIs and IX", +"dashboard.carried":"Carried", +"dashboard.carried_sub":"in total, this game", "dashboard.chart_total":"Total", "dashboard.customers_are_upset":"customers are upset", "dashboard.delivered_30_days":"Delivered, 30 days", diff --git a/tests/traffic-badges.test.js b/tests/traffic-badges.test.js new file mode 100644 index 0000000..8ea6cc3 --- /dev/null +++ b/tests/traffic-badges.test.js @@ -0,0 +1,62 @@ +// Traffic badges: the rate ladder (1 Tbps, 10 Tbps, then the old 100 Tbps and 1 Pbps) and the odometer, S.vol, the +// petabytes carried in a game, with badges at 1 PB, 100 PB, 1 EB and 1 ZB. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"; + +test('every day adds a day of what was served: 1 Gbps for a day is 10.8 TB', () => { + const { ev, errors } = load(); + ev(start); + assert.equal(ev('S.vol'), 0, 'a new game starts at zero'); + // What a day adds, from the day's own served traffic, whatever it is. + const r = JSON.parse(ev('(()=>{const out=[];for(let i=0;i<20;i++){const v0=S.vol;dayTick();out.push({add:S.vol-v0,srv:R.served});}return JSON.stringify(out);})()')); + for (const x of r) assert.ok(Math.abs(x.add - x.srv * 0.0108) < 1e-9, `${x.add} PB for ${x.srv} Gbps`); + assert.ok(r.some((x) => x.srv > 0), 'some traffic flowed'); + assert.equal(ev('fmtVol(0.0108)'), '11 TB'); + assert.equal(ev('fmtVol(1)'), '1.0 PB'); + assert.equal(ev('fmtVol(1500)'), '1.50 EB'); + assert.equal(ev('fmtVol(2e6)'), '2.00 ZB'); + assert.deepEqual(errors, []); +}); + +test('the ladders: each badge at its line, not before', () => { + const { ev, errors } = load(); + ev(start); + const got = () => JSON.parse(ev("JSON.stringify(['tera','tera10','peta','petabit','vol_pb','vol_100pb','vol_eb','vol_zb'].filter(k=>S.ach&&S.ach[k]!==undefined))")); + const at = (served, vol) => { ev(`R.served=${served};S.vol=${vol};checkBadges()`); return got(); }; + assert.deepEqual(at(999, 0.99), []); + assert.deepEqual(at(1000, 1), ['tera', 'vol_pb']); + assert.deepEqual(at(9999, 99.9), ['tera', 'vol_pb']); + assert.deepEqual(at(10000, 100), ['tera', 'tera10', 'vol_pb', 'vol_100pb']); + assert.deepEqual(at(10000, 1000), ['tera', 'tera10', 'vol_pb', 'vol_100pb', 'vol_eb']); + assert.deepEqual(at(1e6, 1e6), ['tera', 'tera10', 'peta', 'petabit', 'vol_pb', 'vol_100pb', 'vol_eb', 'vol_zb']); + assert.deepEqual(errors, []); +}); + +test('the dashboard shows what was carried', () => { + const { ev, errors } = load(); + ev(start); + ev('S.vol=1234.5'); + ev('renderDash()'); + const h = ev("document.getElementById('dash').innerHTML"); + assert.match(h, /Carried/); + assert.match(h, /1\.23 EB/); + assert.deepEqual(errors, []); +}); + +test('saves: kept, repaired, and an old save starts from the history it still holds', () => { + const { ev, errors } = load(); + ev(start); + ev('S.vol=42;S.hist=[{d:1,srv:1000},{d:2,srv:2000}]'); + const s = JSON.parse(ev('JSON.stringify(packSave(S))')); + const fix = (x) => JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${JSON.stringify(JSON.stringify(x))})).vol)`)); + assert.equal(fix(s), 42); + for (const bad of [-5, 'lots', null, Infinity]) assert.ok(Math.abs(fix({ ...s, vol: bad }) - 3000 * 0.0108) < 1e-9, `${bad} is rebuilt from the history`); + delete s.vol; + assert.ok(Math.abs(fix(s) - 3000 * 0.0108) < 1e-9, 'a save from before the odometer: 3,000 Gbps-days of history'); + s.hist = [{ d: 1, srv: 'x' }, { d: 2, srv: -1 }, null]; + assert.equal(fix(s), 0, 'junk history counts for nothing'); + assert.deepEqual(errors, []); +}); From e6b5464352a4d2126e7c9b17fe96dde9524a2d8f Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 13:12:01 +0100 Subject: [PATCH 03/20] Traffic badges: legendary only at the top of each ladder 1 Tbps is common, 10 Tbps rare, 100 Tbps epic (was legendary) and 1 Pbps stays legendary, the same steps as the petabyte-to-zettabyte ladder. --- CHANGELOG.md | 2 +- src/game/88-days/20-badges.js | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4db3d63..d3bb6b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] -- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far. +- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. ## [3.1.0] — 2026-11-07 - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. diff --git a/src/game/88-days/20-badges.js b/src/game/88-days/20-badges.js index 183b039..95db1c7 100644 --- a/src/game/88-days/20-badges.js +++ b/src/game/88-days/20-badges.js @@ -54,9 +54,9 @@ const BADGES=[ {id:'lv13',i:'🌐',t:tr('badges.is_this_the_internet'),d:tr('badges.reach_customer_level_13'),r:'l',ok:()=>(S.lvl||1)>=13}, {id:'gigawatt',i:'⚛️',t:tr('common.gigawatt_landlord'),d:tr('badges.hold_an_ai_wan_a_training'),r:'l',ok:()=>['aiwan','mtrain','ingest','pairs'].every(t=>S.biz.some(b=>b.type===t))}, {id:'blitz',i:'🚀',t:tr('common.blitz'),d:tr('badges.reach_tier_1_within_two_years'),r:'l',ok:()=>!!S.won&&S.day<=730}, - {id:'tera',i:'📶',t:tr('badges.terabit_club'),d:tr('badges.serve_1_tbps'),r:'r',ok:()=>R.served>=1000}, - {id:'tera10',i:'🚄',t:tr('badges.ten_terabits'),d:tr('badges.serve_10_tbps'),r:'e',ok:()=>R.served>=10000}, - {id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'l',ok:()=>R.served>=100000}, + {id:'tera',i:'📶',t:tr('badges.terabit_club'),d:tr('badges.serve_1_tbps'),r:'c',ok:()=>R.served>=1000}, + {id:'tera10',i:'🚄',t:tr('badges.ten_terabits'),d:tr('badges.serve_10_tbps'),r:'r',ok:()=>R.served>=10000}, + {id:'peta',i:'🌌',t:tr('common.hundred_terabits'),d:tr('badges.serve_100_tbps'),r:'e',ok:()=>R.served>=100000}, {id:'petabit',i:'🪐',t:tr('badges.a_petabit_a_second'),d:tr('badges.serve_1_pbps_a_thousand_terabits'),r:'l',ok:()=>R.served>=1e6}, // Traffic carried in total (15-traffic-volume.js): the odometer, in petabytes. {id:'vol_pb',i:'💾',t:tr('badges.vol_pb'),d:tr('badges.vol_pb_d'),r:'c',ok:()=>(S.vol||0)>=1}, From 2f738dcedad6cece421f9c1366180069f8caaabe Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 13:15:56 +0100 Subject: [PATCH 04/20] Lambda Bazaar: a capacity market for your dark fiber A new NOC tab sells spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold fiber on. Demand per route moves every day (its own cycle, noise, and news: fiber cuts, hyperscalers, AI clusters, rivals lighting glass, mergers) and grows about 15% a year, with buyers moving to bigger waves over the years and carriers on your glass asking to move up a size. You choose what to keep back for your own traffic, from what demand the broker lists, and the price it never sells below. Managed waves come out of capacity you lit; prices follow the fiber's cost, how hot and how full the route is, and its latency (400G at 2.7x 100G on land, 3.8x subsea). A Cable broker pays 3% instead of 10% and sees each route's forecast and routes worth building. Rule F5 now bounds sales by the moving market; new rule F8 covers managed waves. The route fuzz skips dashboard tabs main does not have yet. --- .claude/skills/gameplay-rules/SKILL.md | 3 +- CHANGELOG.md | 2 + scripts/lib/route-fuzz.js | 8 +- site/i18n/de.js | 71 +++++++- site/i18n/es.js | 71 +++++++- site/i18n/fr.js | 71 +++++++- site/i18n/it.js | 71 +++++++- site/i18n/pt.js | 71 +++++++- src/agent/20-commands.js | 7 + src/agent/30-docs.js | 1 + src/game/10-catalog/60-reach-and-subsea.js | 5 +- src/game/40-progress/10-businesses.js | 2 + src/game/40-progress/20-goals.js | 2 +- src/game/60-features/37-cable-broker.js | 4 +- src/game/60-features/37-fiber-broker.js | 15 +- src/game/60-features/37-fiber-market.js | 182 +++++++++++++++++++++ src/game/60-features/38-sales-desk.js | 2 +- src/game/60-features/80-new-game.js | 2 +- src/game/80-simulation/50-sanitize.js | 3 +- src/game/80-simulation/60-requirements.js | 2 +- src/game/88-days/10-day-tick.js | 2 +- src/game/90-actions/53-market.js | 14 ++ src/game/93-ui/70-link-panels.js | 14 +- src/game/93-ui/82-keys.js | 4 +- src/game/94-dashboard/40-connections.js | 2 +- src/game/94-dashboard/55-market.js | 38 +++++ src/game/94-dashboard/60-dashboard.js | 3 +- src/game/94-dashboard/90-noc-window.js | 2 +- src/i18n/en.js | 71 +++++++- src/styles/40-modal.css | 13 ++ tests/capacity-market.test.js | 149 +++++++++++++++++ tests/fiber-broker.test.js | 8 +- tests/gameplay-rules.test.js | 27 ++- tests/issues.test.js | 5 +- 34 files changed, 891 insertions(+), 56 deletions(-) create mode 100644 src/game/60-features/37-fiber-market.js create mode 100644 src/game/90-actions/53-market.js create mode 100644 src/game/94-dashboard/55-market.js create mode 100644 tests/capacity-market.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 294d399..d6fba4b 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -68,9 +68,10 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | | F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | | F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. | -| F5 | Capacity you rent to other carriers never outgrows the route's market: a broker listing sells over time as carriers between the two cities want it, and neither it nor a random offer sells past what both cities' eyeballs support (a landing town counts the big city it serves). | Rent that scales with your own glass and not with demand is a money machine (#203). | +| F5 | Capacity you rent to other carriers never outgrows the route's market: the capacity market sells a listing over time as carriers between the two cities want it, never past what they want that day (both cities' eyeballs, a landing town counting the big city it serves, grown about 15% a year up to 8 times, and at most 2.5 times its usual size on its hottest day), and a random offer never past what the eyeballs alone support. | Rent that scales with your own glass and not with demand is a money machine (#203); a market that never moves or grows makes no decisions. | | F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | | F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | +| F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. | ## DDoS diff --git a/CHANGELOG.md b/CHANGELOG.md index d3bb6b8..0c4ddef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] - New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. +- Lambda Bazaar, a capacity market for your dark fiber, is a new tab in the NOC dashboard. Sell spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold fiber on, and choose how much to keep back for your own traffic, from what demand the broker lists, and the price it never sells below. What each route wants moves all the time and grows every year: hot routes pay more, a fiber cut next door or a hyperscaler breaking ground sends demand up, buyers move from 100G to bigger waves over the years, and carriers already on your glass ask to move up a size. Short, straight routes earn more for fast waves. A Cable broker pays the broker 3% instead of 10%, and sees where each route is heading and which routes between its POPs are worth building. + ## [3.1.0] — 2026-11-07 - Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index efa4c4e..283b41c 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -111,12 +111,14 @@ function playGame(pages, seed, opts = {}) { // A screen's buttons on both pages; the same list or a divergence. // Buttons for actions main's page does not have (a new feature's) are left out: the driver only presses what both have. - // So are the switches and dials of a standing order this checkout retired (main's sheet still shows them). - let baseActs = null, retired = null; + // So are the switches and dials of a standing order this checkout retired (main's sheet still shows them), and a + // dashboard tab main's page does not have yet. + let baseActs = null, retired = null, baseTabs = null; const screen = (w) => { const [a0, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts')); if (!retired) { const [o1, o2] = both('sKeys'); retired = new Set(o1.orders.filter((k) => !o2.orders.includes(k))); } const a = Array.isArray(a0) ? a0.filter((x) => !(/^ops/.test(x.act) && retired.has(x.args && x.args.k))) : a0; - const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act)) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; }; + if (!baseTabs) baseTabs = new Set(JSON.parse(base.ev('JSON.stringify(DTABS)'))); + const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act) && !(x.act === 'dashTab' && x.args && !baseTabs.has(x.args.k))) : b0; same('buttons of ' + JSON.stringify(w), a, b); return a || []; }; const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); }; // Answer whatever window opened, a few levels deep, then close it. const modal = (bias) => { diff --git a/site/i18n/de.js b/site/i18n/de.js index c61b1a9..d780960 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -388,8 +388,6 @@ "broker.goal_wave":"Verkaufe eine Wave auf deinem Glas", "broker.goal_wave_d":"Carrier mieten Alien Waves auf Fiber, die du beleuchtet hast. Nimm eine aus deinen Deals an.", "broker.goal_win_d":"Deine eigenen Kabel landen auf fünf Kontinenten, und Carrier zahlen dir 1 Mio. $ im Monat für Kapazität.", -"broker.how":"verkauft, wie der Markt es will; der Broker behält 10 %", -"broker.lead":"Der Broker behält dein Angebot und verkauft es nach und nach, wenn Carrier zwischen diesen beiden Städten Kapazität brauchen. Er behält 10 % jedes Verkaufs.", "broker.list_all":"Alle {n} anbieten", "broker.list_more":"{n} weitere anbieten", "broker.list_n":{"one":"{n} Welle anbieten","other":"{n} Wellen anbieten"}, @@ -3037,6 +3035,75 @@ "loop.something_in_the_noc_glitched_the":"Im NOC hat etwas gehakt.
Das Spiel lief weiter. Falls dir etwas komisch vorkommt, exportiere deinen Spielstand und mach ein Issue auf GitHub auf.", "loop.welcome_back_name_your_network_is":"Willkommen zurück, {name}.
Dein Netz ist genau da, wo du es gelassen hast: {date}.", "loop.your_saved_game_could_not_be":"Dein Spielstand konnte nicht geladen werden.
Er war beschädigt, also wurde ein Backup aufbewahrt, und du kannst neu anfangen.", +"market.below_floor":"unter deiner Untergrenze", +"market.cool":"❄️ Kühl ×{x}", +"market.days_ago":{"one":"vor {n} Tag","other":"vor {n} Tagen"}, +"market.fee":"Der Broker behält", +"market.fee_broker":"der Satz für Cable broker", +"market.floor":"Nie verkaufen unter", +"market.forecast":"In 30 Tagen {a} · in 90 Tagen {b}", +"market.forecast_lock":"Ein Cable broker sieht auch, wohin sich jede Strecke entwickelt.", +"market.forecast_now":"{n} jetzt · {a} in 30 Tagen · {b} in 90 Tagen", +"market.g_sold_as_managed":"{g} als Managed Waves verkauft", +"market.hold":"Für deinen eigenen Traffic zurückhalten", +"market.hold_d":"Der Anteil an Spektrum und beleuchteter Kapazität jeder Glasfaser, den der Broker nie verkauft, damit dein Traffic Platz zum Wachsen hat.", +"market.hot":"🔥 Heiß ×{x}", +"market.how":"geht weg, wie der Markt will; der Broker behält {n}%", +"market.lead":"Carrier kaufen Kapazität auf den Strecken, auf denen du Dark Fiber hast. Was jede Strecke will, ändert sich ständig: heiße Strecken zahlen mehr und füllen sich schneller, eine kurze, gerade Strecke verkauft Waves mit Aufschlag, und eine lange kostet mehr, weil ihre Glasfaser mehr kostet. Leg fest, was der Broker verkauft, ab welcher Nachfrage und zu welchem Preis.", +"market.lead_fiber":"Der Broker behält dein Angebot und verkauft es nach und nach, wenn Carrier zwischen diesen beiden Städten Kapazität wollen. Er behält {n}% jedes Verkaufs.", +"market.legend":"Jeder Balken: was verkauft ist (grün) von dem, was die Strecke will (der Strich); die rosa Markierung ist dein Minimum.", +"market.managed_wave":"Managed Wave", +"market.min":"Anbieten, solange die Strecke mindestens will", +"market.n_g_left":{"one":"{n} Managed Wave mit {g} noch zu verkaufen","other":"{n} Managed Waves mit {g} noch zu verkaufen"}, +"market.n_g_wave_on":{"one":"{n}× Managed Wave mit {g} auf deiner Glasfaser {a}–{b}","other":"{n}× Managed Waves mit {g} auf deiner Glasfaser {a}–{b}"}, +"market.needs_optic":"braucht eine {g}-Optik auf dieser Glasfaser", +"market.news":"Marktnachrichten", +"market.news_ai_big":"Ein KI-Cluster will zwischen {a} und {b} reden: Waves ab 400G sind dort heiß begehrt.", +"market.news_boom":"Ein Streaming-Hit flutet {a}: Carrier wollen von dort mehr Spektrum und 100G-Waves.", +"market.news_cut":"Glasfaser zwischen {a} und {b} durchtrennt: Carrier wollen getrennte Wege drumherum.", +"market.news_dc_big":"Ein Hyperscaler baut bei {a}: von dort sind große Waves und dunkle Faserpaare gefragt.", +"market.news_exch":"Trader ziehen ihre Matching Engines nach {a}: schnelle Waves von dort bringen mehr.", +"market.news_glut":"Ein Konkurrent beleuchtet neue Glasfaser zwischen {a} und {b}: die Käufer dort kühlen ab.", +"market.news_merge":"Zwei Carrier fusionieren zwischen {a} und {b}: dort gibt es weniger Käufer.", +"market.news_redsea":"Seekabel sind durchtrennt: jede Seekabelstrecke ist gefragt.", +"market.no_news":"Bisher ruhig.", +"market.no_room":"kein Platz mehr: beleuchte mehr Kapazität", +"market.no_routes":"Du hast noch keine fertige Dark Fiber. Miete oder grab welche, dann taucht ihre Strecke hier auf.", +"market.not_selling":"Nicht im Verkauf", +"market.not_yet":"Hier will das noch niemand: {list}.", +"market.open":"Lambda Bazaar", +"market.p_iru":"IRUs für dunkle Faserpaare", +"market.p_iru_d":"Ein freies Faserpaar in einem Graben, den du gegraben hast: zwei Jahre seiner Miete im Voraus, dann ein bisschen Wartung im Monat.", +"market.p_spec":"Spektrum", +"market.p_spec_d":"Eine Alien Wave: ein Kanal deines Line Systems, die Optik bringt der Käufer mit.", +"market.p_w100":"Managed Waves mit 100G", +"market.p_w100_d":"Aus der Kapazität geschnitten, die du beleuchtet hast: bringen mehr als Spektrum, und deinem Traffic bleibt entsprechend weniger.", +"market.p_w1600":"Managed Waves mit 1,6T", +"market.p_w1600_d":"Eine Wave auf einer 1,6T-Optik: das billigste Bit, das du verkaufen kannst, und was die größten Käufer mit den Jahren wollen.", +"market.p_w400":"Managed Waves mit 400G", +"market.p_w400_d":"2,7-mal der Preis einer 100G-Wave für viermal die Kapazität (3,8-mal auf Seekabeln). KI-Rechenzentren wollen sie.", +"market.p_w800":"Managed Waves mit 800G", +"market.p_w800_d":"Eine Wave auf einer 800G-Optik. Käufer steigen nach ein paar Jahren um, KI-Rechenzentren zuerst.", +"market.price":"{price}/Monat · {pct}% vom Listenpreis", +"market.price_pair":"{up} im Voraus + {price}/Monat · {pct}% vom Listenpreis", +"market.route_meta":"{km} km · {ms} ms · schnelle Waves +{n}%", +"market.route_off":"Broker lässt sie in Ruhe", +"market.route_on":"Broker handelt hier", +"market.routes":"Deine Strecken", +"market.row":"{want} gefragt · {sold} verkauft · {listed} angeboten", +"market.sales":"Kapazität, die du verkaufst", +"market.scout":"Strecken, die du bauen könntest", +"market.scout_d":"Zwischen deinen POPs, noch ohne deine Glasfaser: was jede Strecke will und wohin sie sich entwickelt, die wertvollsten zuerst.", +"market.scout_none":"Bau POPs in mehr Städten, um Strecken zwischen ihnen zu sehen.", +"market.scout_spend":"{km} km · Carrier geben dort zu heutigen Preisen etwa {v}/Monat aus", +"market.selling":"Im Verkauf", +"market.sold_pair":"Dein Broker hat ein dunkles Faserpaar verkauft.
{name} zahlt {up} im Voraus für {what}, dann {price}/Monat.", +"market.steady":"Stabil", +"market.tab":"Kapazitätsmarkt", +"market.title":"Lambda Bazaar", +"market.today":"heute", +"market.upgraded":"{name} wächst.
Seine {n}× Waves mit {g0} auf {a}–{b} werden zu {g1}: {price}/Monat.", +"market.wants_more":"{name} will wachsen, von Waves mit {g0} auf {g1} auf {a}–{b}, aber die Glasfaser hat keinen Platz. Beleuchte mehr Kapazität oder halte weniger zurück.", "meet_a_network.all_n_out_of_reach":{"one":"Alle {n} außer Reichweite","other":"Alle {n} außer Reichweite"}, "meet_a_network.peer_with_the_tier_1_club":"Peere mit dem Tier-1-Club: Ihre Kunden kommen gratis mit. Nur Netze, die in niemandes Customer Cone sind, brauchen eigenes Peering.", "meet_a_network.peer_with_the_tier_1_club_n":{"one":"Peere mit dem Tier-1-Club: Ihre Kunden kommen gratis mit. {n} Netz kommt schon mit einem Peer mit.","other":"Peere mit dem Tier-1-Club: Ihre Kunden kommen gratis mit. {n} Netze kommen schon mit einem Peer mit."}, diff --git a/site/i18n/es.js b/site/i18n/es.js index 007a5ff..44de436 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -386,8 +386,6 @@ "broker.goal_wave":"Vende una onda en tu vidrio", "broker.goal_wave_d":"Los operadores alquilan alien waves en fibra que has iluminado. Acepta una de tus ofertas.", "broker.goal_win_d":"Tus propios cables llegan a cinco continentes y los operadores te pagan 1 M$ al mes por capacidad.", -"broker.how":"vende según lo que pida el mercado; el bróker se queda el 10 %", -"broker.lead":"El bróker mantiene tu oferta y la va vendiendo con el tiempo, cuando los operadores entre estas dos ciudades quieren capacidad. Se queda el 10 % de cada venta.", "broker.list_all":"Ofrecer las {n}", "broker.list_more":"Ofrecer {n} más", "broker.list_n":{"one":"Ofrecer {n} onda","other":"Ofrecer {n} ondas"}, @@ -3035,6 +3033,75 @@ "loop.something_in_the_noc_glitched_the":"Algo falló en el NOC.
El juego siguió. Si algo parece raro, exporta tu partida y abre una incidencia en GitHub.", "loop.welcome_back_name_your_network_is":"Bienvenido de nuevo, {name}.
Tu red está justo donde la dejaste: {date}.", "loop.your_saved_game_could_not_be":"No se pudo cargar tu partida guardada.
Estaba dañada, así que se guardó una copia y puedes empezar de cero.", +"market.below_floor":"por debajo de tu mínimo", +"market.cool":"❄️ Fría ×{x}", +"market.days_ago":{"one":"hace {n} día","other":"hace {n} días"}, +"market.fee":"El broker se queda con", +"market.fee_broker":"la tarifa de Cable broker", +"market.floor":"Nunca vender por debajo de", +"market.forecast":"En 30 días {a} · en 90 días {b}", +"market.forecast_lock":"Un Cable broker también ve hacia dónde va cada ruta.", +"market.forecast_now":"{n} ahora · {a} en 30 días · {b} en 90 días", +"market.g_sold_as_managed":"{g} vendidos como waves gestionadas", +"market.hold":"Reservar para tu propio tráfico", +"market.hold_d":"La parte del espectro y de la capacidad encendida de cada fibra que el broker nunca vende, para que tu tráfico tenga sitio para crecer.", +"market.hot":"🔥 Caliente ×{x}", +"market.how":"se vende según quiere el mercado; el broker se queda con el {n}%", +"market.lead":"Los operadores compran capacidad en las rutas donde tienes dark fiber. Lo que quiere cada ruta cambia todo el tiempo: las rutas calientes pagan más y se llenan antes, una ruta corta y recta vende waves con prima, y una larga cuesta más porque su fibra cuesta más. Elige qué vende el broker, a partir de qué demanda y a qué precio.", +"market.lead_fiber":"El broker guarda tu anuncio y lo va vendiendo con el tiempo, cuando los operadores entre estas dos ciudades quieren capacidad. Se queda con el {n}% de cada venta.", +"market.legend":"Cada barra: lo vendido (verde) de lo que quiere la ruta (la línea); la marca rosa es tu mínimo.", +"market.managed_wave":"Wave gestionada", +"market.min":"Anunciar mientras la ruta quiera al menos", +"market.n_g_left":{"one":"{n} wave gestionada de {g} por vender","other":"{n} waves gestionadas de {g} por vender"}, +"market.n_g_wave_on":{"one":"{n}× wave gestionada de {g} en tu fibra {a}–{b}","other":"{n}× waves gestionadas de {g} en tu fibra {a}–{b}"}, +"market.needs_optic":"necesita una óptica de {g} en esta fibra", +"market.news":"Noticias del mercado", +"market.news_ai_big":"Un clúster de IA quiere hablar entre {a} y {b}: allí las waves de 400G para arriba están muy buscadas.", +"market.news_boom":"Una serie de streaming inunda {a}: los operadores quieren más espectro y waves de 100G desde allí.", +"market.news_cut":"Fibra cortada entre {a} y {b}: los operadores quieren caminos diversos alrededor.", +"market.news_dc_big":"Un hyperscaler empieza a construir cerca de {a}: se buscan waves grandes y pares oscuros desde allí.", +"market.news_exch":"Los traders mueven sus motores de matching a {a}: las waves rápidas desde allí pagan más.", +"market.news_glut":"Un rival enciende fibra nueva entre {a} y {b}: allí los compradores se enfrían.", +"market.news_merge":"Dos operadores se fusionan entre {a} y {b}: allí hay menos compradores.", +"market.news_redsea":"Hay cables submarinos cortados: todas las rutas submarinas están en demanda.", +"market.no_news":"Todo tranquilo por ahora.", +"market.no_room":"sin sitio: enciende más capacidad", +"market.no_routes":"Aún no tienes dark fiber lista. Alquila o cava alguna, y su ruta aparece aquí.", +"market.not_selling":"No a la venta", +"market.not_yet":"Aquí nadie quiere esto todavía: {list}.", +"market.open":"Lambda Bazaar", +"market.p_iru":"IRUs de pares oscuros", +"market.p_iru_d":"Un par libre en una zanja que cavaste tú: dos años de su alquiler por adelantado, luego un poco de mantenimiento al mes.", +"market.p_spec":"Espectro", +"market.p_spec_d":"Una alien wave: un canal de tu line system, y el comprador pone la óptica.", +"market.p_w100":"Waves gestionadas de 100G", +"market.p_w100_d":"Sacadas de la capacidad que encendiste: pagan más que el espectro, y a tu tráfico le queda eso de menos.", +"market.p_w1600":"Waves gestionadas de 1,6T", +"market.p_w1600_d":"Una wave en una óptica de 1,6T: el bit más barato que puedes vender, y lo que quieren los mayores compradores con los años.", +"market.p_w400":"Waves gestionadas de 400G", +"market.p_w400_d":"2,7 veces el precio de una wave de 100G por cuatro veces la capacidad (3,8 veces en submarino). Los data centers de IA las quieren.", +"market.p_w800":"Waves gestionadas de 800G", +"market.p_w800_d":"Una wave en una óptica de 800G. Los compradores se pasan a ellas tras unos años, los data centers de IA primero.", +"market.price":"{price}/mes · {pct}% de la tarifa", +"market.price_pair":"{up} por adelantado + {price}/mes · {pct}% de la tarifa", +"market.route_meta":"{km} km · {ms} ms · waves rápidas +{n}%", +"market.route_off":"El broker la deja en paz", +"market.route_on":"El broker vende aquí", +"market.routes":"Tus rutas", +"market.row":"{want} pedidas · {sold} vendidas · {listed} anunciadas", +"market.sales":"Capacidad que vendes", +"market.scout":"Rutas que podrías construir", +"market.scout_d":"Entre tus POPs, todavía sin fibra tuya: qué quiere cada ruta y hacia dónde va, las más valiosas primero.", +"market.scout_none":"Construye POPs en más ciudades para ver rutas entre ellas.", +"market.scout_spend":"{km} km · los operadores allí gastan unos {v}/mes a precios de hoy", +"market.selling":"A la venta", +"market.sold_pair":"Tu broker vendió un par oscuro.
{name} paga {up} por adelantado por {what}, luego {price}/mes.", +"market.steady":"Estable", +"market.tab":"Mercado de capacidad", +"market.title":"Lambda Bazaar", +"market.today":"hoy", +"market.upgraded":"{name} crece.
Sus {n}× waves de {g0} en {a}–{b} pasan a {g1}: {price}/mes.", +"market.wants_more":"{name} quiere crecer de waves de {g0} a {g1} en {a}–{b}, pero esa fibra no tiene sitio. Enciende más capacidad, o reserva menos.", "meet_a_network.all_n_out_of_reach":{"one":"{n} fuera de alcance","other":"Las {n} fuera de alcance"}, "meet_a_network.peer_with_the_tier_1_club":"Haz peering con el club de los Tier 1: sus clientes vienen gratis. Solo las redes que no están en el cono de nadie necesitan peering propio.", "meet_a_network.peer_with_the_tier_1_club_n":{"one":"Haz peering con el club de los Tier 1: sus clientes vienen gratis. {n} red ya viene con un peer.","other":"Haz peering con el club de los Tier 1: sus clientes vienen gratis. {n} redes ya vienen con un peer."}, diff --git a/site/i18n/fr.js b/site/i18n/fr.js index b79b0fc..069032e 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -386,8 +386,6 @@ "broker.goal_wave":"Vends une longueur d’onde sur ton verre", "broker.goal_wave_d":"Les opérateurs louent des alien waves sur la fibre que tu as allumée. Accepte-en une dans tes offres.", "broker.goal_win_d":"Tes propres câbles atterrissent sur cinq continents, et les opérateurs te paient 1 M$ par mois de capacité.", -"broker.how":"il vend selon la demande ; le courtier garde 10 %", -"broker.lead":"Le courtier garde ton annonce et la vend au fil du temps, quand les opérateurs entre ces deux villes veulent de la capacité. Il garde 10 % de chaque vente.", "broker.list_all":"Proposer les {n}", "broker.list_more":"En proposer {n} de plus", "broker.list_n":{"one":"Proposer {n} longueur d’onde","other":"Proposer {n} longueurs d’onde"}, @@ -3035,6 +3033,75 @@ "loop.something_in_the_noc_glitched_the":"Un truc a buggé dans le NOC.
Le jeu a continué. Si quelque chose semble bizarre, exporte ta sauvegarde et ouvre une issue sur GitHub.", "loop.welcome_back_name_your_network_is":"Re-bonjour, {name}.
Ton réseau est exactement là où tu l’as laissé : {date}.", "loop.your_saved_game_could_not_be":"Impossible de charger ta sauvegarde.
Elle était endommagée : une copie a été conservée et tu peux repartir de zéro.", +"market.below_floor":"sous ton plancher", +"market.cool":"❄️ Froide ×{x}", +"market.days_ago":{"one":"il y a {n} jour","other":"il y a {n} jours"}, +"market.fee":"Le broker garde", +"market.fee_broker":"le tarif d'un Cable broker", +"market.floor":"Ne jamais vendre sous", +"market.forecast":"Dans 30 jours {a} · dans 90 jours {b}", +"market.forecast_lock":"Un Cable broker voit aussi où va chaque route.", +"market.forecast_now":"{n} maintenant · {a} dans 30 jours · {b} dans 90 jours", +"market.g_sold_as_managed":"{g} vendus en waves gérées", +"market.hold":"Garder pour ton propre trafic", +"market.hold_d":"La part du spectre et de la capacité allumée de chaque fibre que le broker ne vend jamais, pour que ton trafic ait de la place pour grandir.", +"market.hot":"🔥 Chaude ×{x}", +"market.how":"elle se vend au gré du marché ; le broker garde {n} %", +"market.lead":"Les opérateurs achètent de la capacité sur les routes où tu as de la dark fiber. Ce que veut chaque route bouge tout le temps : les routes chaudes paient plus et se remplissent plus vite, une route courte et droite vend ses waves plus cher, et une longue coûte plus parce que sa fibre coûte plus. Choisis ce que vend le broker, à partir de quelle demande et à quel prix.", +"market.lead_fiber":"Le broker garde ton annonce et la vend au fil du temps, quand les opérateurs entre ces deux villes veulent de la capacité. Il garde {n} % de chaque vente.", +"market.legend":"Chaque barre : ce qui est vendu (vert) de ce que veut la route (le trait) ; la marque rose est ton minimum.", +"market.managed_wave":"Wave gérée", +"market.min":"En vente tant que la route veut au moins", +"market.n_g_left":{"one":"{n} wave gérée {g} encore à vendre","other":"{n} waves gérées {g} encore à vendre"}, +"market.n_g_wave_on":{"one":"{n}× wave gérée {g} sur ta fibre {a}–{b}","other":"{n}× waves gérées {g} sur ta fibre {a}–{b}"}, +"market.needs_optic":"il faut une optique {g} sur cette fibre", +"market.news":"Nouvelles du marché", +"market.news_ai_big":"Un cluster d'IA veut causer entre {a} et {b} : les waves de 400G et plus y sont très demandées.", +"market.news_boom":"Une série en streaming inonde {a} : les opérateurs veulent plus de spectre et de waves 100G depuis là-bas.", +"market.news_cut":"Fibre coupée entre {a} et {b} : les opérateurs veulent des chemins de secours autour.", +"market.news_dc_big":"Un hyperscaler lance un chantier près de {a} : on cherche de grosses waves et des paires noires depuis là-bas.", +"market.news_exch":"Les traders déplacent leurs moteurs d'appariement à {a} : les waves rapides depuis là-bas paient plus.", +"market.news_glut":"Un rival allume de la nouvelle fibre entre {a} et {b} : les acheteurs s'y refroidissent.", +"market.news_merge":"Deux opérateurs fusionnent entre {a} et {b} : moins d'acheteurs là-bas.", +"market.news_redsea":"Des câbles sous-marins sont coupés : toutes les routes sous-marines sont demandées.", +"market.no_news":"Calme plat pour l'instant.", +"market.no_room":"plus de place : allume plus de capacité", +"market.no_routes":"Tu n'as pas encore de dark fiber prête. Loue-en ou creuse, et sa route apparaît ici.", +"market.not_selling":"Pas en vente", +"market.not_yet":"Personne n'en veut encore ici : {list}.", +"market.open":"Lambda Bazaar", +"market.p_iru":"IRU de paires noires", +"market.p_iru_d":"Une paire libre dans une tranchée que tu as creusée : deux ans de sa location d'avance, puis un peu d'entretien chaque mois.", +"market.p_spec":"Spectre", +"market.p_spec_d":"Une alien wave : un canal de ton line system, et l'acheteur apporte l'optique.", +"market.p_w100":"Waves gérées 100G", +"market.p_w100_d":"Prises sur la capacité que tu as allumée : elles paient plus que le spectre, et ton trafic en a d'autant moins.", +"market.p_w1600":"Waves gérées 1,6T", +"market.p_w1600_d":"Une wave sur une optique 1,6T : le bit le moins cher que tu puisses vendre, et ce que veulent les plus gros acheteurs au fil des années.", +"market.p_w400":"Waves gérées 400G", +"market.p_w400_d":"2,7 fois le prix d'une wave 100G pour quatre fois la capacité (3,8 fois en sous-marin). Les data centers d'IA en raffolent.", +"market.p_w800":"Waves gérées 800G", +"market.p_w800_d":"Une wave sur une optique 800G. Les acheteurs y passent au bout de quelques années, les data centers d'IA d'abord.", +"market.price":"{price}/mois · {pct} % du tarif", +"market.price_pair":"{up} d'avance + {price}/mois · {pct} % du tarif", +"market.route_meta":"{km} km · {ms} ms · waves rapides +{n} %", +"market.route_off":"Le broker la laisse tranquille", +"market.route_on":"Le broker vend ici", +"market.routes":"Tes routes", +"market.row":"{want} demandées · {sold} vendues · {listed} en vente", +"market.sales":"Capacité que tu vends", +"market.scout":"Routes que tu pourrais construire", +"market.scout_d":"Entre tes POP, sans ta fibre pour l'instant : ce que veut chaque route et où elle va, les plus précieuses d'abord.", +"market.scout_none":"Construis des POP dans plus de villes pour voir les routes entre elles.", +"market.scout_spend":"{km} km · les opérateurs y dépensent environ {v}/mois aux prix d'aujourd'hui", +"market.selling":"En vente", +"market.sold_pair":"Ton broker a vendu une paire noire.
{name} paie {up} d'avance pour {what}, puis {price}/mois.", +"market.steady":"Stable", +"market.tab":"Marché de la capacité", +"market.title":"Lambda Bazaar", +"market.today":"aujourd'hui", +"market.upgraded":"{name} grandit.
Ses {n}× waves {g0} sur {a}–{b} passent en {g1} : {price}/mois.", +"market.wants_more":"{name} veut grandir de waves {g0} à {g1} sur {a}–{b}, mais cette fibre n'a plus de place. Allume plus de capacité, ou garde moins de côté.", "meet_a_network.all_n_out_of_reach":{"one":"Les {n} hors couverture","other":"Les {n} hors couverture"}, "meet_a_network.peer_with_the_tier_1_club":"Peere avec le club des Tier 1 : leurs clients viennent gratuitement avec. Seuls les réseaux qui ne sont dans le cône de personne demandent leur propre peering.", "meet_a_network.peer_with_the_tier_1_club_n":{"one":"Peere avec le club des Tier 1 : leurs clients viennent gratuitement avec. {n} réseau vient déjà avec un peer.","other":"Peere avec le club des Tier 1 : leurs clients viennent gratuitement avec. {n} réseaux viennent déjà avec un peer."}, diff --git a/site/i18n/it.js b/site/i18n/it.js index cd12377..3469d49 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -386,8 +386,6 @@ "broker.goal_wave":"Vendi una wave sul tuo vetro", "broker.goal_wave_d":"Gli operatori affittano alien wave sulla fibra che hai acceso. Accettane una dalle tue offerte.", "broker.goal_win_d":"I tuoi cavi approdano su cinque continenti e gli operatori ti pagano 1 M$ al mese di capacità.", -"broker.how":"vende quando il mercato lo chiede; il broker tiene il 10%", -"broker.lead":"Il broker tiene la tua offerta e la vende nel tempo, quando gli operatori tra queste due città vogliono capacità. Tiene il 10% di ogni vendita.", "broker.list_all":"Offri tutte le {n}", "broker.list_more":"Offrine altre {n}", "broker.list_n":{"one":"Offri {n} onda","other":"Offri {n} onde"}, @@ -3035,6 +3033,75 @@ "loop.something_in_the_noc_glitched_the":"Qualcosa nel NOC si è inceppato.
Il gioco è andato avanti. Se qualcosa sembra strano, esporta il salvataggio e apri una issue su GitHub.", "loop.welcome_back_name_your_network_is":"Bentornato, {name}.
La tua rete è proprio dove l’avevi lasciata: {date}.", "loop.your_saved_game_could_not_be":"Impossibile caricare la partita salvata.
Era danneggiata: ne abbiamo tenuto una copia di backup e puoi ricominciare da zero.", +"market.below_floor":"sotto il tuo minimo", +"market.cool":"❄️ Freddo ×{x}", +"market.days_ago":{"one":"{n} giorno fa","other":"{n} giorni fa"}, +"market.fee":"Il broker trattiene", +"market.fee_broker":"la tariffa da Cable broker", +"market.floor":"Mai vendere sotto", +"market.forecast":"Tra 30 giorni {a} · tra 90 giorni {b}", +"market.forecast_lock":"Un Cable broker vede anche dove va ogni tratta.", +"market.forecast_now":"{n} ora · {a} tra 30 giorni · {b} tra 90 giorni", +"market.g_sold_as_managed":"{g} venduti come wave gestite", +"market.hold":"Tieni da parte per il tuo traffico", +"market.hold_d":"La quota di spettro e di capacità accesa di ogni fibra che il broker non vende mai, così il tuo traffico ha spazio per crescere.", +"market.hot":"🔥 Caldo ×{x}", +"market.how":"si vende come vuole il mercato; il broker trattiene il {n}%", +"market.lead":"Gli operatori comprano capacità sulle tratte dove hai dark fiber. Quello che vuole ogni tratta cambia di continuo: le tratte calde pagano di più e si riempiono prima, una tratta corta e dritta vende wave a prezzo premium, e una lunga costa di più perché costa di più la sua fibra. Scegli cosa vende il broker, da quale domanda e a che prezzo.", +"market.lead_fiber":"Il broker tiene il tuo annuncio e lo vende nel tempo, man mano che gli operatori tra queste due città vogliono capacità. Trattiene il {n}% di ogni vendita.", +"market.legend":"Ogni barra: quanto è venduto (verde) di quanto vuole la tratta (la linea); la tacca rosa è il tuo minimo.", +"market.managed_wave":"Wave gestita", +"market.min":"In vendita finché la tratta vuole almeno", +"market.n_g_left":{"one":"{n} wave gestita da {g} ancora da vendere","other":"{n} wave gestite da {g} ancora da vendere"}, +"market.n_g_wave_on":{"one":"{n}× wave gestita da {g} sulla tua fibra {a}–{b}","other":"{n}× wave gestite da {g} sulla tua fibra {a}–{b}"}, +"market.needs_optic":"serve un'ottica da {g} su questa fibra", +"market.news":"Notizie dal mercato", +"market.news_ai_big":"Un cluster di IA vuole parlare tra {a} e {b}: lì le wave da 400G in su vanno a ruba.", +"market.news_boom":"Una serie in streaming invade {a}: gli operatori vogliono più spettro e wave da 100G da lì.", +"market.news_cut":"Fibra tranciata tra {a} e {b}: gli operatori cercano percorsi alternativi.", +"market.news_dc_big":"Un hyperscaler apre un cantiere vicino a {a}: da lì si cercano wave grandi e coppie di dark fiber.", +"market.news_exch":"I trader spostano i loro motori di matching a {a}: le wave veloci da lì pagano di più.", +"market.news_glut":"Un rivale accende nuova fibra tra {a} e {b}: lì i compratori si raffreddano.", +"market.news_merge":"Due operatori si fondono tra {a} e {b}: lì ci sono meno compratori.", +"market.news_redsea":"Cavi sottomarini tranciati: tutte le tratte sottomarine sono richieste.", +"market.no_news":"Tutto tranquillo finora.", +"market.no_room":"niente spazio: accendi più capacità", +"market.no_routes":"Non hai ancora dark fiber pronta. Prendila in leasing o scavala, e la sua tratta compare qui.", +"market.not_selling":"Non in vendita", +"market.not_yet":"Qui nessuno le vuole ancora: {list}.", +"market.open":"Lambda Bazaar", +"market.p_iru":"IRU di coppie dark", +"market.p_iru_d":"Una coppia libera in una trincea che hai scavato tu: due anni del suo leasing in anticipo, poi un po' di manutenzione al mese.", +"market.p_spec":"Spettro", +"market.p_spec_d":"Una alien wave: un canale del tuo line system, e l'ottica la porta il compratore.", +"market.p_w100":"Wave gestite da 100G", +"market.p_w100_d":"Ricavate dalla capacità che hai acceso: pagano più dello spettro, e al tuo traffico ne resta altrettanto di meno.", +"market.p_w1600":"Wave gestite da 1,6T", +"market.p_w1600_d":"Una wave su un'ottica da 1,6T: il bit più economico che puoi vendere, e quello che vogliono i compratori più grossi col passare degli anni.", +"market.p_w400":"Wave gestite da 400G", +"market.p_w400_d":"2,7 volte il prezzo di una wave da 100G per quattro volte la capacità (3,8 volte sui cavi sottomarini). I data center di IA le vogliono.", +"market.p_w800":"Wave gestite da 800G", +"market.p_w800_d":"Una wave su un'ottica da 800G. I compratori ci passano dopo qualche anno, prima i data center di IA.", +"market.price":"{price}/mese · {pct}% del listino", +"market.price_pair":"{up} in anticipo + {price}/mese · {pct}% del listino", +"market.route_meta":"{km} km · {ms} ms · wave veloci +{n}%", +"market.route_off":"Il broker la lascia stare", +"market.route_on":"Il broker vende qui", +"market.routes":"Le tue tratte", +"market.row":"{want} richieste · {sold} vendute · {listed} in vendita", +"market.sales":"Capacità che vendi", +"market.scout":"Tratte che potresti costruire", +"market.scout_d":"Tra i tuoi POP, senza ancora la tua fibra: cosa vuole ogni tratta e dove sta andando, le più preziose prima.", +"market.scout_none":"Costruisci POP in più città per vedere le tratte tra di loro.", +"market.scout_spend":"{km} km · lì gli operatori spendono circa {v}/mese ai prezzi di oggi", +"market.selling":"In vendita", +"market.sold_pair":"Il tuo broker ha venduto una coppia dark.
{name} paga {up} in anticipo per {what}, poi {price}/mese.", +"market.steady":"Stabile", +"market.tab":"Mercato della capacità", +"market.title":"Lambda Bazaar", +"market.today":"oggi", +"market.upgraded":"{name} cresce.
Le sue {n}× wave da {g0} su {a}–{b} diventano da {g1}: {price}/mese.", +"market.wants_more":"{name} vuole crescere da wave da {g0} a {g1} su {a}–{b}, ma quella fibra non ha spazio. Accendi più capacità, o tieni da parte di meno.", "meet_a_network.all_n_out_of_reach":{"one":"Tutte le {n} fuori copertura","other":"Tutte le {n} fuori copertura"}, "meet_a_network.peer_with_the_tier_1_club":"Fai peering con il club dei Tier 1: i loro clienti arrivano gratis. Solo le reti che non stanno nel cono di nessuno vogliono un peering tutto loro.", "meet_a_network.peer_with_the_tier_1_club_n":{"one":"Fai peering con il club dei Tier 1: i loro clienti arrivano gratis. {n} rete arriva già con un peer.","other":"Fai peering con il club dei Tier 1: i loro clienti arrivano gratis. {n} reti arrivano già con un peer."}, diff --git a/site/i18n/pt.js b/site/i18n/pt.js index bb8e786..2b86373 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -386,8 +386,6 @@ "broker.goal_wave":"Venda uma wave no seu vidro", "broker.goal_wave_d":"Operadoras alugam alien waves na fibra que você acendeu. Aceite uma das suas ofertas.", "broker.goal_win_d":"Seus próprios cabos chegam a cinco continentes e as operadoras pagam US$ 1 mi por mês de capacidade.", -"broker.how":"vende conforme a demanda; o corretor fica com 10%", -"broker.lead":"O corretor mantém seu anúncio e vende aos poucos, quando operadoras entre estas duas cidades querem capacidade. Ele fica com 10% de cada venda.", "broker.list_all":"Anunciar todas as {n}", "broker.list_more":"Anunciar mais {n}", "broker.list_n":{"one":"Anunciar {n} onda","other":"Anunciar {n} ondas"}, @@ -3035,6 +3033,75 @@ "loop.something_in_the_noc_glitched_the":"Algo no NOC deu pau.
O jogo continuou. Se algo parecer estranho, exporte seu save e abra uma issue no GitHub.", "loop.welcome_back_name_your_network_is":"Bem-vindo de volta, {name}.
Sua rede está do jeitinho que você deixou: {date}.", "loop.your_saved_game_could_not_be":"Não deu para carregar seu jogo salvo.
Ele estava corrompido, então guardamos um backup e você pode começar do zero.", +"market.below_floor":"abaixo do seu mínimo", +"market.cool":"❄️ Fria ×{x}", +"market.days_ago":{"one":"há {n} dia","other":"há {n} dias"}, +"market.fee":"O broker fica com", +"market.fee_broker":"a taxa de Cable broker", +"market.floor":"Nunca vender abaixo de", +"market.forecast":"Em 30 dias {a} · em 90 dias {b}", +"market.forecast_lock":"Um Cable broker também vê para onde cada rota está indo.", +"market.forecast_now":"{n} agora · {a} em 30 dias · {b} em 90 dias", +"market.g_sold_as_managed":"{g} vendidos como waves gerenciadas", +"market.hold":"Reservar para o seu próprio tráfego", +"market.hold_d":"A parte do espectro e da capacidade acesa de cada fibra que o broker nunca vende, para o seu tráfego ter espaço para crescer.", +"market.hot":"🔥 Quente ×{x}", +"market.how":"vende conforme o mercado quer; o broker fica com {n}%", +"market.lead":"As operadoras compram capacidade nas rotas onde você tem dark fiber. O que cada rota quer muda o tempo todo: rotas quentes pagam mais e enchem mais rápido, uma rota curta e reta vende waves com prêmio, e uma longa custa mais porque a fibra dela custa mais. Escolha o que o broker vende, a partir de qual demanda e a que preço.", +"market.lead_fiber":"O broker guarda o seu anúncio e vende aos poucos, conforme as operadoras entre essas duas cidades querem capacidade. Ele fica com {n}% de cada venda.", +"market.legend":"Cada barra: o que está vendido (verde) do que a rota quer (a linha); o traço rosa é o seu mínimo.", +"market.managed_wave":"Wave gerenciada", +"market.min":"Anunciar enquanto a rota quiser pelo menos", +"market.n_g_left":{"one":"{n} wave gerenciada de {g} ainda à venda","other":"{n} waves gerenciadas de {g} ainda à venda"}, +"market.n_g_wave_on":{"one":"{n}× wave gerenciada de {g} na sua fibra {a}–{b}","other":"{n}× waves gerenciadas de {g} na sua fibra {a}–{b}"}, +"market.needs_optic":"precisa de uma óptica de {g} nesta fibra", +"market.news":"Notícias do mercado", +"market.news_ai_big":"Um cluster de IA quer conversar entre {a} e {b}: as waves de 400G para cima lá estão disputadas.", +"market.news_boom":"Uma série de streaming inunda {a}: as operadoras querem mais espectro e waves de 100G de lá.", +"market.news_cut":"Fibra cortada entre {a} e {b}: as operadoras querem caminhos diversos em volta.", +"market.news_dc_big":"Um hyperscaler começa a construir perto de {a}: procuram-se waves grandes e pares escuros de lá.", +"market.news_exch":"Traders levam seus motores de matching para {a}: waves rápidas de lá pagam mais.", +"market.news_glut":"Um rival acende fibra nova entre {a} e {b}: os compradores lá esfriam.", +"market.news_merge":"Duas operadoras se fundem entre {a} e {b}: menos compradores lá.", +"market.news_redsea":"Cabos submarinos cortados: todas as rotas submarinas estão em alta.", +"market.no_news":"Tudo calmo por enquanto.", +"market.no_room":"sem espaço: acenda mais capacidade", +"market.no_routes":"Você ainda não tem dark fiber pronta. Alugue ou cave alguma, e a rota dela aparece aqui.", +"market.not_selling":"Fora de venda", +"market.not_yet":"Ninguém quer isto aqui ainda: {list}.", +"market.open":"Lambda Bazaar", +"market.p_iru":"IRUs de pares escuros", +"market.p_iru_d":"Um par livre numa vala que você cavou: dois anos do aluguel dele adiantados, depois uma pequena manutenção por mês.", +"market.p_spec":"Espectro", +"market.p_spec_d":"Uma alien wave: um canal do seu line system, e o comprador traz a óptica.", +"market.p_w100":"Waves gerenciadas de 100G", +"market.p_w100_d":"Tiradas da capacidade que você acendeu: pagam mais que o espectro, e o seu tráfego fica com isso a menos.", +"market.p_w1600":"Waves gerenciadas de 1,6T", +"market.p_w1600_d":"Uma wave numa óptica de 1,6T: o bit mais barato que você pode vender, e o que os maiores compradores querem com o passar dos anos.", +"market.p_w400":"Waves gerenciadas de 400G", +"market.p_w400_d":"2,7 vezes o preço de uma wave de 100G por quatro vezes a capacidade (3,8 vezes no submarino). Data centers de IA querem.", +"market.p_w800":"Waves gerenciadas de 800G", +"market.p_w800_d":"Uma wave numa óptica de 800G. Os compradores passam para elas depois de alguns anos, data centers de IA primeiro.", +"market.price":"{price}/mês · {pct}% da tabela", +"market.price_pair":"{up} adiantado + {price}/mês · {pct}% da tabela", +"market.route_meta":"{km} km · {ms} ms · waves rápidas +{n}%", +"market.route_off":"O broker deixa quieta", +"market.route_on":"O broker negocia aqui", +"market.routes":"Suas rotas", +"market.row":"{want} pedidas · {sold} vendidas · {listed} anunciadas", +"market.sales":"Capacidade que você vende", +"market.scout":"Rotas que você poderia construir", +"market.scout_d":"Entre os seus POPs, ainda sem fibra sua: o que cada rota quer e para onde vai, as mais valiosas primeiro.", +"market.scout_none":"Construa POPs em mais cidades para ver rotas entre elas.", +"market.scout_spend":"{km} km · as operadoras lá gastam cerca de {v}/mês aos preços de hoje", +"market.selling":"À venda", +"market.sold_pair":"O seu broker vendeu um par escuro.
{name} paga {up} adiantado por {what}, depois {price}/mês.", +"market.steady":"Estável", +"market.tab":"Mercado de capacidade", +"market.title":"Lambda Bazaar", +"market.today":"hoje", +"market.upgraded":"{name} cresce.
As suas {n}× waves de {g0} em {a}–{b} viram {g1}: {price}/mês.", +"market.wants_more":"{name} quer crescer de waves de {g0} para {g1} em {a}–{b}, mas essa fibra não tem espaço. Acenda mais capacidade, ou reserve menos.", "meet_a_network.all_n_out_of_reach":{"one":"Todas as {n} fora de alcance","other":"Todas as {n} fora de alcance"}, "meet_a_network.peer_with_the_tier_1_club":"Faça peering com o clube dos Tier 1: os clientes deles vêm de graça. Só as redes que não estão no cone de ninguém precisam de peering próprio.", "meet_a_network.peer_with_the_tier_1_club_n":{"one":"Faça peering com o clube dos Tier 1: os clientes deles vêm de graça. {n} rede já vem junto com um peer.","other":"Faça peering com o clube dos Tier 1: os clientes deles vêm de graça. {n} redes já vêm junto com um peer."}, diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 7c0c97a..266cf70 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -225,6 +225,12 @@ const API_CMD={ /* ---------- capacity broker ---------- */ listFiber:{args:[['id','entityId'],['w','integer'],['p','integer',false]],watch:['links.#id'], doc:'List spare capacity on a dark-fiber span with a capacity broker as a standing listing: w alien waves, and p (own cables only) your spare fiber pair. The broker sells them off over time as carriers on that route want capacity; a busy route sells in days, a road to nowhere maybe once.'}, + mktHold:{args:[['v','integer']],watch:['cm'], + doc:'Capacity market (Lambda Bazaar): the share of every fiber (0, 10, 25 or 50%) the broker never sells, kept for your own traffic.'}, + mktCfg:{args:[['p','string'],['k','string'],['v','integer']],watch:['cm'], + doc:'Capacity market: for product p (spec = alien-wave spectrum, w100/w400 = managed 100G/400G waves carved from your lit capacity, iru = dark pairs on fiber you dug), set k: on (v 1 or 0: the broker lists it on every route by your thresholds), min (list only while the route wants at least v units; spec/w400 1,2,4,8, w100 1,4,8,16, iru 1,2) or floor (never sell below v% of list: 60, 80, 100, 120). Demand and prices move every day.'}, + mktRoute:{args:[['k','string']],watch:['cm'], + doc:'Capacity market: toggle whether the broker trades on a route (k = the two city ids sorted and joined by |, e.g. ams|fra).'}, unlistFiber:{args:[['id','entityId']],watch:['links.#id'], doc:'Take the listing down. What the broker already sold stays sold.'}, setChCount:{args:[['id','entityId'],['o','opticId'],['n','integer']],watch:['links.#id'], @@ -465,6 +471,7 @@ const API_VIEW={ dashClose:{args:[],doc:'Close the NOC dashboard.'}, nocWindow:{args:[],doc:'Open the NOC dashboard in a window of its own, for a second display.'}, dashTab:{args:[['k','dashTab']],doc:'Switch the NOC dashboard tab.'}, + marketOpen:{args:[],doc:'Open the NOC dashboard at the capacity market (Lambda Bazaar).'}, dashSort:{args:[['k','dashSortKey']],doc:'Flip a dashboard column\'s sort.'}, dashLink:{args:[['id','entityId']],doc:'Jump from the dashboard to a link\'s panel.'}, bank:{args:[],doc:'Open the bank.'}, diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js index 831f97c..83e7449 100644 --- a/src/agent/30-docs.js +++ b/src/agent/30-docs.js @@ -76,6 +76,7 @@ const API_STATE_DOC={ confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, + cm:{type:'map',doc:'The capacity market (Lambda Bazaar): hold (% of every fiber never sold, kept for your own traffic), p (per product spec/w100/w400/w800/w1600/iru: on, min demand, floor % of list), off (routes the broker leaves alone, by "a|b"), sh (market shocks: why, from, until, m multiplier, on a route k, a city c or every subsea route), news (the latest market news), seen (incident ids already turned into news).'}, cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, won:{type:'boolean',doc:'You reached Tier 1.'}, diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index d4f368f..8fd1c7b 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -68,7 +68,10 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1) // all its channels. Nothing changes while a frame is drawn, so draw() keeps the answers in DFC for that frame. let DFC=null; const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; -const dfCap0=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; +// dfLit: everything the optics carry; dfCap0: what is left for your own traffic once managed waves sold on it (mwG(), +// the capacity market) are carved out. +const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; +const dfCap0=l=>Math.max(0,dfLit(l)-mwG(l)); const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); diff --git a/src/game/40-progress/10-businesses.js b/src/game/40-progress/10-businesses.js index 717a1a2..a79314c 100644 --- a/src/game/40-progress/10-businesses.js +++ b/src/game/40-progress/10-businesses.js @@ -18,6 +18,8 @@ const BIZ_T={ event:{l:tr('common.event_network'),opts:[100,200,400,800,1600,3200],rate:0,event:true,lv:2,names:['Carnaval Parade','Diwali Streaming Night','The Big Football Final','NANOG 99','APRICOT 2027','DENOG 18','UKNOF 56','RIPE 94','DKNOG 16','Burning Router Festival','Euro-Pop Song Contest','Formula Ping Grand Prix','The Big Game','Olympic Pings','A Pop Megastar Stadium Tour','LAN Party of the Century','The Keynote (One More Thing)','Gamer-Con Expo','Oktoberfest Livestream']}, sdwan:{l:tr('businesses.sd_wan_for_a_chain'),opts:[1,2,5,10],rate:0,l2:true,sdwan:true,km:0,lv:2,names:['Kebab Kingdom','Pretzel Palace','Burger Router Inc.','Café Latte-ncy','Hardware Hut Stores','Pharma-See Pharmacies','Bank of Tiny Branches','Supermarket Superhighway','Fitness Pings Gyms','Hotel Hops Group','Doughnut Data Diners']}, wwave:{l:tr('common.wholesale_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Zay-No Fiber','Loomin’ Technologies','Clown Castle Fiber','G&T (Gin and Transit)','A Hyperscaler Who Shall Not Be Named','Megapork','youNetworks']}, + // A managed wave (the capacity market): carved out of capacity you lit; b.g is its size (100 or 400G), b.slots how many. + mwave:{l:tr('market.managed_wave'),opts:[1],rate:0,fiber:true,lv:2,names:['Lambda Lambda Lambda','Coherent Thoughts Inc.','Photon Express','Transponder Tribe','Sea Change Networks','Spectrum Spectacle','Wavelength Wanderers','Muxed Signals Ltd.']}, dfpair:{l:tr('businesses.dark_fiber_pair_lease'),opts:[1],rate:0,fiber:true,lv:3,names:['A Hyperscaler Who Shall Not Be Named','Goggle Fiber Division','Faceplant Infra','Amazin’ Backbone Team','A Very Secretive Trading Firm']}, scrub:{l:tr('businesses.ddos_protection_dia'),opts:[1,5,10,20],rate:900}, aiwan:{l:tr('businesses.ai_wan_between_two_ai_factories'),opts:[3200,6400,12800],rate:0,l2:true,div:true,mega:true,km:0.45,lv:4,names:['Fairweather AI WAN','Planet-Scale Superfactory Link','Two Brains One Model Inc.','Distributed Godlike Compute','The Gigawatt Handshake']}, diff --git a/src/game/40-progress/20-goals.js b/src/game/40-progress/20-goals.js index ffe756b..72624ce 100644 --- a/src/game/40-progress/20-goals.js +++ b/src/game/40-progress/20-goals.js @@ -24,7 +24,7 @@ const GOALS=[ // (37-cable-broker.js). Ids of their own, so a save keeps the ladder it ran. Rewards are larger: glass costs more. const BROKER_GOALS=[ {id:'bk_df',t:tr('goals.light_your_own_dark_fiber'),d:tr('broker.goal_df_d'),r:25000,ok:()=>S.links.some(l=>l.kind==='df'&&dfCap(l)>0)}, - {id:'bk_wave',t:tr('broker.goal_wave'),d:tr('broker.goal_wave_d'),r:40000,ok:()=>S.biz.some(b=>b.type==='wwave'||b.type==='capw'&&!capPend(b))}, + {id:'bk_wave',t:tr('broker.goal_wave'),d:tr('broker.goal_wave_d'),r:40000,ok:()=>S.biz.some(b=>b.type==='wwave'||b.type==='mwave'||b.type==='capw'&&!capPend(b))}, {id:'bk_pair',t:tr('broker.goal_pair'),d:tr('broker.goal_pair_d'),r:50000,ok:()=>S.biz.some(b=>(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')&&!capPend(b))}, {id:'bk_sea',t:tr('broker.goal_sea'),d:tr('broker.goal_sea_d'),r:150000,ok:()=>S.links.some(l=>ownGlassL(l)&&l.sub)}, {id:'bk_deal',t:tr('broker.goal_deal'),d:tr('broker.goal_deal_d'),r:100000,ok:()=>(S.stats.capDone||0)>0}, diff --git a/src/game/60-features/37-cable-broker.js b/src/game/60-features/37-cable-broker.js index b63ed87..acb830f 100644 --- a/src/game/60-features/37-cable-broker.js +++ b/src/game/60-features/37-cable-broker.js @@ -10,11 +10,11 @@ const glassKm=()=>S.links.reduce((a,l)=>a+(ownGlassL(l)?l.km:0),0); // The continents your own subsea cables land on. function cableConts(){const r=new Set();for(const l of S.links)if(ownGlassL(l)&&l.sub)for(const c of [l.a,l.b])r.add(CITY[c].reg);return r.size;} // Capacity other carriers buy from you: alien waves, fiber pairs and capacity deals (once delivered). -const CAP_TYPES=['wwave','dfpair','pairs','capw','capsub','capfib']; +const CAP_TYPES=['wwave','mwave','dfpair','pairs','capw','capsub','capfib']; const capSold=b=>CAP_TYPES.includes(b.type)&&!capPend(b); const capSalesMo=()=>S.biz.reduce((a,b)=>a+(capSold(b)?bizMo(b):0),0); // Lit capacity sold, in Gbps: waves (400G each) and subsea capacity. A dark pair is the buyer's to light. -const capSoldG=()=>S.biz.reduce((a,b)=>a+(!capSold(b)?0:b.type==='wwave'?(b.slots||1)*400:b.type==='capw'||b.type==='capsub'?b.bw:0),0); +const capSoldG=()=>S.biz.reduce((a,b)=>a+(!capSold(b)?0:b.type==='wwave'?(b.slots||1)*400:b.type==='mwave'?(b.slots||1)*(b.g||100):b.type==='capw'||b.type==='capsub'?b.bw:0),0); // Two hops of your own glass through one city, each lit to at least g. function glassChain(g){const by={};for(const l of S.links)if(ownGlassL(l)&&dfCap(l)>=g)for(const [c,o] of [[l.a,l.b],[l.b,l.a]])(by[c]=by[c]||new Set()).add(o); return Object.values(by).some(s=>s.size>=2);} diff --git a/src/game/60-features/37-fiber-broker.js b/src/game/60-features/37-fiber-broker.js index d419095..ac03cea 100644 --- a/src/game/60-features/37-fiber-broker.js +++ b/src/game/60-features/37-fiber-broker.js @@ -21,16 +21,5 @@ const brFree=l=>Math.max(0,brMarket(l.a,l.b)-brSold(l.a,l.b)); const WW_SHARE=0.3,WW_FALL=0.6; function wwRate(l,n,cut=1){const F=dfLeaseMo(l.km)+ampCount(l.km)*AMP_MO,M=brMarket(l.a,l.b),s=brSold(l.a,l.b);let r=0; for(let i=0;i0&&freeCh(l)>=1&&Math.random()0&&pairFree(l)&&free>=BR_PAIR&&Math.random()<1/90){brSell(l,'dfpair',1);L.p--;} - if(!(L.w>0)&&!(L.p>0))delete l.list;}} -// A sale: a new carrier on this fiber, or more waves for one that already rents here. -function brSell(l,t,n){const T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;}; - const o=fiberOffer(t,l,nm,0.9);if(t==='wwave'){o.slots=n;o.rate=wwRate(l,n,0.9);o.what=wwWhat(l,n);} - const more=t==='wwave'&&S.biz.find(b=>b.type==='wwave'&&b.link===l.id&&b.name===o.name); - if(more){more.slots=(more.slots||0)+n;more.rate+=o.rate;more.what=wwWhat(l,more.slots);}else S.biz.push(clSign(offerCustomer(o))); - toast(tr('broker.sold',{name:esc(o.name),what:esc(t==='wwave'?wwWhat(l,n):o.what),price:fmt$(o.rate)}),'good'); - floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');} +// The listings sell in the capacity market now (cmDay(), 37-fiber-market.js), with prices and demand that move. +const brTick=()=>cmDay(S.day); diff --git a/src/game/60-features/37-fiber-market.js b/src/game/60-features/37-fiber-market.js new file mode 100644 index 0000000..6236f09 --- /dev/null +++ b/src/game/60-features/37-fiber-market.js @@ -0,0 +1,182 @@ +/* ---------- the capacity market: what carriers want on each route, today and tomorrow ---------- + Every route you hold dark fiber on has buyers for spectrum (an alien wave, the buyer brings the optics), managed + 100G, 400G, 800G and 1.6T waves (carved out of capacity you lit yourself), and dark pairs on fiber you dug (an IRU: a + big sum up front, then a little upkeep a month). How much each route wants moves all the time, as it does in real + life: a slow cycle of its own, weeks of noise, and news (a cable cut next door, a hyperscaler breaking ground, a rival + lighting new glass). Underneath, it grows: carriers want more every year, and bigger waves as the years go by (100G + gives way to 400G, then 800G and 1.6T), and carriers already on your glass ask to move up a size. Hot routes pay more + and fill faster; a short, straight route sells waves at a premium, and a long one costs more because its fiber does. The broker keeps 10% (3% for a Cable broker, who also sees where + each route is heading). S.cm: hold (share kept for your own traffic), p (per product: auto on, min demand, price + floor), off (routes left alone), sh (shocks), news, seen (incidents already turned into news). */ +const CM_P=['spec','w100','w400','w800','w1600','iru'],CM_W=['w100','w400','w800','w1600']; +const CM_L={spec:'w',w100:'m1',w400:'m4',w800:'m8',w1600:'m16',iru:'p'},CM_G={w100:100,w400:400,w800:800,w1600:1600}; +const CM_HOLD=[0,10,25,50],CM_FLOOR=[60,80,100,120],CM_MIN={spec:[1,2,4,8],w100:[1,4,8,16],w400:[1,2,4,8],w800:[1,2,4,8],w1600:[1,2,4],iru:[1,2]}; +const CM_DEF={spec:{on:false,min:2,floor:80},w100:{on:false,min:4,floor:80},w400:{on:false,min:2,floor:80},w800:{on:false,min:1,floor:80},w1600:{on:false,min:1,floor:80},iru:{on:false,min:1,floor:100}}; +// A wave's price against a 100G one, on land and on subsea: 2.7x and 3.8x for 400G (real markets in 2025), and the +// price of a bit keeps falling as waves grow. +const CM_X={w100:[1,1],w400:[2.7,3.8],w800:[4.6,6.6],w1600:[7.8,11]}; +// Cities where trading firms sit: a short route between two of them pays the most for a fast wave. +const CM_FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash']; +const CM_HMAX=2.5; +const cmNew=()=>({hold:25,p:JSON.parse(JSON.stringify(CM_DEF)),off:{},sh:[],news:[],seen:[]}); +const cmCut=()=>broker()?0.97:0.9; +/* A fiber's listing, l.list: {w: spectrum slots, p: pairs} as it always was, plus m1/m4/m8/m16 (managed 100G to 1.6T + waves) when any are listed. cmClean() checks one (a save, or after a day of sales) and returns null when nothing is left. */ +const cmLs=l=>l.list||(l.list={w:0,p:0}); +function cmClean(L){if(!L||typeof L!=='object'||Array.isArray(L))return null;const x={w:int(L.w,0,256,0),p:int(L.p,0,2,0)};let any=x.w||x.p; + for(const p of CM_W){const v=int(L[CM_L[p]],0,256,0);if(v){x[CM_L[p]]=v;any=1;}}return any?x:null;} +// A stable number in [0,1) for a route and a question, different in every game. +const cmU=(k,q)=>hstr(k+'|'+q+'|'+((S&&S.asn)||0))%100000/100000; +/* How hot a route is (1 = its usual self). Its own slow cycle (two waves of 4 to 10 and 1.5 to 3 months) is what a + forecast can see; the weeks of noise on top and news nobody has heard yet are not. */ +function cmCycle(k,d){const p1=120+180*cmU(k,'p1'),p2=40+50*cmU(k,'p2');return 1+0.25*Math.sin(2*Math.PI*(d/p1+cmU(k,'f1')))+0.15*Math.sin(2*Math.PI*(d/p2+cmU(k,'f2')));} +function cmNoise(k,d){const i=Math.floor(d/15),t=(d-i*15)/15,u=t*t*(3-2*t),v=j=>0.85+0.3*cmU(k,'n'+j);return v(i)*(1-u)+v(i+1)*u;} +// News: a shock ramps up over a week, holds, and fades over the last 40% of its time. +const cmShockF=(x,d)=>d=x.until?0:Math.max(0,Math.min(1,(d-x.from+1)/7,(x.until-d)/Math.max(1,(x.until-x.from)*0.4))); +const cmHits=(x,r)=>x.k?x.k===r.k:x.c?x.c===r.a||x.c===r.b:!!x.sub&&r.sub; +function cmShock(r,p,d){let m=1;for(const x of S.cm.sh)if(cmHits(x,r)&&(!x.p||x.p.includes(p))){const f=cmShockF(x,d);if(f)m*=1+(x.m-1)*f;}return m;} +function cmHeat(r,p,d,fc){return clamp(cmCycle(r.k,d)*(fc?1:cmNoise(r.k,d))*cmShock(r,p,d),0.3,CM_HMAX);} +// What a route is: its cities, its fiber (yours, if any), how far and how fast. Without fiber, as you could dig it +// (straight, at your own fiber's 1.1 path factor). +function cmRoute(a,b,ls=[]){const k=al.km)):kmBetween(a,b),sub=ls.length?ls.some(l=>l.sub):isSub(a,b); + const lat=ls.length?Math.min(...ls.map(linkLat)):kmBetween(a,b)*1.1/200,gc=kmBetween(a,b)/200,st=gc>0?lat/gc:2,fin=CM_FIN.includes(a)&&CM_FIN.includes(b); + // Latency is dominated by the length of the route: a short, straight one sells fast waves at a premium (up to +50%, + // +80% between two trading cities). + const lp=1+0.5*clamp((1.5-st)/0.4,0,1)*(fin?1.6:1); + return {k,a,b,ls,km,sub,lat,st,lp,fin,dc:MEGA.some(m=>m.c===a||m.c===b)};} +// The routes you hold ready dark fiber on. +function cmRoutes(){const by=new Map();for(const l of S.links)if(l.kind==='df'&&l.ready<=S.day){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);} + const rs=new Map();for(const [k,ls] of by){const [a,b]=k.split('|');rs.set(k,cmRoute(a,b,ls));}return rs;} +/* Growth: carriers want about 15% more every year (non-AI traffic grows about that fast, AI traffic faster), up to 8 + times what they wanted at the start. */ +const cmGrowth=d=>Math.min(8,Math.pow(1.15,Math.max(0,d)/365)); +/* Which wave sizes buyers want: each size catches on along an S-curve over game years plus the network era, and takes + over from the one before (100G, then 400G, 800G from about year 5, 1.6T from about year 9; a later network era + brings each a little sooner). */ +const CM_ADOPT={w400:1.5,w800:5,w1600:9}; +const cmA=(p,d)=>1/(1+Math.exp(-(Math.max(0,d)/365+0.15*lvl()-CM_ADOPT[p])/1.3)); +function cmShare(p,d){const a4=cmA('w400',d),a8=cmA('w800',d),a16=cmA('w1600',d);return p==='w100'?1-a4:p==='w400'?a4-a8:p==='w800'?a8-a16:a16;} +/* What a route wants of a product, in units: spectrum slots, waves of that size, dark pairs. The size comes from the + eyeballs at both ends (brMarket(), as before) and growth; managed waves split by the sizes buyers want now, fast + waves from latency, the big ones and dark pairs from data centers at either end; dark pairs are mostly bought for + shorter hauls. */ +function cmDem(r,p,d,fc){const M=brMarket(r.a,r.b),H=cmHeat(r,p,d,fc),g=cmGrowth(d); + if(p==='spec')return M*0.5*Math.pow(g,0.7)*H; + if(p==='iru')return Math.min(2,M/12*(r.dc?2:1)*clamp(900/r.km,0.35,1.5))*Math.sqrt(g)*H; + const dc=r.dc&&p!=='w100'?(p==='w400'?1.3:1.6):1;return M*160*Math.sqrt(r.lp)*g*cmShare(p,d)*dc*H/CM_G[p];} +// What carriers already rent on a route, by product, in the same units. +const cmWP=g=>CM_W.find(p=>CM_G[p]===g)||'w100'; +function cmSold(rs){const m=new Map(),ids=new Map();for(const r of rs.values()){m.set(r.k,Object.fromEntries(CM_P.map(p=>[p,0])));for(const l of r.ls)ids.set(l.id,r.k);} + for(const b of S.biz){const k=b.link&&ids.get(b.link);if(!k)continue;const s=m.get(k); + if(b.type==='wwave')s.spec+=b.slots||0;else if(b.type==='mwave')s[cmWP(b.g)]+=b.slots||0;else if(b.type==='dfpair')s.iru++;} + return m;} +/* List prices, before the market index (mkt()) and the broker's cut: spectrum is 30% of what the fiber costs a month + (as before, #203); a managed 100G wave 30% of that times the latency premium, bigger ones by CM_X; a dark pair two + years of its lease up front, then 15% of it a month. */ +const cmF=r=>dfLeaseMo(r.km)+ampCount(r.km)*AMP_MO; +function cmList(r,p){return p==='spec'?cmF(r)*WW_SHARE:p==='iru'?dfLeaseMo(r.km)*0.15:cmF(r)*WW_SHARE*0.3*r.lp*CM_X[p][r.sub?1:0];} +const cmUpList=r=>dfLeaseMo(r.km)*0.9*24; +/* The price of the i-th unit from now, as a share of list: heat pushes it up or down (hot routes pay off), and each + unit sold on the route makes the next one cheaper, down to 40% once its market is full. */ +function cmIdx(r,p,s,i,d,fc){const D=cmDem(r,p,d,fc),H=cmHeat(r,p,d,fc);return clamp(Math.pow(H,0.6),0.7,1.35)*(1-WW_FALL*Math.min(1,D>0?(s+i)/D:1));} +// Managed waves sold on a fiber, in Gbps: they come off what your own traffic gets (dfCap0()). +let CM_MW=null,CM_V=0; +function mwG(l){if(!S||!S.biz)return 0;if(!CM_MW||CM_MW.b!==S.biz||CM_MW.n!==S.biz.length||CM_MW.v!==CM_V){const m=new Map(); + for(const b of S.biz)if(b.type==='mwave'&&b.link)m.set(b.link,(m.get(b.link)||0)+(b.slots||0)*(b.g||100));CM_MW={b:S.biz,n:S.biz.length,v:CM_V,m};} + return CM_MW.m.get(l.id)||0;} +// How much of a product a fiber has spare, after the share kept back for your own traffic (spectrum slots, or lit +// capacity your traffic is not using). A wave rides one channel, so an 800G or 1.6T one needs an optic that big. A pair +// is never kept back: it is glass you are not lighting. +const cmFreeG=(l,hold=S.cm.hold)=>dfCap0(l)-(R.load[l.id]||0)*1.05-hold/100*dfLit(l); +const cmOptG=l=>Math.max(0,...(l.ch||[]).map(c=>optG(c,l))); +function cmSpare(l,p,hold=S.cm.hold){ + if(p==='spec')return Math.max(0,freeCh(l)-Math.ceil(hold/100*chMax(l))); + if(p==='iru')return l.own&&pairFree(l)&&!(l.cut>S.day)?1:0; + return cmOptG(l)p==='spec'?wwWhat(l,n):p==='iru'?tr('requirements.a_spare_fiber_pair_in_your',{a:CITY[l.a].name,b:CITY[l.b].name}):trn('market.n_g_wave_on',n,{g:fmtCap(CM_G[p]),a:CITY[l.a].name,b:CITY[l.b].name}); +// A sale: a new carrier on this fiber, or more of the same product for one that already rents here. +function cmSell(l,p,n,rate,up){const t=p==='spec'?'wwave':p==='iru'?'dfpair':'mwave',T=BIZ_T[t],nm=()=>{const list=T.names.filter(x=>!S.usedNames.includes(x)),x=list.length?pick(list):pick(T.names);useName(x);return x;}; + const g=CM_G[p],name=nm(),more=t!=='dfpair'&&S.biz.find(b=>b.type===t&&b.link===l.id&&b.name===name&&(t!=='mwave'||b.g===g)); + if(more){more.slots=(more.slots||0)+n;more.rate+=rate;more.what=cmWhat(l,p,more.slots);} + else{const o={id:uid(),city:l.a,city2:l.b,link:l.id,slots:t==='dfpair'?0:n,what:cmWhat(l,p,n),name,type:t,bw:1,rate,reqs:[],exp:S.day+30};const b=clSign(offerCustomer(o));if(g)b.g=g;S.biz.push(b);} + CM_V++;if(up)S.cash+=up;S.stats.cmSold=(S.stats.cmSold||0)+1; + toast(up?tr('market.sold_pair',{name:esc(name),what:esc(cmWhat(l,p,n)),up:fmt$(up),price:fmt$(rate)}):tr('broker.sold',{name:esc(name),what:esc(cmWhat(l,p,n)),price:fmt$(rate)}),'good'); + floater((CITY[l.a].x+CITY[l.b].x)/2,(CITY[l.a].y+CITY[l.b].y)/2-20,tr('common.signed'),'#16A866');} +// What one fiber can still sell of a product right now, whatever is listed: free spectrum, lit capacity your traffic +// is not using, a free pair. +function cmCan(l,p){if(!fiberOk({link:l.id,type:p==='iru'?'dfpair':'wwave'}))return 0;return p==='spec'?Math.max(0,freeCh(l)):p==='iru'?cmSpare(l,'iru'):cmSpare(l,p,0);} +/* News: incidents that cut glass become news the next morning, and every so often something happens on its own. + Each one is a shock on a route, around a city, or on every subsea route, for some products, for a while. */ +const CM_NEWS={ + cut:{m:1.6,days:45,p:null,t:N_('market.news_cut')},redsea:{m:1.8,days:90,p:null,t:N_('market.news_redsea')}, + dc:{m:2,days:150,p:['w400','w800','w1600','iru'],t:N_('market.news_dc_big')},ai:{m:2.5,days:70,p:['w400','w800','w1600'],t:N_('market.news_ai_big')}, + glut:{m:0.6,days:120,p:null,t:N_('market.news_glut')},exch:{m:1.7,days:60,p:CM_W,t:N_('market.news_exch')}, + merge:{m:0.75,days:90,p:null,t:N_('market.news_merge')},boom:{m:1.4,days:60,p:['spec','w100'],t:N_('market.news_boom')}}; +function cmNews(why,x,d){const N=CM_NEWS[why],s={why,from:d,until:d+N.days,m:N.m,...x};if(N.p)s.p=N.p.slice();S.cm.sh.push(s); + S.cm.news.unshift({d,why,a:x.a||x.c||null,b:x.b||null});S.cm.news.length=Math.min(S.cm.news.length,8); + const rs=cmRoutes();if([...rs.values()].some(r=>cmHits(s,r)))toast(cmNewsText(S.cm.news[0]),N.m>1?'info':'warn',[{l:tr('market.open'),act:'marketOpen',args:{}}]);} +const cmNewsText=n=>tr(CM_NEWS[n.why].t,{a:n.a?CITY[n.a].name:'',b:n.b?CITY[n.b].name:''}); +function cmShocks(d){const C=S.cm;C.sh=C.sh.filter(x=>x.until>d); + for(const i of S.inc)if(LINKCUT_TR.includes(i.type)&&!C.seen.includes(i.id)){C.seen.push(i.id);if(C.seen.length>40)C.seen.shift(); + if(i.type==='redsea'){cmNews('redsea',{sub:1},d);continue;} + const l=S.links.find(x=>x.id===i.ref||x.trench===i.ref);if(l)cmNews('cut',{c:hstr(String(i.id))%2?l.a:l.b,a:l.a,b:l.b},d);} + // Without dark fiber there is no market to move, and no random number is drawn (the rest of the day stays as it was). + const rs=[...cmRoutes().values()],cs=[...new Set(rs.flatMap(r=>[r.a,r.b]))];if(!rs.length||Math.random()>=1/10)return; + const why=pick(['dc','ai','glut','exch','merge','boom','boom','dc']),r=pick(rs),c=pick(cs); + if(why==='dc'||why==='boom')cmNews(why,{c},d); + else if(why==='exch'){const f=cs.filter(x=>CM_FIN.includes(x));if(f.length){const x=pick(f);cmNews(why,{c:x},d);}} + else cmNews(why,{k:r.k,a:r.a,b:r.b},d);} +/* Once a day: news, then on every route the broker lists what your thresholds allow (spare after the share kept back, + while demand is at least your minimum and the price at least your floor) or takes it off, then each listing may + find a buyer: the more room the route has left and the hotter it is, the sooner; the fastest fiber sells first. */ +function cmList1(r,p,s,d){const c=S.cm.p[p],lk=CM_L[p];if(!c.on||S.cm.off[r.k])return;const ok=cmDem(r,p,d)>=c.min&&cmIdx(r,p,s,0,d)*100>=c.floor; + for(const l of r.ls){const n=ok?cmSpare(l,p):0;if(n>0)cmLs(l)[lk]=n;else if(l.list)l.list[lk]=0;}} +// The listings as the thresholds want them right now (after you change a setting), without selling anything. +function cmRelist(){const rs=cmRoutes(),sold=cmSold(rs);for(const r of rs.values())for(const p of CM_P)cmList1(r,p,sold.get(r.k)[p],S.day);cmTidy();} +const cmTidy=()=>{for(const l of S.links)if(l.list){const L=cmClean(l.list);if(L)l.list=L;else delete l.list;}}; +function cmDay(d=S.day){const C=S.cm;cmShocks(d);const rs=cmRoutes(),sold=cmSold(rs); + for(const r of rs.values()){const s=sold.get(r.k); + for(const p of CM_P){const lk=CM_L[p];cmList1(r,p,s[p],d); + // Room rounds to the nearest unit: a road to nowhere that wants about one wave sells one. + const D=cmDem(r,p,d),room=Math.round(D-s[p]);if(room<1)continue; + const ls=r.ls.filter(l=>l.list&&l.list[lk]>0&&cmCan(l,p)>0).sort((x,y)=>linkLat(x)-linkLat(y));if(!ls.length)continue; + if(Math.random()>=Math.min(0.35,0.06+0.25*room/Math.max(1,D))*(p==='iru'?0.08:1)*(p==='spec'?1:Math.sqrt(r.lp)))continue; + const l=ls[0];let n=p==='iru'?1:Math.max(1,Math.min(l.list[lk],cmCan(l,p),room,1+Math.floor(Math.random()*(p==='spec'||p==='w100'?4:2)))); + // Never below your floor: fewer units, or none. + while(n>0&&cmIdx(r,p,s[p],n-1,d)*100cmDem(r,p,S.day+t,true); +/* Growth inside contracts: once the next size is common (15% of what buyers want), a carrier on a managed wave asks + now and then to move all its waves up one size. With room on the fiber (after what you keep back) it moves at once + and pays more (a bigger wave, at a lower price per bit); without, it tells you, at most twice a year. */ +function cmGrow(d){for(const b of S.biz){if(b.type!=='mwave')continue;const i=CM_W.indexOf(cmWP(b.g)),q=CM_W[i+1];if(!q||cmShare(q,d)<0.15||Math.random()>=1/300)continue; + const l=S.links.find(x=>x.id===b.link);if(!l||!fiberOk(b))continue;const g1=CM_G[q],extra=(g1-b.g)*(b.slots||1),sub=l.sub?1:0,arg={name:esc(b.name),n:b.slots||1,g0:fmtCap(b.g),g1:fmtCap(g1),a:CITY[l.a].name,b:CITY[l.b].name}; + if(cmOptG(l)>=g1&&cmFreeG(l)>=extra){const p0=cmWP(b.g);b.rate=Math.round(b.rate*CM_X[q][sub]/CM_X[p0][sub]*0.85);b.g=g1;b.what=cmWhat(l,q,b.slots||1);CM_V++; + toast(tr('market.upgraded',{...arg,price:fmt$(b.rate)}),'good');} + else if(!(b.gw>d-180)){b.gw=d;toast(tr('market.wants_more',arg),'warn',[{l:tr('lease_swaps.open_your_fiber'),act:'dashLink',args:{id:l.id}}]);}}} +// How many more spectrum slots a fiber's route wants today (the fiber panel's market line). +function cmRoomSpec(l){const rs=cmRoutes(),r=rs.get(edgeKey(l));if(!r)return 0;return Math.max(0,Math.round(cmDem(r,'spec',S.day)-cmSold(rs).get(r.k).spec));} +// Routes a Cable broker could build between two of its POPs, the most wanted first. +function cmScout(n=6){const ps=Object.keys(S.pops),have=new Set(S.links.filter(l=>l.kind==='df').map(edgeKey)),out=[]; + for(let i=0;i1500||!dfAllowed(a,b))continue;const r=cmRoute(a,b); + out.push({r,v:CM_P.reduce((s,p)=>s+cmDem(r,p,S.day)*cmList(r,p),0)});} + return out.sort((x,y)=>y.v-x.v).slice(0,n).map(x=>x.r);} +// Saves: everything checked, old saves get the defaults. +function cmFix(s){const c=s.cm&&typeof s.cm==='object'&&!Array.isArray(s.cm)?s.cm:{},n=cmNew(); + n.hold=CM_HOLD.includes(+c.hold)?+c.hold:25; + for(const p of CM_P){const x=c.p&&c.p[p]||{};n.p[p]={on:!!x.on,min:CM_MIN[p].includes(+x.min)?+x.min:CM_DEF[p].min,floor:CM_FLOOR.includes(+x.floor)?+x.floor:CM_DEF[p].floor};} + if(c.off&&typeof c.off==='object')for(const k in c.off){const [a,b]=k.split('|');if(c.off[k]&&isCity(a)&&isCity(b)&&ax&&own(CM_NEWS,x.why)&&(x.k?typeof x.k==='string'&&x.k.split('|').every(isCity):x.c?isCity(x.c):!!x.sub)).slice(-24).map(x=>{ + const y={why:x.why,from:int(x.from,-1e6,1e7,0),until:int(x.until,-1e6,1e7,0),m:clamp(num(x.m,1),0.3,3)};if(x.k)y.k=x.k;else if(x.c)y.c=x.c;else y.sub=1; + if(isCity(x.a))y.a=x.a;if(isCity(x.b))y.b=x.b;if(Array.isArray(x.p)){const p=x.p.filter(q=>CM_P.includes(q));if(p.length)y.p=p;}return y;}); + if(Array.isArray(c.news))n.news=c.news.filter(x=>x&&own(CM_NEWS,x.why)).slice(0,8).map(x=>({d:int(x.d,-1e6,1e7,0),why:x.why,a:isCity(x.a)?x.a:null,b:isCity(x.b)?x.b:null})); + if(Array.isArray(c.seen))n.seen=c.seen.filter(x=>typeof x==='string').slice(-40); + s.cm=n; + for(const l of s.links){if(l.kind!=='df'||!l.list)continue;const L=cmClean(l.list);if(L)l.list=L;else delete l.list;} + for(const b of s.biz)if(b.type==='mwave'){b.g=CM_W.some(p=>CM_G[p]===b.g)?b.g:100;b.slots=Math.max(1,Math.round(b.slots||1));if(b.gw!==undefined)b.gw=int(b.gw,-1e6,1e7,0);}} diff --git a/src/game/60-features/38-sales-desk.js b/src/game/60-features/38-sales-desk.js index ff2efd0..a76a30f 100644 --- a/src/game/60-features/38-sales-desk.js +++ b/src/game/60-features/38-sales-desk.js @@ -19,7 +19,7 @@ const SALES={ const SALES_LV=2,SALES_VP=50000,SALES_VP_DAYS=30; // The ones the engineer never lands, and the nerds the shark never calls back. const salesBig=t=>{const T=BIZ_T[t];return !!T&&(!!T.mega||(T.lv||1)>=4);}; -const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','dfpair']; +const SALES_NERDS=['hft','edu','isp','l2vpn','bulk','provedor','fabl2','wwave','mwave','dfpair']; const SALES_SAY=[N_('sales.ceo_say_synergy'),N_('sales.ceo_say_golf'),N_('sales.ceo_say_blockchain'),N_('sales.ceo_say_napkin'),N_('sales.ceo_say_mbps'),N_('sales.ceo_say_airport')]; const slP=()=>S&&S.sales&&own(SALES,S.sales.p)?S.sales.p:null; const slName=(long)=>{const p=slP();return p?tr(long?SALES[p].n:SALES[p].s):'';}; diff --git a/src/game/60-features/80-new-game.js b/src/game/60-features/80-new-game.js index 227dbec..d21c562 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:4,auV:1,calV:1,pieV:1,pie:null,ops:opsNew(),slAuto:slAutoNew(),achP:{},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:{},pairMet:{}, - done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; + done:{},inc:[],fleet:{},ev:{ddosMore:[]},ddosStarts:[],priceMul:1,nextFail:45,nextEvent:40,usedNames:[],stats:{survived:0,incidents:0,peak:0},vol:0,cnLic:{state:'none'},scrubs:[],scrubMode:'always',ddosAuto:{rtbh:false,scrub:true},capDeal:null,core:{lv:0,run:0},popStd:null,won:false,lost:false,neg:0,loans:[],loanOffers:[],loanStrikes:0,ppol:'open',pdesk:null,pdeskRep:null,hw:{},rules:makeRules('oncall'),charter:'global',cm:cmNew(),chartSet:false,demo:{},seatOff:null,solWon:0,monkey:{next:null,on:0}}; } diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 94b2e47..fff9a44 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -21,7 +21,7 @@ function sanitize(s){ if(!isCity(s.home))s.home=Object.keys(s.pops)[0]||'fra'; opsSanitize(s); 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);if(l.list!==undefined){const L=l.list;if(l.kind==='df'&&L&&typeof L==='object'&&!Array.isArray(L)){const w=int(L.w,0,256,0),p=int(L.p,0,2,0);if(w||p)l.list={w,p};else delete l.list;}else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}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);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);if(l.list!==undefined){const L=l.kind==='df'?cmClean(l.list):null;if(L)l.list=L;else delete l.list;}l.km=num(l.km,kmBetween(l.a,l.b));l.mo=num(l.mo,0);l.cut=num(l.cut,0);if(l.cname!=null)l.cname=String(l.cname).slice(0,60);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)||!cablePair(l.cable,l.a,l.b)))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);if(l.day!==undefined)l.day=Math.min(s.day,Math.max(0,num(l.day,s.day)));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.seaPath!==undefined){if(l.own&&l.sub&&Array.isArray(l.seaPath)&&l.seaPath.length>=2&&l.seaPath.length<=2048&&l.seaPath.every(p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90))l.seaPath=l.seaPath.map(p=>p.slice());else delete l.seaPath;}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);return l;}); for(const l of s.links)repairSubUpgradeDates(l,s.day); /* Metrics moved from each link to its city pair (#122). Older saves routed a pair at the lowest metric of its links, with all of them carrying traffic, so the pair keeps that metric and nothing goes on standby. */ @@ -111,6 +111,7 @@ function sanitize(s){ {const r=s.rules&&typeof s.rules==='object'&&!Array.isArray(s.rules)?s.rules:{}; const m={mods:r.mods};s.rules=s.scn&&typeof s.scn==='object'?makeRules('oncall',m):s.mode==='sandbox'?makeRules('sandbox',{...m,chaos:r.chaos}):makeRules(NORMAL_PRESETS.includes(r.preset)?r.preset:'oncall',m);} specSanitize(s); + cmFix(s); pieSanitize(s);pieIncFix(s);volFix(s); 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;} diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index f392883..8e3aab0 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -80,7 +80,7 @@ const linkIds=()=>{const m=new Map();for(const l of S.links)if(!m.has(l.id))m.se function fiberUse(){const sold=new Map(),dfp=new Map(),pairs=new Set(); for(const b of S.biz){if(b.type==='wwave')sold.set(b.link,(sold.get(b.link)||0)+(b.slots||0));else if(b.type==='dfpair')dfp.set(b.link,(dfp.get(b.link)||0)+1);else if(b.type==='pairs'||b.type==='capfib')pairs.add(b.link);} return {sold,dfp,pairs};} -function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day);} +function fiberOk(b,ids){const l=ids?ids.get(b.link):S.links.find(x=>x.id===b.link);if(!l)return false;if(b.type==='dfpair'||b.type==='pairs'||b.type==='capfib')return l.ready<=S.day&&!(l.cut>S.day);return l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day)&&(b.type!=='mwave'||dfLit(l)>=mwG(l));} function soldSlots(l,u){return u?u.sold.get(l.id)||0:S.biz.filter(b=>b.type==='wwave'&&b.link===l.id).reduce((a,b)=>a+(b.slots||0),0);} // Spare capacity other carriers can rent on a dark fiber (#51): free channels for alien waves, and on your own build // a spare pair in the trench. Random offers and broker listings follow the same rules and the same prices. diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 13fd9d8..24e0c78 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -95,7 +95,7 @@ function* dayPost(d){ if(rule('money')==='infinite'&&S.cash<1e8)S.cash=1e9; // offers S.offers=S.offers.filter(o=>o.exp>d); - brTick(); + cmDay(d); if(S.offers.length<5&&Math.random()<(0.05+0.01*(S.lvl||1))*(ppol()==='closed'?0.6:1)*(confSpOn()?SP_OFFERS:1)*salesSpawn()){const n0=S.offers.length;spawnOffer();mktPrice(n0);salesShape(n0);} yield DAY_REST; // failures & events diff --git a/src/game/90-actions/53-market.js b/src/game/90-actions/53-market.js new file mode 100644 index 0000000..c9e593b --- /dev/null +++ b/src/game/90-actions/53-market.js @@ -0,0 +1,14 @@ +// The capacity market (37-fiber-market.js): its tab, and the settings the broker sells by. +Object.assign(ACT,{ + marketOpen:()=>{if(!S||pzOn())return;UI.dtab='market';$('dash').hidden=false;renderDash();}, + mktHold:({v})=>{if(!CM_HOLD.includes(v))return;S.cm.hold=v;cmRelist();sfx('click');after();}, + // Switching a product off takes what the broker listed of it off the market; what it already sold stays sold. + mktCfg:({p,k,v})=>{const c=CM_P.includes(p)&&S.cm.p[p];if(!c)return; + if(k==='on'){c.on=!!v;if(!c.on)for(const l of S.links)if(l.list&&l.list[CM_L[p]])l.list[CM_L[p]]=0;} + else if(k==='min'&&CM_MIN[p].includes(v))c.min=v;else if(k==='floor'&&CM_FLOOR.includes(v))c.floor=v;else return; + cmRelist();sfx('click');after();}, + // A route the broker leaves alone keeps nothing listed by the thresholds. + mktRoute:({k})=>{const r=typeof k==='string'&&cmRoutes().get(k);if(!r)return;if(S.cm.off[k]){delete S.cm.off[k];}else{S.cm.off[k]=1; + for(const l of r.ls)if(l.list)for(const p of CM_P)if(S.cm.p[p].on)l.list[CM_L[p]]=0;} + cmRelist();sfx('click');after();}, +}); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 628dc3a..44ab4bb 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -117,10 +117,10 @@ function dfPanel(l){ if(bld){const tot=Math.max(1,l.ready-l.day),done=clamp((S.day-l.day)/tot,0,1); h+=`

${l.own?tr('common.under_construction'):tr('common.being_spliced')}

${l.own?tr('link_panels.permits_trenching_splicing'):tr('common.iru_handover')}${tr('common.n_days_left',{n:l.ready-S.day})}
${l.own&&l.sub?layPanel(l):l.own?`
${btn(tr('link_panels.hire_extra_crews_price_30_days',{price:fmt$(crewCost(l))}),'crews',{id:l.id},'sm',!crewSteps(l)||S.cash${!crewSteps(l)&&l.ready>S.day+1?`

${tr('link_panels.crews_can_halve_a_build_at_most')}

`:''}`:''}

${tr('link_panels.you_can_pre_install_optics_now')}

`;} else if(inc&&linkDown(l))h+=`

${tr('common.dark_6bf5')}

${esc(inc.msg)}

${shipNote(inc)}${inc.cost?btn(`${esc(inc.fix||tr('common.rush_repair'))} ${fmt$(inc.cost)}`,'fixInc',{id:inc.id},'red',S.cash`; - h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${fmtG(load)} / ${fmtG(cap)}
+ h+=`

${tr('common.capacity')}

${tr('link_panels.n_of_max_channels_lit',{n:(l.ch||[]).length,max:chMax(l)})}${soldSlots(l)?` · ${tr('link_panels.n_sold_as_alien_waves',{n:soldSlots(l)})}`:''}${mwG(l)?` · ${tr('market.g_sold_as_managed',{g:fmtCap(mwG(l))})}`:''}${fmtG(load)} / ${fmtG(cap)}
${seatPanel(l)}${l.own&&l.sub?`
${tr('common.cable_design')}${tr((SEA_DESIGNS[l.seaDesign]||SEA_DESIGNS.standard).n)}
`:''}
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${tr('link_panels.n_amp_huts',{n:amps})}${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}
${!bld&&!(l.ch||[]).length?`

${tr('link_panels.this_fiber_is_dark_add_optics')}

`:''}
`; - 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); + if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='mwave'||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')}
`:brListHtml(l,fc)}
`;} @@ -188,10 +188,10 @@ function offTransitHint(id,city){const n=NET[id];if(n.type==='t1'&&n.pol==='rest if(pniC.length)return tr('link_panels.pni_in_city_why',{city:CITY[pniC[0]].name,why:pOk.why});{const x=nearestSpot(id);return x?tr('link_panels.not_in_your_cities_yet_nearest',{city:CITY[x.c].name}):tr('link_panels.not_present_in_any_of_your');}} function transitTop(ids,k=5){const m={};for(const id of ids)for(const [n,v] of Object.entries(R.tNet[id]||{}))m[n]=(m[n]||0)+v;return Object.entries(m).filter(([,v])=>v>0.01).sort((a,b)=>b[1]-a[1]).slice(0,k);} // The broker: what is listed and how the route's market looks, or the buttons to list some (#203). -function brListHtml(l,fc){const L=l.list,free=brFree(l),pf=l.own&&pairFree(l)&&!(L&&L.p); +function brListHtml(l,fc){const L=l.list,free=cmRoomSpec(l),pf=l.own&&pairFree(l)&&!(L&&L.p),cut=Math.round((1-cmCut())*100),go=`
${btn(tr('market.open'),'marketOpen',{},'ghost sm')}
`; const mk=`
${tr('broker.market',{a:CITY[l.a].name,b:CITY[l.b].name})}${trn('broker.n_waves',free)}
`; - if(L)return mk+`
${tr('broker.listed_title')}
${[L.w?trn('broker.n_waves_left',L.w):'',L.p?trn('broker.n_pairs_left',L.p):''].filter(Boolean).join(' · ')} · ${tr('broker.how')}
${btn(tr('broker.unlist'),'unlistFiber',{id:l.id},'ghost sm')}
`+ - (fc-L.w>=1?`
${btn(tr('broker.list_more',{n:Math.min(4,fc-L.w)}),'listFiber',{id:l.id,w:Math.min(4,fc-L.w)},'ghost sm')}
`:''); - if(fc<1&&!pf)return mk+`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`; + if(L)return mk+`
${tr('broker.listed_title')}
${[L.w?trn('broker.n_waves_left',L.w):'',...CM_W.map(p=>L[CM_L[p]]?trn('market.n_g_left',L[CM_L[p]],{g:fmtCap(CM_G[p])}):''),L.p?trn('broker.n_pairs_left',L.p):''].filter(Boolean).join(' · ')} · ${tr('market.how',{n:cut})}
${btn(tr('broker.unlist'),'unlistFiber',{id:l.id},'ghost sm')}
`+ + (fc-L.w>=1?`
${btn(tr('broker.list_more',{n:Math.min(4,fc-L.w)}),'listFiber',{id:l.id,w:Math.min(4,fc-L.w)},'ghost sm')}${btn(tr('market.open'),'marketOpen',{},'ghost sm')}
`:go); + if(fc<1&&!pf)return mk+`

${tr('link_panels.nothing_spare_to_sell_on_this')}

`+go; const ns=[...new Set([1,4,Math.min(16,fc),fc])].filter(n=>n>=1&&n<=fc); - return mk+`

${tr('broker.lead')}

${ns.map(n=>btn(n===fc&&n>1?tr('broker.list_all',{n}):trn('broker.list_n',n),'listFiber',{id:l.id,w:n},'sm')).join('')}${pf?btn(tr('broker.list_pair'),'listFiber',{id:l.id,p:1},'sm'):''}
`+(free<1?`

${tr('broker.no_market')}

`:'');} + return mk+`

${tr('market.lead_fiber',{n:cut})}

${ns.map(n=>btn(n===fc&&n>1?tr('broker.list_all',{n}):trn('broker.list_n',n),'listFiber',{id:l.id,w:n},'sm')).join('')}${pf?btn(tr('broker.list_pair'),'listFiber',{id:l.id,p:1},'sm'):''}
`+(free<1?`

${tr('broker.no_market')}

`:'')+go;} diff --git a/src/game/93-ui/82-keys.js b/src/game/93-ui/82-keys.js index c109756..94232af 100644 --- a/src/game/93-ui/82-keys.js +++ b/src/game/93-ui/82-keys.js @@ -6,7 +6,7 @@ const popOrder=()=>S&&S.pops?Object.keys(S.pops).filter(isCity).sort((a,b)=>CITY const offerOrder=()=>S&&S.offers?S.offers.filter(o=>isCity(o.city)).sort((a,b)=>a.exp-b.exp):[]; // n opens the NOC dashboard, and a letter within KEY_LEAD ms of it picks a tab (n c: Connections). n never closes the // dashboard, so n c switches tabs without it flashing shut; Escape closes it. -const DASH_KEYS={o:'overview',u:'cust',c:'conn',t:'traffic',r:'infra',l:'lease'},KEY_LEAD=1000;let keyLead=0; +const DASH_KEYS={o:'overview',u:'cust',c:'conn',t:'traffic',r:'infra',l:'lease',m:'market'},KEY_LEAD=1000;let keyLead=0; // Arrow keys and WASD move the map while held, at a steady speed on screen. Their own frame loop runs only while one is // down, so the game loop does no extra work; letting go, a window opening or leaving the browser window stops it. const PAN_KEYS={ArrowUp:[0,-1],w:[0,-1],ArrowDown:[0,1],s:[0,1],ArrowLeft:[-1,0],a:[-1,0],ArrowRight:[1,0],d:[1,0]},PAN_SPEED=700; @@ -15,7 +15,7 @@ function panFrame(t){if(!panHeld.size||!$('modal').hidden||!$('dash').hidden){pa // A slow frame (a busy day, a background tab) moves at most 50 ms worth, not a jump across the map. const dt=panAt==null?0:Math.min(0.05,(t-panAt)/1000);panAt=t;let dx=0,dy=0;for(const k of panHeld){dx+=PAN_KEYS[k][0];dy+=PAN_KEYS[k][1];} cam.x+=dx*PAN_SPEED*dt/cam.z;cam.y+=dy*PAN_SPEED*dt/cam.z;wrapCam();requestAnimationFrame(panFrame);} -function showKeys(){const k=s=>`${s}`,TN={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines')}; +function showKeys(){const k=s=>`${s}`,TN={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),lease:tr('common.leased_lines'),market:tr('market.tab')}; const tabs=Object.entries(DASH_KEYS).map(([l,t])=>`${k(l)} ${TN[t]}`).join(' '); const rows=[[[...'←↑↓→'].map(k).join(' ')+'
'+[...'wasd'].map(k).join(' '),tr('keys.move_around_the_map')],[k(tr('keys.space')),tr('keys.pause_or_play')],[k('0')+' – '+k('4'),tr('keys.game_speed')],[k('/'),tr('find.find_a_city')],[k('[')+' '+k(']'),tr('keys.previous_or_next_of_your')],[k('$'),tr('keys.next_open_offer_soonest_to')],[k('-')+' '+k('='),tr('keys.zoom_the_map_out_or')],[k('n'),`${tr('keys.noc_dashboard_a_letter_right')}
${tabs}`],[k(tr('keys.esc')),tr('keys.close_a_window_or_deselect')],[k('?'),tr('keys.show_this_list')]]; openModal(`

⌨️ ${tr('keys.keyboard_shortcuts')}

diff --git a/src/game/94-dashboard/40-connections.js b/src/game/94-dashboard/40-connections.js index 8a894a9..83145b3 100644 --- a/src/game/94-dashboard/40-connections.js +++ b/src/game/94-dashboard/40-connections.js @@ -66,4 +66,4 @@ function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||( function netWhere(n,where){const ch=(where||netWhereIdx())(n.id); if(!ch.length)return '';const MAX=6; return `
${ch.slice(0,MAX).map(([l,c,k])=>btn(`${esc(l)} ${esc(CITY[c].name)}`,'goConn',{city:c,k},'ghost sm')).join('')}${ch.length>MAX?btn(tr('dashboard.n_more',{n:ch.length-MAX}),'connFor',{net:n.id},'ghost sm'):''}
`;} -const DTABS=['overview','cust','conn','traffic','infra','pops','lease']; +const DTABS=['overview','cust','conn','traffic','infra','pops','lease','market']; diff --git a/src/game/94-dashboard/55-market.js b/src/game/94-dashboard/55-market.js new file mode 100644 index 0000000..a25f7d3 --- /dev/null +++ b/src/game/94-dashboard/55-market.js @@ -0,0 +1,38 @@ +/* ---------- the capacity market tab (37-fiber-market.js) ---------- + Your settings (what the broker may sell, from what demand and price, and how much it keeps back), the news, and + every route you hold dark fiber on: per product what is wanted, sold and listed, as a bar with your threshold on + it, and today's price against your floor. A Cable broker also sees where each route is heading, and routes it could + build. Markup is deterministic (the NOC window copies it). */ +const CM_NAME={spec:N_('market.p_spec'),w100:N_('market.p_w100'),w400:N_('market.p_w400'),w800:N_('market.p_w800'),w1600:N_('market.p_w1600'),iru:N_('market.p_iru')}; +const CM_DESC={spec:N_('market.p_spec_d'),w100:N_('market.p_w100_d'),w400:N_('market.p_w400_d'),w800:N_('market.p_w800_d'),w1600:N_('market.p_w1600_d'),iru:N_('market.p_iru_d')}; +const cmN=v=>v>=10?String(Math.round(v)):v.toFixed(1).replace(/\.0$/,''); +// Why nothing is listed although the route wants it and the price is right: no optic that big, or no room left on +// the fiber after what you keep back. Growing means lighting more. +// A bar: sold (green) of what the route wants (the dark line), and your minimum (the pink tick) when the broker lists. +function cmBar(D,sold,min){const top=Math.max(D,sold,min||0,1)*1.15,w=v=>(100*Math.min(1,v/top)).toFixed(1)+'%'; + return `
${min?``:''}
`;} +const cmSeg=(vals,cur,act,args,f)=>`
${vals.map(v=>btn(f(v),act,{...args,v},v===cur?'pink sm':'ghost sm')).join('')}
`; +function cmHeatTag(r){const H=cmHeat(r,'spec',S.day);return H>=1.15?`${tr('market.hot',{x:H.toFixed(1)})}`:H<=0.85?`${tr('market.cool',{x:H.toFixed(1)})}`:`${tr('market.steady')}`;} +function cmProdLine(r,p,s,L,fc){const C=S.cm.p[p],D=cmDem(r,p,S.day),i=cmIdx(r,p,s,0,S.day),pc=Math.round(i*100),m=mkt()*cmCut(); + const price=p==='iru'?tr('market.price_pair',{up:fmt$(Math.round(cmUpList(r)*i*m)),price:fmt$(Math.round(cmList(r,p)*m)),pct:pc}):tr('market.price',{price:fmt$(Math.round(cmList(r,p)*i*m)),pct:pc}); + return `
${tr(CM_NAME[p])} · ${tr('market.row',{want:cmN(D),sold:s,listed:L})} · ${price}${C.on&&pc${tr('market.below_floor')}`:C.on&&!L&&D>=C.min&&p!=='iru'&&!S.cm.off[r.k]?` ${CM_G[p]&&!r.ls.some(l=>cmOptG(l)>=CM_G[p])?tr('market.needs_optic',{g:fmtCap(CM_G[p])}):tr('market.no_room')}`:''}
+ ${cmBar(D,s,C.on?C.min:0)}${fc?`
${tr('market.forecast',{a:cmN(cmFc(r,p,30)),b:cmN(cmFc(r,p,90))})}
`:''}
`;} +function marketTab(){const C=S.cm,rs=[...cmRoutes().values()].sort((x,y)=>brMarket(y.a,y.b)-brMarket(x.a,x.b)),sold=cmSold(new Map(rs.map(r=>[r.k,r]))),bk=broker(); + const mo=S.biz.reduce((a,b)=>a+(['wwave','mwave','dfpair'].includes(b.type)?bizMo(b):0),0),ago=n=>S.day-n.d<1?tr('market.today'):trn('market.days_ago',S.day-n.d); + let h=`

${tr('market.title')}

${tr('market.lead')}

+
${tr('market.sales')}${tr('common.price_mo',{price:fmt$(mo)})}
+
${tr('market.fee')}${Math.round((1-cmCut())*100)}%${bk?` · ${tr('market.fee_broker')}`:''}
+
${tr('market.hold')}
${tr('market.hold_d')}
${cmSeg(CM_HOLD,C.hold,'mktHold',{},v=>v+'%')}
+ ${CM_P.map(p=>{const c=C.p[p];return `
${tr(CM_NAME[p])} ${btn(c.on?tr('market.selling'):tr('market.not_selling'),'mktCfg',{p,k:'on',v:c.on?0:1},c.on?'pink sm':'ghost sm')}
${tr(CM_DESC[p])}
+ ${c.on?`
${tr('market.min')}
${cmSeg(CM_MIN[p],c.min,'mktCfg',{p,k:'min'},v=>'≥ '+v)}
${tr('market.floor')}
${cmSeg(CM_FLOOR,c.floor,'mktCfg',{p,k:'floor'},v=>v+'%')}`:''}
`;}).join('')} +

${tr('market.news')}

${C.news.length?C.news.slice(0,5).map(n=>`
${ago(n)} · ${cmNewsText(n)}
`).join(''):`

${tr('market.no_news')}

`}
`; + h+=`

${tr('market.routes')}

${rs.length?`

${tr('market.legend')}${bk?'':' '+tr('market.forecast_lock')}

`+rs.map(r=>{const s=sold.get(r.k),off=!!C.off[r.k],L=p=>r.ls.reduce((a,l)=>a+((l.list&&l.list[CM_L[p]])||0),0); + return `
${CITY[r.a].name} ⇄ ${CITY[r.b].name} ${r.sub?tr('common.subsea'):tr('common.land')} ${cmHeatTag(r)}
+
${tr('market.route_meta',{km:Math.round(r.km).toLocaleString(),ms:r.lat.toFixed(1),n:Math.round((r.lp-1)*100)})}
+ ${(()=>{const shown=CM_P.filter(p=>s[p]>0||L(p)>0||cmDem(r,p,S.day)>=0.3||bk&&cmFc(r,p,90)>=0.3),rest=CM_P.filter(p=>!shown.includes(p)); + return shown.map(p=>cmProdLine(r,p,s[p],L(p),bk)).join('')+(rest.length?`
${tr('market.not_yet',{list:rest.map(p=>tr(CM_NAME[p])).join(', ')})}
`:'');})()} +
${btn(off?tr('market.route_off'):tr('market.route_on'),'mktRoute',{k:r.k},off?'ghost sm':'pink sm')}${btn(tr('lease_swaps.open_your_fiber'),'dashLink',{id:r.ls[0].id},'ghost sm')}
`;}).join(''):`

${tr('market.no_routes')}

`}
`; + if(bk){const sc=cmScout();h+=`

${tr('market.scout')}

${tr('market.scout_d')}

${sc.length?sc.map(r=>{const v=CM_P.reduce((a,p)=>a+cmDem(r,p,S.day)*cmList(r,p),0)*mkt()*cmCut(); + return `
${CITY[r.a].name} ⇄ ${CITY[r.b].name} ${r.sub?tr('common.subsea'):tr('common.land')} ${cmHeatTag(r)}
+
${tr('market.scout_spend',{km:Math.round(r.km).toLocaleString(),v:fmt$(Math.round(v))})}
${CM_P.filter(p=>cmDem(r,p,S.day)>=0.3||cmFc(r,p,90)>=0.3).map(p=>`
${tr(CM_NAME[p])} · ${tr('market.forecast_now',{n:cmN(cmDem(r,p,S.day)),a:cmN(cmFc(r,p,30)),b:cmN(cmFc(r,p,90))})}
`).join('')}
`;}).join(''):`

${tr('market.scout_none')}

`}
`;} + return h;} diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index 69bc314..5a379e3 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -1,4 +1,4 @@ -function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),pops:tr('unbuilt_pops.no_pop_yet'),lease:tr('common.leased_lines')}; +function dashTabs(){const u=custStats().unhappy,cur=UI.dtab||'overview',L={overview:tr('common.overview'),cust:tr('common.customers'),conn:tr('common.connections'),traffic:tr('common.traffic'),infra:tr('common.links_routers'),pops:tr('unbuilt_pops.no_pop_yet'),lease:tr('common.leased_lines'),market:tr('market.tab')}; return ``;} function renderDash(){checkLayer(); const H=S.hist||[],rows=H.slice(-90),last30=H.slice(-30); @@ -31,5 +31,6 @@ function renderDash(){checkLayer();

${tr('common.your_as')}

${tr('common.as_number')}AS${S.asn}
${tr('common.prefixes')}${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6
${tr('common.bgp_sessions')}${R.sessions}
${tr('common.upstreams')}${new Set(S.transit.map(t=>t.net)).size}
${tr('common.reach')}${pct(R.reach)}
${tr('common.customers')}${tr('dashboard.n_businesses',{n:S.biz.length})}
`; if(DT==='pops')h+=popsSection(); if(DT==='lease')h+=leaseTab(); + if(DT==='market')h+=marketTab(); if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);} } diff --git a/src/game/94-dashboard/90-noc-window.js b/src/game/94-dashboard/90-noc-window.js index d833449..49ff64b 100644 --- a/src/game/94-dashboard/90-noc-window.js +++ b/src/game/94-dashboard/90-noc-window.js @@ -6,7 +6,7 @@ const NOC_HB=3000,NOC_LOST=10000,NOC_GAP=1000; // What a click in the window does: changes only its own view, or runs in the game. Every button the dashboard draws is in one list. const NOC_LOCAL=['chartToggle','connCity','connF','connNet','connSort','custCity','custF','custSort','dashClose','dashSort','dashTab','listMore','popsReg','popsSort']; -const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagNni','lagP','lagT','leaseSwap','netFocus','opsOpen','pni','pniAllOpen','popGo']; +const NOC_GO=['buyIx','buyNni','buyTransit','cache','connCancel','custGo','dashLink','goConn','lagIx','lagNni','lagP','lagT','leaseSwap','mktCfg','mktHold','mktRoute','netFocus','opsOpen','pni','pniAllOpen','popGo']; const NOC={win:false,id:null,ctl:null,st:null,stId:null,peer:false,until:0,dirty:false,sent:0,speed:1,hid:false,yoAt:0,gone:false}; {const id=RW_IN?null:new URLSearchParams(location.search).get('noc');if(slotOkId(id)){NOC.win=true;NOC.id=id;}} if(!RW_IN)try{if(typeof BroadcastChannel==='function'){NOC.ctl=new BroadcastChannel('sot-noc');NOC.ctl.onmessage=e=>{const m=e.data;if(!m||typeof m!=='object'||!slotOkId(m.id))return;if(NOC.win)nocWinMsg(m);else nocGameMsg(m);};}}catch(e){} diff --git a/src/i18n/en.js b/src/i18n/en.js index 59789da..11a050a 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -387,8 +387,6 @@ "broker.goal_wave":"Sell a wave on your glass", "broker.goal_wave_d":"Carriers rent alien waves on fiber you have lit. Accept one from your deals.", "broker.goal_win_d":"Your own cables land on five continents, and carriers pay you $1M a month for capacity.", -"broker.how":"it sells as the market wants; the broker keeps 10%", -"broker.lead":"The broker keeps your listing and sells it off over time, as carriers between these two cities want capacity. It keeps 10% of each sale.", "broker.list_all":"List all {n}", "broker.list_more":"List {n} more", "broker.list_n":{"one":"List {n} wave","other":"List {n} waves"}, @@ -3036,6 +3034,75 @@ "loop.something_in_the_noc_glitched_the":"Something in the NOC glitched.
The game kept going. If things look odd, export your save and open an issue on GitHub.", "loop.welcome_back_name_your_network_is":"Welcome back, {name}.
Your network is right where you left it: {date}.", "loop.your_saved_game_could_not_be":"Your saved game could not be loaded.
It was damaged, so a backup was kept and you can start fresh.", +"market.below_floor":"below your floor", +"market.cool":"❄️ Cool ×{x}", +"market.days_ago":{"one":"{n} day ago","other":"{n} days ago"}, +"market.fee":"The broker keeps", +"market.fee_broker":"a Cable broker's rate", +"market.floor":"Never sell below", +"market.forecast":"In 30 days {a} · in 90 days {b}", +"market.forecast_lock":"A Cable broker also sees where each route is heading.", +"market.forecast_now":"{n} now · {a} in 30 days · {b} in 90 days", +"market.g_sold_as_managed":"{g} sold as managed waves", +"market.hold":"Keep back for your own traffic", +"market.hold_d":"The share of every fiber's spectrum and lit capacity the broker never sells, so your own traffic has room to grow.", +"market.hot":"🔥 Hot ×{x}", +"market.how":"it sells as the market wants; the broker keeps {n}%", +"market.lead":"Carriers buy capacity on the routes you hold dark fiber on. What each route wants moves all the time: hot routes pay more and fill faster, a short, straight route sells waves at a premium, and a long one costs more because its fiber does. Choose what the broker sells, from what demand and at what price.", +"market.lead_fiber":"The broker keeps your listing and sells it off over time, as carriers between these two cities want capacity. It keeps {n}% of each sale.", +"market.legend":"Each bar: what is sold (green) of what the route wants (the line); the pink tick is your minimum.", +"market.managed_wave":"Managed wave", +"market.min":"List while the route wants at least", +"market.n_g_left":{"one":"{n} managed {g} wave left to sell","other":"{n} managed {g} waves left to sell"}, +"market.n_g_wave_on":{"one":"{n}× {g} managed wave on your {a}–{b} fiber","other":"{n}× {g} managed waves on your {a}–{b} fiber"}, +"market.needs_optic":"needs a {g} optic on this fiber", +"market.news":"Market news", +"market.news_ai_big":"An AI cluster wants to talk between {a} and {b}: 400G and bigger waves there are hot.", +"market.news_boom":"A streaming hit floods {a}: carriers want more spectrum and 100G waves from there.", +"market.news_cut":"Fiber cut between {a} and {b}: carriers want diverse paths around it.", +"market.news_dc_big":"A hyperscaler breaks ground near {a}: big waves and dark pairs from there are wanted.", +"market.news_exch":"Trading firms move their matching engines to {a}: fast waves from there pay more.", +"market.news_glut":"A rival lights new fiber between {a} and {b}: buyers there cool off.", +"market.news_merge":"Two carriers merge between {a} and {b}: fewer buyers there.", +"market.news_redsea":"Subsea cables are cut: every subsea route is in demand.", +"market.no_news":"Quiet so far.", +"market.no_room":"no room left: light more capacity", +"market.no_routes":"You hold no ready dark fiber yet. Lease or dig some, and its route shows up here.", +"market.not_selling":"Not selling", +"market.not_yet":"Nobody wants these here yet: {list}.", +"market.open":"Lambda Bazaar", +"market.p_iru":"Dark pair IRUs", +"market.p_iru_d":"A spare pair in a trench you dug: two years of its lease up front, then a little upkeep every month.", +"market.p_spec":"Spectrum", +"market.p_spec_d":"An alien wave: a channel of your line system, and the buyer brings the optics.", +"market.p_w100":"Managed 100G waves", +"market.p_w100_d":"Carved out of capacity you lit: they pay more than spectrum, and your own traffic gets that much less.", +"market.p_w1600":"Managed 1.6T waves", +"market.p_w1600_d":"One wave on a 1.6T optic: the cheapest bit you can sell, and what the biggest buyers want once the years go by.", +"market.p_w400":"Managed 400G waves", +"market.p_w400_d":"2.7 times the price of a 100G wave for four times the capacity (3.8 times on subsea). AI data centers want them.", +"market.p_w800":"Managed 800G waves", +"market.p_w800_d":"One wave on an 800G-capable optic. Buyers move to them a few years in, AI data centers first.", +"market.price":"{price}/mo · {pct}% of list", +"market.price_pair":"{up} up front + {price}/mo · {pct}% of list", +"market.route_meta":"{km} km · {ms} ms · fast waves +{n}%", +"market.route_off":"Broker leaves it alone", +"market.route_on":"Broker trades here", +"market.routes":"Your routes", +"market.row":"{want} wanted · {sold} sold · {listed} listed", +"market.sales":"Capacity you sell", +"market.scout":"Routes you could build", +"market.scout_d":"Between your POPs, without your fiber yet: what each route wants and where it is heading, the most valuable first.", +"market.scout_none":"Build POPs in more cities to see routes between them.", +"market.scout_spend":"{km} km · carriers there spend about {v}/mo at today's prices", +"market.selling":"Selling", +"market.sold_pair":"Your broker sold a dark pair.
{name} pays {up} up front for {what}, then {price}/mo.", +"market.steady":"Steady", +"market.tab":"Capacity market", +"market.title":"Lambda Bazaar", +"market.today":"today", +"market.upgraded":"{name} grows.
Its {n}× {g0} waves on {a}–{b} become {g1}: {price}/mo.", +"market.wants_more":"{name} wants to grow from {g0} to {g1} waves on {a}–{b}, but that fiber has no room. Light more capacity, or keep back less.", "meet_a_network.all_n_out_of_reach":{"one":"All {n} out of reach","other":"All {n} out of reach"}, "meet_a_network.peer_with_the_tier_1_club":"Peer with the Tier 1 club: their customers come along for free. Only networks in nobody’s customer cone need peering of their own.", "meet_a_network.peer_with_the_tier_1_club_n":{"one":"Peer with the Tier 1 club: their customers come along for free. {n} network already comes along with a peer.","other":"Peer with the Tier 1 club: their customers come along for free. {n} networks already come along with a peer."}, diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 32acfbd..4c1884e 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -216,3 +216,16 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} /* A phone on its side: the three side by side, so nothing scrolls. */ @media (orientation:landscape) and (max-height:500px){.chpick h2{font-size:21px !important}.chpick .tagline{display:none} .chopts{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.chopt{flex-direction:column;gap:2px;margin-top:6px;padding:8px 10px}.chi{font-size:22px}.cht span{font-size:12px;line-height:1.3}} +/* The capacity market (Lambda Bazaar): a product's bar is what is sold (green) of what the route wants (the line), with + your minimum as a pink tick. */ +.cmset{border-top:1.5px dashed var(--line);padding:8px 0 4px} +.cmset .nm{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.cmset .seg{margin:4px 0 6px} +.cmp{margin:6px 0 4px} +.cmbar{position:relative;height:9px;border-radius:5px;background:var(--soft);border:1.5px solid var(--line);margin-top:3px;overflow:visible} +.cmbar i{position:absolute;left:0;top:0;bottom:0;background:var(--eye);border-radius:4px} +.cmbar b{position:absolute;top:-4px;bottom:-4px;width:3px;margin-left:-1.5px;background:var(--ink);border-radius:2px} +.cmbar u{position:absolute;top:-5px;bottom:-5px;width:0;margin-left:-1px;border-left:3px dotted var(--me)} +.cmroute{align-items:flex-start} +.tag.cmhot{background:#FFE1D6;color:#B43A12} +.tag.cmcool{background:#DDF1FB;color:#1E6A8C} diff --git a/tests/capacity-market.test.js b/tests/capacity-market.test.js new file mode 100644 index 0000000..b5996f3 --- /dev/null +++ b/tests/capacity-market.test.js @@ -0,0 +1,149 @@ +// The capacity market, Lambda Bazaar (37-fiber-market.js): products from spectrum to 1.6T waves and dark pairs, demand +// that moves and grows, thresholds, managed waves carved out of your own capacity, customers moving up a size, the +// Cable broker's fee and forecast, and saves. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e9;S.lvl=6;S.offers=[];S.biz=[];S.inc=[]"); +const fiber = (ev, id, a, b, ch = 'tp16', n = 8) => ev(`for(const c of ['${a}','${b}'])if(!S.pops[c])ACT.buildPop({city:c});closeModal(); + S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'cl',ch:Array(${n}).fill('${ch}'),km:Math.round(kmBetween('${a}','${b}')*1.05),ready:0,day:0,cut:0,mo:100,trench:'own:${id}',pairs:1});compute();`); +const route = (k) => `cmRoutes().get('${k}')`; + +test('demand moves all the time: its own cycle, noise, and news; a forecast sees the cycle and the news already out', () => { + const { ev, errors } = load(); + start(ev); + fiber(ev, 'f', 'fra', 'ams'); + const hs = JSON.parse(ev(`JSON.stringify(Array.from({length:24},(_, i)=>cmHeat(${route('ams|fra')},'w400',i*15)))`)); + assert.ok(Math.max(...hs) - Math.min(...hs) > 0.3, `heat over a year: ${Math.min(...hs).toFixed(2)} to ${Math.max(...hs).toFixed(2)}`); + assert.ok(hs.every((h) => h >= 0.3 && h <= 2.5)); + assert.equal(ev(`cmFc(${route('ams|fra')},'w400',30)`), ev(`cmDem(${route('ams|fra')},'w400',S.day+30,true)`)); + // A cut on a fiber next door is news the next morning, and carriers want routes around it. + const before = ev(`cmDem(${route('ams|fra')},'spec',S.day+10)`); + // (No other news today: the daily roll for news of its own comes out high.) + ev("S.inc.push({id:'cut1',type:'cut',ref:'own:f',until:S.day+5,msg:''});const r0=Math.random;Math.random=()=>0.99;cmShocks(S.day);Math.random=r0"); + assert.equal(ev('S.cm.news[0].why'), 'cut'); + assert.ok(ev(`cmDem(${route('ams|fra')},'spec',S.day+10)`) > before * 1.4, 'a cut makes the route around it hot'); + ev('const r0=Math.random;Math.random=()=>0.99;cmShocks(S.day);Math.random=r0'); + assert.equal(ev("S.cm.news.filter(n=>n.why==='cut').length"), 1, 'one incident is news once'); + assert.deepEqual(errors, []); +}); + +test('demand grows every year, and buyers move from 100G to 400G, 800G and 1.6T', () => { + const { ev, errors } = load(); + start(ev); + fiber(ev, 'f', 'fra', 'ams'); + ev('S.cm.sh=[]'); + const gbps = (d) => ev(`CM_W.reduce((a,p)=>a+cmDem(${route('ams|fra')},p,${d},true)*CM_G[p],0)`); + assert.ok(Math.abs(ev('cmGrowth(365*5)') - Math.pow(1.15, 5)) < 1e-9, 'about 15% more every year'); + assert.ok(gbps(365 * 5) > gbps(0) * 1.3, `five years on, carriers want ${Math.round(gbps(365 * 5))} G against ${Math.round(gbps(0))} G`); + const sh = (p, d) => ev(`cmShare('${p}',${d})`); + assert.ok(sh('w100', 0) > sh('w100', 365 * 4), '100G fades'); + assert.ok(sh('w1600', 0) < 0.05 && sh('w1600', 365 * 10) > 0.5, '1.6T is rare at first and common ten years on'); + assert.ok(Math.abs(['w100', 'w400', 'w800', 'w1600'].reduce((a, p) => a + sh(p, 900), 0) - 1) < 1e-9, 'the shares add up'); + assert.ok(ev('cmGrowth(365*40)') <= 8, 'growth has a ceiling'); + assert.deepEqual(errors, []); +}); + +test('prices: a 400G wave is 2.7 times a 100G one on land and 3.8 on subsea, short straight routes earn more, and floors hold', () => { + const { ev, errors } = load(); + start(ev); + fiber(ev, 'f', 'fra', 'ams'); + const r = route('ams|fra'); + assert.ok(Math.abs(ev(`cmList(${r},'w400')/cmList(${r},'w100')`) - 2.7) < 1e-9); + assert.ok(Math.abs(ev(`(()=>{const x={...${r},sub:true};return cmList(x,'w400')/cmList(x,'w100')})()`) - 3.8) < 1e-9); + assert.ok(ev(`cmList(${r},'w1600')/16 < cmList(${r},'w100')`), 'a bit on a 1.6T wave is cheaper than on a 100G one'); + assert.ok(ev(`${r}.lp`) > ev(`({...${r},lp:0}, cmRoute('ams','fra',[{...S.links.find(l=>l.id==='f'),km:2000}]).lp)`), 'a long detour loses the latency premium'); + // Each unit sold makes the next cheaper, and the broker never sells below the floor. + ev("for(const p of CM_P){S.cm.p[p].on=true;S.cm.p[p].floor=100;S.cm.p[p].min=1;}__reseed(5)"); + ev('for(let d=0;d<400;d++){S.day++;cmDay(S.day);}'); + const sales = JSON.parse(ev("JSON.stringify(S.biz.map(b=>({t:b.type,g:b.g||0})))")); + assert.ok(sales.length > 0, 'something sold'); + assert.ok(ev(`(()=>{const rs=cmRoutes(),s=cmSold(rs).get('ams|fra');return CM_P.every(p=>!s[p]||cmIdx(rs.get('ams|fra'),p,s[p]-1,0,S.day)*100>=0)})()`)); + assert.deepEqual(errors, []); +}); + +test('auto-listing follows the thresholds and the share kept back; managed waves come out of your own capacity', () => { + const { ev, errors } = load(); + start(ev); + fiber(ev, 'f', 'fra', 'ams', 'zr4', 8); + ev("S.cm.hold=50;S.cm.p.w400.on=true;S.cm.p.w400.min=1;S.cm.p.w400.floor=60;S.cm.p.w800.on=true;S.cm.p.w800.min=1;S.cm.p.w800.floor=60;cmRelist()"); + const L = () => JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').list||{})")); + assert.ok(L().m4 > 0 && L().m4 <= 4, `half of 3.2T kept back leaves at most four 400G waves (${L().m4})`); + assert.equal(L().m8, undefined, 'no 800G wave on 400G optics'); + ev("S.cm.p.w400.min=16;cmRelist()"); + assert.equal(L().m4, undefined, 'below the minimum demand the broker takes it off'); + // A sold managed wave carves its capacity out of your own; when your optics cannot carry it, its customer suffers. + ev("const l=S.links.find(x=>x.id==='f');cmSell(l,'w400',2,1000,0);compute()"); + assert.equal(ev("dfLit(S.links.find(l=>l.id==='f'))-dfCap(S.links.find(l=>l.id==='f'))"), 800); + assert.equal(ev("fiberOk(S.biz.find(b=>b.type==='mwave'))"), true); + ev("S.links.find(l=>l.id==='f').ch=['zr4']"); + assert.equal(ev("fiberOk(S.biz.find(b=>b.type==='mwave'))"), false, '400G lit cannot carry 800G sold'); + ev("ACT.mktCfg({p:'w400',k:'on',v:0})"); + assert.equal(ev("S.cm.p.w400.on"), false); + assert.deepEqual(errors, []); +}); + +test('a carrier on your glass moves up a size once the next one is common, if there is room', () => { + const { ev, errors } = load(); + start(ev); + fiber(ev, 'f', 'fra', 'ams', 'tp16', 8); + ev("S.day=365*4;S.cm.hold=0;const l=S.links.find(x=>x.id==='f');cmSell(l,'w400',2,2000,0);compute()"); + const b0 = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.type==='mwave'))")); + ev("Math.random=()=>0;cmGrow(S.day)"); + const b1 = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.type==='mwave'))")); + assert.equal(b1.g, 800); + assert.ok(b1.rate > b0.rate, `pays more: ${b0.rate} to ${b1.rate}`); + assert.equal(ev("dfLit(S.links.find(l=>l.id==='f'))-dfCap(S.links.find(l=>l.id==='f'))"), 1600); + // No room: it asks, and does not ask again for half a year (1.6T is common by year 9). + ev("S.links.find(l=>l.id==='f').ch=['tp16'];S.cm.hold=50;S.day=365*9;cmGrow(S.day)"); + const gw = ev('S.biz.find(b=>b.type===\'mwave\').gw'); + ev('S.day+=30;cmGrow(S.day)'); + const b2 = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.type==='mwave'))")); + assert.equal(b2.g, 800); + assert.equal(gw, 365 * 9); + assert.equal(b2.gw, 365 * 9, 'not again a month later'); + assert.deepEqual(errors, []); +}); + +test('a Cable broker pays 3% instead of 10% and sees routes it could build with their forecast', () => { + const { ev, errors } = load(); + start(ev); + assert.equal(ev('cmCut()'), 0.9); + ev("ACT.charter({k:'broker'});closeModal();S.cash=1e9"); + assert.equal(ev('cmCut()'), 0.97); + for (const c of ['fra', 'ams', 'par', 'bru']) ev(`if(!S.pops['${c}'])ACT.buildPop({city:'${c}'});closeModal()`); + const sc = JSON.parse(ev('JSON.stringify(cmScout().map(r=>r.k))')); + assert.ok(sc.length > 0 && sc.every((k) => k.includes('|'))); + ev("UI.dtab='market';$('dash').hidden=false;renderDash()"); + const html = ev("$('dashCard').textContent"); + assert.match(html, /Lambda Bazaar/); + assert.match(html, /Routes you could build/); + assert.deepEqual(errors, []); +}); + +test('the market is kept in the save, checked, and old saves get the defaults', () => { + const { ev, errors } = load(); + start(ev); + fiber(ev, 'f', 'fra', 'ams'); + ev("S.cm.hold=10;S.cm.p.w1600.on=true;S.cm.p.w1600.min=2;S.cm.off['ams|fra']=1;cmNews('glut',{k:'ams|fra',a:'ams',b:'fra'},S.day);cmSell(S.links[S.links.length-1],'w800',1,500,0)"); + ev('const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))'); + const cm = JSON.parse(ev('JSON.stringify(S.cm)')); + assert.equal(cm.hold, 10); + assert.deepEqual(cm.p.w1600, { on: true, min: 2, floor: 80 }); + assert.equal(cm.off['ams|fra'], 1); + assert.equal(cm.sh[0].why, 'glut'); + assert.equal(ev("S.biz.find(b=>b.type==='mwave').g"), 800); + ev("const o=JSON.parse(JSON.stringify(packSave(S)));o.cm={hold:33,p:{w100:{on:'yes',min:999,floor:-1}},off:{'zzz|ams':1},sh:[{why:'nope'},{why:'dc',c:'atlantis'}],news:'x'};o.biz.find(b=>b.type==='mwave').g=999;o.links.find(l=>l.id==='f').list={m8:'lots',m16:3};S=migrate(o)"); + const c2 = JSON.parse(ev('JSON.stringify(S.cm)')); + assert.equal(c2.hold, 25); + assert.deepEqual(c2.p.w100, { on: true, min: 4, floor: 80 }); + assert.deepEqual(c2.off, {}); + assert.deepEqual(c2.sh, []); + assert.deepEqual(c2.news, []); + assert.equal(ev("S.biz.find(b=>b.type==='mwave').g"), 100); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').list)")), { w: 0, p: 0, m16: 3 }); + ev('const o=JSON.parse(JSON.stringify(packSave(S)));delete o.cm;S=migrate(o)'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.cm.p.spec)')), { on: false, min: 2, floor: 80 }); + assert.deepEqual(errors, []); +}); diff --git a/tests/fiber-broker.test.js b/tests/fiber-broker.test.js index f893c3d..7248473 100644 --- a/tests/fiber-broker.test.js +++ b/tests/fiber-broker.test.js @@ -16,6 +16,8 @@ test('a route\'s market follows the eyeballs at both ends, and a landing town co assert.ok(ev("brMarket('nyc','bde')") > ev("brMarket('nyc','gdx')")); }); +// The market moves (37-fiber-market.js): demand has its own cycle and grows, so days pass here; at its hottest a route +// wants CM_HMAX times its usual spectrum. test('a listing sells over time, never past the market, and rent from a road to nowhere stays small', () => { const { ev, errors } = load(); start(ev); @@ -23,11 +25,11 @@ test('a listing sells over time, never past the market, and rent from a road to fiber(ev, 'far', 'jed', 'gdx', 9089); ev("__reseed(7);ACT.listFiber({id:'big',w:60});ACT.listFiber({id:'far',w:60})"); assert.equal(ev("S.biz.length"), 0, 'nothing sells the moment it is listed'); - ev('for(let d=0;d<720;d++)brTick()'); + ev('for(let d=0;d<720;d++){S.day++;brTick();}'); const sold = (id) => ev(`S.biz.filter(b=>b.link==='${id}').reduce((a,b)=>a+(b.slots||0),0)`); assert.ok(sold('big') >= 3, `Frankfurt–Amsterdam sold ${sold('big')}`); - assert.ok(sold('big') <= ev("brMarket('fra','ams')"), 'never more than the route wants'); - assert.equal(sold('far'), 1, 'Jeddah–Magadan: one wave, then the market is full'); + assert.ok(sold('big') <= ev("brMarket('fra','ams')*0.5*CM_HMAX*Math.pow(cmGrowth(S.day),0.7)"), 'never more than the route wants at its hottest'); + assert.ok(sold('far') >= 1 && sold('far') <= 2, `Jeddah–Magadan: a wave or two, then the market is full (${sold('far')})`); assert.equal(ev("brFree(S.links.find(l=>l.id==='far'))"), 0); // random alien-wave offers respect the market too ev("S.offers=[];for(let i=0;i<400;i++)spawnOffer()"); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 63a28ec..38795de 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -432,8 +432,11 @@ test('F5: rented capacity never outgrows the route\'s market (#203)', () => { const g = load(); g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.biz=[];S.offers=[];for(const c of ['jed','gdx'])ACT.buildPop({city:c})"); g.ev("S.links.push({id:'f',a:'jed',b:'gdx',kind:'df',own:true,sys:'roadm',ch:[],km:9089,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});compute();__reseed(5);ACT.listFiber({id:'f',w:120,p:1})"); - g.ev('for(let d=0;d<1500;d++){brTick();if(d%7===0)spawnOffer();}for(const o of S.offers.filter(o=>o.link===\'f\'))ACT.accept({id:o.id})'); - assert.ok(g.ev("brSold('jed','gdx')") <= g.ev("brMarket('jed','gdx')"), 'F5: no more than the route wants'); + g.ev('for(let d=0;d<1500;d++){S.day++;brTick();if(d%7===0)spawnOffer();}for(const o of S.offers.filter(o=>o.link===\'f\'))ACT.accept({id:o.id})'); + // The market moves and grows (37-fiber-market.js): never more than the route wants at its hottest, today. + const most = g.ev("Math.max(brMarket('jed','gdx'),Math.round(brMarket('jed','gdx')*0.5*CM_HMAX*Math.pow(cmGrowth(S.day),0.7)))"); + assert.ok(g.ev("brSold('jed','gdx')") <= most, `F5: no more than the route wants (${g.ev("brSold('jed','gdx')")} of ${most})`); + assert.ok(g.ev("brSold('jed','gdx')") <= 3, 'a road to nowhere still sells only a little'); assert.deepEqual(g.errors, []); }); @@ -462,6 +465,26 @@ test('F7: extra crews cut a build on land to half its planned time at most (#203 assert.deepEqual(g.errors, []); }); +test('F8: a managed wave costs your own capacity, rides one optic, and is priced against its fiber', () => { + const g = load(); + g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[];for(const c of ['fra','ams'])if(!S.pops[c])ACT.buildPop({city:c})"); + g.ev("S.links.push({id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'cl',ch:['zr4','zr4'],km:400,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});compute()"); + const r = "cmRoutes().get('ams|fra')"; + for (const [p, land, sea] of [['w400', 2.7, 3.8], ['w800', 4.6, 6.6], ['w1600', 7.8, 11]]) { + assert.ok(Math.abs(g.ev(`cmList(${r},'${p}')/cmList(${r},'w100')`) - land) < 1e-9, `F8: ${p} on land`); + assert.ok(Math.abs(g.ev(`(()=>{const x={...${r},sub:true};return cmList(x,'${p}')/cmList(x,'w100')})()`) - sea) < 1e-9, `F8: ${p} on subsea`); + } + for (let i = 1; i < 4; i++) assert.ok(g.ev(`cmList(${r},CM_W[${i}])/CM_G[CM_W[${i}]]= 0.7 - 1e-9 && x <= 1.35 + 1e-9, `F8: heat moves a price by ${x}`); } + assert.equal(g.ev("cmSpare(S.links[S.links.length-1],'w800',0)"), 0, 'F8: no 800G wave on 400G optics'); + g.ev("cmSell(S.links[S.links.length-1],'w400',1,100,0);compute()"); + assert.equal(g.ev("dfLit(S.links[S.links.length-1])-dfCap(S.links[S.links.length-1])"), 400, 'F8: it comes out of your own capacity'); + g.ev("S.links[S.links.length-1].ch=[]"); + assert.equal(g.ev("fiberOk(S.biz.find(b=>b.type==='mwave'))"), false, 'F8: unlit, its customer is down'); + assert.deepEqual(g.errors, []); +}); + // D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail. const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()"); const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`); diff --git a/tests/issues.test.js b/tests/issues.test.js index 55ae84d..d09c13b 100644 --- a/tests/issues.test.js +++ b/tests/issues.test.js @@ -1270,7 +1270,10 @@ test('#51 a dark fiber shows what is rented out, and spare capacity can be liste ev("for(let i=0;i<120&&!S.biz.some(b=>b.link==='df1');i++)brTick();renderPanel()"); const b = JSON.parse(ev("JSON.stringify(S.biz.find(x=>x.link==='df1'))")); assert.equal(b.type, 'wwave'); - assert.equal(b.rate, ev(`(()=>{const F=dfLeaseMo(450)+ampCount(450)*AMP_MO,M=brMarket('fra','ams');let r=0;for(let i=0;i<${b.slots};i++)r+=F*WW_SHARE*(1-WW_FALL*Math.min(1,i/M));return Math.round(r*0.9)})()`), 'the alien-wave price, priced against the fiber, minus the broker'); + // The capacity market prices it (37-fiber-market.js): 30% of the fiber's cost a month, moved by how hot the route is + // and how full, minus the broker. + assert.equal(b.rate, ev(`(()=>{const r=cmRoutes().get('ams|fra');let x=0;for(let i=0;i<${b.slots};i++)x+=cmList(r,'spec')*cmIdx(r,'spec',0,i,S.day);return Math.round(x*0.9*mkt())})()`), 'the alien-wave price, priced against the fiber, minus the broker'); + assert.ok(Math.abs(ev("cmList(cmRoutes().get('ams|fra'),'spec')/(dfLeaseMo(450)+ampCount(450)*AMP_MO)") - 0.3) < 1e-9); assert.ok(txt().includes(b.name), 'the customer is listed on the fiber'); assert.match(txt(), new RegExp(`Free channels\\s*${62 - b.slots} / 64`)); assert.equal(ev("S.links[0].list?S.links[0].list.w:0"), 4 - b.slots, 'the listing shrinks by what sold'); From 91b2afe70679a19e5914eed3c2a047a2f0cf5c34 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 14:11:01 +0100 Subject: [PATCH 05/20] Lambda Bazaar capacity market and traffic badges (3.2.0) --- CHANGELOG.md | 2 ++ package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c4ddef..5a20e42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [3.2.0] — 2026-11-07 + - New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. - Lambda Bazaar, a capacity market for your dark fiber, is a new tab in the NOC dashboard. Sell spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold fiber on, and choose how much to keep back for your own traffic, from what demand the broker lists, and the price it never sells below. What each route wants moves all the time and grows every year: hot routes pay more, a fiber cut next door or a hyperscaler breaking ground sends demand up, buyers move from 100G to bigger waves over the years, and carriers already on your glass ask to move up a size. Short, straight routes earn more for fast waves. A Cable broker pays the broker 3% instead of 10%, and sees where each route is heading and which routes between its POPs are worth building. diff --git a/package-lock.json b/package-lock.json index 28dc651..8a24e5f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "3.1.0", + "version": "3.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "3.1.0", + "version": "3.2.0", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index 097e4de..62a142d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "3.1.0", + "version": "3.2.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT", From d03dde6fcd5089eb7bdeb1e73953ffa36e9b1074 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sat, 7 Nov 2026 14:38:19 +0100 Subject: [PATCH 06/20] Release deploys again when its tests were skipped on purpose A skipped job skips every job that needs it, even through one that runs anyway: since auto-release passes tested=true, the tests job is skipped, build ran with always(), and deploy (no condition of its own) was skipped. v3.2.0 built and never went live. Deploy and IndexNow now run whenever the job before them succeeded. --- .github/workflows/release.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9c2defa..213596f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -125,8 +125,11 @@ jobs: with: path: ./_site + # A skipped job skips everything that needs it, even through build (which runs anyway): without always() here, a + # release whose tests auto-release.yml already ran built and never deployed (v3.2.0). deploy: needs: build + if: ${{ always() && needs.build.result == 'success' }} runs-on: ubuntu-latest permissions: pages: write @@ -140,7 +143,7 @@ jobs: # the site is live. indexnow: needs: deploy - if: ${{ !inputs.weekly }} + if: ${{ always() && needs.deploy.result == 'success' && !inputs.weekly }} runs-on: ubuntu-latest env: # IndexNow keys are public by design (also served at /.txt). From b9d63193028c11ff7afd36994893fdec25d0a4eb Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:21:22 +0100 Subject: [PATCH 07/20] The page stays free while big networks play: ambient map at 30 fps, saves in the worker, less to carry back The game plays exactly as before; only what holds the page changes. * mapStill() tells three cases apart: still (drawn once a second), ambient (only the animation clock moved: drawn at most every 29 ms, so 30 fps on 60 and 120 Hz screens) and moving (camera, pointer, selection, network: every frame). The animations follow the clock, so they keep their speed. * save() skips the storage write when the text is the one the slot already holds (SLOT.txt) and no write is on its way; leaving the page still writes. A big autosave that moved on is packed, turned into text, stamped and compressed in the route worker (rwSave(), rwGzip()); the page only writes what comes back. A lost worker hands its pending saves back to the page (rwSaveBack(), rwGzBack()). * Less crosses back from the worker: R.efg stays there while R is its own last answer (RW.wR, efg 0), R.egDesc comes as 0 or as the entries that changed (rwDescOut()/rwDescIn()), what crossed each link travels as typed arrays decoded on demand (rwLOut()/rwLIn()), and the full ports (hotMap) come along with R. Every message is read in order (rwMsg()), so both sides always hold the same last answer. * Idle frames build the diverse-paths map and the latency floors a millisecond at a time (diversityWarm(), latWarm()), before the first offer asks. * Diagnostic info shows how fast days really come: speed asked, speed held, how long a day takes (15-day-pace.js). * perf-bench: "The NOC intern's shift: opsDay()" and, in Chromium, "One game day in play: page time only", a day played with the real route worker counting only the time it holds the page. Tests: frame-pacing, day-pace, save-size, persist, route-worker (efg as typed arrays, hotMap from the worker), day-steps (a second page plays the worker: answers without R.egDesc, with only its changes, posts without R.efg, renewal haggles answered through the worker), intern-dark-fiber-worker, webgl-zoom-sprites, speed. --- .claude/skills/write-tests/SKILL.md | 5 +- CHANGELOG.md | 4 + docs/ARCHITECTURE.md | 21 +++- scripts/perf-bench.js | 18 ++-- scripts/perf-browser.js | 29 +++++- src/game/80-simulation/28-route-worker.js | 82 +++++++++++++--- src/game/80-simulation/60-requirements.js | 33 ++++--- .../80-simulation/80-geography-and-latency.js | 13 ++- src/game/88-days/15-day-pace.js | 15 +++ src/game/91-save.js | 23 +++-- src/game/91-slots.js | 9 +- src/game/96-map/97-diagnostics.js | 4 +- src/game/99-loop.js | 22 +++-- tests/day-pace.test.js | 35 +++++++ tests/day-steps.test.js | 32 +++--- tests/frame-pacing.test.js | 65 ++++++++++++- tests/intern-dark-fiber-worker.test.js | 64 ++++++++++++ tests/persist.test.js | 8 +- tests/route-worker.test.js | 13 ++- tests/save-size.test.js | 97 ++++++++++++++++++- tests/speed.test.js | 4 +- tests/webgl-zoom-sprites.test.js | 7 +- 22 files changed, 517 insertions(+), 86 deletions(-) create mode 100644 src/game/88-days/15-day-pace.js create mode 100644 tests/day-pace.test.js create mode 100644 tests/intern-dark-fiber-worker.test.js diff --git a/.claude/skills/write-tests/SKILL.md b/.claude/skills/write-tests/SKILL.md index bfdc934..33f7aa9 100644 --- a/.claude/skills/write-tests/SKILL.md +++ b/.claude/skills/write-tests/SKILL.md @@ -45,9 +45,10 @@ pull requests collide. Run one file with `npm test -- tests/route-servers.test.j or set state directly (`S.day=…`, `S.ev.x=…`). - **Force a specific random failure or event** by patching the picker: ```js - ev("eval('('+fireFailure.toString().replace('const e=pick(opts);',\"const e='crash';\")+')')()"); + ev("runNow(eval('('+failureRun.toString().replace('if(only)type=only;',\"type='crash';\")+')')())"); ``` - Check the current source for the exact `pick` line first (`grep -rn "function fireFailure" src/game`); it may differ. + `failureRun()` is a generator (its yield is the routing): play it with `runNow()`. Check the current source for the + exact line first (`grep -rn "function\* failureRun" src/game`); it may differ. Or simply `fireFailure('crash')`. - **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`. - **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through `parseSave()`/`migrate()`, and test that an *old* save without the new field still loads. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a20e42..ec4da9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. +- A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds. +- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. + ## [3.2.0] — 2026-11-07 - New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e7d386..762873d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -120,6 +120,9 @@ the chaos monkey's snip (`mkSnipRun()`), an event's cut (`eventRun()`: its routi sales desk's trials (a `{trial}` yield the worker answers with yes or no, `offerTrial()`) are all steps. The intern's orders are generators too, with a rest after each job. `UI.tick` (what the day itself announces, which quiet notifications may keep to the NOC log) is set around every step (`dayStep()`), on both sides of the worker. +A big autosave is packed, turned into text and compressed in the worker (`rwSave()`), the page only writes it. The +diverse-paths map and the latency floors new offers need are worked out a millisecond a frame ahead (`diversityWarm()`, +`latWarm()`). A rest waits for the next frame only when none was drawn just now (`rwLater()`). The daily mood check asks "a path without subsea" for each customer that wants one: during that loop the land-connected islands are worked out once (`TERR`, `terrIslands()`), and two cities have a land path when they share one. @@ -206,7 +209,12 @@ network does not freeze the page once a day. saved; nothing else starts meanwhile. `tests/day-steps.test.js` plays a second page as the worker and compares every day with `dayTick()`. - **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays - transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. + transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. What crossed each + link (`R.efp.L`) crosses as typed arrays with each exit key once (`rwLOut()`), and the page decodes a link only when + something reads it (`rwLIn()`). Two parts are not sent again when they would be the same: `R.egDesc` comes back as 0 + when it is the last one key for key (the page keeps `RW.desc`), and `R.efg` is not posted back while R is the worker's + own last answer (`RW.wR`; the worker keeps it in `RW.last`). Both sides read every message in order, so they always + hold the same last one; `tests/day-steps.test.js` plays a second page as the worker and checks it all. - **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's answer is stale: it is dropped and the day ends with the action's R. - **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a @@ -227,8 +235,11 @@ network does not freeze the page once a day. controlled by `renderTabbar()`. - These panels and the dashboard are rebuilt as HTML every tick and written with `morph()`, which patches only what changed. Buttons whose action changed are replaced, so taps stay safe (#44). -- The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses - a simplified style; parallel waves are grouped by `linkGroups()`. +- The map is a canvas drawn by `draw()` from `frame()`. Zoomed out (`lodFar()`) it uses + a simplified style; parallel waves are grouped by `linkGroups()`. `mapStill()` decides whether a frame is drawn: + when nothing changed (paused, animations off) it is not, except once a second; when only the animation clock moved + (packets, waves, clouds, floaters) the map is ambient and drawn at most 30 times a second; anything else that moves + (camera, pointer, selection, the network) gets every frame (`tests/frame-pacing.test.js`). ## The weekly puzzle @@ -273,7 +284,9 @@ back to the in-browser `weekly()`. - `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot (`UI.slot`, `src/game/91-slots.js`): `sot-save-v1:`, plain JSON or `gz:`-compressed above a million characters, with a stamp `sv:{seq,at}` appended. Then the index `sot-slots` (name, ASN, preset, day, tier, - cash, last played, size, seq) is updated; the title screen lists networks from the index alone. + cash, last played, size, seq) is updated; the title screen lists networks from the index alone. A save whose text is + the one the slot already holds (`SLOT.txt`: a paused game, nothing changed) is not written again, unless the page is + closing: on a big network the storage write costs more than making the text. - Each tab keeps its slot in `sessionStorage['sot-slot']`. One window per slot: a Web Lock (`sot-slot:`) where supported, plus a heartbeat `sot-open:`; BroadcastChannel `sot-slots` asks another window to hand over, and the `storage` event stops a window whose slot was saved newer elsewhere diff --git a/scripts/perf-bench.js b/scripts/perf-bench.js index a46c048..62997f8 100644 --- a/scripts/perf-bench.js +++ b/scripts/perf-bench.js @@ -43,6 +43,11 @@ const METRICS = [ ['panels', 'Side panel and left list', "for(const f of [true,false]){UI.sel={type:'city',id:f?'fra':'ams'};UI.tab=f?'peer':'up';UI.left=f?'nets':'noc';UI.leftOpen=true;renderPanel();renderLeft();}"], ['dash', 'NOC dashboard tabs', "$('dash').hidden=false;for(const k of ['overview','conn','traffic','infra','cust']){UI.dtab=k;renderDash();}$('dash').hidden=true"], ['map', 'Map at three zoom levels', "for(const z of [1,3.2,7]){cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=z;draw(0);}"], + // The NOC intern runs every order, every day: one shift, its recomputes included (hired here if the save has none). + ['ops', "The NOC intern's shift: opsDay()", "if(!S.ops.intern){S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;}S.cash=1e9;opsDay(S.day)"], + // A day as it is played: its routing in the route worker, and only the time it holds the page counted (what a player + // feels as a hitch). Chromium only: jsdom has no Worker. See perf-browser.js. + ['play', 'One game day in play: page time only', null, { play: true }], ]; function open(file) { @@ -57,13 +62,14 @@ function open(file) { } const median = (a) => { const s = [...a].sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2; }; -const ms = (x) => x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2); +const ms = (x) => x == null ? '–' : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2); (async () => { const head = open(HEAD), base = BASE ? open(BASE) : null; const sameOutcome = base ? base.outcome() === head.outcome() : null; const res = {}; -for (const [k, , body] of METRICS) { +for (const [k, , body, o] of METRICS) { + if (o && o.play) { res[k] = { head: null, base: null, samples: null }; continue; } const h = [], b = []; for (const v of [head, base].filter(Boolean)) { v.time(body); v.time(body); } // warm up for (let i = 0; i < RUNS; i++) { @@ -78,7 +84,7 @@ const browser = args.includes('--browser') ? await require('./perf-browser').run const { mannWhitneyP } = require('./perf-stats'); const pOf = (r) => (r.samples && r.samples.base ? mannWhitneyP(r.samples.head, r.samples.base) : 1); const verdict = (r, noise = 2) => { - if (r.base == null) return ''; + if (r.base == null || r.head == null) return ''; const ratio = r.head / (r.base || 1e-9); if (Math.abs(r.head - r.base) < noise || pOf(r) >= 0.01) return '≈'; if (ratio >= 1.5) return '🔴 slower'; @@ -86,8 +92,8 @@ const verdict = (r, noise = 2) => { if (ratio <= 0.85) return '🟢 faster'; return '≈'; }; -const pct = (r) => r.base == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`; -const pTxt = (r) => { const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); }; +const pct = (r) => r.base == null || r.head == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`; +const pTxt = (r) => { if (r.base == null || r.head == null) return ''; const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); }; // One table per environment, all the same shape. `noise` is the absolute floor below which nothing counts. const table = (res, noise) => (base ? '| What | Base | This PR | Change | p | |\n|---|--:|--:|--:|--:|---|\n' : '| What | Time |\n|---|--:|\n') + METRICS.map(([k, label]) => { const r = res[k]; return base ? `| ${label} | ${ms(r.base)} | ${ms(r.head)} | ${pct(r)} | ${pTxt(r)} | ${verdict(r, noise)} |` : `| ${label} | ${ms(r.head)} |`; }).join('\n') + '\n'; @@ -95,7 +101,7 @@ const slowIn = (res, noise) => METRICS.filter(([k]) => /slower/.test(verdict(res const s = head.size; let md = `## Performance on a big network\n\n${s.pops} POPs · ${s.links} links · ${s.pni} PNIs · ${s.caches} cache boxes · ${s.ix} IX ports · ${s.customers} customers. Median of ${RUNS} runs, in milliseconds.\n\n`; -md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here.\n\n` + table(res, 2); +md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here. It has no Worker either: a day in play is timed in Chromium only.\n\n` + table(res, 2); const slow = base ? slowIn(res, 2) : []; const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] }; for (const p of PROFILES) { diff --git a/scripts/perf-browser.js b/scripts/perf-browser.js index 01bf39e..545cd13 100644 --- a/scripts/perf-browser.js +++ b/scripts/perf-browser.js @@ -45,7 +45,23 @@ async function openPage(browser, profile, file, save, errors) { const t = performance.now(); f(); void document.documentElement.offsetHeight; const gl = G && G.shown && G.gl; if (gl) gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); else map.getImageData(0, 0, 1, 1); return { ms: performance.now() - t, map: G && G.shown ? 'gl' : '2d' }; }, [k, body]); }; - return { ctx, time }; + // One game day as it is played: its steps on the page, its routing in the route worker (built from the page itself, + // see 28-route-worker.js). Only the time it holds the page counts: starting the day, each answer from the worker and + // each step that waited for a frame. Waiting for the worker does not count; the page is free meanwhile. + // null when this page has no worker to play with. + const play = async () => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(async () => { + window.__TUBES_TEST__ = false; + try { + const w = typeof rwOn === 'function' && rwOn() && rwStart(); if (!w) return null; + let busy = 0; const wrap = (f) => function (...a) { const t = performance.now(); try { return f.apply(this, a); } finally { busy += performance.now() - t; } }; + const om = w.onmessage, later = RW.later; w.onmessage = wrap(om); if (later) RW.later = (f) => later(wrap(f)); + S.nextFail = S.nextEvent = S.day + 99; + try { const t = performance.now(); rwDay(); busy += performance.now() - t; while (RW.job) await new Promise((r) => setTimeout(r, 1)); } + finally { w.onmessage = om; if (later) RW.later = later; } + return RW.dead ? null : busy; + } finally { window.__TUBES_TEST__ = true; } + }); }; + return { ctx, time, play }; } // Returns {version, profiles: {desktop: {compute: {head, base}, ...}, phone: {...}}, errors}. @@ -61,14 +77,17 @@ async function runBrowser({ head, base, save, metrics, runs, exe }) { const res = out.profiles[p.key] = {}; // Which map each version drew with, over all the runs that drew one (a version falling back mid-run shows both). const maps = res.maps = { head: new Set(), base: new Set() }; - for (const [k, , body] of metrics) { - const H = [], B = [], go = async (v, into, m) => { const r = await v.time(k, body); into.push(r.ms); if (k === 'map') m.add(r.map); }; - for (const v of [h, b].filter(Boolean)) { await v.time(k, body); await v.time(k, body); } // warm up + for (const [k, , body, o] of metrics) { + const H = [], B = [], run = (v) => (o && o.play ? v.play() : v.time(k, body)); + const go = async (v, into, m) => { const r = await run(v); if (o && o.play) into.push(r); else { into.push(r.ms); if (k === 'map') m.add(r.map); } }; + for (const v of [h, b].filter(Boolean)) { await run(v); await run(v); } // warm up (and the worker starts) for (let i = 0; i < runs; i++) { // Alternate who goes first, like the jsdom runs. if (b && i % 2) { await go(b, B, maps.base); await go(h, H, maps.head); } else { await go(h, H, maps.head); if (b) await go(b, B, maps.base); } } - res[k] = { head: median(H), base: b ? median(B) : null, samples: { head: H.map((x) => +x.toFixed(1)), base: b ? B.map((x) => +x.toFixed(1)) : null } }; + // A version without a worker gives nothing to compare. + const ok = (a) => a.every((x) => x != null); + res[k] = { head: ok(H) ? median(H) : null, base: b && ok(B) ? median(B) : null, samples: { head: ok(H) ? H.map((x) => +x.toFixed(1)) : null, base: b && ok(B) ? B.map((x) => +x.toFixed(1)) : null } }; } res.maps = { head: [...maps.head], base: b ? [...maps.base] : null }; await h.ctx.close(); if (b) await b.ctx.close(); diff --git a/src/game/80-simulation/28-route-worker.js b/src/game/80-simulation/28-route-worker.js index a21f290..d05ebfa 100644 --- a/src/game/80-simulation/28-route-worker.js +++ b/src/game/80-simulation/28-route-worker.js @@ -10,7 +10,7 @@ const RW_IN=!!self.__TUBES_WORKER__; const RW_EL=!RW_IN&&typeof document!=='undefined'?document.currentScript:null; // RW_SLOW: a frame time (ms) above which the device does not keep up anyway, and a day may take longer slices (99-loop.js). const RW_SLOW=20; -const RW={w:null,dead:false,seq:0,gen:0,job:null,budget:8,later:f=>rwLater(f),stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}}; +const RW={w:null,dead:false,seq:0,gz:0,gzq:new Map(),svq:new Map(),gen:0,job:null,desc:null,wR:null,wseq:0,last:null,budget:8,later:f=>rwLater(f),stat:{n:0,post:0,de:0,apply:0,wait:0,work:0}}; function rwOn(){return !RW_IN&&!RW.dead&&!window.__TUBES_TEST__&&!window.__TUBES_SYNC__&&typeof Worker==='function'&&!!RW_EL;} function rwStart(){if(RW.w)return RW.w; try{const L=LANG,dict=L!=='en'&&window.I18N[L]?JSON.stringify(window.I18N[L]):'null'; @@ -23,12 +23,12 @@ if(${dict})self.I18N[${JSON.stringify(L)}]=${dict}; `; const url=URL.createObjectURL(new Blob([pre,RW_EL.textContent,'\n;self.onmessage=e=>rwServe(e.data);'],{type:'text/javascript'})); const w=RW.w=new Worker(url);URL.revokeObjectURL(url); - w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwDone(m,t);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();}; + w.onmessage=e=>{const t=performance.now(),m=e.data;RW.stat.de+=performance.now()-t;rwMsg(m,t);};w.onerror=w.onmessageerror=e=>{console.error('[tubes] route worker failed',e.message||e);rwKill();}; }catch(e){console.error('[tubes] no route worker',e);rwKill();} return RW.w;} // Gone for good this session: the routing in flight is done here instead, and the day goes on without the worker. // (A day resting between steps goes on by itself, on the page from then on.) -function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;if(!j||j.rest)return;RW.job=null; +function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;rwGzBack();rwSaveBack();const j=RW.job;if(!j||j.rest)return;RW.job=null; if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAgain(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);} // One day in play (dayRun(), 10-day-tick.js): its steps run here, every routing it asks for runs in the worker. function rwDay(){rwGo(dayRun());} @@ -45,7 +45,9 @@ function rwGo(g,v){const t0=performance.now();for(;;){let s;try{s=dayStep(g,v);} const w=rwOn()&&rwStart();if(!w){try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;} const t=performance.now(),seq=++RW.seq; // The worker also needs what compute() reads from yesterday's R: link loads, and the scenic circuits' paths. - try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg),...(tr?{trial:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{b:tr.trial,hx:tr.hx}}:{})});} + // While R is the worker's own last answer (RW.wR), it keeps its R.efg rather than getting it back (efg 0, rwServe()). + const mine=R===RW.wR; + try{w.postMessage({seq,S,load:R.load,l2route:R.l2route,efg:mine?0:rwEfgOut(R.efg),wseq:mine?RW.wseq:0,...(tr?{trial:tr.dark?{dark:tr.dark,s0:tr.s0,L0:tr.L0}:{b:tr.trial,hx:tr.hx}}:{})});} catch(e){console.error('[tubes] route worker post',e);rwKill();try{here();}catch(e){tickErr(e);rwDayDone();return;}continue;} const t1=performance.now();RW.stat.post+=t1-t;RW.job={seq,g,gen:RW.gen,t:t1,state:S,tr};return;}} /* Where a resting day goes on. A frame drawn moments ago leaves time before the next one: the day goes on in a task of @@ -57,6 +59,15 @@ function rwLater(f){if(RW_CH&&performance.now()-(RW.lf||-1e9)<(RW.fms||16)*0.75) else requestAnimationFrame(()=>setTimeout(f,0));} // The day rests: it goes on after the next frame, still in flight meanwhile (no next day, no save). function rwRest(g,v){const j=RW.job={rest:true,g,state:S};RW.later(()=>{if(RW.job!==j)return;RW.job=null;if(j.state!==S){rwDayDone();return;}rwGo(g,v);});} +// Every answer from the worker, in order. +function rwMsg(m,t0){if(m.gz!==undefined){rwGzDone(m);return;}if(m.sv!==undefined){rwSaveDone(m);return;}if(m.R){const d=m.R.egDesc;if(d===0)m.R.egDesc=RW.desc;else RW.desc=m.R.egDesc=d&&d.dK!==undefined?rwDescIn(d,RW.desc):d;}rwDone(m,t0);} +/* A changed R.egDesc comes as its keys, in order, and only the entries that changed (rwDescOut()): a few among thousands. + The rest are yesterday's entries, so the page holds the same object, key for key and in the same order. */ +// dK 0: the keys are yesterday's, in yesterday's order (most days), so they do not come along either. +function rwDescOut(d,old){if(!old)return d;const K=Object.keys(d),O=Object.keys(old),ch={}; + for(const k of K){const x=d[k],y=old[k];if(!y||x.lab!==y.lab||x.city!==y.city||x.k!==y.k)ch[k]=x;} + let same=K.length===O.length;for(let i=0;same&&iRW.budget/2)rwRest(j.g,v);else rwGo(j.g,v);} -function rwDayDone(){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}} +function rwDayDone(){paceEnd(performance.now());UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;if(UI.saveDue){UI.saveDue=false;save();}} +/* A save's compression (91-save.js) runs in the worker too: deflating a big network held the page about as long as + writing it plain. The text goes over as it is (a string is copied flat, without walking a game), the compressed + text comes back. In order with the routings, so a save may wait for one. */ +function rwGzip(txt){const w=rwOn()&&rwStart();if(!w)return null;const k=++RW.gz; + return new Promise((res,rej)=>{RW.gzq.set(k,{res,rej,txt});try{w.postMessage({gz:k,txt});}catch(e){RW.gzq.delete(k);rej(e);}});} +function rwGzDone(m){const q=RW.gzq.get(m.gz);if(!q)return;RW.gzq.delete(m.gz);if(m.err)q.rej(new Error(m.err));else q.res(m.data);} +/* A whole save in the worker (save(), 91-save.js): the game as it was when saved (the copy postMessage makes), packed, + turned into text, stamped and compressed there. Back come the text (the slot keeps it, to spot an unchanged game) and + what to write. The worker lost meanwhile: that save is gone, so the next frame saves again, here. */ +function rwSave(st,seq){const w=rwOn()&&rwStart();if(!w)return null;const k=++RW.gz; + return new Promise((res,rej)=>{RW.svq.set(k,{res,rej});try{w.postMessage({sv:k,S:st,seq});}catch(e){RW.svq.delete(k);rej(e);}});} +function rwSaveDone(m){const q=RW.svq.get(m.sv);if(!q)return;RW.svq.delete(m.sv);if(m.err)q.rej(new Error(m.err));else q.res({txt:m.txt,data:m.data});} +function rwSaveBack(){const q=[...RW.svq.values()];RW.svq.clear();if(q.length)UI.lastSave=0;for(const x of q)x.rej(new Error('route worker lost'));} +function rwSaveServe(m){let txt;try{txt=JSON.stringify(packSave(m.S));}catch(e){postMessage({sv:m.sv,err:String(e)});return;} + const st=slotStamp(txt,m.seq);(txt.length>=GZ_BG?gzB64(st).then(b=>GZ+b):Promise.resolve(st)).then(data=>postMessage({sv:m.sv,txt,data}),e=>postMessage({sv:m.sv,err:String(e)}));} +// The worker gone: what it was compressing is compressed here. +function rwGzBack(){const q=[...RW.gzq.values()];RW.gzq.clear();for(const x of q)gzB64(x.txt).then(x.res,x.rej);} /* R as plain data. R.ef and R.fl are lazy getters, sent as the pieces they are built from (R.efp, R.flc, see efBuild() and flDefine() in 30-compute.js), their typed arrays moved, not copied. Exits become their ids (all R.fl reads), and an attack record names its attack in S by id. */ const FL_COLS=['FREM','FCI','FNJ','FCA','FBZ','FGT','FGI','FGP','FGH','FTI','FII']; function rwPack(R){const o={};for(const k in R)o[k]=k==='ef'?0:k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k]; - const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>({id:e.id}))},tr=[p.ACN.buffer,p.ACD.buffer];for(const k of FL_COLS)tr.push(c[k].buffer); - return {o,p:{...p,flc:c},tr};} -function rwUnpack(o,p){o.ef={};efBuild(o,p.L,p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc); + const p=R.efp,c={...R.flc,E:R.flc.E.map(e=>e.id)},L=rwLOut(p.L),tr=[p.ACN.buffer,p.ACD.buffer,...L.tr];for(const k of FL_COLS)tr.push(c[k].buffer); + return {o,p:{...p,L:L.o,flc:c},tr};} +function rwUnpack(o,p){o.ef={};p.flc.E=p.flc.E.map(id=>({id}));efBuild(o,rwLIn(p.L),p.ACN,p.ACD,p.NKN,p.NC,p.NN);flDefine(o,p.flc); const as=ddosAll(S,false);for(const m of o.ddos){m.attack=as.find(a=>a.id===m.attack)||null;m.ports=new Map();}return o;} +/* What crossed each link (efp.L: [link id, edge index, t], t = {g: exit key → slot, v: sums by slot, n, d}) is the + biggest part of R, and as plain objects it took longer to read on the page than all the rest. It crosses as typed + arrays instead, the exit keys once each, and the page decodes a link's t only when something reads it: the link panel + (R.ef) or a scenic circuit routed on the page (R.efg). Decoded, it is the same t, Map order included. */ +function rwLOut(L){const n=L.length,K=[],ki=new Map(),ID=new Array(n),EI=new Int32Array(n),OG=new Int32Array(n+1),ON=new Int32Array(n+1),OD=new Int32Array(n+1); + let ng=0,nn=0,nd=0;for(const x of L){const t=x[2];ng+=t.g.size;nn+=t.n.length;nd+=t.d.length;} + const G=new Int32Array(2*ng),V=new Float64Array(ng),N=new Int32Array(nn),D=new Int32Array(nd);ng=nn=nd=0; + for(let j=0;j{if(!t){const g=new Map(),v=[];for(let a=OG[j];a{if(!efg)return null;const o={};for(const k in efg)o[k]=efg[k].t;return o;}; const rwEfgIn=o=>{const efg={};for(const k in o)efg[k]=new EgSums(o[k]);return efg;}; // In the worker: route the state it was sent, answer with R. -function rwServe(m){try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{};if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)}); - // A sales trial (offerTrial()): its answer only. +/* R.egDesc names every exit that carried traffic (about two thirds of R on a big network) and only changes with the + network. When it is yesterday's again, key for key, the worker sends 0 and the page keeps the one it has (RW.desc): + every answer is read in order, the stale ones too, so both sides always hold the same last one. */ +function rwSameDesc(a,b){if(!a||!b)return false;const ka=Object.keys(a),kb=Object.keys(b);if(ka.length!==kb.length)return false; + for(let i=0;ipostMessage({gz:m.gz,data}),e=>postMessage({gz:m.gz,err:String(e)}));return;} + if(m.sv!==undefined){rwSaveServe(m);return;} + try{S=m.S;R=emptyR();R.load=m.load||{};R.l2route=m.l2route||{}; + if(m.efg===0){if(!RW.last||RW.last.seq!==m.wseq)throw new Error('route worker: no R.efg for answer '+m.wseq);Object.defineProperty(R,'efg',{value:RW.last.efg});} + else if(m.efg)Object.defineProperty(R,'efg',{value:rwEfgIn(m.efg)}); + // A sales trial (offerTrial()) or the intern's fiber test (opsDarkTrial()): its answer only. What the worker keeps + // for the next routing (RW.last, RW.desc) stays. if(m.trial){const t=performance.now(),ok=m.trial.dark?opsDarkTrial(m.trial):!!offerTrial(m.trial.b,m.trial.hx);postMessage({seq:m.seq,ok,ms:performance.now()-t});return;} - const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);postMessage({seq:m.seq,R:o,ef:p,ms},tr);} + const t=performance.now();compute();const ms=performance.now()-t,{o,p,tr}=rwPack(R);RW.last={seq:m.seq,efg:R.efg}; + if(rwSameDesc(RW.desc,o.egDesc))o.egDesc=0;else{const d=o.egDesc;o.egDesc=rwDescOut(d,RW.desc);RW.desc=d;}postMessage({seq:m.seq,R:o,ef:p,hot:UI.hotMap,ms},tr);} catch(e){postMessage({seq:m.seq,err:String(e&&e.stack||e)});}} diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index 8e3aab0..88e4f13 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -47,28 +47,35 @@ let diversityMap=null; function diversityPossible(a,b,state=S){ if(!CITY[a]||!CITY[b]||a===b)return false; const rules=state.scn&&state.scn.rules||{},key=JSON.stringify([!!state.won,rules]); - if(!diversityMap||diversityMap.key!==key){ - /* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with - the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable - on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the - links were added, as a graph built from a list of them would. */ + if(!diversityMap||diversityMap.key!==key){if(!DIVW||DIVW.key!==key)DIVW={key,g:diversityBuild(key,rules,!!state.won)}; + for(;;){const s=DIVW.g.next();if(s.done){diversityMap=s.value;DIVW=null;break;}}} + const pair=[a,b].sort().join(':'),M=diversityMap; + return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b))); +} +/* Built once per ruleset, over every city pair, so it runs on the first load of every save: on city indices, with + the cables between each pair from a table. A link is the number of its risk: each land trench and your own cable + on its own, every segment of one cable (or one fabric) the same; adj[i] lists [neighbour, risk] in the order the + links were added, as a graph built from a list of them would. It only follows from the catalog and the key, so idle + frames build it a few rows at a time (diversityWarm()) before the first offer asks; one that asks first finishes it. */ +let DIVW=null; +function* diversityBuild(key,rules,won){ const cities=CITIES.filter(c=>!(rules.banCities||[]).includes(c.id)).map(c=>c.id),N=cities.length,ix=new Map(cities.map((c,i)=>[c,i])); const cab=new Map();for(const c of CABLE_PAIRS){const k=c.aFABS.filter(f=>f.cities.includes(c))),ban=rules.banPairs||[]; const adj=cities.map(()=>[]),grp=new Map();let n=0,k=0;const add=(i,j,g)=>{let r;if(g===undefined)r=k++;else{r=grp.get(g);if(r===undefined)grp.set(g,r=k++);}adj[i].push(j,r);adj[j].push(i,r);n++;}; - for(let i=0;ip===c.cid+':'+a+'-'+b||p===c.cid+':'+b+'-'+a))add(i,j,'cab:'+c.cid); - if(state.won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j); + if(won&&land[i]&&land[j]&&(sub||cs)&&!cn[i]&&!cn[j])add(i,j); if(fab[i].length&&fab[j].length)for(const f of FABS)if(fab[i].includes(f)&&fab[j].includes(f))add(i,j,'fab:'+f.id); - } - diversityMap={key,ix,adj,links:n,answers:{}}; - } - const pair=[a,b].sort().join(':'),M=diversityMap; - return M.answers[pair]??(M.answers[pair]=M.ix.has(a)&&M.ix.has(b)&&disjointOn(M.adj,M.ix.get(a),M.ix.get(b))); -} + }} + return {key,ix,adj,links:n,answers:{}};} +// A frame's spare time on it: at most ms, until it is built for the game's current rules. +function diversityWarm(ms){if(!S||!S.pops)return;const rules=S.scn&&S.scn.rules||{},key=JSON.stringify([!!S.won,rules]); + if(diversityMap&&diversityMap.key===key)return;if(!DIVW||DIVW.key!==key)DIVW={key,g:diversityBuild(key,rules,!!S.won)}; + const t=performance.now();for(;;){const s=DIVW.g.next();if(s.done){diversityMap=s.value;DIVW=null;return;}if(performance.now()-t>ms)return;}} // disjointRoutes() on such a graph: a shortest path by hops, then another one that shares none of its risks. function disjointOn(adj,a,b){const N=adj.length,bfs=skip=>{const prev=new Int32Array(N).fill(-1),pl=new Int32Array(N),q=[a];prev[a]=a; for(let h=0;h!linkDown(l)&&(!f||f(l)));con // design follows it at 0.9 or better). A sea route that no cable takes needs a survey, so it does not count. // Built from the map alone, so it is worked out once per city. const LATF=new Map();let LATC=null; -function latFloor(a,b){let D=LATF.get(a);if(!D){LATF.set(a,D=latFloor0(a));}return D[CIDX[b]];} -function latFloor0(a){const n=CITIES.length,D=new Float64Array(n).fill(Infinity),done=new Uint8Array(n); +function latFloor(a,b){let D=LATF.get(a);if(!D){if(LATW&&LATW.a===a){for(;;){const s=LATW.g.next();if(s.done){D=s.value;break;}}LATW=null;}else D=latFloor0(a);LATF.set(a,D);}return D[CIDX[b]];} +function latFloor0(a){const g=latFloorRun(a);for(;;){const s=g.next();if(s.done)return s.value;}} +/* Each city's floor follows from the catalog alone, and costs a few milliseconds: idle frames work them out ahead, a + few cities at a time (latWarm()), your POPs' first, then the financial centres latency customers ask about. */ +let LATW=null;const LAT_FIN=['nyc','chi','lon','fra','tok','sin','hkg','ams','ash']; +function latWarm(ms){if(!S||!S.pops)return;const t=performance.now(); + for(;;){if(!LATW){const a=Object.keys(S.pops).concat(LAT_FIN).find(c=>CITY[c]&&!LATF.has(c));if(!a)return;LATW={a,g:latFloorRun(a)};} + const s=LATW.g.next();if(s.done){if(!LATF.has(LATW.a))LATF.set(LATW.a,s.value);LATW=null;}if(performance.now()-t>ms)return;}} +function* latFloorRun(a){const n=CITIES.length,D=new Float64Array(n).fill(Infinity),done=new Uint8Array(n);let k=0; if(!LATC){LATC=new Map();for(const c of CABLE_PAIRS){const k=Math.min(CIDX[c.a],CIDX[c.b])*4096+Math.max(CIDX[c.a],CIDX[c.b]),w=c.km*Math.min(0.9,CAB[c.cid].lat||1);if(!(LATC.get(k)<=w))LATC.set(k,w);}} - D[CIDX[a]]=0;for(;;){let u=-1,ud=Infinity;for(let i=0;i13)P.st.shift();P.t0=now;} +function paceEnd(now){const P=PACE;if(!P.t0)return;P.d.push(now-P.t0);if(P.d.length>12)P.d.shift();P.t0=0;} +function diagPace(){const P=PACE;if(!S||!UI.speed)return 'days: paused';if(P.s!==S||P.sp!==UI.speed||P.st.length<3)return `days: x${UI.speed} asked · measuring`; + const gap=(P.st[P.st.length-1]-P.st[0])/(P.st.length-1),d=P.d.length?P.d.reduce((a,x)=>a+x,0)/P.d.length:0; + return `days: x${UI.speed} asked · x${(DAY_MS/gap).toFixed(1)} held (one every ${Math.round(gap)} ms)`+(d?` · a day takes ${Math.round(d)} ms, slowest ${Math.round(Math.max(...P.d))}`:'');} diff --git a/src/game/91-save.js b/src/game/91-save.js index faea37c..f407d76 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -14,28 +14,39 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot; UI.lastSave=performance.now(); // Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do. if(st!==S&&!failed&&(SLOT.top[id]||0)>0)return; + /* A big network that moved on since its last save cannot be the same text: the route worker packs it, turns it into + text and compresses it (rwSave()); the page only copies the game over and writes what comes back. */ + if(!force&&!failed&&st===S&&SLOT.day[id]!==undefined&&SLOT.day[id]!==st.day&&((SLOT.txt[id]||'').length>=GZ_BG||SLOT.big[id])&&gzOk()){ + const seq=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,p=rwSave(st,seq); + if(p){SLOT.top[id]=seq;let tier=null;try{tier=tierLabel();}catch(e){}gzSave({id,s:st,txt:null,seq,day:st.day,meta:slotMeta(st,tier),p});return;}} const txt=JSON.stringify(packSave(st)); + // The very text the slot already holds (a paused game, nothing changed): writing a big network to storage costs more + // than turning it into text, every 5 seconds, for nothing. Unless a write is still on its way, or the page is closing. + if(!force&&!failed&&SLOT.txt[id]===txt&&(SLOT.top[id]||0)===(SLOT.sq[id]||0))return; let tier=null;if(st===S)try{tier=tierLabel();}catch(e){} - const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,meta:slotMeta(st,tier)}; - if(txt.length>=GZ_MIN&&gzOk())gzSave(j);else slotPut(j,slotStamp(txt,seq));} + const seq=SLOT.top[id]=Math.max(SLOT.top[id]||0,SLOT.sq[id]||0)+1,j={id,s:st,txt,seq,day:st.day,meta:slotMeta(st,tier)}; + if(gzOk()&&(txt.length>=GZ_MIN||!force&&txt.length>=GZ_BG&&rwOn()))gzSave(j);else slotPut(j,slotStamp(txt,seq));} function saveErr(e,s){const f=UI.saveFail,again=f&&f.s===s;UI.saveFail={s,at:performance.now(),wait:again?Math.min(300000,f.wait*2):60000,full:saveFull(e)}; // Say so once per game (#176): a save that silently fails loses everything since the last one that worked. if(!again&&(s===S||s===UI.pzKeep))toast(saveFailMsg(),'bad',[{l:tr('common.export_save'),act:'exportSave',args:{}},...(UI.saveFail.full&&slotOthers().length?[{l:tr('slots.free_up_space'),act:'slotSpace',args:{}}]:[])]);} /* Saves of huge networks are gzipped by the browser (#176): about ten times smaller, so they fit in its storage. Compressing runs in the background, one at a time, and the newest save of each network wins; one that a newer save - of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. */ -const GZ='gz:',GZ_MIN=1e6,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function'; + of the same network has overtaken meanwhile is dropped. Small saves stay plain JSON, written at once, as before. + From GZ_BG up, the autosave is compressed too when the route worker does it: writing that much plain text held the + page longer than everything else in a save (a save as the page closes stays plain below GZ_MIN: at once). */ +const GZ='gz:',GZ_MIN=1e6,GZ_BG=2e5,gzOk=()=>typeof CompressionStream==='function'&&typeof DecompressionStream==='function'; async function gzPipe(bytes,stream){const w=stream.writable.getWriter(),no=()=>{};w.write(bytes).catch(no);w.close().catch(no);// a bad stream is reported by read() below const r=stream.readable.getReader(),parts=[];let n=0; for(;;){const {done,value}=await r.read();if(done)break;parts.push(value);n+=value.length;} const out=new Uint8Array(n);let o=0;for(const p of parts){out.set(p,o);o+=p.length;}return out;} const b64=u=>{let s='';for(let i=0;i{const s=atob(t),u=new Uint8Array(s.length);for(let i=0;iGZ+b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip'))); +const gzB64=async txt=>b64(await gzPipe(new TextEncoder().encode(txt),new CompressionStream('gzip'))); +const gzip=async txt=>GZ+await (rwGzip(txt)||gzB64(txt)); const gunzip=async raw=>new TextDecoder().decode(await gzPipe(unb64(raw.slice(GZ.length)),new DecompressionStream('gzip'))); // Jobs carry their slot, not the game object: a save still compressing lands in its own network whatever S is by then. function gzSave(j){if(UI.gzBusy){SLOT.gzQ.set(j.id,j);return;}UI.gzBusy=true; - gzip(slotStamp(j.txt,j.seq)).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);}) + (j.p?j.p.then(r=>{j.txt=r.txt;return r.data;}):gzip(slotStamp(j.txt,j.seq))).then(v=>{if(j.seq===SLOT.top[j.id])slotPut(j,v);}) .catch(e=>{console.error('[tubes] compressing the save failed',e);}) .finally(()=>{UI.gzBusy=false;const n=SLOT.gzQ.values().next().value;if(n){SLOT.gzQ.delete(n.id);gzSave(n);}else slotIdle();});} /* Big networks are mostly customers, and most of a customer record was defaults (#176): no second city, no diff --git a/src/game/91-slots.js b/src/game/91-slots.js index c647112..b94d4d4 100644 --- a/src/game/91-slots.js +++ b/src/game/91-slots.js @@ -6,7 +6,8 @@ writes over a newer one that another window saved. Each tab keeps its slot in sessionStorage: a reload continues it. Only one window plays a slot at a time: a Web Lock where the browser has them, else a heartbeat key, sot-open:. */ const SLOT_K='sot-save-v1:',SLOT_IX='sot-slots',SLOT_OLD='sot-save-v1',SLOT_HB='sot-open:',SLOT_SS='sot-slot',SLOT_MAIN='main'; -const SLOT={sq:{},top:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''}; +// txt: the text of each slot's last save that landed, before its stamp. +const SLOT={sq:{},top:{},txt:{},day:{},big:{},rel:new Set(),no:new Set(),locks:new Map(),gzQ:new Map(),idle:[],wait:null,html:''}; function slotRid(){try{const a=new Uint32Array(2);crypto.getRandomValues(a);return (a[0].toString(36)+a[1].toString(36)).slice(0,10);}catch(e){return (Date.now().toString(36)+(uidN++).toString(36)).slice(-10);}} const WIN=slotRid();// this page load; a reload is a new window that takes its tab's slot back const lsGet=k=>{try{return localStorage.getItem(k);}catch(e){return null;}}; @@ -87,12 +88,14 @@ function slotWrite(j,data){const id=j.id;if(SLOT.no.has(id))return false; catch(e){// A migrated save the browser has no room to copy keeps living in the old key, as it always did. if(id!==SLOT_MAIN||lsGet(SLOT_OLD)==null)throw e;localStorage.setItem(SLOT_OLD,data);lsDel(k);k=SLOT_OLD;} if(id===SLOT_MAIN&&k!==SLOT_OLD)lsDel(SLOT_OLD);// the new key has a newer save now: the old one is no longer needed - SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq); + SLOT.sq[id]=Math.max(SLOT.sq[id]||0,j.seq);SLOT.txt[id]=j.txt;SLOT.day[id]=j.day; const e=ent||{id};if(!ent)list.push(e);Object.assign(e,slotClean({...e,...j.meta,tier:j.meta.tier||e.tier,seq:j.seq,at:Date.now(),size:data.length,gz:data.startsWith(GZ),broken:false})); slotIdxPut(list);return true;} function slotPut(j,data){try{if(slotWrite(j,data))UI.saveFail=null;}catch(e){saveErr(e,j.s);}} // ---------- opening, leaving, losing ---------- -function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0; +function slotIn(id,sv){const e=slotIdx().find(x=>x.id===id);UI.slot=id;ssSet(SLOT_SS,id);SLOT.no.delete(id);SLOT.top[id]=0;delete SLOT.txt[id]; + // The day the slot holds, and whether it is big (compressed, or long): the first save that moves on goes to the worker. + {const raw=slotRaw(id);SLOT.day[id]=S?S.day:undefined;SLOT.big[id]=!!raw&&(raw.startsWith(GZ)||raw.length>=GZ_BG);} SLOT.sq[id]=Math.max(sv&&isFinite(sv.seq)?+sv.seq:0,e?e.seq:0);} function slotNew(){const id=slotRid();UI.slot=id;ssSet(SLOT_SS,id);SLOT.sq[id]=0;SLOT.no.delete(id);slotClaim(id,true,()=>{});return id;} // Leave this window's network (saved first); the slot is free for other windows once its last save has landed. diff --git a/src/game/96-map/97-diagnostics.js b/src/game/96-map/97-diagnostics.js index 7098b72..5adf20f 100644 --- a/src/game/96-map/97-diagnostics.js +++ b/src/game/96-map/97-diagnostics.js @@ -1,6 +1,6 @@ /* Settings › Diagnostic info: one readout in a corner, for bug reports. What the screen tells the game (for phone layouts), how the map is drawn (the graphics card or 2D, and why), and how fast: frames per second, the slowest - frames, the time draw() takes. It is also opened with ?vp or ?fps in the address (?novp, ?nofps close it), and, + frames, the time draw() takes, and the pace of days (asked and held). It is also opened with ?vp or ?fps in the address (?novp, ?nofps close it), and, inside an installed app where there is no address bar, with five quick taps on the date. Its words are technical on purpose and stay in English: they are pasted into bug reports. */ const DIAG={on:false,el:null,t:null,fr:[],dr:[],last:0,dms:-1}; @@ -27,7 +27,7 @@ function diagShow(){const D=DIAG;let el=D.el; `inner ${innerWidth}×${innerHeight} · screen ${screen.width}×${screen.height} · dpr ${window.devicePixelRatio||1}\n`+ `vv ${vv?Math.round(vv.width)+'×'+Math.round(vv.height)+' top '+Math.round(vv.offsetTop):'-'} · client ${de.clientHeight}\nsafe top ${cs.paddingTop} bottom ${cs.paddingBottom}\n`+ `standalone ${sa} · iosfix ${de.classList.contains('iosfix')} · CH ${CH}\nbody ${Math.round(document.body.getBoundingClientRect().height)} · tabbar ${Math.round(tb.top)}–${Math.round(tb.bottom)}\n`+ - diagMap()+'\n'+diagPerf();} + diagMap()+'\n'+diagPerf()+'\n'+diagPace();} // Shows or hides the readout, and remembers it on this device. function diagOn(on){const D=DIAG;clearInterval(D.t);D.t=null;if(D.el){D.el.remove();D.el=null;}D.on=!!on;D.fr.length=D.dr.length=0;D.last=0;D.dms=-1; if(on){D.t=setInterval(diagShow,500);diagShow();} diff --git a/src/game/99-loop.js b/src/game/99-loop.js index af978d3..03f7aaa 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -17,8 +17,11 @@ function frame(now){ if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt); if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ const t=animOn()?animT:0; - if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){const d0=DIAG.on?performance.now():0;try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;if(DIAG.on)DIAG.dms=performance.now()-d0;} + if(!(UI.mapHid=mapHidden())){const st=mapStill(t,now);if(st!==MAP_STILL&&!(st===MAP_AMBIENT&&now-(UI.drawnAt||0)=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}} + if(rwOn()){if(!RW.w)rwStart();if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);paceStart(performance.now());try{rwDay();}catch(e){tickErr(e);}}} else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;} if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}} /* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map @@ -37,12 +40,17 @@ function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c const r=c.getBoundingClientRect();if(r.top<=1&&r.left<=1&&r.right>=innerWidth-1&&r.bottom>=innerHeight-1)return true;}return false;} /* Paused, or with animations off, the map only changes when you move it, point at something or the network changes. Until then the last frame is still right, so it is not drawn again (phones keep cool). It is redrawn at least once - a second anyway, and every frame while the land picture is still catching up with a zoom (the WebGL map has none). */ -const FRAME=[]; + a second anyway, and every frame while the land picture is still catching up with a zoom (the WebGL map has none). + Playing, when only the animation clock moved (packets, waves, clouds, money floating up), the map is ambient: drawn + at most 30 times a second, not at the screen's 60 or 120. The animations follow the clock, so they keep their speed + and only lose frames nobody follows that closely; anything else that moves (the camera, a pointer, the network, a + selection) gets every frame again at once. */ +const FRAME=[],MAP_MOVING=0,MAP_AMBIENT=1,MAP_STILL=2,AMB_MS=29; function mapStill(t,now){const sl=UI.sel,dr=UI.drag; const v=[t,cam.x,cam.y,cam.z,CW,CH,DPR,S,R,S&&S.day,S&&S.links.length,S&&S.offers.length,S&&S.inc.length,sl&&sl.type,sl&&sl.id,UI.hover,UI.snap&&UI.snap.id,dr&&dr.mode,dr&&dr.cx,dr&&dr.cy,FLOATS.length,UI.mk?UI.mk.tx:0,UI.mk?UI.mk.mood:0,zoomMoving()]; - let same=v.length===FRAME.length;for(let i=0;i { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=8;"); + assert.equal(ev('diagPace()'), 'days: x8 asked · measuring'); + // A day every 400 ms (x8 asks one every 312.5), each taking 300 ms, one of them 700. + ev('for(let i=0;i<14;i++){const t=1000+i*400;paceStart(t);paceEnd(t+(i===10?700:300));}'); + assert.equal(ev('diagPace()'), 'days: x8 asked · x6.3 held (one every 400 ms) · a day takes 333 ms, slowest 700'); + // Another speed: the measure starts again. + ev('UI.speed=4;'); + assert.equal(ev('diagPace()'), 'days: x4 asked · measuring'); + ev('paceStart(9000);paceStart(9625);paceStart(10250);'); + assert.match(ev('diagPace()'), /^days: x4 asked · x4\.0 held \(one every 625 ms\)/); + ev('UI.speed=0;'); + assert.equal(ev('diagPace()'), 'days: paused'); + assert.deepEqual(errors, []); +}); + +test('the clock with the worker feeds the measure and starts days as it always did', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();autoPause=()=>false;UI.speed=8;"); + // A stand-in worker day that ends at once: one day per 312.5 ms of clock, as before. + ev(`window.__n=0;rwOn=()=>true;RW.w={postMessage(){},terminate(){}};rwDay=()=>{__n++;S.day++;rwDayDone();}; + for(let i=0;i<600;i++)runClock(1000/60);`); + assert.equal(ev('__n'), Math.floor(600 * 1000 / 60 / 312.5), 'one day per 312.5 ms of clock'); + assert.equal(ev('PACE.st.length'), 13, 'the last days are measured'); + assert.match(ev('diagPace()'), /^days: x8 asked · x\d+\.\d held/); + assert.deepEqual(errors, []); +}); diff --git a/tests/day-steps.test.js b/tests/day-steps.test.js index b9dba8f..4981c1a 100644 --- a/tests/day-steps.test.js +++ b/tests/day-steps.test.js @@ -1,7 +1,8 @@ // The day as steps (dayRun() in src/game/88-days/10-day-tick.js): every routing a day needs, its own and the // recomputes after a failure or the intern's jobs, is a yield the route worker answers in play. jsdom has no Worker, so // a second page plays it: rwServe() there, messages cloned both ways the way postMessage clones them. A day played that -// way must be the day dayTick() plays, move for move, with a frame let through in the middle of each day. +// way must be the day dayTick() plays, move for move, R.egDesc left out of the answers that repeat it and R.efg out of +// the posts that would only send the worker its own, and a frame let through in the middle of each day. const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -9,11 +10,12 @@ const path = require('node:path'); const { load } = require('./harness'); const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); -// The big network with an intern running every order, a failure and an event due soon, and its circuits on scenic -// routes, which read yesterday's R.efg. Ids come from Date.now(), +// The big network with an intern running every order, a failure and an event due soon, its circuits on scenic +// routes, which read yesterday's R.efg, and renewal haggles the sales desk answers (slRenRun() routes after them). Ids come from Date.now(), // so the clock stands still in every page. const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false; - S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true; + S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;S.slAuto.ren=true;window.__ren=0;{const f=slRenOne;slRenOne=function(){__ren++;return f.apply(this,arguments);};} + for(const b of S.biz.filter(b=>clOn(b)&&!BIZ_T[b.type].fiber).slice(0,20)){b.te=S.day+28;b.hag={rate:Math.round(b.rate*0.7),until:S.day+28};} S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0; S.nextFail=S.day+3;S.nextEvent=S.day+5;for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';compute();__reseed(4242);`; const open = (t, seed) => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; }; @@ -25,18 +27,22 @@ function played(t) { page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});'); wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};'); // Answers what is waiting, one message at a time; returns how many routings it served. - let rests = 0, trials = 0; + // kept: answers that left R.egDesc out, the page keeping the one it has; lean: posts that left R.efg out, the worker + // keeping its own. + let kept = 0, lean = 0, rests = 0, delta = 0, trials = 0; const pump = () => { let n = 0; for (;;) { if (page.ev('__later.length')) { rests++; page.ev('__later.shift()()'); continue; } if (!page.ev('__q.length')) break; + if (page.ev('__q[0].efg===0')) lean++; if (page.ev('!!__q[0].trial')) trials++; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); - page.ev('rwDone(__a)'); n++; } return n; }; + if (wk.ev('!!__out.R&&__out.R.egDesc===0')) kept++; + if (wk.ev('!!(__out.R&&__out.R.egDesc&&__out.R.egDesc.dK!==undefined)')) delta++; page.ev('rwMsg(__a)'); n++; } return n; }; // One message to the worker and its answer back (the trial test steps through a day with it). - const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); }; - return { ...page, pump, pump1, rests: () => rests, trials: () => trials }; + const pump1 = () => { if (!page.ev('__q.length')) return; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); }; + return { ...page, pump, pump1, kept: () => kept, lean: () => lean, rests: () => rests, delta: () => delta, trials: () => trials }; } -// R.egDesc too, key for key and in order. +// R.egDesc too, key for key and in order: the worker sends only what changed in it. const STATE = "JSON.stringify({S,R:{served:R.served,demand:R.demand,rev:R.revMo,cost:R.costMo,load:R.load,useT:R.useT,usePni:R.usePni,egDesc:R.egDesc}})"; // Equal states, or which of their fields differ. const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = JSON.parse(b), d = []; @@ -46,8 +52,8 @@ const same = (a, b, msg) => { if (a === b) return; const A = JSON.parse(a), B = test('a day whose routings the worker answers is the day dayTick() plays', (t) => { const ref = open(t, 777), p = played(t); ref.ev(SETUP); - // The page itself never routes, the failure on day 3 (failureRun()) and the sales desk's trials (offerTrial()) - // included: they are steps like the others, routed by the worker. + // The page itself never routes, the failure on day 3 (failureRun()), the sales desk's trials (offerTrial()) and its + // renewal answers included: they are steps like the others, routed by the worker. p.ev('window.__pc=0;window.__tr=0;const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};'); let served = 0, extra = 0; for (let i = 0; i < 12; i++) { @@ -63,7 +69,11 @@ test('a day whose routings the worker answers is the day dayTick() plays', (t) = assert.ok(ref.ev('S.inc.length') > 0 || ref.ev('S.stats.incidents') > 0, 'a failure happened'); assert.equal(p.ev('__pc'), 0, 'no routing on the page'); assert.ok(p.trials() > 0, `sales trials the worker ran: ${p.trials()}`); + assert.ok(p.ev('__ren') > 0 && p.ev('__ren') === ref.ev('__ren'), `renewal haggles the desk answered: ${p.ev('__ren')}`); assert.ok(p.ev('S.ops.log.some(e=>e.r.some(([k])=>k==="caches"))'), 'the intern racked cache boxes'); + assert.ok(p.kept() > 0 && p.kept() < served, `answers without R.egDesc: ${p.kept()} of ${served}`); + assert.ok(p.delta() > 0, `answers with only what changed in R.egDesc: ${p.delta()}`); + assert.ok(p.lean() > 0 && p.lean() < served, `posts without R.efg: ${p.lean()} of ${served}`); // A frame through before the intern's shift, after each of the orders on duty (decommissioning aside), and after // each job of an order (a generator's yields). const orders = p.ev('OPS_ORDER.slice(0,-1).filter(k=>S.ops.on[k]).length'); diff --git a/tests/frame-pacing.test.js b/tests/frame-pacing.test.js index e495306..4bfd402 100644 --- a/tests/frame-pacing.test.js +++ b/tests/frame-pacing.test.js @@ -1,8 +1,33 @@ -// How long a day may run on the page between two frames (src/game/99-loop.js, rwGo()): half a frame, from 3 to 8 ms. +// The map's frame pacing (src/game/99-loop.js, mapStill()): while only the animation clock moves, the map is drawn at +// most 30 times a second; anything else that moves gets every frame; paused, it is drawn about once a second. const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); +// A second of frames at 60 Hz (each() runs before every frame), and how many of them drew the map. +const second = (ev, each = '') => ev(`(()=>{let n=0;const d=draw;draw=t=>{n++;return d(t);}; + try{for(let i=0;i<60;i++){window.__now=(window.__now||1000)+1000/60;${each};frame(__now);}}finally{draw=d;}return n;})()`); + +test('ambient frames are drawn at most 30 times a second, the camera moving gets them all, paused about one', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;ACT.launchBB({city:'fra'});closeModal();UI.anim='on';UI.speed=1;autoPause=()=>false;"); + second(ev); // the land picture and the first frames settle + const ambient = second(ev); + assert.ok(ambient >= 28 && ambient <= 31, `ambient: ${ambient} draws`); + assert.equal(second(ev, 'cam.x+=0.5'), 60, 'the camera moving'); + assert.equal(second(ev, "UI.hover=UI.hover==='fra'?null:'fra'"), 60, 'the pointer over a city and off it'); + ev('UI.speed=0'); + second(ev); + const paused = second(ev); + assert.ok(paused <= 2, `paused: ${paused} draws`); + ev("UI.anim='off';UI.speed=1"); + second(ev); + assert.ok(second(ev) <= 2, 'animations off: nothing moves, nothing to draw'); + assert.deepEqual(errors, []); +}); + +// A day's steps on the page take half a frame at most before letting one through (RW.budget, rwGo()): 8 ms on a 60 Hz +// screen, 3 ms on a 240 Hz one. One long frame (a big save, a tab switch) does not move it much. test("a day's steps follow the screen: half a frame between two, from 3 to 8 ms", () => { const { ev, errors } = load(); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;"); @@ -29,3 +54,41 @@ test("a device that cannot hold 50 frames a second gives a day half its frame, 3 }); // The diverse-paths map new offers ask about (60-requirements.js) is built a millisecond a frame, before the first one +// asks: the very map one go would build. One that asks halfway finishes it at once. +test('idle frames build the diverse-paths map in slices, the same map as in one go', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;"); + const sig = "JSON.stringify([diversityMap.key,diversityMap.links,diversityMap.adj])"; + ev('diversityMap=null;DIVW=null;diversityPossible("fra","ams");'); + const once = ev(sig); + ev('diversityMap=null;DIVW=null;'); + let frames = 0; + for (; frames < 2000 && ev('!diversityMap'); frames++) ev('window.__now=(window.__now||1000)+4;diversityWarm(0.05);'); + assert.ok(frames > 3, `built over several frames: ${frames}`); + assert.equal(ev(sig), once, 'the same map'); + // Halfway, an offer asks: the rest is built at once, and it is still the same map. + ev('diversityMap=null;DIVW=null;diversityWarm(0.05);'); + assert.equal(ev('!diversityMap&&!!DIVW'), true, 'half built'); + assert.equal(ev('typeof diversityPossible("fra","ams")'), 'boolean'); + assert.equal(ev(sig), once, 'finished at once, the same map'); + assert.deepEqual(errors, []); +}); + +// The latency floors latency customers are offered against (80-geography-and-latency.js) are worked out ahead too, a +// few cities a frame, your POPs first: the same numbers as working one out when asked, even halfway through one. +test('idle frames work the latency floors out ahead, the same numbers as when asked', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();closeModal();UI.speed=0;ACT.buildPop({city:'ams'});"); + const ref = ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(latFloor0(c))))"); + ev('LATF.clear();LATW=null;'); + let n = 0; + for (; n < 5000 && !(ev("LATF.has('fra')&&LATF.has('ams')&&LATF.has('nyc')")); n++) ev('latWarm(0.05)'); + assert.ok(n > 3, `over several frames: ${n}`); + assert.equal(ev("JSON.stringify(['fra','ams','nyc'].map(c=>Array.from(LATF.get(c))))"), ref, 'the same floors'); + // Halfway through a city, an offer asks about it: finished at once, the same numbers. + ev("LATF.clear();LATW=null;latWarm(0.01);"); + const a = ev('LATW&&LATW.a'); + assert.ok(a, 'a city half done'); + assert.equal(ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor('${a}',b)))`), ev(`JSON.stringify(['nyc','lon'].map(b=>latFloor0('${a}')[CIDX[b]]))`)); + assert.deepEqual(errors, []); +}); diff --git a/tests/intern-dark-fiber-worker.test.js b/tests/intern-dark-fiber-worker.test.js new file mode 100644 index 0000000..2c4729f --- /dev/null +++ b/tests/intern-dark-fiber-worker.test.js @@ -0,0 +1,64 @@ +// The intern's line system swap asks first whether a day without the fiber still serves everything (opsDark(), +// 95-standing-orders.js). That test routes the whole network: in play the route worker answers it, like a sales trial, +// so the shift never routes on the page. jsdom has no Worker: a second page plays it (rwServe()), messages cloned both +// ways. The shift played that way is the shift opsDay() plays; an action while the worker routes makes the page test again. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// tests/intern-optical-upgrade.test.js's network: a full, hot fiber Frankfurt–Amsterdam and the long way round through +// Paris on two waves, big enough (tier 4) to carry the day without the fiber, or not (tier 0). +const base = tier => "Date.now=()=>1.7e12;ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=6;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + + "for(const c of ['ams','par'])ACT.buildPop({city:c});for(const c of ['fra','ams','par']){S.pops[c].rgen=mainRG(3);S.pops[c].routers=2;}ACT.launchBB({city:'ams'});" + + "S.transit=[];ACT.buyTransit({city:'fra',net:'cog',tier:2});" + + "S.links=[{id:'f',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(16).fill('zr4'),km:450,trench:'t1',ready:0,cut:0,mo:1,pairs:1}," + + `{id:'w1',a:'fra',b:'par',kind:'wave',tier:${tier},km:480,cut:0,mo:1},{id:'w2',a:'par',b:'ams',kind:'wave',tier:${tier},km:430,cut:0,mo:1}];compute();` + + "ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap.optup=0;closeModal();S.ops.on.optup=true;S.ops.p.optup={at:80};R.load.f=dfCap(S.links[0])*0.9"; +const open = (t) => { const h = load(); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; }; +// The page with a stand-in worker (tests/day-steps.test.js): what it posts waits until pump() hands it to the other page. +function played(t, tier) { + const page = open(t), wk = open(t); + page.ev(base(tier)); + page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});'); + page.ev('window.__pc=0;{const c0=compute;compute=function(){__pc++;return c0.apply(this,arguments);};}'); + wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};'); + let dark = 0; + const one = () => { if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) dark++; wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwMsg(__a)'); }; + const pump = () => { for (;;) { if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; } if (!page.ev('__q.length')) break; one(); } }; + return { ...page, pump, one, dark: () => dark }; +} +const STATE = "JSON.stringify({links:S.links,cash:S.cash,log:S.ops.log,spent:S.ops.spent,no:OPTUP_NO.get('f')??null,served:R.served})"; + +for (const [tier, sys] of [[4, 'roadm'], [0, 'lite']]) { + test(`the dark fiber test goes to the worker and plays as on the page (waves of tier ${tier}: ${sys})`, (t) => { + const ref = open(t), p = played(t, tier); + ref.ev(base(tier)); + ref.ev('opsDay(S.day)'); + p.ev('rwGo(opsRun(S.day))'); + assert.equal(p.ev('!!(__q.length||__later.length)'), true, 'the shift waits for the worker'); + p.pump(); + assert.equal(p.ev('!!RW.job'), false, 'the shift is over'); + assert.equal(p.ev(STATE), ref.ev(STATE)); + assert.equal(p.ev('S.links[0].sys'), sys); + assert.equal(p.dark(), 1, 'the worker tested the fiber dark'); + assert.equal(p.ev('__pc'), 0, 'no routing on the page'); + assert.equal(p.ev("S.links[0].eqDown===undefined||S.links[0].eqDown>S.day"), true); + assert.deepEqual([...ref.errors, ...p.errors], []); + }); +} + +test('an action while the worker tests the fiber: the page tests it again on the game as it is', (t) => { + const ref = open(t), p = played(t, 4); + ref.ev(base(4)); + ref.ev('opsDay(S.day)'); + p.ev('rwGo(opsRun(S.day))'); + // Up to the dark fiber's trial, then an action (it routes on the page, as always), then the worker's stale answer. + for (let i = 0; i < 50 && !p.ev('!!(__q[0]&&__q[0].trial&&__q[0].trial.dark)'); i++) { if (p.ev('__later.length')) p.ev('__later.shift()()'); else if (p.ev('__q.length')) p.one(); else break; } + assert.equal(p.ev('!!(__q[0].trial&&__q[0].trial.dark)'), true, 'the trial is in flight'); + p.ev('__pc=0;after()'); + p.pump(); + assert.equal(p.ev('__pc'), 2, "the action's routing, and the test made again here"); + assert.equal(p.ev(STATE), ref.ev(STATE)); + assert.equal(p.ev('S.links[0].sys'), 'roadm'); + assert.deepEqual([...ref.errors, ...p.errors], []); +}); diff --git a/tests/persist.test.js b/tests/persist.test.js index 08ebb69..6034f40 100644 --- a/tests/persist.test.js +++ b/tests/persist.test.js @@ -47,9 +47,11 @@ test('a save too big for the browser is not retried every few seconds, but leavi assert.equal(a.ev('__tries'), 3, 'tried again once the wait is over'); assert.equal(JSON.parse(a.ev("slotRaw(UI.slot)")).day, a.ev('S.day')); assert.equal(a.ev('UI.saveFail'), null); - a.ev('save()'); - assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time'); - a.ev('__full=true;save();S=migrate(JSON.parse(JSON.stringify(S)));save()'); + a.ev('S.cash++;save()'); + assert.equal(a.ev('__tries'), 4, 'a save that works keeps saving every time the network changes'); + a.ev('save();save()'); + assert.equal(a.ev('__tries'), 4, 'and writes nothing while nothing changes'); + a.ev('__full=true;S.cash++;save();S=migrate(JSON.parse(JSON.stringify(S)));S.cash++;save()'); assert.equal(a.ev('__tries'), 6, 'another game (a new state) tries at once'); }); diff --git a/tests/route-worker.test.js b/tests/route-worker.test.js index 116206a..28aeda1 100644 --- a/tests/route-worker.test.js +++ b/tests/route-worker.test.js @@ -15,11 +15,17 @@ const big = (t) => { const h = load({ seed: 777 }); t.after(() => h.dom.window.c // R with its lazy parts (R.ef, R.fl) read out, attacks by id. const SIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()"; +// R.efg, which the next day's routing reads: every link's sums, Map order included (they cross as typed arrays). +const EFG = "JSON.stringify(Object.entries(R.efg).map(([k,e])=>[k,[...e.t.g],e.t.v,e.t.n,e.t.d]))"; + test('R packed, cloned and unpacked is the same R, lazy parts and key order included', (t) => { const { ev, errors } = big(t); - const want = ev(SIG); + const want = ev(SIG), efg = ev(EFG); ev("{const {o,p,tr}=rwPack(R);const c=structuredClone({o,p},{transfer:tr});R=rwUnpack(c.o,c.p);UI.hotMap=hotByCity();}"); + assert.equal(ev(EFG), efg); assert.equal(ev(SIG), want); + // Sent back to the worker after an action, a link's sums still clone whole. + assert.equal(ev("JSON.stringify(Object.entries(structuredClone(rwEfgOut(R.efg))).map(([k,t])=>[k,[...t.g],t.v,t.n,t.d]))"), efg); assert.equal(ev('pniFlows(Object.keys(S.pops)[0])!==null'), true, 'the PNI list reads the unpacked flows'); assert.deepEqual(errors, []); }); @@ -30,10 +36,13 @@ test('the worker side routes what it is sent: same R as routing on the page', (t ev("window.__got=null;window.postMessage=(m)=>{window.__got=m;};"); ev("{window.__R0=R;const prev={load:R.load,l2route:R.l2route,efg:rwEfgOut(R.efg)};const keep=S;window.__S0=JSON.stringify(S);rwServe(structuredClone({seq:1,S,...prev}));S=keep;}"); ev("R=rwUnpack(structuredClone(__got.R),__got.ef)"); - const fromWorker = ev(SIG); + const fromWorker = ev(SIG), hot = ev('JSON.stringify(structuredClone(__got.hot))'); ev('R=__R0;S=JSON.parse(__S0);compute()'); assert.equal(ev('JSON.stringify(S)'), ev('__S0'), 'routing does not change S'); assert.equal(ev(SIG), fromWorker); + // The full ports it found come along (the page no longer works them out again), key order included. + assert.equal(hot, ev('JSON.stringify(UI.hotMap)')); + assert.ok(Object.keys(JSON.parse(hot)).length > 5, 'some ports are full on the big network'); assert.deepEqual(errors, []); }); diff --git a/tests/save-size.test.js b/tests/save-size.test.js index e3b0ffa..97af225 100644 --- a/tests/save-size.test.js +++ b/tests/save-size.test.js @@ -11,7 +11,7 @@ const refuse = name => `window.__err=${lit(name)};{const P=Object.getPrototypeOf test('#176 a save that does not fit tells the player once, with Export, and the menu says so', () => { const { ev, dom, errors } = load(); ev("ACT.start({});UI.saveFail=null;" + refuse('QuotaExceededError')); - ev('save()'); + ev('S.cash++;save()'); const toasts = () => [...dom.window.document.querySelectorAll('.toast')].filter(t => /not being saved/.test(t.textContent)); assert.equal(toasts().length, 1, 'one warning'); assert.match(toasts()[0].textContent, /too big for this browser/); @@ -31,7 +31,8 @@ test('#176 a save that does not fit tells the player once, with Export, and the test('#176 storage that is blocked altogether gets its own advice', () => { const { ev, dom, errors } = load(); - ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';save()'); + // The game moves on first: a save of the very text the slot already holds writes nothing. + ev("ACT.start({});UI.saveFail=null;" + refuse('SecurityError') + ';S.cash+=1;save()'); assert.match(dom.window.document.body.textContent, /private window/); assert.deepEqual(errors, []); }); @@ -126,3 +127,95 @@ test('#176 a damaged compressed save is kept, marked damaged, and the player is assert.equal(ev('!!UI.started'), false); assert.deepEqual(errors, []); }); + +// A big network's autosave is compressed in the route worker (rwGzip()), not on the page: deflating it there held the +// page about as long as writing it plain. jsdom has no Worker: a second page answers as the worker, messages cloned +// both ways. A save as the page closes stays plain, and a worker lost mid-job leaves its job to the page. +test('a big autosave is compressed in the route worker and loads back; a closing save stays plain', async () => { + const a = load({ gzip: true }), w = load({ gzip: true }); + for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone; + a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()"); + const len = a.ev('JSON.stringify(packSave(S)).length'); + assert.ok(len >= a.ev('GZ_BG') && len < a.ev('GZ_MIN'), `between the two thresholds: ${len}`); + a.ev("window.__q=[];window.__pz=0;const gp=gzPipe;gzPipe=(...x)=>{__pz++;return gp(...x);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});"); + w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};'); + const pump = async () => { for (let k = 0; k < 200; k++) { + while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); } + while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); } + if (a.ev("(slotRaw(UI.slot)||'').startsWith(GZ)&&!UI.gzBusy")) return; await new Promise((r) => setTimeout(r, 5)); } }; + // Closing: plain text, at once. + a.ev('save(true)'); + assert.equal(a.ev('slotRaw(UI.slot)[0]'), '{', 'a save as the page closes is written plain'); + // The autosave: compressed by the worker. + a.ev("S.name='Worker Zip';save()"); + assert.equal(a.ev('__q.length'), 1, 'the text went to the worker'); + await pump(); + assert.ok(a.ev("slotRaw(UI.slot).startsWith(GZ)"), 'stored compressed'); + assert.equal(a.ev('__pz'), 0, 'nothing was deflated on the page'); + a.ev("gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length].join('|');})"); + await settle(a.ev, '!!window.__t'); + assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length].join('|')")); + // The worker lost while it compresses: the page compresses that save itself. + a.ev("__pz=0;S.name='Page Zip';save();rwKill()"); + await settle(a.ev, "!UI.gzBusy&&__pz>0", 'compressed on the page'); + a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>window.__t=JSON.parse(t).name)"); + await settle(a.ev, '!!window.__t'); + assert.equal(a.ev('__t'), 'Page Zip'); + assert.deepEqual(a.errors, []); + assert.deepEqual(w.errors, []); +}); + +// A big network that moved on since its last save is packed, turned into text and compressed by the route worker +// (rwSave()): the page copies the game over and writes what comes back. A paused game (same day) is still compared on +// the page, so an unchanged one is not written again. The worker lost mid-save: the next frame saves again, here. +test('a big game that moved on is saved by the route worker, a paused one is still compared on the page', async () => { + const a = load({ gzip: true }), w = load({ gzip: true }); + for (const h of [a, w]) h.dom.window.structuredClone = globalThis.structuredClone; + a.ev(bigBiz + ";for(let i=0;i<2500;i++){const slots=1+i%4;S.biz.push({id:'m'+i,city:'fra',city2:'ams',name:'Mid Carrier '+i,type:'wwave',bw:1,rate:4000+i,mood:100,since:i,link:'df1',slots,what:wwWhat(S.links.find(l=>l.id==='df1'),slots)});}compute()"); + a.ev("window.__q=[];window.__pk=0;const pk=packBiz;packBiz=b=>{__pk++;return pk(b);};rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});"); + w.ev('window.__out=[];window.postMessage=(m)=>{__out.push(structuredClone(m));};'); + const pump = async (cond) => { for (let k = 0; k < 300; k++) { + while (a.ev('__q.length')) { w.dom.window.__m = a.ev('__q.shift()'); w.ev('rwServe(__m)'); } + while (w.ev('__out.length')) { a.dom.window.__a = w.ev('__out.shift()'); a.ev('rwMsg(__a)'); } + if (a.ev(cond)) return; await new Promise((r) => setTimeout(r, 5)); } assert.fail('never: ' + cond); }; + // The first save of the session is made here, and tells the slot which day it holds. + a.ev('save()'); await pump("!UI.gzBusy&&(slotRaw(UI.slot)||'').startsWith(GZ)"); + // A day later: the whole save goes to the worker. + a.ev("__pk=0;S.day++;S.name='Moved On';save()"); + assert.equal(a.ev('__q.length&&!!__q[0].sv&&!!__q[0].S'), true, 'the game went to the worker'); + await pump("!UI.gzBusy&&SLOT.day[UI.slot]===S.day"); + assert.equal(a.ev('__pk'), 0, 'nothing was packed on the page'); + a.ev("window.__t=null;gunzip(slotRaw(UI.slot)).then(t=>{const j=JSON.parse(t);window.__t=[j.name,j.day,j.biz.length,!!j.sv].join('|');})"); + await settle(a.ev, '!!window.__t'); + assert.equal(a.ev('__t'), a.ev("[S.name,S.day,S.biz.length,true].join('|')"), 'the slot holds the game, stamped'); + assert.equal(a.ev('SLOT.txt[UI.slot]===JSON.stringify(packSave(S))'), true, 'the slot knows its text'); + a.ev('__pk=0'); + // Paused, nothing changed: compared on the page and not written again. + a.ev("__pk=0;window.__w=0;const sp=slotPut;slotPut=(...x)=>{__w++;return sp(...x);};save()"); + assert.equal(a.ev('__q.length'), 0, 'nothing went to the worker'); + assert.ok(a.ev('__pk') > 0, 'packed here, to compare'); + assert.equal(a.ev('__w'), 0, 'the same game is not written again'); + // The worker lost while it saves: the next frame saves again. + a.ev("S.day++;save();rwKill()"); + await settle(a.ev, '!UI.gzBusy'); + assert.equal(a.ev('UI.lastSave'), 0, 'the next frame saves again'); + assert.deepEqual(a.errors, []); + assert.deepEqual(w.errors, []); +}); + +// Loaded from a big slot, the game's first save once it moves on already goes to the worker: the slot knows its day. +test('the first save after loading a big slot goes to the route worker once the game moves on', async () => { + const a = load({ gzip: true }); + a.ev(bigBiz + ';' + huge); + a.ev('save(true)'); + await settle(a.ev, "(slotRaw(UI.slot)||'').startsWith(GZ)"); + const b = load({ gzip: true, storage: { 'sot-save-v1': a.ev('slotRaw(UI.slot)') } }); + await settle(b.ev, 'UI.started===true'); + b.dom.window.structuredClone = globalThis.structuredClone; + b.ev("window.__q=[];rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){}});"); + assert.equal(b.ev('SLOT.big[UI.slot]===true&&SLOT.day[UI.slot]===S.day'), true, 'the slot knows its day and size'); + b.ev('S.day++;save()'); + assert.equal(b.ev('__q.length===1&&!!__q[0].sv'), true, 'the whole save went to the worker'); + assert.deepEqual(a.errors, []); + assert.deepEqual(b.errors, []); +}); diff --git a/tests/speed.test.js b/tests/speed.test.js index c90ae89..500405f 100644 --- a/tests/speed.test.js +++ b/tests/speed.test.js @@ -195,7 +195,9 @@ test('the map is only redrawn when something on it can have changed', () => { assert.ok(frame('', 1100) > 0, 'and once a second anyway'); assert.ok(frame('WL.key=null') > 0, 'the land picture catching up after a zoom or resize redraws'); ev('UI.speed=1'); - assert.ok(frame() > 0 && frame() > 0, 'with the clock running every frame moves'); + // Only the animation clock moves: ambient, drawn at most 30 times a second (tests/frame-pacing.test.js). + const run = [frame(), frame(), frame(), frame()].filter((n) => n > 0).length; + assert.ok(run >= 2 && run < 4, `with the clock running the map moves, every other frame at 60 Hz (${run} of 4)`); ev("ACT.animSet({v:'off'})"); frame(); frame(); assert.equal(frame(), 0, 'with animations off the running map stands still between days'); diff --git a/tests/webgl-zoom-sprites.test.js b/tests/webgl-zoom-sprites.test.js index 67ce100..005d3d6 100644 --- a/tests/webgl-zoom-sprites.test.js +++ b/tests/webgl-zoom-sprites.test.js @@ -68,14 +68,15 @@ test('a still map is drawn again when the zoom comes to rest, so the stretched p const { ev, errors } = open(); ev(STUB); // Animations off: the loop skips frames while nothing changes. + // mapStill() says how the map stands (MAP_MOVING, MAP_AMBIENT, MAP_STILL; 99-loop.js), not just whether it is still. ev(`cam.z=1;draw(__T);mapStill(0,__T);UI.drawnAt=__T;cam.z=1.3;__T+=16;mapStill(0,__T);draw(__T);UI.drawnAt=__T;`); ev(`__T+=16`); - assert.equal(ev('mapStill(0,__T)'), true, 'nothing moved since the last frame'); + assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'nothing moved since the last frame'); ev(`__T+=300`); - assert.equal(ev('mapStill(0,__T)'), false, 'the zoom has rested: one more frame'); + assert.equal(ev('mapStill(0,__T)'), ev('MAP_MOVING'), 'the zoom has rested: one more frame'); ev(`draw(__T);UI.drawnAt=__T;__T+=16`); assert.equal(ev('ZH.f'), 1); - assert.equal(ev('mapStill(0,__T)'), true, 'and then the map stays still again'); + assert.equal(ev('mapStill(0,__T)'), ev('MAP_STILL'), 'and then the map stays still again'); assert.deepEqual(errors, []); }); From 1edf0abb54c719d86215e0e29fb3308d3191c40a Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:21:23 +0100 Subject: [PATCH 08/20] Routing core made once, list orders kept, and Auto-TE's detour searches cut: same routing, much less work The game plays exactly as before. * The core of compute() (rankPass, directPass, sendGroup, send, push, carry, altPath) is ROUTE in 29-route-core.js, built once by routeCore(): made inside compute() they were new functions every call and V8 threw away their code. Exits are read by number from typed columns (USED, CAPX, CIX, HPX, VISX), each list is an object of one shape. * The route cache keeps, for each list and source city, the order routing tries it (xOrder()); a list whose exits, cities and preferences are unchanged on the same graph keeps its orders when other exits change (rcExitKeep()). * Auto-TE: pairs with no detour are marked (TEF), exits that cannot help are skipped (dud()), one failed search answers the next ones, dijkstraTo() searches in arrays kept between calls, teSearch() runs on the graph as flat arrays and picks up where the last search from the same POP stopped. * The PNI/IX tie-break (#298) reaches the core. Tests: route-cache, routing-reference, speed (the fast core against the plain path, Auto-TE on crowded meshes with POPs outside the core, picked-up searches counted). --- CHANGELOG.md | 2 + docs/ARCHITECTURE.md | 18 +- src/game/80-simulation/10-dijkstra.js | 15 ++ src/game/80-simulation/29-route-cache.js | 22 ++- src/game/80-simulation/29-route-core.js | 224 +++++++++++++++++++++++ src/game/80-simulation/30-compute.js | 135 +------------- tests/helpers/reference-allocation.js | 9 +- tests/route-cache.test.js | 42 +++++ tests/routing-reference.test.js | 13 +- tests/speed.test.js | 88 +++++++-- 10 files changed, 409 insertions(+), 159 deletions(-) create mode 100644 src/game/80-simulation/29-route-core.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a20e42..d12a86b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Routing a big network's day takes about half the work, with exactly the same results: on a network of 390 POPs with Auto-TE, a day's routing went from about 0.7 to 0.3 seconds on a computer. + ## [3.2.0] — 2026-11-07 - New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e7d386..afbd701 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -181,10 +181,20 @@ them. Only indices are kept: exits, lists and paths are made fresh every call, b `scripts/route-fuzz.js` plays hundreds of random seeded games on main's page and this checkout's at once, comparing all of R and S after every move and day, with the kept tables and without (`tests/route-fuzz.test.js` plays a few). -Each loop of `compute()` runs in a function of its own (the stages are closures, the busiest is `rankPass`; -the money is `computeMoney()`). V8 optimises a small function quickly and keeps it; `compute()` as one 33 KB function -never stayed optimised: it ran in baseline code, boxing every number, and was compiled again and again in the background -only to be thrown away, which cost more CPU than the routing itself. Keep it that way: a new loop goes in a function. +Each loop of `compute()` runs in a function of its own (the money is `computeMoney()`). V8 optimises a small function +quickly and keeps it; `compute()` as one 33 KB function never stayed optimised: it ran in baseline code, boxing every +number, and was compiled again and again in the background only to be thrown away, which cost more CPU than the routing +itself. Keep it that way: a new loop goes in a function. + +The routing core, the loops that place every flow on an exit (`rankPass`, `directPass`, `sendGroup`, `send`, `push`, +`carry`, `altPath`), lives in `ROUTE` (`29-route-core.js`), made once at load: `compute()` hands it the day's state +(`ROUTE.nodes()`, `ROUTE.run()`). Made inside `compute()`, as they were, they were new functions every call, and V8 threw +away the code it had compiled for the old ones. The core reads exits by number from typed columns (`USED`, `CAPX`, `CIX`, +`HPX`, `VISX`), and each list as an object of one shape (`lx()`). For each list and source city, the route cache also +keeps the list in the order routing tries it (`xOrder()`: by preference, then distance, a stable sort): on a day the cache +is used, a flow's first group is where that order starts, past the exits that filled up, instead of a scan of the whole +list, and what is left needs no sort. Auto-TE marks the pairs that have no detour (`TEF`), the answer to most of its +asks. `tests/day-steps.test.js` and the routing equivalence tests hold all this to the same results. Served share per city (`sfOf`) drives eyeball revenue and customer mood. diff --git a/src/game/80-simulation/10-dijkstra.js b/src/game/80-simulation/10-dijkstra.js index 5b53685..71cd4c4 100644 --- a/src/game/80-simulation/10-dijkstra.js +++ b/src/game/80-simulation/10-dijkstra.js @@ -13,6 +13,21 @@ function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n) if(done[u]||d>D[u])continue;done[u]=1;if(u===stop)break; for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd2e9){DJ.n=n;DJ.D=new Float64Array(n);DJ.P=new Array(n);DJ.S=new Int32Array(n);DJ.done=new Int32Array(n);DJ.g=0;} + const g=++DJ.g,D=DJ.D,P=DJ.P,ST=DJ.S,DN=DJ.done;let hd=DJ.hd,hu=DJ.hu,cap=hd.length,m=0; + const put=(d,u)=>{if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;} + let i=m++;hd[i]=d;hu[i]=u;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}; + D[src]=0;ST[src]=g;put(0,src); + while(m){const d=hd[0],u=hu[0];m--; + if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l(ST[u]===g?D[u]:Infinity))continue;DN[u]=g;if(u===stop)break; + for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<(ST[v]===g?D[v]:Infinity)){D[v]=nd;ST[v]=g;P[v]=e;put(nd,v);}}} + return ST[stop]===g?D[stop]:Infinity;} // The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices. function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};} // The same for compute()'s sender, with the marks it keeps on a path (full, its latency, its far-exit traffic) there from the start: one object shape. diff --git a/src/game/80-simulation/29-route-cache.js b/src/game/80-simulation/29-route-cache.js index 7b8e93b..15dc982 100644 --- a/src/game/80-simulation/29-route-cache.js +++ b/src/game/80-simulation/29-route-cache.js @@ -39,14 +39,26 @@ function exIdx(L){L.hi=L.some(e=>e.hp===0);L.mx=L.some(e=>e.dt>0)&&L.some(e=>e.d function rcReachTake(R2){return {reachable:{...R2.reachable},nt:{...R2.nt},cone:{...R2.cone},reach:R2.reach,reachNT:R2.reachNT};} function rcReachPut(X,R2){const r=X.reach;Object.assign(R2.reachable,r.reachable);Object.assign(R2.nt,r.nt);Object.assign(R2.cone,r.cone);R2.reach=r.reach;R2.reachNT=r.reachNT;} // Keep what was built (on a miss): okBy, the exit lists (each shared list once), each network's lists by rank, DSEL, RSET. -function rcExitKeep(key,E,okBy,reach,LIST,BRJ,DSEL,RSET){const ok=[];for(let j=0;j{for(let i=0;i=P.sig.length||P.sig[x]!==sig[x])return false;}return true;}; + const kept=(k,a)=>{if(!P)return null;const o=old.get(k);return o&&same(a)?o:null;}; const id=new Map(),lists=[];for(const V of LIST.values()){id.set(V,lists.length); - if(V.cs){const cs=[];for(let k=0;k{const o=[];for(const r in m)o.push(r,id.get(m[r]));return o;}); - RC.xk=key;RC.x={ok,reach,lists,brj,DSEL,RSET:[...RSET]};} + RC.xk=key;RC.x={ok,reach,lists,brj,DSEL,RSET:[...RSET],gk:RC.gk,bk,sig};} // Fresh lists for today's exits from a kept build. -function rcExitLists(X,E,BRJ,DSEL,RSET){const V=X.lists.map(d=>{if(d.cs){const cs={cs:[]};for(let k=0;k{if(d.cs){const cs={cs:[]};for(let k=0;ke.w; + // Each network's list at one rank, in an array by network index: BRX[j] are objects of as many shapes as networks have + // sets of ranks, and reading one per flow made the loop's code give up on them. + const byRank=rank=>{const B=new Array(BRX.length);for(let j=0;j{const o=NRES[i];NRES[i]=o-a;if(o>1e-3&&NRES[i]<=1e-3)EP++;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;}; + // t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum). + const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=a; + let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;}; + // TEF[src*NC+dst]: 1 once no detour exists for that pair (capacity only shrinks, so there never will be one again). + // Most calls are those: a byte read, not a Map lookup. The kept path is still valid while every edge and node on it has room. + const altPath=(src,dst,base)=>{const key=src*NC+dst;if(TEF[key]===1)return null;const c0=teCache.get(key); + if(c0){let ok=true;const p=c0.path,ni=c0.ni;for(let k=0;k1e-3)){ok=false;break;} + if(ok)for(let k=0;k1e-3)){ok=false;break;}} + if(ok)return c0;} + const d=teSearch(src,dst); + if(d===Infinity||d>REACH*base+60){teCache.set(key,false);TEF[key]=1;return null;} + const Q=walkP(DJ.P,src,dst);teCache.set(key,Q);return Q;}; + /* Auto-TE's detour search (the one 10-dijkstra.js does to a stop), step for step: neighbours in the same order, the same heap, written into the + same DJ (walkP() reads its paths, the reuse above its marks). Only on the graph as flat arrays (TEO offsets by city, + TEN neighbours, TEE edges, made once per routing in run()) and with the test of an edge written out: no pairs to + unpack and no call for each edge. On a big network with Auto-TE these searches were most of the routing. */ + /* A search from one POP picks up where the last one from there stopped (LR*), as a search of its own would run: every + city closer than the last exit is settled and the heap holds the rest, so the next exit has its answer already or + the search goes on from there, the last exit's neighbours first (it stops before them). One that found nothing has + walked all src reaches and answers the next ones at once. Only on the same graph: EP counts the edges and routers + that run out of room (capacity only shrinks while routing, so none comes back), and another search in DJ moves its + mark. An exit out of the core is let into a graph of its own (OUT[dst]): that search neither resumes nor is resumed. + On a big network nearly all detours of a flow are found from one search (extreme: 3.6 M heap steps a routing → 0.17 M). */ + let TEO=null,TEN=null,TEE=null,LRs=-1,LRe=-1,LRg=-1,LRD=null,LRu=-1,LRm=0; + const teSearch=(src,dst)=>{const n=TEO.length-1,core=CORE,cut=!!(core&&OUT[dst]),go=LRs===src&&LRe===EP&&LRg===DJ.g&&LRD===DJ.D&&!cut; + let g,m=0,u=-1; + if(go){g=LRg;if(DJ.done[dst]===g)return DJ.D[dst];m=LRm;u=LRu;} + else{if(DJ.n!==n||DJ.g>2e9){DJ.n=n;DJ.D=new Float64Array(n);DJ.P=new Array(n);DJ.S=new Int32Array(n);DJ.done=new Int32Array(n);DJ.g=0;}g=++DJ.g;} + const D=DJ.D,P=DJ.P,ST=DJ.S,DN=DJ.done;let hd=DJ.hd,hu=DJ.hu,cap=hd.length; + if(!go){D[src]=0;ST[src]=g; + if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=DJ.hd=a;hu=DJ.hu=b;} + let i=m++;hd[i]=0;hu[i]=src;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}} + for(;;){ + if(u>=0){const d=D[u];for(let k=TEO[u],K=TEO[u+1];k0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}}}} + if(!m){u=-1;break;} + const d=hd[0];u=hu[0];m--; + if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l(ST[u]===g?D[u]:Infinity)){u=-1;continue;}DN[u]=g;if(u===dst)break;} + // An exit out of the core that was found sits in the heap of its own graph; one never found was never let in. + if(cut&&u>=0)LRs=-1;else{LRs=src;LRe=EP;LRg=g;LRD=D;LRu=u;LRm=m;} + return ST[dst]===g?D[dst]:Infinity;}; + /* The routing loops work on exits by number (xi, their index in E): what they read for every exit they look at sits in + columns, USED, CAPX, CIX, HPX, DTX and VISX, and the lists they scan hold numbers (lst.x, lst.xat). Scanning objects of + thirty fields each read one cache line per exit; the columns keep a list's exits side by side. The objects are only + read for an exit that takes traffic (push()), and e.used is written back once routing is done (run()). */ + // An exit the flow can still try: not visited yet, not full when the flow started, reachable, and not on a saturated path. + const usable=x=>VISX[x]!==vis&&USED[x]HPX[a]-HPX[b]||Dv[CIX[a]]-Dv[CIX[b]]+(DTX[a]-DTX[b]); + // Push up to `want` along one path to exit e; returns what fitted. Index loops: for…of allocates an iterator until optimised. Capacity only shrinks while routing, so a + // path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing + // (most tries are into paths that filled up earlier). + const push=(x,P,want,keep=0)=>{if(P.dead)return 0;const e=E[x];const path=P.path,ni=P.ni;let amt=want; + const PN=path.length;for(let k=0;k1e-3&&l.res<=1e-3)EP++;l.ld+=amt;carry(l,ek,nr,ci,amt);} + USED[x]+=amt;FREM[F]-=amt; + {let ok=amt;const cf=CNB[ci],ce=e.cn,cn=NCN[nr],bz=FBZ[F]===1; + 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[ci]+=ok;R2.served+=ok;if(bz)R2.bizSrv[CITIES[ci].id]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const k=e.ts*NN+nr;if(!TNS[k]){TNS[k]=1;if(!TNK[e.ts]){TNK[e.ts]=[];TORD.push(e);}TNK[e.ts].push(nr);}TNA[k]+=ok;} + // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then + // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays, + // Korean users notice any exit far away, transit or not, and much sooner. + if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr)){let ms=P.ms;if(ms<0){ms=0;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)){LATP[ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; + // Where each flow left (the PNI list asks what a PNI here would take over, #175). + if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);} + if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}} + return amt; + }; + // Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths + // with free capacity, as long as they are no more than twice as long. + const send=(x,want)=>{ + let room=Math.min(want,FREM[F],CAPX[x]-USED[x]);if(room<=1e-6)return;const ci=CIX[x]; + const P=PP[ci]||(PP[ci]=walkP(Pv,fci,ci));if(!P.dead)room-=push(x,P,room,TE&&SPILL<1?1-SPILL:0); + if(TE&&room>1e-6&&FREM[F]>1e-6&&USED[x]1e-6;k++){const P=altPath(fci,ci,Dv[ci]);if(!P)break;const m=push(x,P,Math.min(room,CAPX[x]-USED[x]));if(m<=1e-6)break;room-=m;R2.teMoved+=m;} + }; + // Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over + // them by free capacity (like several transits in one city), then top up in order if one fills. + // The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order). + // Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes). + const gone=x=>{if(TE)return false;const P=PP[CIX[x]];return !!P&&P.dead===1;}; + // Every exit of a remembered group still has room (a loop, not every(): no closure per flow). NOG: no group. + const allRoom=c=>{for(let k=0;k{const ci=CIX[x],P=PP[ci];return P!==undefined&&P.dead===1&&(!TE||ci===fci||TEF[fci*NC+ci]===1);}; + const ROOM=[],sendGroup=(g,i0=0,i1=g.length)=>{let live=false;for(let k=i0;k1){let tot=0;for(let k=i0;k1e-6)for(let k=i0;k{if(n>24){if(n===a.length)a.sort(byDist);else{const t=a.slice(0,n).sort(byDist);for(let i=0;i=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}}; + // The direct ranks (25-direct-egress.js) have short lists, one carrier's ports, so they take the plain way: the usable exits + // nearest first, tried in groups of equal distance, as the reference loop in the tests does. A direct rank only concerns the + // networks that have an exit there, and nothing from a POP where Prefer has the say; a port that is not set to carry only takes + // its own POP's traffic. Kept in a function of its own so the loop below stays as it was: the JIT is sensitive to its shape. + const directPass=(rank,pass)=>{const DS=DSEL.get(rank),LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1],BR=byRank(rank); + for(F=0;F1e-6;){let j=i+1;while(j{const BR=byRank(rank); + for(F=0;F=CAPX[A[k]]||gone(A[k])))k++;cur[fci]=k; + if(k===N){gc[fci]=NOG;continue;} + const bh=HPX[A[k]],bd=Dv[CIX[A[k]]]+DTX[A[k]]; + for(let i=k;i=1e-6)break;if(USED[x]=CAPX[e]||gone(e)){full++;continue;}const d=Dv[CIX[e]]+DTX[e];if(d===Infinity)continue;const h=HPX[e]; + if(h=L.length&&full){let k=0;for(let li=0;li1){gc[fci]=NOG;continue;} + if(GN>1)sortD(G,GN);gc[fci]=G.slice(0,GN);}}} + sendGroup(G,0,GN); + if(FREM[F]<=1e-6)continue; + // What is left, nearest first: with a kept order, the usable exits in it (the order sorting them gives). + REST.length=0;if(lst.ord){const A=xOrder(lst,fci);for(let i=lst.cur[fci]|0;i1e-6;){ + let j=i+1;while(j{let a=lst.ord[ci];if(a===undefined){const b=[],L=lst.x; + for(let i=0;i{let w=W.get(A);if(w)return w; + if(A.cs)w={x:null,xat:null,hi:false,mx:false,gc:null,ord:null,cur:null,cs:A.cs.map(s=>s&&lx(s,W))}; + else{const xat=new Map();for(const [c,h] of A.at)xat.set(c,h.map(e=>e.xi));w={x:A.map(e=>e.xi),xat,hi:!!A.hi,mx:!!A.mx,gc:[],ord:A.ord||null,cur:[],cs:null};} + W.set(A,w);return w;}; + return {nodeTake,carry, + nodes(o){({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD}=o);}, + run(o,PASSES,RANKS,RSET){({E,HAS,PASS,R2,FREM,FNJ,FCI,FCA,FBZ,NF,CNB,NCN,ev,day,SRV,TNS,NN,TNK,TORD,TNA,snd,LATP,FARL,EGT,EGO,NEG,NEO,NEA,FGT,FTI,FGI,FII,FGH,FGP, + TE,SPILL,teCache,adj,CORE,OUT,REACH,DSEL,PREFC,BRJ,COMP,SDi,SPi,ALONE,TR,base,eff}=o); + NX=E.length;USED=new Float64Array(NX);CAPX=new Float64Array(NX);CIX=new Int32Array(NX);HPX=new Uint8Array(NX);DTX=new Float64Array(NX);VISX=new Int32Array(NX); + for(let x=0;xday?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);} // Who reaches whom and each network's exit lists, kept while the exits are the same (XC, 29-route-cache.js). - const XK=RCON?rcExitKey(GK,E,(depeer?1:0)+'|'+leak+'|'+(snd?1:0)+'|'+(rp?ev.rpki.nets.join(','):'')+'|'+(TRX?S.te.script:'')+'|'+(PX&&PX.bh.length?PX.bh.map(e=>e.bh.city+'>'+e.bh.land).join(','):'')):null,XC=XK!==null&&RC.xk===XK?RC.x:null; + // A backhaul through a dish changes a cut-off POP's distances: lists kept in order (29-route-cache.js) only for the same one. + const BHK=PX&&PX.bh.length?PX.bh.map(e=>e.bh.city+'>'+e.bh.land).join(','):''; + const XK=RCON?rcExitKey(GK,E,(depeer?1:0)+'|'+leak+'|'+(snd?1:0)+'|'+(rp?ev.rpki.nets.join(','):'')+'|'+(TRX?S.te.script:'')+'|'+BHK):null,XC=XK!==null&&RC.xk===XK?RC.x:null; // coneOf: does exit e reach network n only through a peer's customer cone (#85)? const coneOf=(e,n)=>e.k==='p'?e.net!==n:!!e.dir&&!e.dir.has(n); // ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank. @@ -125,12 +127,10 @@ function compute(){RW.gen++; for(const k in edges)edges[k].res=edges[k].cap;for(const c of pops){const i=CIDX[c];NRES[i]=nodeCap(c);HAS[i]=1;R2.nodeCap[c]=NRES[i];} // The core (backbone technology): what passing-through traffic costs each router, and which POPs TE must avoid. const CORE=coreOn()&&S.core.run>=1;if(CORE)for(const c of pops){const i=CIDX[c];PASS[i]=corePass(c);OUT[i]=inCore(c)?0:1;} - const nodeTake=(i,a)=>{NRES[i]-=a;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;}; const TNA=new Float64Array(TSL.size*NN),TNS=new Uint8Array(TSL.size*NN),TNK=[],TORD=[]; const NKN=NN+3,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[]; - // t.g gives each egress a slot in t.v, so adding to it allocates nothing (a Map of numbers boxes every new sum). - const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),v:[],n:[],d:[]};EL.push(l);}const s=t.g.get(eg);if(s===undefined){t.g.set(eg,t.v.length);t.v.push(0+a);}else t.v[s]+=a; - let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;}; + // The routing core (29-route-core.js) adds up what floods and circuits carry too. + ROUTE.nodes({NRES,NSEEN,NORD,NLOAD,EL,NKN,SEN,ACN,NC,SED,ACD});const nodeTake=ROUTE.nodeTake,carry=ROUTE.carry; R2.l2route={};R2.l2split={}; /* compute() reads only S, except here: scenic circuits remember yesterday's path in R.l2route and R.efg (deliberate hysteresis, so they do not flap). A second call can still move one; the third gives the same answer as the second. */ @@ -187,11 +187,6 @@ function compute(){RW.gen++; for(const i of ni)if(HAS[i])nodeTake(i,amt);for(const l of path){l.res-=amt;l.ld+=amt;if(!clean){l.jk=(l.jk||0)+amt;JK=1;}carry(l,ek,clean?NN+2:NN,Bi,amt);}return amt;}; const DD=ddosLoad({E,okBy,R2,autoBh:!!(TRX&&TRX.blackhole),haul,ms:msOf}); const TE=!!(S.te&&S.te.on)&&coreTE(),TR=TE?teRules():null,REACH=coreTeReach();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1; - const altPath=(src,dst,base)=>{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)||(CORE&&OUT[v]&&v!==dst),dst); - if(D[dst]===Infinity||D[dst]>REACH*base+60){teCache.set(key,false);return null;} - const Q=walkP(P,src,dst);teCache.set(key,Q);return Q;}; /* A network in a peer's customer cone, reached through that peer (#85): after every network you peer with directly (its AS path is one hop longer) and before transit. */ const base=(e,n)=>e.pref==='low'?4:e.rank>0&&e.rank<3&&coneOf(e,n)?CONE_RANK:e.rank; @@ -215,123 +210,13 @@ function compute(){RW.gen++; if(dm&&r===3&&e.k==='t'){const t=dm.get(e.net);if(t){const d=DIRECT_RANK[t][e.carry?0:1];let ds=DSEL.get(d);if(!ds)DSEL.set(d,ds=new Uint8Array(NET_IDS.length));ds[j]=1;RSET.add(d);(m[d]||(m[d]=[])).push(e);}}} for(const r in m){const L=m[r],key=L.map(e=>e.xi).join(','),o=LIST.get(key);if(o){m[r]=o;continue;} let V=L;if(NCOMP>1){const cs=[];for(const e of L){const k=COMP[e.ci];if(k>=0)(cs[k]||(cs[k]=[])).push(e);}for(const s of cs)if(s)idx(s);V={cs};}else idx(L);LIST.set(key,V);m[r]=V;}} - if(RCH)rcExitKeep(XK,E,okBy,RCH,LIST,BRJ,DSEL,RSET);})(); - // The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index. - // F: its index; fci, fnj: its city and network index. - let F=0,fci=0,fnj=0,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],REST=[],NEG=[];let GN=0; + if(RCH)rcExitKeep(XK,E,okBy,RCH,LIST,BRJ,DSEL,RSET,BHK);})(); /* What each kind of exit served, in all (EGT) and per network (NEA, by network index and kind): numbers in typed arrays, where a sum by key would box every new value. EGO and NEO keep the order each first got traffic, which is the order - R.egT and R.netEg list them in; both are written back after routing. */ - const EGT=new Float64Array(4),EGO=[],NEA=new Float64Array(NN*4),NEO=[]; - // An exit the flow can still try: not visited yet, not full when the flow started, reachable, and not on a saturated path. - // byDist: (Da-Db)+(dta-dtb), so exits of one kind at one distance compare as exactly equal and keep their order. - const usable=e=>e.vis!==vis&&e.useda.hp-b.hp||Dv[a.ci]-Dv[b.ci]+(a.dt-b.dt); - // Push up to `want` along one path to exit e; returns what fitted. Index loops: for…of allocates an iterator until optimised. Capacity only shrinks while routing, so a - // path with one full link or node fits nothing for the rest of this pass: mark it, and later tries cost nothing - // (most tries are into paths that filled up earlier). - const push=(e,P,want,keep=0)=>{if(P.dead)return 0;const path=P.path,ni=P.ni;let amt=want; - const PN=path.length;for(let k=0;kx.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);} - SRV[ci]+=ok;R2.served+=ok;if(bz)R2.bizSrv[CITIES[ci].id]+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const k=e.ts*NN+nr;if(!TNS[k]){TNS[k]=1;if(!TNK[e.ts]){TNK[e.ts]=[];TORD.push(e);}TNK[e.ts].push(nr);}TNA[k]+=ok;} - // Backhaul to transit: users notice the round trip to the exit. Up to 20 ms (about 1,500 km) is free, then - // it gets worse, and past 50 ms broadband and internet services count as bad service (#…). Under sender pays, - // Korean users notice any exit far away, transit or not, and much sooner. - if(path.length&&(e.k==='t'||snd&&CITIES[ci].kr)){let ms=P.ms;if(ms<0){ms=0;for(let k=0;k(kl?KR_LAT_OK:LAT_OK)){LATP[ci]+=ok*(kl?krLatLoss(rtt):latLoss(rtt));if(!P.fg){P.fg=0;FARL.push(P,ci,e.ci);}P.fg+=ok;}}const kx=e.kx;if(EGT[kx]===0&&!EGO.includes(kx))EGO.push(kx);EGT[kx]+=ok;if(!NEG[nr]){NEG[nr]=R2.netEg[NET_IDS[nr]]={c:0,p:0,ix:0,t:0};NEO.push(nr);}NEA[nr*4+kx]+=ok; - // Where each flow left (the PNI list asks what a PNI here would take over, #175). - if(e.J>0){const m=e.byC||(e.byC=new Map()),v=m.get(ci);if(v){v[0]+=ok;if(bz)v[1]+=ok;}else m.set(ci,[ok,bz?ok:0]);} - if(e.k==='t'){FGT[F]+=ok;FTI[F]=e.xi;}else if(e.k==='ix'){FGI[F]+=ok;FII[F]=e.xi;}else if(e.k==='p'){if(e.ci===ci&&e.net===NET_IDS[nr])FGH[F]+=ok;else FGP[F]+=ok;}} - return amt; - }; - // Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths - // with free capacity, as long as they are no more than twice as long. - const send=(e,want)=>{ - let room=Math.min(want,FREM[F],e.cap-e.used);if(room<=1e-6)return; - const P=PP[e.ci]||(PP[e.ci]=walkP(Pv,fci,e.ci));if(!P.dead)room-=push(e,P,room,TE&&SPILL<1?1-SPILL:0); - if(TE&&room>1e-6&&FREM[F]>1e-6&&e.used1e-6;k++){const P=altPath(fci,e.ci,Dv[e.ci]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;} - }; - // Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over - // them by free capacity (like several transits in one city), then top up in order if one fills. - // The group is g[i0..i1): plain loops and one scratch array, since this runs for most flows (same sums, same order). - // Without Auto-TE an exit whose path from here is full takes nothing: skip the call (and the numbers it boxes). - const gone=e=>{if(TE)return false;const P=PP[e.ci];return !!P&&P.dead===1;}; - // Every exit of a remembered group still has room (a loop, not every(): no closure per flow). NOG: no group. - const allRoom=c=>{for(let k=0;k{for(let k=i0;k1){let tot=0;for(let k=i0;k1e-6)for(let k=i0;k{if(n>24){if(n===a.length)a.sort(byDist);else{const t=a.slice(0,n).sort(byDist);for(let i=0;i=0&&byDist(a[j],x)>0){a[j+1]=a[j];j--;}a[j+1]=x;}}; - // The direct ranks (25-direct-egress.js) have short lists, one carrier's ports, so they take the plain way: the usable exits - // nearest first, tried in groups of equal distance, as the reference loop in the tests does. A direct rank only concerns the - // networks that have an exit there, and nothing from a POP where Prefer has the say; a port that is not set to carry only takes - // its own POP's traffic. Kept in a function of its own so the loop below stays as it was: the JIT is sensitive to its shape. - const directPass=(rank,pass)=>{const DS=DSEL.get(rank),LOC=rank===DIRECT_RANK[1][1]||rank===DIRECT_RANK[2][1]; - for(F=0;F1e-6;){let j=i+1;while(j{ - for(F=0;F=e.cap||gone(e)){full++;continue;}const d=Dv[e.ci]+e.dt;if(d===Infinity)continue;const h=e.hp; - if(h=lst.length&&full){let k=0;for(let li=0;li1){gc[fci]=NOG;continue;} - if(GN>1)sortD(G,GN);gc[fci]=G.slice(0,GN);}} - sendGroup(G,0,GN); - if(FREM[F]<=1e-6)continue; - REST.length=0;for(let li=0;li1e-6;){ - let j=i+1;while(j{ diff --git a/tests/helpers/reference-allocation.js b/tests/helpers/reference-allocation.js index ca0541d..d771194 100644 --- a/tests/helpers/reference-allocation.js +++ b/tests/helpers/reference-allocation.js @@ -1,7 +1,8 @@ // Deliberately scan all exits for every flow, without byRank, local-city // shortcuts or first-group selection. Stable sorting preserves E order on ties. // Without Auto-TE, an exit whose shortest path from this POP is already full fits nothing, so it counts as -// unusable, like a full exit (#210). +// unusable, like a full exit (#210). It runs inside the routing core (29-route-core.js), which reads what exits have +// used from its columns (USED, CAPX) and sends to exits by number (xi). module.exports = ` // A carrier's own port (dr) is also a plain transit exit. A POP with a Prefer-marked transit port keeps what Prefer // says, and a port not set to carry only takes its own POP's traffic. @@ -13,14 +14,14 @@ module.exports = ` for(F=0;Fe.usedUSED[e.xi](a.pref==='high'?0:1)-(b.pref==='high'?0:1)||Dv[CIDX[a.city]]-Dv[CIDX[b.city]]+(tie(a)-tie(b))); for(let i=0;i1e-6;){ let j=i+1;while(je.xi));i=j; } } } diff --git a/tests/route-cache.test.js b/tests/route-cache.test.js index 79d1093..4a0af1d 100644 --- a/tests/route-cache.test.js +++ b/tests/route-cache.test.js @@ -86,3 +86,45 @@ test('days in a row reuse the kept tables and route like a fresh start every day } assert.deepEqual(errors, []); }); + +test('with Auto-TE, kept orders and the no-detour marks route like a fresh start every day', () => { + // The routing core (29-route-core.js) keeps each list's order for each city with the tables, and Auto-TE marks the + // pairs with no detour: both have to give exactly what scanning and searching afresh give. The network is made busy + // (half its link capacity) so that flows spill, detours are searched and many fail. + const { ev, errors } = open(); + ev("S.core.run=2;S.te={on:true,day:S.day,script:'spill at 85%'};for(const b of S.biz)if(BIZ_T[b.type].l2&&b.city2)b.route='scenic';for(const l of S.links)if(l.kind==='wave')l.cap=(l.cap||0)/2;compute();compute();"); + assert.equal(ev('!!(S.te.on&&coreTE())'), true); + let tried = 0; + for (let d = 0; d < 4; d++) { + ev('dayTick()'); + const r = step(ev, ''); + assert.ok(r.same, `day ${d}: the same routing with and without the kept tables`); + assert.ok(!r.g && !r.x, `day ${d}: a day of demand only keeps the tables`); + tried = Math.max(tried, ev('R.teMoved')); + } + assert.ok(tried > 0, 'Auto-TE moved traffic onto detours'); + assert.deepEqual(errors, []); +}); + +// When the exits change but the graph does not (a network leaves an exchange because its PNI came up), the lists that +// did not change keep the orders routing worked out for them (the same arrays, used the same day), the ones that did +// start again, and routing is still exactly routing without the kept tables, day after day. +test('lists an exit change leaves alone keep their orders; routing stays the same as without the kept tables', () => { + const { ev, errors } = open(); + // Two days on the kept build: the lists get their orders. + ev('compute();compute();'); + ev('window.__ords=new Set(RC.x.lists.flatMap(d=>d.cs?d.ord.filter(Boolean):[d.ord]).filter(o=>Object.keys(o).length));'); + assert.ok(ev('__ords.size') > 5, `orders worked out: ${ev('__ords.size')}`); + // One network leaves one exchange: the exits key moves, the graph does not. + const r = step(ev, `(()=>{const ix=Object.keys(S.ixp).find(x=>ixSessions(x).size>3),n=[...ixSessions(ix)][0];window.__left=n+'@'+ix; + S.peers[n+'@'+ix]=false;delete S.peers[n+'@'+ix];S.rs[ix]=false;S.pni.push({id:'pk1',net:n,city:ixCity(ix),tier:1,n:1});})()`); + assert.equal(r.g, false, 'same graph'); + assert.equal(r.x, true, 'the exits changed'); + assert.equal(r.same, true, 'the same routing as without the kept tables'); + const kept = ev('RC.x.lists.flatMap(d=>d.cs?d.ord.filter(Boolean):[d.ord]).filter(o=>__ords.has(o)).length'); + const all = ev('RC.x.lists.length'); + assert.ok(kept > 0 && kept < ev('__ords.size') + 1, `lists that kept their orders: ${kept} of ${all}`); + // And a few more days, with the next change between them. + for (let d = 0; d < 3; d++) assert.equal(step(ev, 'for(const c in S.pops)if(S.pops[c].bb)S.pops[c].bb.d*=1.03').same, true, `day ${d + 1} after`); + assert.deepEqual(errors, []); +}); diff --git a/tests/routing-reference.test.js b/tests/routing-reference.test.js index 0524726..5f60938 100644 --- a/tests/routing-reference.test.js +++ b/tests/routing-reference.test.js @@ -22,15 +22,16 @@ function network(ev) { } compute();`); // Share the model and path sender, but replace indexed exit selection with - // the original full scan and stable sort for every flow. - const source = ev('compute.toString()'); - const start = source.indexOf(' for(const pass of PASSES)for(const rank of RANKS){'); - const end = source.indexOf(' for(const i of NORD)', start); + // the original full scan and stable sort for every flow: in the routing core (29-route-core.js), the passes of run(). + const core = ev('routeCore.toString()'), source = ev('compute.toString()'); + const start = core.indexOf(' for(const pass of PASSES)for(const rank of RANKS){'); + const end = core.indexOf(' for(let x=0;x= 0 && end > start, 'allocation loop boundaries must exist'); // The reference also builds every table afresh, so the comparison covers what routing keeps between calls. assert.ok(source.includes('RCON=RC.on'), 'compute() can be told not to keep its tables'); - const ref = (source.slice(0,start)+referenceAllocation+source.slice(end)).replace('RCON=RC.on', 'RCON=false'); - ev(`window.referenceCompute=eval('('+${lit(ref)}+')')`); + const refCore = (core.slice(0, start) + referenceAllocation + core.slice(end)).replace(/^function routeCore/, 'function'); + ev(`window.referenceCore=(${refCore})();window.referenceRaw=(0,eval)('('+${lit(source.replace('RCON=RC.on', 'RCON=false').replace(/^function compute/, 'function'))}+')'); + window.referenceCompute=function(){const r=ROUTE;ROUTE=referenceCore;try{referenceRaw();}finally{ROUTE=r;}};`); } test('indexed routing matches the simple allocation loop across network changes', () => { diff --git a/tests/speed.test.js b/tests/speed.test.js index c90ae89..fdc373f 100644 --- a/tests/speed.test.js +++ b/tests/speed.test.js @@ -287,28 +287,41 @@ test('the map is not drawn while the dashboard covers the whole screen', () => { // compare the two on a busy network (Auto-TE, then a RouteScript that keeps headroom on every link) and on a small one // where Auto-TE has to route around a full link, so it keeps holding when the game's numbers change. function plainCompute(ev) { - const src = ev('compute.toString()'); - let plain = src + const src = ev('compute.toString()'), csrc = ev('routeCore.toString()'); + const plain = src + .replace('const ns=e.nets||NET_IDS;', 'const ns=NET_IDS;') + // ...and without what routing keeps between calls (29-route-cache.js): the plain path builds everything afresh, + // which also leaves the lists without kept orders, so the first group and the rest are scanned and sorted. + .replace('RCON=RC.on', 'RCON=false'); + // The routing core (29-route-core.js) with its shortcuts off: Auto-TE's no-detour marks and its searches picked up + // where the last one stopped back to the cache lookup and a fresh dijkstra() for every detour. + let core = csrc .replace('if(!lst.hi&&!lst.mx&&ALONE[fci])', 'if(false)') .replace('if(!GN){\n // One scan', 'if(false){\n // One scan') - .replace('const ns=e.nets||NET_IDS;', 'const ns=NET_IDS;') .replace('if(P.dead)return 0;', '').replaceAll('if(r<=1e-6){P.dead=1;return 0;}', '') - .replace('if(!P.dead)room-=push(', 'room-=push(').replace(/const gone=e=>\{[^\n]*\};/, 'const gone=e=>false;') - // ...and without what routing keeps between calls (29-route-cache.js): the plain path builds everything afresh. - .replace('RCON=RC.on', 'RCON=false'); + .replace('if(!P.dead)room-=push(', 'room-=push(').replace(/const gone=x=>\{[^\n]*\};/, 'const gone=x=>false;') + // ...and every exit is called, even one whose path is full with no detour (dud()). + .replace(/const dud=x=>\{[^\n]*\};/, 'const dud=x=>false;') + .replace('if(TEF[key]===1)return null;const c0=teCache.get(key);', 'const c0=teCache.get(key);if(c0===false)return null;') + .replace('const d=teSearch(src,dst);', 'const d=dijkstraTo(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3)||(CORE&&OUT[v]&&v!==dst),dst);') + .replace('const d=dijkstraTo(adj,src,wW,', 'const {D:D0,P:P0}=dijkstra(adj,src,wW,').replace(',dst);\n if(d===Infinity', ',dst),d=D0[dst];\n if(d===Infinity') + .replace('walkP(DJ.P,src,dst)', 'walkP(P0,src,dst)'); // ...and the group split and sorting written the plain way, with array copies, as before they were made allocation-free - const sg = plain.indexOf('const ROOM=[],sendGroup='), sd = plain.indexOf('const sortD='); + const sg = core.indexOf('const ROOM=[],sendGroup='), sd = core.indexOf('const sortD='); assert.ok(sg > 0 && sd > sg, 'found the group sender and the sort'); - plain = plain.slice(0, sg) + `const ROOM=[],sendGroup=(g0,i0=0,i1=g0.length)=>{const g=g0.slice(i0,i1);for(const e of g)e.vis=vis; - if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=FREM[F];if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));} - for(const e of g){if(FREM[F]<=1e-6)break;send(e,FREM[F]);}};\n ` + plain.slice(sd).replace(/^const sortD=\(a,n=a\.length\)=>\{[^\n]*\};/, 'const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);for(let i=0;i{const g=g0.slice(i0,i1);for(const x of g)VISX[x]=vis; + if(g.length>1){const room=g.map(x=>Math.max(0,CAPX[x]-USED[x])),tot=room.reduce((a,b)=>a+b,0),want=FREM[F];if(tot>1e-6)g.forEach((x,k)=>send(x,want*room[k]/tot));} + for(const x of g){if(FREM[F]<=1e-6)break;send(x,FREM[F]);}};\n ` + core.slice(sd).replace(/^const sortD=\(a,n=a\.length\)=>\{[^\n]*\};/, 'const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);for(let i=0;ifalse;'), 'every exit of a group is called'); assert.ok(plain.includes('RCON=false') && !plain.includes('RC.on'), 'the kept routing tables were switched off'); - assert.ok(plain.includes('const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);') && plain.includes('g.forEach('), 'the plain group split and sort are in'); - ev('window.__plain=' + plain.replace(/^function compute/, 'function')); + assert.ok(!core.includes('TEF[key]===1') && !core.includes('dijkstraTo(') && !core.includes('const d=teSearch(') && core.includes('if(c0===false)return null;'), "Auto-TE's shortcuts were switched off"); + assert.ok(core.includes('const sortD=(a,n=a.length)=>{const t=a.slice(0,n).sort(byDist);') && core.includes('g.forEach('), 'the plain group split and sort are in'); + ev('window.__plainC=' + plain.replace(/^function compute/, 'function') + ';window.__plainR=(' + core.replace(/^function routeCore/, 'function') + ')();'); + ev('window.__plain=function(){const r=ROUTE;ROUTE=__plainR;try{__plainC();}finally{ROUTE=r;}};'); } test('fast routing gives exactly the same result as the plain path it replaces', () => { @@ -363,6 +376,51 @@ test('Auto-TE routes around a full link exactly like the plain path', () => { assert.deepEqual(errors, []); }); +// Auto-TE's searches for a detour, on meshes of thin and thick links where POPs fill up and some sit outside the core +// (TE never steers through them, but may end there): a search from a city picks up where the last one from there +// stopped until a link or router runs out of room, and an exit whose full path has no detour is not called. Several +// seeded networks, from light to heavy load, must route exactly as the plain path that searches every time. +test('Auto-TE detours route like the plain path on crowded meshes with POPs outside the core', () => { + const { ev, errors } = load(); + plainCompute(ev); + // The fast core, counting the searches that were picked up: answered at once, or gone on from where the last stopped. + const csrc = ev('routeCore.toString()'), counted = csrc.replace('if(go){g=LRg;if(DJ.done[dst]===g)return DJ.D[dst];', 'if(go){g=LRg;if(DJ.done[dst]===g){__TE.had++;return DJ.D[dst];}__TE.went++;'); + assert.notEqual(counted, csrc, 'found the picked-up search'); + ev('window.__TE={had:0,went:0};ROUTE=(' + counted.replace(/^function routeCore/, 'function') + ')();'); + const CS = ['fra', 'ams', 'bru', 'par', 'lon', 'zrh', 'mil', 'vie', 'prg', 'ber', 'muc', 'mad', 'cph', 'waw', 'mrs', 'ham', 'dus']; + let moved = 0, outs = 0; + for (let seed = 1; seed <= 6; seed++) { + let a = seed * 7919; + const rnd = () => { a = (a * 16807) % 2147483647; return a / 2147483647; }, int = (n) => Math.floor(rnd() * n); + const cs = CS.filter(() => rnd() < 0.75), links = []; + for (let i = 1; i < cs.length; i++) links.push([cs[int(i)], cs[i], int(4)]); + for (let k = 0; k < cs.length; k++) { const x = cs[int(cs.length)], y = cs[int(cs.length)]; if (x !== y) links.push([x, y, int(4)]); } + const out = cs.filter(() => rnd() < 0.3), up = cs.filter((c) => out.includes(c) || rnd() < 0.3).concat(cs[0]); + ev(`ACT.start({});S.cash=1e12;S.lvl=13;for(const g of GOALS)S.done[g.id]=0;S.pops={};S.links=[];S.transit=[]; + const cs=${JSON.stringify(cs)},out=${JSON.stringify(out)},IN=RG.findIndex(g=>g.cr>=3&&!g.noMpls),OUT=RG.findIndex(g=>g.cr<2); + for(const c of cs){ACT.buildPop({city:c});const p=S.pops[c];p.rgen=RG_TOP;p.routers=RMAX;if(!p.bb)ACT.launchBB({city:c});} + const L=(a,b,t)=>{UI.via=null;UI.lmode='wave';UI.route='main';try{openLinkModal(a,b);ACT.buildLink({tier:t});}catch(e){}closeModal();}; + for(const [a,b,t] of ${JSON.stringify(links)})L(a,b,t); + for(const c of ${JSON.stringify(up)}){const t=NETS.find(n=>n.price&&n.pops.includes(c)&&(n.type==='t1'||n.type==='t2'));if(t)ACT.buyTransit({city:c,net:t.id,tier:3});} + // Then the routers: some too old for the core, and few enough that POPs fill up too. + for(const c of cs){const p=S.pops[c];p.rgen=out.includes(c)?OUT:IN;p.routers=1+${int(3)};} + S.ixp={};S.pni=[];S.caches=[];S.biz=[];S.te={on:true,day:0};S.core={lv:3,run:2};S.nextFail=1e9;S.nextEvent=1e9;`); + assert.ok(ev('coreOn()&&coreTE()'), 'the core rules apply and Auto-TE runs'); + outs += ev('Object.keys(S.pops).filter(c=>!inCore(c)).length'); + const sig = () => ev('JSON.stringify({served:R.served,teMoved:R.teMoved,egT:R.egT,load:S.links.map(l=>R.load[l.id]||0),node:R.nodeLoad,t:R.useT,f:R.fl.map(f=>[f.got,f.via])})'); + for (const load of [0.3, 0.8, 1.6, 3]) { + ev(`for(const c in S.pops)S.pops[c].bb.d=CITY[c].P*${load}`); + ev('compute()'); const fast = sig(); moved += ev('R.teMoved'); + ev('__plain()'); const ref = sig(); + assert.equal(fast, ref, `network ${seed} at load ${load}: the fast and the plain path route the same`); + } + } + assert.ok(moved > 100, 'Auto-TE found detours'); + assert.ok(outs > 0, 'some POPs are outside the core'); + assert.ok(ev('__TE.had') > 0 && ev('__TE.went') > 0, 'searches were picked up: some answered at once, some gone on'); + assert.deepEqual(errors, []); +}); + test('fiber customers are checked by link id the same way with or without the lookup tables', () => { const { ev, errors } = load(); ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'})"); From 44116103be4e2d6592c4f3f99a5328dac815d40f Mon Sep 17 00:00:00 2001 From: Antoine <20756073+antt0n@users.noreply.github.com> Date: Sat, 7 Nov 2026 22:21:22 +0100 Subject: [PATCH 09/20] The intern and customers' promises counted once per network: ports, caches and PNIs in one pass, shared searches The game plays exactly as before. * The NOC intern plans every POP in one pass: portsAt() counts router ports for all cities at once (routers, ports and cache orders; the ports job keeps ports in use and reserved by city between two jobs), cachePlan() sorts the boxes by POP once and cityShSum() sums a city's shares once per table, pniFlows() reads every POP's flows from routing's columns (R.flc) in one pass and pniWant() gives the weekly PNI round its sort key from typed columns. pniBatchRun() lets a frame through every few networks; pniQuote() looks existing PNIs and ports up from the batch. * A dark fiber's capacity asks optG() once per run of identical optics (dfLit()); linkDown() and ownGlass() ask dfOn(), whether it carries anything for you, without the sum unless an optic is out or managed waves are sold on it. terrIslands() tests !l.sub first. * Latency: latGraph() lists each city's links once in S.links order (typed arrays), latRun() is the same search with the same sums, latPairs() searches once per city for a boutique's finance routes and the latency offers. * Diverse paths: divGraph()/divOn() number the cities and risks once; promiseCheck() shares a diversity graph, the land islands and one latency search per origin across every customer when the intern weighs taking a fiber out, and spots0() shares the graph for sovereign offers. Tests: day-steps (cache planner, ports at every POP and flows from columns equal the old ways; the PNI round through pniBatchRun), fiber-lit-and-latency (with failed optics and managed waves), shared-promise-checks, intern-personas. --- CHANGELOG.md | 4 + docs/ARCHITECTURE.md | 6 +- src/game/10-catalog/40-ports.js | 27 ++++-- src/game/10-catalog/60-reach-and-subsea.js | 8 +- src/game/60-features/36-specialist.js | 8 +- src/game/60-features/95-standing-orders.js | 50 +++++++---- src/game/70-rules/35-pni-orders.js | 21 +++-- src/game/70-rules/38-pni-value.js | 26 ++++-- src/game/70-rules/95-utilities.js | 22 +++-- src/game/80-simulation/40-billing.js | 2 +- src/game/80-simulation/60-requirements.js | 24 ++--- .../80-simulation/80-geography-and-latency.js | 19 +++- tests/day-steps.test.js | 63 ++++++++++++- tests/fiber-lit-and-latency.test.js | 69 +++++++++++++++ tests/intern-personas.test.js | 2 +- tests/shared-promise-checks.test.js | 88 +++++++++++++++++++ 16 files changed, 373 insertions(+), 66 deletions(-) create mode 100644 tests/fiber-lit-and-latency.test.js create mode 100644 tests/shared-promise-checks.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a20e42..d07d4f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. +- A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before. +- The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before. + ## [3.2.0] — 2026-11-07 - New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1e7d386..e9ba500 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -134,9 +134,11 @@ The day: Then the NOC intern's standing orders (`opsRun()`, or `opsDay()` in one go), if one is hired: each order clicks the same `ACT` actions a player would, muted, within its monthly budget, and the shift routes again (a yield) before decommissioning, which reads today's loads, and at the end, each only if a job changed the network. An order that - throws is paused; the day goes on. The NOC gets one notice a week. + throws is paused; the day goes on. The NOC gets one notice a week. The orders plan for every POP each day, so what + they count is counted for all POPs in one pass (`portsAt()`, `cachePlan()`, `pniFlows()`, `pniBatch()`), never one + pass over the network per POP. Then the sales desk (`slAutoDay()`), if someone runs sales and the player lets them sign: deals are Sales', never - the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything). + the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything).5. Updates customer mood, churn and new offers; IX members join; loans tick. 5. Updates customer mood, churn and new offers; IX members join; loans tick. 6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy. 7. Checks goals, level, badges and scenario end conditions. diff --git a/src/game/10-catalog/40-ports.js b/src/game/10-catalog/40-ports.js index 8712607..c7b7789 100644 --- a/src/game/10-catalog/40-ports.js +++ b/src/game/10-catalog/40-ports.js @@ -9,20 +9,29 @@ const cachePerPort=(c,g)=>{const p=S.pops[c];return p?Math.max(1,Math.floor(port const cacheG=x=>x.g===CACHE_BIG?CACHE_BIG:CACHE_CAP,cacheMo=x=>x.g===CACHE_BIG?CACHE_BIG_MO:CACHE_MO,cachesMo=()=>S.caches.reduce((a,x)=>a+cacheMo(x),0); const cacheBox=c=>{const p=S.pops[c];return p&&portG(p.rgen||0)>=CACHE_BIG?{g:CACHE_BIG}:{};}; function cachePorts(c,extra=[],g){const n={a:0,b:0};for(const x of S.caches)if(x.city===c)n[x.site==='b'?'b':'a']+=cacheG(x);for(const x of extra)n[x.site==='b'?'b':'a']+=cacheG(x); - const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);} + return cachePortsOf(c,n,g);} +// n: the Gbps of boxes per site. +function cachePortsOf(c,n,g){const p=S.pops[c],k=p?portG(g===undefined?(p.rgen||0):g):CACHE_CAP;return Math.ceil(n.a/k-1e-9)+Math.ceil(n.b/k-1e-9);} const cachePortsAdd=(c,adds)=>cachePorts(c,adds)-cachePorts(c); /* A dark fiber channel takes as many router ports at each end as the optic's speed needs (#256): a pluggable sits in one port, but a 1.6T transponder shelf hands off to an 800G router as two 800G clients. */ const chPorts=(o,c,g)=>{const p=S.pops[c];return p&&OPT[o]?Math.max(1,Math.ceil(OPT[o].g/portG(g===undefined?(p.rgen||0):g)-1e-9)):1;}; -function portsUsed(c,g){let u=0; - for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);} +function portsUsed(c,g){return portsAt([c],g).get(c);} +/* The router ports in use at each of the cities cs, in one pass over the network: the intern sizes every POP each day, + and a pass per POP was a pass over every link, PNI and cache box for each. Each city's count adds the same things in + the same order as on its own. g: another router model at those cities (what would fit). */ +function portsAt(cs,g){const u=new Map(),box=new Map();for(const c of cs){u.set(c,0);box.set(c,{a:0,b:0});} + const add=(c,v)=>{const x=u.get(c);if(x!==undefined)u.set(c,x+v);}; + for(const l of S.links){if(l.kind==='vxc')continue;for(const c of l.a===l.b?[l.a]:[l.a,l.b]){if(!u.has(c))continue; + if(l.kind!=='df'){add(c,1);continue;}for(const o of l.ch||[])add(c,chPorts(o,c,g));}} // A puzzle's content origin (t.pz) hands off on a port of its own: it takes none of yours. - for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1); - for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1); - for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1); - if(S.myIx[c])u+=1; - for(const x of S.nni||[])if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1); - u+=cachePorts(c,[],g); + for(const t of S.transit)if(!t.pz)add(t.city,PORT_SLOT(t.tier)*(t.n||1)); + for(const x of S.pni)add(x.city,PORT_SLOT(x.tier)*(x.n||1)); + for(const c of u.keys()){for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])add(c,PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1)); + if(S.myIx[c])add(c,1);} + for(const x of S.caches){const n=box.get(x.city);if(n)n[x.site==='b'?'b':'a']+=cacheG(x);} + for(const x of S.nni||[])add(x.city,PORT_SLOT(x.tier)*(x.n||1)); + for(const c of u.keys())add(c,cachePortsOf(c,box.get(c),g)); return u;} function portsMax(c,g,rt){const p=S.pops[c];if(!p)return 0;return RG[g===undefined?(p.rgen||0):g].ports*(rt||p.routers||1);} function portGate(c,add){if(!S.pops[c]||add<=0)return true;const u=portsUsed(c),m=portsMax(c);if(u+add<=m+1e-9)return true; diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 8fd1c7b..8d63b91 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -69,9 +69,13 @@ const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/reachOn(OPT[o].reach,l.sub))-1) let DFC=null; const dfCap=l=>{if(!DFC)return dfCap0(l);let g=DFC.get(l);if(g===undefined)DFC.set(l,g=dfCap0(l));return g;}; // dfLit: everything the optics carry; dfCap0: what is left for your own traffic once managed waves sold on it (mwG(), -// the capacity market) are carved out. -const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; +// the capacity market) are carved out. A fiber's channels come in runs of one optic (a big one: a thousand of them): +// optG() once per run, added up in order. +const dfLit=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0,o=null,x=0;for(const c of ch){if(c!==o){o=c;x=optG(c,l);}g+=x;}const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);}; const dfCap0=l=>Math.max(0,dfLit(l)-mwG(l)); +// Whether a fiber carries anything for you (linkDown() asks of every fiber, often): dfCap(l)>0 without adding up every +// channel. An optic out of service, or managed waves sold on it, take the sum. +const dfOn=l=>{if(l.ready>S.day||l.eqDown>S.day)return false;if(l.chFail&&l.chFail.until>S.day||mwG(l)>0)return dfCap(l)>0;let o=null;for(const c of l.ch||[])if(c!==o){o=c;if(optG(c,l)>0)return true;}return false;}; const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1); // A sick LAG (LACP trouble) keeps only part of its capacity until the incident clears. const lagF=o=>o&&o.lacp&&o.lacp.until>S.day?o.lacp.f:1,ixLagF=x=>lagF(S.ev&&S.ev.ixlacp&&{lacp:S.ev.ixlacp[x]}); diff --git a/src/game/60-features/36-specialist.js b/src/game/60-features/36-specialist.js index f3803d2..c5cb569 100644 --- a/src/game/60-features/36-specialist.js +++ b/src/game/60-features/36-specialist.js @@ -12,12 +12,12 @@ let BIGEYE=null;const bigEye=()=>BIGEYE||(BIGEYE=CITIES.slice().sort((x,y)=>y.P- let SPOTC=null; function spots(){const lv=lvl(),k=S.day+'|'+lv+'|'+S.links.length+'|'+Object.keys(S.pops).length+'|'+charter();if(SPOTC&&SPOTC.s===S&&SPOTC.k===k)return SPOTC.v;const v=spots0(lv);SPOTC={s:S,k,v};return v;} function spots0(lv){const out=[];if(gatesOpen()||S.scn)return out;const up=t=>BIZ_T[t].lv>lv,mine=Object.keys(S.pops).filter(bizCity); - if(up('hft')){const f=FIN.filter(c=>S.pops[c]);for(let i=0;iS.pops[c])))if(ms<=latMaxOf(a,b))out.push({t:'hft',a,b,k:'lat',n:+ms.toFixed(1)}); const dci=['onramp','ai','hyper'].filter(up); if(dci.length)for(const l of S.links){if(l.kind!=='df'||l.sub||l.ready>S.day||linkDown(l))continue;const g=dfCap(l); for(const t of dci){const T=BIZ_T[t];if(g>=T.opts[0]*SPOT_DF&&(!T.div||reqCan('diverse',{city:l.a,city2:l.b})))out.push({t,a:l.a,b:l.b,k:'df',n:g});}} if(up('sov')){const by={};for(const c of mine)(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c); - for(const cs of Object.values(by))for(let i=0;i=0.95)out.push({t:'cgame',a:c,b:null,k:'eye',n:0}); return out;} // A spotted customer starts at the smallest size its type comes in; your level makes them bigger and more frequent. @@ -79,10 +79,10 @@ const RG_GLASS=Math.max(...Object.values(OPT).map(o=>o.rg)),rgGlass=g=>broker()& const latPay=()=>charter()==='boutique'?LAT_PAY:1; // The fastest a leased wave or fiber gets between two cities: overland, or the quickest cable on the route. function leasedLat(a,b){let best=isSub(a,b)?Infinity:kmBetween(a,b)*1.25/200;for(const c of cablesFor(a,b))best=Math.min(best,c.km*Math.min(CAB[c.cid].lat||1,1.25)/200);return best;} -const ownGlass=l=>l.kind==='df'&&l.own&&l.ready<=S.day&&dfCap(l)>0; +const ownGlass=l=>l.kind==='df'&&l.own&&dfOn(l); let SOLC=null; function solRoutes(){const k=S.day+'|'+S.links.length+'|'+S.links.reduce((n,l)=>n+(l.ch||[]).length,0);if(SOLC&&SOLC.s===S&&SOLC.k===k)return SOLC.v; - const f=FIN.filter(c=>S.pops[c]),v=[];if(S.links.some(ownGlass))for(let i=0;iS.pops[c]),v=[];if(S.links.some(ownGlass))for(const [a,b,o] of latPairs(f,ownGlass)){const l=leasedLat(a,b);if(isFinite(o)&&isFinite(l)&&oS.biz.filter(b=>BIZ_T[b.type]&&BIZ_T[b.type].lat&&b.mood>=50&&reqOk(b)).length; // What each charter promises, as the picker and the agent's docs say it. diff --git a/src/game/60-features/95-standing-orders.js b/src/game/60-features/95-standing-orders.js index 90a2ba1..4071caa 100644 --- a/src/game/60-features/95-standing-orders.js +++ b/src/game/60-features/95-standing-orders.js @@ -143,16 +143,18 @@ const opsProv=c=>{const pv=opsP('transit','prov'),n=isNet(pv)?NET[pv]:null;retur // after a job is only a place where a long shift may let a frame through (opsRun()), nothing changes there. const OPS_RUN={ *repair(X){purgeInc();for(const i of S.inc.slice())if(i.type!=='ddos'&&i.until>S.day&&i.cost>0&&!(i.slow&&i.rushed)&&X.can('repair',i.cost)&&X.pay('repair',()=>ACT.fixInc({id:i.id}))){X.did('repair');yield;}}, - *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next', - load=c=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),portsUsed(c)/Math.max(1,portsMax(c))); + // Ports in use are counted for every POP at once, after the model swaps: a router added or swapped here changes no other POP's count. + *routers(X){const at=opsP('routers','at')/100,how=opsP('routers','how'),m=opsP('routers','model'),fix=m!=='next',cs=opsPops('routers'), + load=(c,u)=>Math.max((R.nodeLoad[c]||0)*opsAhead()/(R.nodeCap[c]||nodeCap(c)||1),u/Math.max(1,portsMax(c))); // A chosen model: swap every POP still on a smaller one to it, the busiest first, while the budget lasts. Never a // step down, never a model that is not unlocked or does not fit, and only with a second router or no traffic there. - if(fix&&rgOpen(m))for(const c of opsPops('routers').sort((a,b)=>load(b)-load(a))){const p=S.pops[c],g=p.rgen||0; + if(fix&&rgOpen(m)){const pu=portsAt(cs);for(const c of cs.slice().sort((a,b)=>load(b,pu.get(b))-load(a,pu.get(a)))){const p=S.pops[c],g=p.rgen||0; if(p.rupDay===S.day||g===m||RG[m].cap<=RG[g].cap||modelFits(c,m)||!((p.routers||1)>1||popIdle(c)))continue; const cost=swapCost(c,m);if(!X.can('routers',cost))continue; - if(X.pay('routers',()=>ACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}} - for(const c of opsPops('routers')){const p=S.pops[c];if(p.rupDay===S.day)continue; - const ld=load(c);if(ldACT.upRouter({city:c,g:m}))){X.did('routers',c+' ⇧'+RG[m].pn);yield;}}} + const pu=portsAt(cs); + for(const c of cs){const p=S.pops[c];if(p.rupDay===S.day)continue; + const ld=load(c,pu.get(c));if(ldS.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c); + // Both, by city, are worked out once between two jobs (a job may change them; KV is dropped after each), in the order + // the PNIs come, as the sum over them was: the same numbers. + KV={rv:null,pu:new Map()}, + resv=c=>{if(!KV.rv){KV.rv=new Map();for(const p of S.pni)if(p.up)KV.rv.set(p.city,(KV.rv.get(p.city)||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)));}return KV.rv.get(c)||0;}, + used=c=>{let u=KV.pu.get(c);if(u===undefined)KV.pu.set(c,u=portsUsed(c));return u;},room=c=>portsMax(c)-used(c)+1e-9-resv(c); // Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took. for(const p of S.pni){const c=p.city,use=(R.usePni[p.id]||0)*opsAhead(),cap=()=>lagCap(pniG(p),p.n),n=()=>p.n||1;if(!pniOn(p)||p.up||!(use>0)||cap()>=N*use||!opsHere('ports',c))continue; L.push({city:c,at:c,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(), @@ -200,8 +206,8 @@ const OPS_RUN={ out.push({cost:ixPortMo(x,t)*n(),cap:cap()*lagCap(PORT[t].g,n())/lagCap(g(),n()),w:PORT[t0].n+'→'+PORT[t].n,go:()=>ACT.buyIx({city:x,tier:t})});}return out;}});} for(const o of L.sort((a,b)=>b.u-a.u))for(let step=0;step<3&&!o.busy()&&o.cap()1,ups=wantLag&&lag?null:o.ups(),fit=ups&&(ups.find(u=>u.cap>=N*o.use)||ups.at(-1)),job=wantLag?lag||fit:fit||lag,was=o.sig(); - if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;}))break; - X.did('ports',o.at+' '+job.w);yield;}}, + if(!job||!X.can('ports',job.cost)||!X.pay('ports',()=>{job.go();return o.sig()!==was;})){KV.rv=null;KV.pu.clear();break;} + KV.rv=null;KV.pu.clear();X.did('ports',o.at+' '+job.w);yield;}}, *optics(X){const at=opsP('optics','at')/100,big=opsP('optics','pick')==='big',gpd=(o,l)=>optG(o,l)/optCost(o); for(const l of S.links){if(l.kind!=='df'||l.ready>S.day||l.eqDown>S.day||l.standby||l.cut>S.day)continue; let cap=dfCap(l);const load=((R.load&&R.load[l.id])||0)*opsAhead(); @@ -242,20 +248,25 @@ const OPS_RUN={ X.pay('optup',()=>{ACT.setChCount({id:l.id,o:o1,n:cnt[o1]-1});ACT.setChCount({id:l.id,o:o2,n:n2}); if((l.ch||[]).filter(k=>k===o2).length===n2)return true;ACT.setChCount({id:l.id,o:o1,n:cnt[o1]});return false;}); if(!(dfCap(l)>was))break;X.did('optswap',l.a+'|'+l.b+' '+fmtCap(optG(o1,l))+'→'+fmtCap(optG(o2,l)));yield;}}}, - *caches(X){const g=opsP('caches','g'); - for(const c of opsPops('caches')){const q=utilityCaches(c);if(!q||!q.add.length)continue; - const want=q.add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9; + // The boxes sorted by POP once: the boxes racked at one POP change no other POP's plan. + *caches(X){const g=opsP('caches','g'),by=new Map();for(const x of S.caches){const a=by.get(x.city);if(a)a.push(x);else by.set(x.city,[x]);} + for(const c of opsPops('caches')){const add=cachePlan(c,by.get(c)||[]);if(!add||!add.length)continue; + const want=add.filter(x=>cacheDem(c,x.net)>=g),free=()=>portsMax(c)-portsUsed(c)+1e-9; for(const x of want){if(cachePortsAdd(c,[x])>free())continue;if(!X.can('caches',0,cacheMo(x)))return;S.caches.push({id:uid(),city:c,net:x.net,site:x.site,...(x.g?{g:x.g}:{})});X.book('caches',0,cacheMo(x));X.did('caches',c);} yield;}}, // Weekly, like a person going through PeeringDB on a Monday: route servers, then every willing member (#192). ix(X){if(S.day%7&&!opsIs('annie'))return;for(const ix of utilityRouteServers()){S.rs[ix]=true;X.did('rs');} for(const row of utilityPeers())for(const id of row.requests){S.peers[id+'@'+row.ix]=true;X.did('peer',row.ix);}}, // Weekly too: every willing network above the threshold, at its own minimum size and lead time (#181). - *pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return;const b=pniBatch(null,opsP('pni','tier'));if(!b)return;const g=opsP('pni','g'),paid=opsP('pni','paid'); + *pni(X){if(S.day%7!==3&&!(opsIs('annie')&&S.day%7===6))return; + // The batch a few networks at a time; if the player acted in between (an action routes), it is made again in one go. + const g0=RW.gen,it=pniBatchRun(null,opsP('pni','tier'));let b;for(;;){const s=it.next();if(s.done){b=s.value;break;}yield;} + if(RW.gen!==g0)b=pniBatch(null,opsP('pni','tier'));if(!b)return;yield;const g=opsP('pni','g'),paid=opsP('pni','paid'); // The traffic a PNI there would take over: what your users at that POP send to the network today over transit, an // exchange or a PNI elsewhere, the same figure the PNI list shows. Not the city's whole demand: a network's own // cache boxes in that POP already serve most of it (#244). - const loc=q=>pniVal(q.net,q.city).want; + // pniVal()'s want, without the rest pniVal() prices (the transit it saves, the port): all the order asks (pniWant()). + const lv=new Map(),loc=q=>{let v=lv.get(q);if(v===undefined)lv.set(q,v=pniWant(q.city,q.net));return v;}; // Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift // let a frame through or waited for a routing, and the batch's quote would order it a second time. for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){ @@ -293,8 +304,15 @@ function opsDarkAgain(y){const l=S.links.find(x=>x.id===y.dark);if(!l||S.biz.som return opsDarkTrial({dark:l.id,s0:R.served,L0:R.l2||{}});} // A wave can carry a promise: diverse paths, no subsea, a latency budget. Try the network without it first. function opsDecomSafe(l){const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; - const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?diversePaths(b.city,b.city2):k==='sharks'?terrestrialPath(b.city,b.city2):k==='lat'?bestLat(b.city,b.city2)<=b.latMax:true); - const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}} + const was=bz.filter(promiseCheck()),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(promiseCheck());}finally{S.links=all;}} +/* Those promises, asked for many customers on one network: each search is made once and shared (a diversity graph, the + land islands, one latency search per city a customer starts from). Same answers as diversePaths(), terrestrialPath() + and bestLat() asked one by one. */ +function promiseCheck(){let dg=null,ti=null,lg=null;const dv=new Map(),ld=new Map(); + const div=(a,b)=>{const k=a+'>'+b;let r=dv.get(k);if(r===undefined)dv.set(k,r=divOn(dg||(dg=divGraph()),a,b));return r;}; + const land=(a,b)=>{if(a===b)return true;ti=ti||terrIslands();const A=ti.get(a);return A!==undefined&&A===ti.get(b);}; + const lat=(a,b)=>{lg=lg||latGraph();if(!ld.has(a))ld.set(a,latRun(lg,a));return latAt(lg,ld.get(a),a,b);}; + return b=>(b.reqs||[]).every(k=>k==='diverse'?div(b.city,b.city2):k==='sharks'?land(b.city,b.city2):k==='lat'?lat(b.city,b.city2)<=b.latMax:true);} // The links between each pair of cities, VXCs left out. function opsPairs(){const by=new Map();for(const l of S.links)if(l.kind!=='vxc'){const k=edgeKey(l);(by.get(k)||by.set(k,[]).get(k)).push(l);}return by;} const opsDecomWaits=()=>[...opsPairs().values()].some(ls=>ls.length>1&&ls.some(l=>l.kind==='wave')); diff --git a/src/game/70-rules/35-pni-orders.js b/src/game/70-rules/35-pni-orders.js index 1e42650..30a7918 100644 --- a/src/game/70-rules/35-pni-orders.js +++ b/src/game/70-rules/35-pni-orders.js @@ -1,13 +1,14 @@ /* 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; +// at: for a batch, where to look up the PNI there already is and the ports in use, which the batch itself never changes. +function pniQuote(city,net,tier,reserved=0,at=null){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); + const ex=at?at.ex(city,net):S.pni.find(p=>p.city===city&&p.net===net),used=at?at.used:portsUsed; 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)});} + else if(slots>0&&used(city)+reserved+slots>portsMax(city)+1e-9)why=tr('ports.no_free_router_ports_in_city',{city:esc(CITY[city].name),u:fmtPorts(used(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; @@ -19,12 +20,18 @@ const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots // A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say). // Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them. const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;}; -function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null; +function pniBatch(net,tier){const g=pniBatchRun(net,tier);for(;;){const s=g.next();if(s.done)return s.value;}} +// The same batch with a place to let a frame through every few networks: the intern's weekly round (95-standing-orders.js). +function* pniBatchRun(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null; const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0; + // Asked of every network at every shared POP: the PNIs by POP and network (the first one, as find() would), and the + // ports in use, counted for every POP in one pass the first time a quote needs them. + const exs=new Map();let use=null;for(const p of S.pni){const k=p.city+'|'+p.net;if(!exs.has(k))exs.set(k,p);} + const at={ex:(c,n)=>exs.get(c+'|'+n),used:c=>(use||(use=portsAt(Object.keys(S.pops)))).get(c)}; // 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)+pniUpSlots(p); - for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city); + let nn=0;for(const n of all?NETS:[NET[net]]){if(++nn%16===0)yield;for(const city of n.pops){if(!S.pops[city])continue;shared.push(city); // Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G. - const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots; - 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);} + const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0,at);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots; + 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,raised};} diff --git a/src/game/70-rules/38-pni-value.js b/src/game/70-rules/38-pni-value.js index 193e8bc..5d5d22c 100644 --- a/src/game/70-rules/38-pni-value.js +++ b/src/game/70-rules/38-pni-value.js @@ -8,12 +8,18 @@ function pniIdx(){if(PNIX&&PNIX.R===R)return PNIX; const ix={},pn={}; for(const c in S.ixp){const nm=ixName(c);for(const id of ixSessions(c)){const a=ix[id]||(ix[id]=[]);if(!a.includes(nm))a.push(nm);}} for(const p of S.pni)(pn[p.net]||(pn[p.net]=[])).push(p); - return PNIX={R,fl:{},ix,pn};} + return PNIX={R,fl:{},all:false,ix,pn};} // One POP's flows by network, added up the first time that POP is asked about. -function pniFlows(c){const X=pniIdx();let m=X.fl[c];if(m)return m;m=X.fl[c]={}; - for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}}; - o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;} - return m;} +// Every POP at once, in one pass over the flows: the intern's weekly PNI round asks about all of them, and one POP at a +// time was a pass per POP. The flows are read straight from routing's columns (R.flc), not made into the objects of R.fl +// (tens of thousands on a big network); each POP's sums still add up its flows in their order. +function pniFlows(c){const X=pniIdx();if(!X.all){X.all=true;const F=X.fl,C=R.flc; + const add=(c,n,rem,gt,gi,gp,gh,ti,ii)=>{const m=F[c]||(F[c]={});let o=m[n];if(!o)o=m[n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}}; + o.u+=rem;o.t+=gt;o.ix+=gi;o.p+=gp;o.h+=gh;if(gt)o.T[ti]=(o.T[ti]||0)+gt;if(gi)o.I[ii]=(o.I[ii]||0)+gi;}; + if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP,FGH,FTI,FII,E}=C; + for(let i=0;ip.city===c):null; if(h)return {k:'here',p:h}; @@ -33,6 +39,16 @@ function pniChip(id,c){const s=pniStat(id,c);let t; /* What a new PNI with `id` at `c` would carry and save per month. It takes your users' traffic there that now leaves over transit, an exchange or a PNI elsewhere, or does not leave at all for want of room, up to its port; transit is billed on the 95th percentile, so the saving is the bill now minus the bill with that much less (commits included). */ +/* pniVal()'s want for network n at POP c (what the intern's weekly round sorts by), without the rest pniFlows() keeps + for the PNI list: the same four sums of the same flows in the same order, in columns by (city, network). One pass, + no objects; null when routing left no columns (an old R), then pniFlows() it is. */ +function pniWant(c,n){const X=pniIdx();if(X.w===undefined){const C=R.flc;X.w=null; + if(C){const {NF,FREM,FCI,FNJ,FGT,FGI,FGP}=C;let K=1;for(let i=0;i=K)K=FNJ[i]+1; + const n4=CITIES.length*K,U=new Float64Array(n4),T=new Float64Array(n4),I=new Float64Array(n4),P=new Float64Array(n4); + for(let i=0;i[id,j]))};}} + const W=X.w;if(!W){const o=pniFlows(c)[n];return o?o.t+o.ix+o.p+o.u:0;} + const ci=CIDX[c],j=W.ni.get(n);if(ci===undefined||j===undefined||j>=W.K)return 0;const k=ci*W.K+j;return W.T[k]+W.I[k]+W.P[k]+W.U[k];} function pniVal(id,c){const o=pniFlows(c)[id]||{t:0,ix:0,p:0,h:0,u:0,T:{},I:{}},want=o.t+o.ix+o.p+o.u; const lo=pniMin(id);let tier=-1;for(let i=lo;i=want)break;} if(tier<0)tier=lo;const g=Math.min(want,PORT[tier].g),gt=Math.min(o.t,g);let saved=0; diff --git a/src/game/70-rules/95-utilities.js b/src/game/70-rules/95-utilities.js index 5e3718c..b007039 100644 --- a/src/game/70-rules/95-utilities.js +++ b/src/game/70-rules/95-utilities.js @@ -15,16 +15,26 @@ function utilityCacheMoves(city){if(!S||!S.pops[city])return [];const groups=new // city cannot even reach, and too few for the ones it uses most. const cityShTab=c=>cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH; const cityNetSh=(c,id)=>(cityShTab(c)[id]||0)*(id==='ggl'&&ruCity(c)?0.5:1); -function cacheDem(c,id){const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;} +// A city's total share only depends on its table and on the Russian throttle, and the tables never change after load: +// summed once per kind of city, not once per network asked about (that was cities × networks² every shift). +const CSH_SUM=new Map(); +function cityShSum(c){const T=cityShTab(c),k=ruCity(c)?1:0;let m=CSH_SUM.get(T);if(!m)CSH_SUM.set(T,m=[null,null]); + if(m[k]===null){let t=0;for(const id in T)t+=cityNetSh(c,id);m[k]=t;}return m[k];} +function cacheDem(c,id){const t=cityShSum(c);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;} // One box per site first, if the city sends the network anything at all; then more boxes while that demand outgrows them // (100G each, #248). -function utilityCaches(city){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={}; - for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;} - for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&cacheDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0); +// boxes: the city's own boxes in their order, when the caller has them sorted by city already (S.caches otherwise). +function cachePlan(city,boxes=S.caches){const p=S&&S.pops[city];if(!p)return null;const sites=p.site2?['a','b']:['a'],add=[],have={}; + // One pass over the boxes: how many per network and site, and the capacity per network (summed in the same order). + const capN={};for(const c of boxes)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;capN[c.net]=(capN[c.net]||0)+cacheG(c);} + for(const n of NETS){if(!n.cache||!((R.demTo[n.id]||0)>=n.cache.min))continue;const dem=cacheDem(city,n.id);if(!(dem>1e-6))continue;const box=sites.map(st=>have[n.id+'@'+st]||0),a0=add.length; sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}}); - const dem=cacheDem(city,n.id),nb=cacheBox(city); - let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb); + const nb=cacheBox(city); + let cap=(capN[n.id]||0)+(add.length-a0)*cacheG(nb); while(cap+1e-9c.net+'@'+c.site).join(','),mo:add.reduce((a,x)=>a+cacheMo(x),0),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; diff --git a/src/game/80-simulation/40-billing.js b/src/game/80-simulation/40-billing.js index b7dae0d..ddf1633 100644 --- a/src/game/80-simulation/40-billing.js +++ b/src/game/80-simulation/40-billing.js @@ -2,7 +2,7 @@ // sample is today's own: leave it out, or every recompute later that day counts today twice and drops a day. const histToday=()=>{const H=S.hist,l=H&&H[H.length-1];return !!l&&l.d===S.day;}; function p95(t,cur,today=histToday()){const a=t.hist||[],n=Math.max(0,a.length-(today&&a.length?1:0)),h=a.slice(Math.max(0,n-29),n).concat([cur]).sort((a,b)=>a-b);return h[Math.max(0,Math.ceil(.95*h.length)-1)];} -function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&dfCap(l)<=0);} +function linkDown(l){return l.cut>S.day||(S.ev.runet>S.day&&ruCity(l.a)!==ruCity(l.b))||(S.ev.gulf>S.day&&((CITY[l.a].qa&&(CITY[l.b].gcc||CITY[l.b].uae))||(CITY[l.b].qa&&(CITY[l.a].gcc||CITY[l.a].uae))))||(l.kind==='vxc'&&!!S.ev.fab&&S.ev.fab[l.prov]>S.day)||(l.kind==='df'&&!dfOn(l));} function remoteCities(){return [...new Set(S.links.filter(l=>l.kind==='vxc').flatMap(l=>[l.a,l.b]))].filter(c=>!S.pops[c]);} function nniUsed(c,prov){return S.links.filter(l=>l.kind==='vxc'&&l.prov===prov&&(l.a===c||l.b===c)).reduce((a,l)=>a+VXC[l.vt].g,0)+S.biz.filter(b=>BIZ_T[b.type].nni&&b.prov===prov&&b.city===c).reduce((a,b)=>a+b.bw,0);} // Monthly price of one connection; compute() sums these, the connections overview lists them. diff --git a/src/game/80-simulation/60-requirements.js b/src/game/80-simulation/60-requirements.js index 8e3aab0..d1e35fb 100644 --- a/src/game/80-simulation/60-requirements.js +++ b/src/game/80-simulation/60-requirements.js @@ -25,22 +25,26 @@ const REQS={ TERR names the game and the routing count it was made for: an action between two steps of the day changes a link only through after(), which routes, so the islands are worked out again; another game, and each question walks. */ let TERR=null; -function terrIslands(){const adj={};for(const l of S.links)if(!linkDown(l)&&!l.sub){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} +function terrIslands(){const adj={};for(const l of S.links)if(!l.sub&&!linkDown(l)){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} const m=new Map();let n=0;for(const c in adj){if(m.has(c))continue;const q=[c];m.set(c,n);for(let h=0;h!linkDown(l)&&!l.sub);const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;} + if(a===b)return true;const A=TERR.m.get(a);return A!==undefined&&A===TERR.m.get(b);}const ls=S.links.filter(l=>!l.sub&&!linkDown(l));const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);}const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;} const reqOk=b=>(b.reqs||[]).every(k=>REQS[k]&&REQS[k].ok(b)); // Some requirements only make sense for some customers: nobody can reach another continent without getting wet. const reqCan=(k,b)=>!REQS[k].can||REQS[k].can(b); function reqList(o){return (o.reqs||[]).map(k=>{const ok=REQS[k].ok(o),lab=typeof REQS[k].l==='function'?REQS[k].l(o):REQS[k].l;return `
${ok?'✓':'✗'} ${esc(lab)}
`;}).join('');} -function diversePaths(a,b){ - const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c); - return disjointRoutes(a,b,S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)));} -function disjointRoutes(a,b,live){const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); - const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);} - const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}} - if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;}; - const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));} +/* diversePaths(): a shortest path by hops over the live links (and VXCs to remote cities), then another one that shares + none of its risks. divGraph() numbers the cities and the risks and lists each city's links once, in list order, as + disjointOn() reads them; divOn() asks it, so many pairs on one network (spots0(), opsDecomSafe()) share one graph. The + second search skips the first path's risks rather than rebuilding the graph without them: the same lists in the same + order, so the same answer. */ +const srlgOf=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); +function divGraph(live){if(!live){const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c);live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b));} + const ix=new Map(),rk=new Map(),adj=[],id=c=>{let i=ix.get(c);if(i===undefined){ix.set(c,i=adj.length);adj.push([]);}return i;}; + for(const l of live){const s=srlgOf(l);let r=rk.get(s);if(r===undefined)rk.set(s,r=rk.size);const u=id(l.a),v=id(l.b);adj[u].push(v,r);adj[v].push(u,r);}return {ix,adj};} +function divOn(g,a,b){if(a===b)return true;const i=g.ix.get(a),j=g.ix.get(b);return i!==undefined&&j!==undefined&&disjointOn(g.adj,i,j);} +function diversePaths(a,b){return divOn(divGraph(),a,b);} +function disjointRoutes(a,b,live){return divOn(divGraph(live),a,b);} // Check buildable geography, not today's POPs, capacity or outages. Parallel land // routes can use separate trenches; all segments of one cable share its risk. let diversityMap=null; diff --git a/src/game/80-simulation/80-geography-and-latency.js b/src/game/80-simulation/80-geography-and-latency.js index 72c8f0f..6e5ee0c 100644 --- a/src/game/80-simulation/80-geography-and-latency.js +++ b/src/game/80-simulation/80-geography-and-latency.js @@ -53,7 +53,24 @@ function waveRoute(a,b,mult,border){const cabs=cablesOk(a,b),sub=isSub(a,b);let function viaSeg(a,b){const cabs=cablesOk(a,b),sub=isSub(a,b);if(!cabs.length)return landMult(a,b)>1?`

${landWhy(a,b)}

`:'';const wr=waveRoute(a,b,1,false); const opts=(sub?[]:[{v:'land',l:`${tr('common.overland')} ${landMult(a,b)>1?landMult(a,b)+'× · ':''}${(kmBetween(a,b)*1.3/200).toFixed(1)} ms`}]).concat(cabs.map(c=>({v:c.cid,l:`${esc(CAB[c.cid].name)} ${CAB[c.cid].price}× · ${(c.km*(CAB[c.cid].lat||1)/200).toFixed(1)} ms${CAB[c.cid].age==='old'?' · '+tr('geography_and_latency.old_cuts_often'):''}`}))); return `

${tr('common.route')}

${opts.map(o=>btn(o.l,'via',{v:o.v},wr&&wr.via===o.v?'pink':'ghost')).join('')}
${wr&&wr.cab?`

${esc(CAB[wr.cab].blurb)} ${tr('geography_and_latency.all_your_waves_on_one_cable')}

`:''}`;} -function bestLat(a,b,f){const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]{let i=ix.get(c);if(i===undefined){ix.set(c,i=deg.length);deg.push(0);}return i;}; + for(const l of S.links){if(linkDown(l)||f&&!f(l))continue;const u=id(l.a),v=id(l.b);E.push(u,v,linkLat(l));deg[u]++;if(v!==u)deg[v]++;} + const n=deg.length,off=new Int32Array(n+1);for(let i=0;i{if(a===b)return 0;const k=g.ix.get(b);return d&&k!==undefined?d[k]:Infinity;}; +function bestLat(a,b,f){return latRun(latGraph(f),a,b);} +// From each of these cities to the ones after it in the list: [[a,b,ms]…], one search per city. +function latPairs(f,g){const G=latGraph(g),o=[];for(let i=0;i { // The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile. const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true; - const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a); + const pb=pniBatchRun;pniBatchRun=function*(...a){const b=yield* pb(...a);window.__b=b;return b;}; window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0; for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;} window.__n=S.pni.length-n0;`; @@ -239,3 +240,61 @@ test('an incident repaired while its routing runs: the failure and the monkey st assert.equal(p.ev('typeof __c.impact'), 'number'); assert.deepEqual(p.errors, []); }); + +test('the cache planner plans what the old formula planned, city by city', (t) => { + const h = open(t, 777); + h.ev(SETUP); + // The formula as it was: the total share summed again for every network, the boxes filtered again for each. + h.ev(`window.oldDem=(c,id)=>{const T=cityShTab(c);let t=0;for(const k in T)t+=cityNetSh(c,k);return t>0?((R.cityDem&&R.cityDem[c])||0)*cityNetSh(c,id)/t:0;}; + window.oldPlan=city=>{const p=S.pops[city],sites=p.site2?['a','b']:['a'],add=[],have={}; + for(const c of S.caches)if(c.city===city){const k=c.net+'@'+(c.site==='b'?'b':'a');have[k]=(have[k]||0)+1;} + for(const n of NETS)if(n.cache&&(R.demTo[n.id]||0)>=n.cache.min&&oldDem(city,n.id)>1e-6){const box=sites.map(st=>have[n.id+'@'+st]||0); + sites.forEach((site,i)=>{if(!box[i]){add.push({net:n.id,site,...cacheBox(city)});box[i]=1;}}); + const dem=oldDem(city,n.id),nb=cacheBox(city); + let cap=S.caches.filter(c=>c.city===city&&c.net===n.id).reduce((a,c)=>a+cacheG(c),0)+add.filter(x=>x.net===n.id).length*cacheG(nb); + while(cap+1e-9i%3);S.krExit=true;for(const c of ['mos','pek','icn'])if(!S.pops[c])S.pops[c]={day:0,bb:{d:1},boost:0,down:0,routers:2,gen:true,rgen:0,site2:true};compute();"); + const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))')); + let boxes = 0; + for (const c of cities) { + const got = h.ev(`JSON.stringify(utilityCaches('${c}').add)`); + assert.equal(got, h.ev(`JSON.stringify(oldPlan('${c}'))`), c); + boxes += JSON.parse(got).length; + for (const id of JSON.parse(h.ev('JSON.stringify(NETS.map(n=>n.id))'))) if (h.ev(`cacheDem('${c}','${id}')!==oldDem('${c}','${id}')`)) assert.fail(`cacheDem ${c} ${id}`); + } + assert.ok(boxes > 50, `boxes planned: ${boxes}`); + assert.deepEqual(h.errors, []); +}); + +test('ports counted for every POP at once, and flows summed from the columns, are what each POP counted alone', (t) => { + const h = open(t, 777); + h.ev(SETUP); + // The old ways: one pass over the whole network per POP, and the flows as objects (R.fl). + h.ev(`window.oldPorts=(c,g)=>{let u=0; + for(const l of S.links){if(l.a!==c&&l.b!==c||l.kind==='vxc')continue;if(l.kind!=='df'){u++;continue;}for(const o of l.ch||[])u+=chPorts(o,c,g);} + for(const t of S.transit)if(t.city===c&&!t.pz)u+=PORT_SLOT(t.tier)*(t.n||1); + for(const x of S.pni)if(x.city===c)u+=PORT_SLOT(x.tier)*(x.n||1); + for(const x of ixIdsIn(c))if(S.ixp[x]!==undefined&&!S.myIx[x])u+=PORT_SLOT(S.ixp[x])*((S.ixn||{})[x]||1); + if(S.myIx[c])u+=1; + u+=cachePorts(c,[],g)+(S.nni||[]).filter(x=>x.city===c).length;return u;}; + window.oldFlows=c=>{const m={};for(const f of R.fl||[]){if(f.junk||f.c!==c)continue;let o=m[f.n];if(!o)o=m[f.n]={t:0,ix:0,p:0,h:0,u:0,T:{},I:{}}; + o.u+=f.rem;o.t+=f.gt;o.ix+=f.gi;o.p+=f.gp;o.h+=f.gh;if(f.gt)o.T[f.ti]=(o.T[f.ti]||0)+f.gt;if(f.gi)o.I[f.ii]=(o.I[f.ii]||0)+f.gi;}return m;};`); + const cities = JSON.parse(h.ev('JSON.stringify(Object.keys(S.pops))')); + for (const g of ['undefined', '0', 'RG.length-1']) { + const all = JSON.parse(h.ev(`JSON.stringify([...portsAt(Object.keys(S.pops),${g})])`)); + assert.deepEqual(all, cities.map((c) => [c, h.ev(`oldPorts('${c}',${g})`)]), `ports, router model ${g}`); + } + assert.ok(h.ev('Object.keys(S.pops).some(c=>portsUsed(c)>10)')); + for (const c of cities) assert.equal(h.ev(`JSON.stringify(pniFlows('${c}'))`), h.ev(`JSON.stringify(oldFlows('${c}'))`), `flows from ${c}`); + assert.ok(h.ev('Object.keys(S.pops).some(c=>Object.keys(pniFlows(c)).length>5)')); + // The intern's weekly PNI round reads only pniVal()'s want, from typed columns (pniWant()): the very same numbers, for + // every network at every POP (and 0 where no flow goes). + const odd = h.ev(`(()=>{const bad=[];let n=0;for(const c in S.pops)for(const id of NET_IDS){const v=pniVal(id,c).want,w=pniWant(c,id);if(v>0)n++; + if(!Object.is(v,w))bad.push(c+'/'+id+' '+v+' '+w);}return JSON.stringify({n,bad:bad.slice(0,5)});})()`); + const r = JSON.parse(odd); + assert.deepEqual(r.bad, [], 'pniWant() is pniVal().want'); + assert.ok(r.n > 50, `pairs with traffic: ${r.n}`); + assert.deepEqual(h.errors, []); +}); diff --git a/tests/fiber-lit-and-latency.test.js b/tests/fiber-lit-and-latency.test.js new file mode 100644 index 0000000..c924927 --- /dev/null +++ b/tests/fiber-lit-and-latency.test.js @@ -0,0 +1,69 @@ +// A fiber's capacity added up per run of identical optics, "is this fiber lit?" answered without adding it up +// (dfOn(), linkDown()), and latency searches over one list of each city's links (latGraph(), latRun(), latPairs(): +// bestLat(), the boutique's routes, latency offers). Same answers as before: the old ways are written out here. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +// The fixture's links as the player's own dark fiber (it has none), lit with 2 to 40 channels of one or two optics. +const GLASS = "S.links.forEach((l,i)=>{l.kind='df';l.own=true;l.sys='roadm';l.ready=0;l.regen=3;const o=['zr4','zr8','tp16','tp32'][i%4];l.ch=Array.from({length:2+i%39},(_,j)=>i%5===0&&j%3===0?'zr4':o);delete l.tier;})"; +// Before: every channel's optG() added up, and the search that walked every link for every city it reached. +const OLD = `window.oldCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,Math.max(0,g)-mwG(l));}; +window.oldLat=(a,b,f)=>{const ls=S.links.filter(l=>!linkDown(l)&&(!f||f(l)));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k] `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day; + for(const l of S.links){const r=rnd();if(r<.06)l.cut=D+5;else if(r<.14){if(rnd()<.4)l.ch=l.ch.slice(0,1);l.chFail={o:rnd()<.5&&l.ch.length?l.ch[l.ch.length-1]:rnd()<.5?'tp32':null,until:rnd()<.8?D+3:D-1};} + else if(r<.18)l.eqDown=D+2;else if(r<.22)l.ready=D+4;else if(r<.28)l.ch=l.ch.slice(0,Math.floor(rnd()*3));else if(r<.32)l.ch=l.ch.map((c,i)=>i%2?c:'zr8'); + else if(r<.36){l.sub=true;l.km=2000+Math.floor(rnd()*9000);if(rnd()<.5)l.subterminal=D-1;if(rnd()<.5)l.subengineering=D-1;} + if(rnd()<.15)S.biz.push({type:'mwave',link:l.id,slots:1+Math.floor(rnd()*30),g:rnd()<.5?100:400});}})()`; + +test('a fiber is lit, and carries, what adding up every channel said', () => { + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${GLASS};${OLD}`); + let lit0 = 0, dark = 0; + for (let v = 0; v < 6; v++) { + ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(v)};S.day+=${v}`); + const r = JSON.parse(ev(`JSON.stringify(S.links.map(l=>[oldCap(l),dfCap(l),dfOn(l),linkDown(l),l.cut>S.day]))`)); + for (const [want, cap, on, down, cut] of r) { + assert.equal(cap, want); + assert.equal(on, want > 0); + assert.equal(down, cut || !(want > 0)); + if (on) lit0++; else dark++; + } + } + assert.ok(lit0 > 600 && dark > 30, `lit ${lit0}, dark ${dark}`); + assert.deepEqual(errors, []); +}); + +test('latency searches give what walking every link gave: bestLat, every pair at once, the boutique\'s routes', () => { + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`); + const P = "Object.keys(S.pops).slice(0,25).concat(FIN.filter(c=>S.pops[c]))"; + const check = (f) => JSON.parse(ev(`(()=>{const P=${P},f=${f},bad=[];let n=0; + for(let i=0;i 150, `pairs with a path: ${r.n}`); + ev("S.links.forEach((l,i)=>{if(i%4===0)l.cut=S.day+3;})"); + r = check("l=>l.kind!=='vxc'"); + assert.deepEqual(r.bad, []); + ev(`S=migrate(JSON.parse(${lit(BIG)}));${GLASS};${MESS(2)};S.mode='normal';delete S.scn;S.charter='boutique'`); + r = check('ownGlass'); + assert.deepEqual(r.bad, []); + assert.ok(r.n > 50, `pairs over own glass: ${r.n}`); + // The boutique's routes: each financial pair, its own glass against the best leased latency. In trouble, then not. + const SOL = `(()=>{const f=FIN.filter(c=>S.pops[c]),v=[];for(let i=0;i= 1, `routes that beat leased: ${want}`); + assert.deepEqual(errors, []); +}); diff --git a/tests/intern-personas.test.js b/tests/intern-personas.test.js index f663cf1..e157c96 100644 --- a/tests/intern-personas.test.js +++ b/tests/intern-personas.test.js @@ -37,7 +37,7 @@ test('Annie peers every day and orders PNIs twice a week; the others weekly', t ev("S.ops.on.ix=true;S.day=15;opsDay(S.day)"); assert.equal(ev('Object.keys(S.rs).length>0'), want, `${id} on a Tuesday`); // How often the PNI order looks for networks to order from, over one week. - ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}"); + ev("S.ops.on.ix=false;S.ops.on.pni=true;window.__pb=0;pniBatch=function(){__pb++;return null;};if(typeof pniBatchRun==='function')pniBatchRun=function*(){__pb++;return null;};for(let d=21;d<28;d++){S.day=d;opsDay(d);}"); assert.equal(ev('__pb'), want ? 2 : 1, `${id}: PNI rounds a week`); assert.deepEqual(errors, []); } diff --git a/tests/shared-promise-checks.test.js b/tests/shared-promise-checks.test.js new file mode 100644 index 0000000..9ced4d0 --- /dev/null +++ b/tests/shared-promise-checks.test.js @@ -0,0 +1,88 @@ +// Diverse paths, a land path and a latency budget asked for many pairs on one network: the offers spotted for +// sovereign clouds (spots0()) and the intern's check before taking a wave out (opsDecomSafe()) build one graph per +// network and ask it for every pair (divGraph()/divOn(), promiseCheck()). Same answers as before: the old ways are +// written out here. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); +// Before: each question filtered the links again and built both searches' graphs from lists. +const OLD = `window.oldDiv=(a,b)=>{const rem=remoteCities(),ok=c=>popUp(c)||rem.includes(c),live=S.links.filter(l=>!linkDown(l)&&ok(l.a)&&ok(l.b)); + const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); + const bfs=ls=>{const adj={};for(const l of ls){(adj[l.a]=adj[l.a]||[]).push([l.b,l]);(adj[l.b]=adj[l.b]||[]).push([l.a,l]);} + const prev={[a]:null},q=[a];while(q.length){const u=q.shift();if(u===b)break;for(const [v,l] of adj[u]||[])if(!(v in prev)){prev[v]=l;q.push(v);}} + if(!(b in prev))return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=l.a===v?l.b:l.a;}return path;}; + const p1=bfs(live);if(!p1)return false;const used=new Set(p1.map(srlg));return !!bfs(live.filter(l=>!used.has(srlg(l))));}; +window.oldLand=(a,b)=>{const adj={};for(const l of S.links.filter(l=>!l.sub&&!linkDown(l))){(adj[l.a]=adj[l.a]||[]).push(l.b);(adj[l.b]=adj[l.b]||[]).push(l.a);} + const seen=new Set([a]),q=[a];while(q.length){const u=q.shift();if(u===b)return true;for(const v of adj[u]||[])if(!seen.has(v)){seen.add(v);q.push(v);}}return false;}; +window.oldLat=(a,b)=>{const ls=S.links.filter(l=>!linkDown(l));const dist={[a]:0},done=new Set();for(;;){let u=null,ud=Infinity;for(const k in dist)if(!done.has(k)&&dist[k]{const bz=S.biz.filter(b=>(b.reqs||[]).some(k=>k==='diverse'||k==='sharks'||k==='lat')&&b.city2);if(!bz.length)return true; + const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true); + const was=bz.filter(chk),all=S.links;S.links=all.filter(x=>x!==l);try{return was.every(chk);}finally{S.links=all;}};`; +// Seeded trouble: cuts, POPs down, trenches shared by several links, a VXC to a city with no POP. +const MESS = (v) => `(()=>{let x=${v * 7919 + 13};const rnd=()=>{x=(x*1103515245+12345)%2147483648;return x/2147483648;};const D=S.day; + for(const l of S.links)if(rnd()<.1)l.cut=D+3;for(const c in S.pops)if(rnd()<.06)S.pops[c].down=D+2; + const ls=S.links.filter(l=>!l.sub);for(let i=${v};if.cities.some(c=>S.pops[c])&&f.cities.some(c=>!S.pops[c]));if(p&&${v}%2){const a=p.cities.find(c=>S.pops[c]),b=p.cities.find(c=>!S.pops[c]); + S.links.push({id:'vx'+${v},a,b,kind:'vxc',prov:p.id,vt:'1g',km:kmBetween(a,b),sub:isSub(a,b),mo:1,cut:0,day:0});}})()`; + +test('diverse paths: one graph for every pair answers like a search per pair, and spots the same sovereign clouds', () => { + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`); + let yes = 0, no = 0; + for (let v = 0; v < 6; v++) { + ev(`S=migrate(JSON.parse(${lit(BIG)}));${v ? MESS(v) : ''}`); + const r = JSON.parse(ev(`(()=>{const C=Object.keys(S.pops).filter((c,i)=>i%3===0).concat(S.links.filter(l=>l.kind==='vxc').map(l=>l.b),['nowhere']),g=divGraph(),bad=[];let y=0,n=0; + for(const a of C)for(const b of C){const w=oldDiv(a,b);if(diversePaths(a,b)!==w||divOn(g,a,b)!==w)bad.push(a+'-'+b);w?y++:n++;} + const by={};for(const c of Object.keys(S.pops).filter(bizCity))(by[CITY[c].cc]=by[CITY[c].cc]||[]).push(c);const sov=[]; + for(const cs of Object.values(by))for(let i=0;is.t==='sov').map(s=>s.a+'-'+s.b);return JSON.stringify({y,n,bad:bad.slice(0,5),sov,got});})()`)); + assert.deepEqual(r.bad, [], `state ${v}`); + assert.deepEqual(r.got, r.sov, `sovereign clouds, state ${v}`); + yes += r.y; no += r.n; + } + assert.ok(yes > 300 && no > 1000, `diverse ${yes}, not ${no}`); + assert.deepEqual(errors, []); +}); + +test('taking a wave out: the shared check refuses what asking customer by customer refused, for each promise', () => { + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();${OLD}`); + // Customers between linked POPs: diverse paths, afraid of sharks, a latency budget just above today's best. + const BIZ = `(()=>{const ls=S.links.filter(l=>S.pops[l.a]&&S.pops[l.b]);let n=0;for(let i=0;i{const P=Object.keys(S.pops),H=P.filter((c,i)=>i%25===0);let n=0;for(const a of H)for(const b of P)if(a!==b)for(const k of ['diverse','sharks','lat']){const o={id:'hb'+n++,city:a,city2:b,type:'l2',bw:1,reqs:[k]}; + if(k==='lat')o.latMax=n%2?oldLat(a,b):oldLat(a,b)*0.995;S.biz.push(o);} + const chk=b=>(b.reqs||[]).every(k=>k==='diverse'?oldDiv(b.city,b.city2):k==='sharks'?oldLand(b.city,b.city2):k==='lat'?oldLat(b.city,b.city2)<=b.latMax:true); + const pc=promiseCheck(),bz=S.biz.filter(b=>/^hb/.test(b.id)),w=bz.map(chk);S.biz=S.biz.filter(b=>!/^hb/.test(b.id)); + return JSON.stringify({bad:bz.filter((b,i)=>pc(b)!==w[i]).map(b=>b.id).slice(0,5),yes:w.filter(Boolean).length,n:w.length});})()`)); + assert.deepEqual(hub.bad, [], `hubs, state ${v}`); + assert.ok(hub.yes > 50 && hub.n - hub.yes > 50, JSON.stringify(hub)); + const r = JSON.parse(ev(`(()=>{const bad=[],why=[],all=S.biz;for(const l of S.links.slice(0,60)){const w=oldSafe(l);if(opsDecomSafe(l)!==w)bad.push(l.id); + if(!w)for(const k of ['diverse','sharks','lat']){S.biz=all.filter(b=>/^pc/.test(b.id)&&b.reqs[0]===k);if(!oldSafe(l))why.push(k);S.biz=all;}} + return JSON.stringify({bad,why});})()`)); + assert.deepEqual(r.bad, [], `state ${v}`); + for (const k of r.why) refused[k]++; + } + for (const k in refused) assert.ok(refused[k] >= 2, `refused for ${k}: ${JSON.stringify(refused)}`); + assert.deepEqual(errors, []); +}); + +test('latency searches at the edges: a city with no link, the same city twice, a city nobody reaches', () => { + const { ev, errors } = load({ seed: 3 }); + ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();`); + const r = JSON.parse(ev(`(()=>{const lone=CITIES.find(c=>!S.links.some(l=>l.a===c.id||l.b===c.id)).id,p=S.links[0].a,g=latGraph(),d=latRun(g,p); + return JSON.stringify([bestLat(lone,lone),bestLat(p,p),bestLat(lone,p),bestLat(p,lone),latRun(g,lone),latAt(g,d,p,p),latAt(g,d,p,lone),latAt(g,null,lone,p), + latPairs([lone,p,lone]).map(x=>x[2])]);})()`)); + assert.deepEqual(r, [0, 0, null, null, null, 0, null, null, [null, 0, null]]); + assert.deepEqual(errors, []); +}); From d971ded259e2e6a7ee7886d11bcfe5a46998eaab Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sun, 8 Nov 2026 17:57:27 +0000 Subject: [PATCH 10/20] Hold the lay ship through a construction delay instead of restarting the lay (#322) A delay that hit your own subsea cable while it was being laid moved the whole laying stretch later: the ship vanished, the laid km went back to zero and the survey and factory could be hurried and paid for again. The delay now holds the ship where it is (l.lay: start, share laid, resume day), so laying picks up after the delay. Old saves without the field lay as before; sanitize() repairs or drops it. --- CHANGELOG.md | 1 + src/game/10-catalog/60-reach-and-subsea.js | 2 +- src/game/80-simulation/50-sanitize.js | 5 +- src/game/85-incidents/50-cable-ships.js | 8 ++- src/game/88-days/10-day-tick.js | 2 +- tests/lay-ship-delay.test.js | 75 ++++++++++++++++++++++ 6 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 tests/lay-ship-delay.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index d0fb62a..36a135e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- A delay while your own subsea cable is being laid now holds the lay ship where it is, instead of sending it back to port and starting the laying over. The cable already on the seabed stays there, the build simply finishes later, and there is nothing to pay twice (#322). - While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. - A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds. - At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. diff --git a/src/game/10-catalog/60-reach-and-subsea.js b/src/game/10-catalog/60-reach-and-subsea.js index 8d63b91..a00410d 100644 --- a/src/game/10-catalog/60-reach-and-subsea.js +++ b/src/game/10-catalog/60-reach-and-subsea.js @@ -15,7 +15,7 @@ const subUpgradeReady=(l,k)=>l.kind==='df'&&l.sub&&l.own&&Number.isFinite(l['sub const subUpgradeCost=(l,k)=>SUB_UPGRADES[k].cost+(k==='engineering'?Math.round(l.km*1000):0); // Pending transmission work follows the construction schedule. Keep the actual // shift (the last crew purchase can save fewer than 30 days) and completed work. -function setCableReady(l,ready,day=S.day){const shift=ready-l.ready; +function setCableReady(l,ready,day=S.day){const shift=ready-l.ready;layHold(l,shift,day); if(l.kind==='df'&&l.own&&l.sub)for(const k of Object.keys(SUB_UPGRADES)){ const f='sub'+k;if(Number.isFinite(l[f])&&l[f]>day)l[f]=Math.max(day+1,l[f]+shift); }l.ready=ready; diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index fff9a44..7e33b48 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -76,7 +76,10 @@ function sanitize(s){ for(const i of s.inc){if(i.type!=='cut'||i.st==null){for(const k of ['ship','seaq','st','sw','sp','sl'])delete i[k];continue;} i.st=clamp(num(i.st,0.5),0.03,0.97);i.sw=int(i.sw,1,30,4);i.sp=int(i.sp,0,60,0);i.sl=typeof i.sl==='string'?i.sl.slice(0,40):'';i.rushed=!!i.rushed||undefined; if(i.ship!=null&&!(own(SHIP,i.ship)&&o[i.ship]&&o[i.ship].inc===i.id))i.ship=null;if(i.ship==null){i.ship=null;i.seaq=1;}else delete i.seaq;} - for(const l of s.links)if(l.ship2&&l.kind==='df'&&l.own&&l.sub)l.ship2=1;else delete l.ship2;} + for(const l of s.links)if(l.ship2&&l.kind==='df'&&l.own&&l.sub)l.ship2=1;else delete l.ship2; + // A lay ship held by a delay (#322): only on your own subsea cable still being laid. + for(const l of s.links){const v=l.lay;if(v===undefined)continue;if(!(v&&typeof v==='object'&&!Array.isArray(v)&&l.kind==='df'&&l.own&&l.sub&&l.ready>s.day)){delete l.lay;continue;} + const t=Math.round(clamp(num(v.t,s.day),0,l.ready));l.lay={s:Math.round(clamp(num(v.s,s.day),0,Math.min(s.day,t))),q:clamp(num(v.q,0),0,1),t};}} s.loans=s.loans.filter(l=>l&&own(BANKS,l.bank));for(const l of s.loans){if(l.model!==undefined&&!['balloon','storm','transit','astro'].includes(l.model))delete l.model;for(const k of ['apr0','cut','share'])if(l[k]!==undefined&&!isFinite(+l[k]))delete l[k];if(!Array.isArray(l.covs))l.covs=[];l.covs=l.covs.filter(c=>own(COVS,c));}s.loanOffers=s.loanOffers.filter(l=>l&&own(BANKS,l.bank)); s.usedNames=[...new Set(s.usedNames.filter(x=>typeof x==='string'))];s.log=s.log.filter(e=>e&&typeof e.t==='string').slice(0,LOG_KEEP).map(e=>{const o=e.o&&typeof e.o==='object'&&e.o.a==='inbox'?{a:'tab',v:'nets'}:e&&e.o&&typeof e.o==='object'&&LOG_OPEN.includes(e.o.a)?(e.o.a==='bank'||e.o.a==='ops'?{a:e.o.a}:typeof e.o.v==='string'&&e.o.v.length<=64&&(e.o.a!=='city'||isCity(e.o.v))&&(e.o.a!=='tab'||LOG_TABS.includes(e.o.v))?{a:e.o.a,v:e.o.v}:null):null; return {id:typeof e.id==='string'&&e.id.length<=40?e.id:uid(),d:num(e.d,0),t:e.t.slice(0,600),h:typeof e.h==='string'?e.h.slice(0,200):'',k:LOG_KINDS.includes(e.k)?e.k:'',at:Number.isFinite(+e.at)?+e.at:0,o,n:int(e.n,1,9999,1)};}); diff --git a/src/game/85-incidents/50-cable-ships.js b/src/game/85-incidents/50-cable-ships.js index 02febde..d83ca62 100644 --- a/src/game/85-incidents/50-cable-ships.js +++ b/src/game/85-incidents/50-cable-ships.js @@ -73,7 +73,11 @@ function shipStatus(i){if(!shipSea(i))return '';const l=shipLink(i);if(!l)return /* Laying your own subsea cable: the last part of the build is a lay ship at sea, about 150 km a day. A second ship, booked before laying starts, works from the other end and halves that part; nothing at sea speeds up the survey, the permits or the cable factory. */ -const layDays=l=>Math.max(1,Math.ceil((l.km||0)/LAY_KMD)),layLen=l=>l.ship2?Math.ceil(layDays(l)/2):layDays(l),layStart=l=>l.ready-layLen(l); +const layDays=l=>Math.max(1,Math.ceil((l.km||0)/LAY_KMD)),layLen=l=>l.ship2?Math.ceil(layDays(l)/2):layDays(l),layStart=l=>l.lay?l.lay.s:l.ready-layLen(l); +/* A delay once the ship is at sea (#322) holds it where it is: l.lay = {s: the day laying began, q: the share laid, + t: the day it lays on}. Without it, laying is simply the last layLen() days before ready. */ +function layHold(l,shift,day){if(!layOwn(l)||!(shift>0)||l.ready<=day||dayl.kind==='df'&&l.own&&l.sub; const layName=(l,k=0)=>{let h=0;for(const ch of String(l.id))h=(h*31+ch.charCodeAt(0))>>>0;return LAY_SHIPS[(h+k)%LAY_SHIPS.length];}; function layQuote(l){if(!layOwn(l)||l.ship2||S.day>=layStart(l)||l.ready<=S.day+1)return null;const save=Math.floor(layDays(l)/2);if(save<1)return null;return {save,cost:SHIP_MOB+save*LAY_DAY};} @@ -83,4 +87,4 @@ function layQuote(l){if(!layOwn(l)||l.ship2||S.day>=layStart(l)||l.ready<=S.day+ const PREP_STEP=30,prepMin=l=>leadDays(Math.round(60+(l.km||0)*0.012)),prepCost=l=>Math.round((500000+(l.km||0)*60)*hwMul('build')), prepFloor=l=>Math.max(S.day+1,(l.day||0)+prepMin(l))+layLen(l), prepSteps=l=>layOwn(l)&&l.ready>S.day&&S.dayclamp((T-layStart(l))/layLen(l),0,1); +const layDone=(l,T)=>l.lay?l.lay.q+(1-l.lay.q)*clamp((T-l.lay.t)/Math.max(1,l.ready-l.lay.t),0,1):clamp((T-layStart(l))/layLen(l),0,1); diff --git a/src/game/88-days/10-day-tick.js b/src/game/88-days/10-day-tick.js index 24e0c78..572e7ed 100644 --- a/src/game/88-days/10-day-tick.js +++ b/src/game/88-days/10-day-tick.js @@ -61,7 +61,7 @@ function* dayPost(d){ S.hist=S.hist||[];S.hist.push({d,dem:+R.demand.toFixed(2),srv:+R.served.toFixed(2),c:+(R.egT.c||0).toFixed(2),p:+(R.egT.p||0).toFixed(2),ix:+(R.egT.ix||0).toFixed(2),t:+(R.egT.t||0).toFixed(2),l2:+(R.egT.l2||0).toFixed(2),rev:Math.round(R.revMo),cost:Math.round(R.costMo),cash:Math.round(S.cash),inc:S.inc.length});if(S.hist.length>180)S.hist.shift(); {const top=custLevel();if(top>(S.lvl||1)){for(let lv=(S.lvl||1)+1;lv<=top;lv++){track('level_'+lv);toast(tr('day_tick.customer_level_lv_name_new_customers',{lv,name:LEVELS[lv-1].n,unlock:LEVELS[lv-1].unlock})+`
${esc(LEVELS[lv-1].q)}`,'goal');}S.lvl=top;sfx('coin');}} for(const l of S.links){if(l.kind!=='df')continue; - if(l.ready===d){toast(`${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.open'),act:'selLink',args:{id:l.id}}]);sfx('coin');} + if(l.ready===d){delete l.lay;toast(`${l.own?tr('day_tick.your_fiber_is_finished_a_b',{a:CITY[l.a].name,b:CITY[l.b].name}):tr('day_tick.dark_fiber_handed_over_a_b',{a:CITY[l.a].name,b:CITY[l.b].name})}
${(l.ch||[]).length?tr('day_tick.channels_are_lighting_up_now'):tr('day_tick.it_is_dark_add_optics_to')}`,'goal',[{l:tr('common.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+leadDays(extra));toast(tr('day_tick.construction_delay_n_days_why_a',{n:leadDays(extra),why:pick(l.sub?SEA_DELAYS.map(x=>tr(x)):[tr('day_tick.archaeologists_found_a_roman'),tr('day_tick.a_protected_hamster_species_lives'),tr('day_tick.the_railway_changed_its_mind_about'),tr('day_tick.the_drilling_crew_hit_a_granite'),tr('day_tick.a_town_council_wants_a_public'),tr('day_tick.somebody_else_s_gas_main_was'),tr('day_tick.the_permit_office_lost_your_permit')]),a:CITY[l.a].name,b:CITY[l.b].name}),'bad');}} // DDoS protection SLA: a protected customer under attack who goes down, or is blackholed, is paid out (once per attack). for(const a of ddosAll()){ diff --git a/tests/lay-ship-delay.test.js b/tests/lay-ship-delay.test.js new file mode 100644 index 0000000..336da12 --- /dev/null +++ b/tests/lay-ship-delay.test.js @@ -0,0 +1,75 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// #322: a construction delay that hits your own subsea cable while the lay ship is at sea holds the ship where it is. +// It used to move the whole laying stretch later: the ship vanished, the laid km went back to zero and the survey and +// factory could be hurried (and paid for) all over again. +const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.day=200;S.nextFail=S.nextEvent=1e8;for(const g of GOALS)S.done[g.id]=0;"; +const own = "S.links=[{id:'own',a:'cpt',b:'bue',kind:'df',own:true,sub:true,sys:'roadm',km:6000,ch:[],day:200,ready:800,cut:0,mo:1}];"; + +test('#322 a delay while laying holds the lay ship; it does not start over', () => { + const { ev, dom, errors } = load(); + ev(start + own); + assert.equal(ev('layStart(S.links[0])'), 760); + ev("S.day=770"); + const laid = ev('layDone(S.links[0],S.day)'); + assert.equal(laid, 0.25); + // A storm: 20 days late, as the daily construction delay does it. + ev("setCableReady(S.links[0],S.links[0].ready+20)"); + assert.equal(ev('S.links[0].ready'), 820); + assert.ok(ev('S.day>=layStart(S.links[0])'), 'still laying: the ship stays on the map'); + assert.equal(ev('layDone(S.links[0],S.day)'), laid, 'nothing laid is lost'); + assert.equal(ev('prepSteps(S.links[0])'), 0, 'no paying for the survey and factory again'); + assert.equal(ev('layQuote(S.links[0])'), null); + ev("UI.sel={type:'link',id:'own'};renderPanel()"); + const panel = () => dom.window.document.querySelector('#panelBody').textContent; + assert.match(panel(), /at sea, laying/); + assert.match(panel(), /1,500 of 6,000 km/); + assert.doesNotMatch(panel(), /Survey, permits and the cable factory|Hurry/); + // The ship waits out the delay, then lays the other 30 days' worth, never going backwards. + let prev = laid; + for (let d = 770; d < 820; d++) { + ev('S.day=' + d); + const q = ev('layDone(S.links[0],S.day)'); + assert.ok(q >= prev, `day ${d}: ${q} < ${prev}`); + assert.ok(ev('S.day>=layStart(S.links[0])'), `day ${d}: the ship is at sea`); + if (d <= 790) assert.equal(q, laid, `day ${d}: waiting out the storm`); + prev = q; + } + assert.equal(ev('layDone(S.links[0],819.5)') < 1, true); + assert.equal(ev('layDone(S.links[0],820)'), 1); + // A second delay during the wait adds to it. + ev(start + own + "S.day=770;setCableReady(S.links[0],810);S.day=780;setCableReady(S.links[0],820)"); + assert.equal(ev('S.links[0].lay.t'), 790, 'held until 780, then 10 days more'); + assert.equal(ev('layDone(S.links[0],790)'), 0.25); + assert.ok(ev('layDone(S.links[0],791)') > 0.25); + assert.equal(ev('layDone(S.links[0],820)'), 1); + assert.deepEqual(errors, []); +}); + +test('#322 a held lay ship survives a save, and bad saved values are repaired', () => { + const { ev, errors } = load(); + ev(start + own + "S.day=770;setCableReady(S.links[0],820)"); + const q = ev('layDone(S.links[0],795)'); + ev('S=migrate(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('layDone(S.links[0],795)'), q); + assert.equal(ev('layDone(S.links[0],770)'), 0.25); + // Junk from an edited save, or on a cable that is not your own subsea build, goes away. + ev("S.links[0].lay={s:'x',q:7,t:-5};S=migrate(JSON.parse(JSON.stringify(S)))"); + const l = JSON.parse(ev('JSON.stringify(S.links[0].lay)')); + assert.ok(l.q >= 0 && l.q <= 1 && l.s <= 770 && l.t <= 820, JSON.stringify(l)); + ev("S.links[0].lay=[1];S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.links[0].lay'), undefined); + ev("S.links[0].sub=false;S.links[0].lay={s:760,q:.5,t:790};S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.links[0].lay'), undefined); + // A finished cable drops it. + ev(start + own + "S.day=770;setCableReady(S.links[0],820);S.day=819;dayTick()"); + assert.equal(ev('S.links[0].ready<=S.day'), true); + assert.equal(ev('S.links[0].lay'), undefined); + // Old saves (no lay field) lay as before. + ev(start + own + "S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('layStart(S.links[0])'), 760); + assert.equal(ev('layDone(S.links[0],780)'), 0.5); + assert.deepEqual(errors, []); +}); From 71e7dcec59a2e70382411151eddea297117f66c7 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sun, 8 Nov 2026 17:57:32 +0000 Subject: [PATCH 11/20] Say how to reach a coast where no subsea cable lands yet (#321) Iqaluit, Adamstown, Murmansk and the Russian Arctic towns have a beach but no cable, so the link modal listed nobody to hop through ("Cables from Iqaluit reach . Hop through one of those."), and from the other side it suggested hops that could never get there. Now it says to go overland when a road leads in, or that only your own cable reaches it, with the own-cable button (or its level hint) underneath. --- CHANGELOG.md | 1 + site/i18n/de.js | 2 ++ site/i18n/es.js | 2 ++ site/i18n/fr.js | 2 ++ site/i18n/it.js | 2 ++ site/i18n/pt.js | 2 ++ src/game/95-modals/70-link-modal.js | 5 +++- src/i18n/en.js | 2 ++ tests/link-modal-no-cable.test.js | 39 +++++++++++++++++++++++++++++ 9 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 tests/link-modal-no-cable.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index d0fb62a..86dbb45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Linking to a coast where no subsea cable lands yet, like Iqaluit, now says how you can get there (overland, or with a cable of your own) instead of listing no cities to hop through (#321). - While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. - A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds. - At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. diff --git a/site/i18n/de.js b/site/i18n/de.js index d780960..a6a5f86 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -2745,6 +2745,8 @@ "link_modal.no_circuit_crosses_between_north_and":"Zwischen Nord- und Südkorea gibt es keine Leitung, und kein Carrier verkauft dir eine. Pjöngjang erreicht die Welt über China und Russland.", "link_modal.no_subsea_cable_lands_in_both":"Kein Seekabel landet sowohl in {a} als auch in {b} an. Kabel aus {a} erreichen {list}. Nimm den Weg über eine dieser Städte.", "link_modal.no_subsea_cable_lands_in_city":"In {city} landet kein Seekabel an. Die nächste Landestation ist {near}: Verleg zuerst Glasfaser dorthin und nimm dann von dort ein Kabel.", +"link_modal.no_subsea_cable_lands_in_city_land":"In {city} landet noch kein Seekabel an. Komm über Land hin oder verleg dein eigenes Seekabel.", +"link_modal.no_subsea_cable_lands_in_city_own":"In {city} landet noch kein Seekabel an, und keine Straße und keine Glasfaser führen über Land dorthin. Nur ein eigenes Seekabel kommt da hin.", "link_modal.nobody_sells_capacity_between_kyiv":"Niemand verkauft Kapazität zwischen Kyjiw und Moskau, und niemand wird es tun. Route stattdessen über Warschau, Bukarest oder Helsinki.", "link_modal.not_without_a_license":"Nicht ohne Lizenz", "link_modal.premium_crossing_60_3_loss":"Premium-Übergang +60 % · ~3 % Verlust", diff --git a/site/i18n/es.js b/site/i18n/es.js index 44de436..6c8f123 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -2743,6 +2743,8 @@ "link_modal.no_circuit_crosses_between_north_and":"Ningún circuito cruza entre Corea del Norte y Corea del Sur, y ningún operador te venderá uno. Pyongyang llega al mundo a través de China y Rusia.", "link_modal.no_subsea_cable_lands_in_both":"Ningún cable submarino aterriza en {a} y {b} a la vez. Los cables de {a} llegan a {list}. Salta por uno de esos.", "link_modal.no_subsea_cable_lands_in_city":"Ningún cable submarino aterriza en {city}. La estación de aterrizaje más cercana es {near}: tiende fibra hasta allí primero y luego toma un cable desde ella.", +"link_modal.no_subsea_cable_lands_in_city_land":"Ningún cable submarino aterriza todavía en {city}. Llega por tierra o tiende tu propio cable submarino.", +"link_modal.no_subsea_cable_lands_in_city_own":"Ningún cable submarino aterriza todavía en {city}, y ninguna carretera ni fibra llega por tierra. Solo un cable submarino propio puede llegar allí.", "link_modal.nobody_sells_capacity_between_kyiv":"Nadie vende capacidad entre Kiev y Moscú, y nadie va a hacerlo. Rodea por Varsovia, Bucarest o Helsinki.", "link_modal.not_without_a_license":"No sin licencia", "link_modal.premium_crossing_60_3_loss":"Cruce premium +60 % · ~3 % de pérdida", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 069032e..4598446 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -2743,6 +2743,8 @@ "link_modal.no_circuit_crosses_between_north_and":"Aucun circuit ne passe entre la Corée du Nord et la Corée du Sud, et aucun opérateur ne t'en vendra un. Pyongyang rejoint le monde par la Chine et la Russie.", "link_modal.no_subsea_cable_lands_in_both":"Aucun câble sous-marin n’atterrit à la fois à {a} et à {b}. Les câbles partant de {a} vont vers {list}. Fais escale dans l’une de ces villes.", "link_modal.no_subsea_cable_lands_in_city":"Aucun câble sous-marin n’atterrit à {city}. La station d’atterrissement la plus proche est {near} : amène d’abord la fibre jusque-là, puis prends un câble depuis là-bas.", +"link_modal.no_subsea_cable_lands_in_city_land":"Aucun câble sous-marin n’atterrit encore à {city}. Arrive par voie terrestre, ou pose ton propre câble sous-marin.", +"link_modal.no_subsea_cable_lands_in_city_own":"Aucun câble sous-marin n’atterrit encore à {city}, et aucune route ni fibre n’y mène par voie terrestre. Seul ton propre câble sous-marin peut y arriver.", "link_modal.nobody_sells_capacity_between_kyiv":"Personne ne vend de capacité entre Kyiv et Moscow, et personne ne le fera. Passe plutôt par Warsaw, Bucharest ou Helsinki.", "link_modal.not_without_a_license":"Pas sans licence", "link_modal.premium_crossing_60_3_loss":"Passage premium +60 % · ~3 % de perte", diff --git a/site/i18n/it.js b/site/i18n/it.js index 3469d49..edb8ab5 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -2743,6 +2743,8 @@ "link_modal.no_circuit_crosses_between_north_and":"Nessun circuito attraversa il confine tra Corea del Nord e Corea del Sud, e nessun operatore te ne venderà uno. Pyongyang raggiunge il mondo attraverso Cina e Russia.", "link_modal.no_subsea_cable_lands_in_both":"Nessun cavo sottomarino approda sia a {a} che a {b}. I cavi da {a} raggiungono: {list}. Fai tappa in una di queste.", "link_modal.no_subsea_cable_lands_in_city":"Nessun cavo sottomarino approda a {city}. La stazione di approdo più vicina è {near}: porta prima la fibra fin lì, poi prendi un cavo da lì.", +"link_modal.no_subsea_cable_lands_in_city_land":"Nessun cavo sottomarino approda ancora a {city}. Arrivaci via terra, oppure posa un cavo sottomarino tutto tuo.", +"link_modal.no_subsea_cable_lands_in_city_own":"Nessun cavo sottomarino approda ancora a {city}, e nessuna strada o fibra ci arriva via terra. Solo un cavo sottomarino tutto tuo può arrivarci.", "link_modal.nobody_sells_capacity_between_kyiv":"Nessuno vende capacità tra Kyiv e Moscow, e nessuno lo farà mai. Passa invece da Warsaw, Bucharest o Helsinki.", "link_modal.not_without_a_license":"Non senza una licenza", "link_modal.premium_crossing_60_3_loss":"Attraversamento premium +60% · ~3% di perdita", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 2b86373..08f4586 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -2743,6 +2743,8 @@ "link_modal.no_circuit_crosses_between_north_and":"Nenhum circuito cruza entre a Coreia do Norte e a Coreia do Sul, e nenhuma operadora vai te vender um. Pyongyang chega ao mundo pela China e pela Rússia.", "link_modal.no_subsea_cable_lands_in_both":"Nenhum cabo submarino desembarca em {a} e {b} ao mesmo tempo. Os cabos de {a} chegam a {list}. Faça um hop por um deles.", "link_modal.no_subsea_cable_lands_in_city":"Nenhum cabo submarino chega a {city}. A estação de chegada mais próxima é {near}: leve fibra até lá primeiro e depois pegue um cabo de lá.", +"link_modal.no_subsea_cable_lands_in_city_land":"Nenhum cabo submarino chega a {city} ainda. Chegue lá por terra ou lance seu próprio cabo submarino.", +"link_modal.no_subsea_cable_lands_in_city_own":"Nenhum cabo submarino chega a {city} ainda, e nenhuma estrada ou fibra chega lá por terra. Só um cabo submarino seu pode chegar lá.", "link_modal.nobody_sells_capacity_between_kyiv":"Ninguém vende capacidade entre Kyiv e Moscou, e ninguém vai vender. Passe por Varsóvia, Bucareste ou Helsinque.", "link_modal.not_without_a_license":"Não sem licença", "link_modal.premium_crossing_60_3_loss":"Travessia premium +60% · ~3% de perda", diff --git a/src/game/95-modals/70-link-modal.js b/src/game/95-modals/70-link-modal.js index a7b5c25..5041ab6 100644 --- a/src/game/95-modals/70-link-modal.js +++ b/src/game/95-modals/70-link-modal.js @@ -9,7 +9,10 @@ function openLinkModal(a,b){ const mode=UI.lmode==='df'?'df':'wave',tabs=`
${btn(tr('link_modal.lease_a_wave'),'dfMode',{m:'wave'},mode==='wave'?'pink':'ghost')}${btn(tr('common.dark_fiber'),'dfMode',{m:'df'},mode==='df'?'pink':'ghost')}
`; const head=`
${sub?tr('common.subsea_a6be'):tr('common.terrestrial_19e4')} · ${km.toLocaleString()} km

${CITY[a].name} → ${CITY[b].name}

${tabs}`; if(mode==='df'){openModal(head+dfModalBody(a,b,km,pop));return;} - if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c));openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${cabOpen()&&!ownCabWhy(a,b)?ownCabTeaser(a,b):''}`);return;} + if(sub&&!cablesOk(a,b).length){const fr=[...new Set(CABLE_PAIRS.filter(c=>c.a===a||c.b===a).map(c=>CITY[c.a===a?c.b:c.a].name))],dry=[a,b].find(c=>!landing(c)); + // a beach with no cable yet (#321): hopping cannot help, only a road in or a cable of your own + const bare=!dry&&[a,b].find(c=>!CABLE_PAIRS.some(p=>p.a===c||p.b===c)),road=bare&&CITIES.some(x=>x.id!==bare&&!isSub(bare,x.id)); + openModal(head+`

${dry?tr('link_modal.no_subsea_cable_lands_in_city',{city:CITY[dry].name,near:CITY[nearLanding(dry)].name}):bare?(road?tr('link_modal.no_subsea_cable_lands_in_city_land',{city:CITY[bare].name}):tr('link_modal.no_subsea_cable_lands_in_city_own',{city:CITY[bare].name})):tr('link_modal.no_subsea_cable_lands_in_both',{a:CITY[a].name,b:CITY[b].name,list:fr.join(', ')})}

${(cabOpen()?!ownCabWhy(a,b):bare)?ownCabTeaser(a,b):''}`);return;} if(isSub(a,b)&&S.ev.landban&&S.ev.landban.until>S.day&&[a,b].includes(S.ev.landban.city)){openModal(head+`

${tr('link_modal.the_landing_permit_dispute_in_city',{city:CITY[S.ev.landban.city].name,n:S.ev.landban.until-S.day})}

`);return;} if(uaePair(a,b)||andesPair(a,b)||rainPair(a,b)||borderPair(a,b))route+=`

${landWhy(a,b)}

`; route+=`

📈 ${esc(marketNote(a,b,sub))}

`; diff --git a/src/i18n/en.js b/src/i18n/en.js index 11a050a..5323950 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -2744,6 +2744,8 @@ "link_modal.no_circuit_crosses_between_north_and":"No circuit crosses between North and South Korea, and no carrier will sell you one. Pyongyang reaches the world through China and Russia.", "link_modal.no_subsea_cable_lands_in_both":"No subsea cable lands in both {a} and {b}. Cables from {a} reach {list}. Hop through one of those.", "link_modal.no_subsea_cable_lands_in_city":"No subsea cable lands in {city}. The nearest landing station is {near}: run fiber there first, then take a cable from it.", +"link_modal.no_subsea_cable_lands_in_city_land":"No subsea cable lands in {city} yet. Reach it overland, or lay a subsea cable of your own.", +"link_modal.no_subsea_cable_lands_in_city_own":"No subsea cable lands in {city} yet, and no road or fiber reaches it overland. Only a subsea cable of your own can get there.", "link_modal.nobody_sells_capacity_between_kyiv":"Nobody sells capacity between Kyiv and Moscow, and nobody is going to. Route through Warsaw, Bucharest or Helsinki instead.", "link_modal.not_without_a_license":"Not without a license", "link_modal.premium_crossing_60_3_loss":"Premium crossing +60% · ~3% loss", diff --git a/tests/link-modal-no-cable.test.js b/tests/link-modal-no-cable.test.js new file mode 100644 index 0000000..74f8feb --- /dev/null +++ b/tests/link-modal-no-cable.test.js @@ -0,0 +1,39 @@ +// #321: a subsea link to or from a coast where no cable lands yet (Iqaluit, Adamstown, Murmansk) said +// "Cables from Iqaluit reach . Hop through one of those." It now says what can actually reach that city. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const card = (ev, a, b) => ev(`UI.lmode='wave';openLinkModal('${a}','${b}');const t=$('modalCard').textContent;closeModal();t`); + +test('#321 no cable lands in Iqaluit: no empty list, the only way in is your own cable', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const g of GOALS)S.done[g.id]=0"); + assert.ok(!ev("cabOpen()")); + for (const [a, b] of [['yfb', 'nuk'], ['nuk', 'yfb'], ['nyc', 'pcn']]) { + const t = card(ev, a, b), city = ev(`CITY['${b === 'nuk' ? a : b}'].name`); + assert.doesNotMatch(t, /reach \.|Hop through/, `${a}→${b}: ${t}`); + assert.ok(t.includes(ev(`tr('link_modal.no_subsea_cable_lands_in_city_own',{city:'${city}'})`)), `${a}→${b}: ${t}`); + assert.match(t, /level 9 or Tier 1/, `${a}→${b} points at the level that unlocks your own cable`); + } + // once you can lay one, the button to do it is right there + ev("S.lvl=9"); + assert.ok(ev("cabOpen()")); + assert.match(card(ev, 'yfb', 'nuk'), /Lay your own subsea cable|Surveying/); + assert.deepEqual(errors, []); +}); + +test('#321 a coast with no cable but a road in: reach it overland, never "hop through" cables that miss it', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const g of GOALS)S.done[g.id]=0"); + for (const [a, b, c] of [['nyc', 'mmk', 'mmk'], ['dks', 'nyc', 'dks']]) { + const t = card(ev, a, b); + assert.doesNotMatch(t, /Hop through/, `${a}→${b}: ${t}`); + assert.ok(t.includes(ev(`tr('link_modal.no_subsea_cable_lands_in_city_land',{city:CITY.${c}.name})`)), `${a}→${b}: ${t}`); + } + // two cities that both have cables, just not a shared one, still get the cities to hop through + const t = card(ev, 'nuk', 'syd'); + assert.match(t, /Hop through one of those/); + assert.doesNotMatch(t, /reach \./); + assert.deepEqual(errors, []); +}); From afd71a089938428a7f0d74200c7f0906e7dd6e8d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:57:10 +0000 Subject: [PATCH 12/20] Tools: Bump playwright-core from 1.64.1 to 1.65.0 in the tools group Bumps the tools group with 1 update: [playwright-core](https://github.com/microsoft/playwright). Updates `playwright-core` from 1.64.1 to 1.65.0 - [Release notes](https://github.com/microsoft/playwright/releases) - [Commits](https://github.com/microsoft/playwright/compare/v1.64.1...v1.65.0) --- updated-dependencies: - dependency-name: playwright-core dependency-version: 1.65.0 dependency-type: direct:development update-type: version-update:semver-minor dependency-group: tools ... Signed-off-by: dependabot[bot] --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8a24e5f..c771089 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", "jsdom": "30.1.3", - "playwright-core": "1.64.1", + "playwright-core": "1.65.0", "ws": "8.22.1" }, "engines": { @@ -439,9 +439,9 @@ } }, "node_modules/playwright-core": { - "version": "1.64.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", - "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "version": "1.65.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", + "integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/package.json b/package.json index 62a142d..a117b72 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,7 @@ "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", "jsdom": "30.1.3", - "playwright-core": "1.64.1", + "playwright-core": "1.65.0", "ws": "8.22.1" } } From 5d76d3afc80c092e656d3992a603e6261dd98d7c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 00:57:31 +0000 Subject: [PATCH 13/20] CI: Bump anthropics/claude-code-action Bumps the actions group with 1 update: [anthropics/claude-code-action](https://github.com/anthropics/claude-code-action). Updates `anthropics/claude-code-action` from 1.0.268 to 1.0.269 - [Release notes](https://github.com/anthropics/claude-code-action/releases) - [Commits](https://github.com/anthropics/claude-code-action/compare/c0949c50a78c1ec8ce2647db36629b870e715d0c...61a9c274fa7110a66dfafc1bbbced03833eb25fe) --- updated-dependencies: - dependency-name: anthropics/claude-code-action dependency-version: 1.0.269 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: actions ... Signed-off-by: dependabot[bot] --- .github/workflows/claude.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 12fba69..10913c4 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -30,6 +30,6 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 1 - - uses: anthropics/claude-code-action@c0949c50a78c1ec8ce2647db36629b870e715d0c # v1.0.268 + - uses: anthropics/claude-code-action@61a9c274fa7110a66dfafc1bbbced03833eb25fe # v1.0.269 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} From 93d7c87dc70086940c9a1dc13087dd570d741cf7 Mon Sep 17 00:00:00 2001 From: Christopher Hawker Date: Fri, 6 Nov 2026 20:52:48 +1100 Subject: [PATCH 14/20] Move a customer to another path between the same two POPs Alien waves and leased fiber pairs sit on one fiber (b.link), so they move to another working fiber between the same cities, under the rules for selling capacity on it. Circuits have no link of their own, so moving one pins it to a list of cities (b.pin), which routing follows while every link on it is up. When one is down the circuit follows routing, and it comes back by itself. The window lists the most diverse options first, compared by trench. Moves are free and instant, and contracts keep their price. --- CHANGELOG.md | 1 + docs/ARCHITECTURE.md | 2 +- scripts/lib/route-fuzz.js | 4 +- site/i18n/de.js | 24 +++ site/i18n/es.js | 24 +++ site/i18n/fr.js | 24 +++ site/i18n/it.js | 24 +++ site/i18n/pt.js | 24 +++ src/agent/20-commands.js | 9 +- src/game/60-features/37-customer-paths.js | 66 ++++++ src/game/80-simulation/30-compute.js | 2 +- src/game/80-simulation/50-sanitize.js | 2 +- src/game/90-actions/53-customer-paths.js | 13 ++ src/game/90-actions/85-routing-and-routers.js | 2 +- src/game/93-ui/50-city-panel.js | 2 +- src/game/93-ui/70-link-panels.js | 2 +- src/i18n/en.js | 24 +++ tests/customer-paths.test.js | 191 ++++++++++++++++++ 18 files changed, 431 insertions(+), 9 deletions(-) create mode 100644 src/game/60-features/37-customer-paths.js create mode 100644 src/game/90-actions/53-customer-paths.js create mode 100644 tests/customer-paths.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bf0969..98ecb9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ All notable changes to this project are documented here. The project follows - Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. - A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before. - The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before. +- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Alien waves and leased fiber pairs move to another fiber, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. ## [3.2.0] — 2026-11-07 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 65247b3..2724f6f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -31,7 +31,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) | | `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) | | `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` | -| `60-features/` | Banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`; renewal haggles: `S.slAuto.ren`, `slRenDay()`) | +| `60-features/` | Moving a customer to another path (`37-customer-paths.js`), banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`; renewal haggles: `S.slAuto.ren`, `slRenDay()`) | | `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | | `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `failureRun()`/`fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) | diff --git a/scripts/lib/route-fuzz.js b/scripts/lib/route-fuzz.js index 283b41c..1c2a064 100644 --- a/scripts/lib/route-fuzz.js +++ b/scripts/lib/route-fuzz.js @@ -55,8 +55,8 @@ const TABS = ['cust', 'up', 'peer', 'links']; const LEFT = ['nets', 'noc', 'deals', 'goals']; const PRESETS = ['freeze', 'oncall', 'bgp']; // How often a button is pressed against the others on screen: what changes the network often, looking around rarely. -const BUILD = /^(buy\w*|pni\w*All|pni|peer|peerAll|unpeer|cache|cacheSite|rmCache|buildLink|buildPop|launchBB|accept|decline|dropBiz|takeLoan|repayLoan|lag[TPI]x?|setPref|setCarry|setStandby|setMetric|togglePrem|cleanPipe|sacrif|rs|foundIx|myIxUp|addRouter|rmRouter|upRouter|addSite|rmSite|siteSet|decomToggle|rmLink|upLink|addParallel|cancel\w*|upVxc|buyNni|rmNni|buildScrub|scrubUp|rmScrub|addGen|regen|addCh|rmCh|addPair|upSys|spares|layShip|crews|fixInc|seaPackage|subUpgrade|orderCable|orderDf|ownCab|opsHire|opsToggle|opsParam|opsCap|opsPop|opsTpl|opsNewPop|popStdSet|coreSet|teRecipe|dkOptOut|dkStay|utility\w*|listFiber|unlistFiber|leaseSwap|custGo|confGo|confSponsor|seatBuy|charter|cnPrem|applyCn|ad|ddosAuto|pz(Pop|RmPop|Link|AddPar|Tier|RmLink|RtAdd|RtRm|RtModel|Route|Via|Div)|setRoute|route|via|metricSet)$/; -const UIACT = /^(tab|dashTab|leftTab|\w*Sort|\w*Filter|pniGrp|trace\w*|focusCity|findGo|selLink|dashLink|logAll|tailTog|listMore|netFocus|netFilter|meetGo|phoneTab|dashClose|connF|connCity|connNet|connFor|custF|custCity|popGo|popsReg|opsOpen|decomOpen|linkCheck)$/; +const BUILD = /^(buy\w*|pni\w*All|pni|peer|peerAll|unpeer|cache|cacheSite|rmCache|buildLink|buildPop|launchBB|accept|decline|dropBiz|pathMove|pathPin|pathAuto|takeLoan|repayLoan|lag[TPI]x?|setPref|setCarry|setStandby|setMetric|togglePrem|cleanPipe|sacrif|rs|foundIx|myIxUp|addRouter|rmRouter|upRouter|addSite|rmSite|siteSet|decomToggle|rmLink|upLink|addParallel|cancel\w*|upVxc|buyNni|rmNni|buildScrub|scrubUp|rmScrub|addGen|regen|addCh|rmCh|addPair|upSys|spares|layShip|crews|fixInc|seaPackage|subUpgrade|orderCable|orderDf|ownCab|opsHire|opsToggle|opsParam|opsCap|opsPop|opsTpl|opsNewPop|popStdSet|coreSet|teRecipe|dkOptOut|dkStay|utility\w*|listFiber|unlistFiber|leaseSwap|custGo|confGo|confSponsor|seatBuy|charter|cnPrem|applyCn|ad|ddosAuto|pz(Pop|RmPop|Link|AddPar|Tier|RmLink|RtAdd|RtRm|RtModel|Route|Via|Div)|setRoute|route|via|metricSet)$/; +const UIACT = /^(tab|dashTab|leftTab|\w*Sort|\w*Filter|pniGrp|trace\w*|focusCity|findGo|selLink|dashLink|logAll|tailTog|listMore|netFocus|netFilter|meetGo|phoneTab|dashClose|connF|connCity|connNet|connFor|custF|custCity|popGo|popsReg|opsOpen|decomOpen|linkCheck|pathOpen)$/; const DW = { launchBB: 4, accept: 4, buyTransit: 3, pni: 3, buyIx: 3, setPref: 4, cache: 2, peerAll: 2, setCarry: 2, takeLoan: 2 }; const weight = (b) => (BUILD.test(b.act) ? 8 : UIACT.test(b.act) ? 0.3 : 1); diff --git a/site/i18n/de.js b/site/i18n/de.js index a6a5f86..39c300f 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1759,6 +1759,30 @@ "core.vendor_zoo":"Hersteller-Zoo", "core.your_auto_te_predates_backbones":"Dein Auto-TE wurde installiert, bevor Backbones eine Technik hatten, also läuft es wie immer. Wechselst du das Backbone, gelten die neuen Regeln.", "core.your_backbone_now_runs_lv":"Dein Backbone läuft jetzt mit {lv}.", +"customer_paths.fiber_label":"{name} · {km} km", +"customer_paths.fits_only_g_of_bw":"Passen nur {g} von {bw}", +"customer_paths.fully_diverse":"Komplett divers", +"customer_paths.its_spare_pairs_are_taken":"Die freien Paare sind schon vermietet", +"customer_paths.let_routing_choose_again":"Wieder das Routing entscheiden lassen", +"customer_paths.move":"Umziehen", +"customer_paths.move_name":"{name} umziehen", +"customer_paths.move_to_another_path":"Auf einen anderen Pfad umziehen", +"customer_paths.name_follows_routing_again":"{name} folgt wieder dem Routing.", +"customer_paths.name_moved_to_fiber":"{name} ist auf {fiber} umgezogen.", +"customer_paths.name_now_rides_path":"{name} läuft jetzt über {path}.", +"customer_paths.no_other_path":"Zwischen {a} und {b} gibt es gerade keinen anderen funktionierenden Pfad.", +"customer_paths.no_other_working_fiber":"Zwischen {a} und {b} gibt es keine andere funktionierende Glasfaser. Bau eine, dann kannst du diesen Kunden darauf umziehen.", +"customer_paths.not_enough_free_channels":"Zu wenig freie Kanäle: {free} frei, {n} nötig", +"customer_paths.now_on":"Aktuell auf", +"customer_paths.only_your_own_fiber_rents_pairs":"Nur deine eigene Glasfaser kann Paare vermieten", +"customer_paths.over_the_ms_budget":"Über dem Budget von {ms} ms", +"customer_paths.path_facts":"{km} km · {ms} ms", +"customer_paths.pinned_to_path":"Festgelegt auf {path}", +"customer_paths.routing_chooses_this_circuit":"Das Routing wählt den Pfad dieses Circuits zwischen {a} und {b} jeden Tag neu. Ein Umzug legt ihn kostenlos auf den gewählten Pfad fest. Fällt ein Link auf diesem Pfad aus, folgt er dem Routing, bis der Link wieder da ist.", +"customer_paths.same_trench":"Gleicher Graben", +"customer_paths.shares_n_spans":{"one":"Teilt {n} Abschnitt","other":"Teilt {n} Abschnitte"}, +"customer_paths.that_path_is_down":"Dieser Pfad ist down, vorerst folgt er dem Routing", +"customer_paths.this_customer_rides_one_fiber":"Dieser Kunde läuft über eine Glasfaser zwischen {a} und {b}. Der Umzug auf eine andere ist kostenlos und passiert sofort.", "customers.attacks_on_city_are_hauled_to":"Angriffe auf {city} werden zum Scrubbing nach {to} geschleppt: +{ms} ms", "customers.everyone_who_pays_you_happiest_last":"Alle, die dich bezahlen, die Zufriedensten zuletzt. Unter 60 % fangen sie an zu meckern, unter 30 % sind sie wütend, und bei 0 % kündigen sie.", "customers.from_unhappy_customers":"von unzufriedenen Kunden", diff --git a/site/i18n/es.js b/site/i18n/es.js index 6c8f123..06a6d27 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1757,6 +1757,30 @@ "core.vendor_zoo":"Zoológico de fabricantes", "core.your_auto_te_predates_backbones":"Tu Auto-TE se instaló antes de que los backbones tuvieran una tecnología, así que funciona como siempre. Cambiar el backbone pasa a las reglas nuevas.", "core.your_backbone_now_runs_lv":"Tu backbone ahora corre {lv}.", +"customer_paths.fiber_label":"{name} · {km} km", +"customer_paths.fits_only_g_of_bw":"Solo caben {g} de {bw}", +"customer_paths.fully_diverse":"Totalmente diversa", +"customer_paths.its_spare_pairs_are_taken":"Sus pares libres ya están alquilados", +"customer_paths.let_routing_choose_again":"Que el enrutamiento vuelva a elegir", +"customer_paths.move":"Mover", +"customer_paths.move_name":"Mover a {name}", +"customer_paths.move_to_another_path":"Mover a otra ruta", +"customer_paths.name_follows_routing_again":"{name} vuelve a seguir el enrutamiento.", +"customer_paths.name_moved_to_fiber":"{name} se ha movido a {fiber}.", +"customer_paths.name_now_rides_path":"{name} ahora va por {path}.", +"customer_paths.no_other_path":"Ahora mismo no hay otra ruta operativa entre {a} y {b}.", +"customer_paths.no_other_working_fiber":"No hay otra fibra operativa entre {a} y {b}. Construye una y podrás mover a este cliente a ella.", +"customer_paths.not_enough_free_channels":"No hay canales libres suficientes: {free} libres, necesita {n}", +"customer_paths.now_on":"Ahora en", +"customer_paths.only_your_own_fiber_rents_pairs":"Solo tu propia fibra puede alquilar pares", +"customer_paths.over_the_ms_budget":"Supera el presupuesto de {ms} ms", +"customer_paths.path_facts":"{km} km · {ms} ms", +"customer_paths.pinned_to_path":"Fijado a {path}", +"customer_paths.routing_chooses_this_circuit":"El enrutamiento elige cada día la ruta de este circuito entre {a} y {b}. Moverlo lo fija a la ruta que elijas, gratis. Mientras un enlace de esa ruta esté caído, seguirá el enrutamiento hasta que vuelva.", +"customer_paths.same_trench":"Misma zanja", +"customer_paths.shares_n_spans":{"one":"Comparte {n} tramo","other":"Comparte {n} tramos"}, +"customer_paths.that_path_is_down":"Esa ruta está caída, así que de momento sigue el enrutamiento", +"customer_paths.this_customer_rides_one_fiber":"Este cliente va por una fibra entre {a} y {b}. Moverlo a otra es gratis e inmediato.", "customers.attacks_on_city_are_hauled_to":"los ataques a {city} se desvían a {to} para depurarlos: +{ms} ms", "customers.everyone_who_pays_you_happiest_last":"Todos los que te pagan, los más felices al final. Por debajo del 60 % empiezan a quejarse, por debajo del 30 % están furiosos y al 0 % cancelan.", "customers.from_unhappy_customers":"de clientes descontentos", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 4598446..2d7fb90 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1757,6 +1757,30 @@ "core.vendor_zoo":"Zoo de constructeurs", "core.your_auto_te_predates_backbones":"Ton Auto-TE a été installé avant que les backbones aient une technologie, il tourne donc comme toujours. Changer de backbone passe aux nouvelles règles.", "core.your_backbone_now_runs_lv":"Ton backbone tourne maintenant en {lv}.", +"customer_paths.fiber_label":"{name} · {km} km", +"customer_paths.fits_only_g_of_bw":"Seuls {g} sur {bw} passent", +"customer_paths.fully_diverse":"Totalement diversifié", +"customer_paths.its_spare_pairs_are_taken":"Ses paires libres sont déjà louées", +"customer_paths.let_routing_choose_again":"Laisser le routage choisir à nouveau", +"customer_paths.move":"Déplacer", +"customer_paths.move_name":"Déplacer {name}", +"customer_paths.move_to_another_path":"Déplacer vers un autre chemin", +"customer_paths.name_follows_routing_again":"{name} suit de nouveau le routage.", +"customer_paths.name_moved_to_fiber":"{name} a été déplacé vers {fiber}.", +"customer_paths.name_now_rides_path":"{name} passe maintenant par {path}.", +"customer_paths.no_other_path":"Il n'y a pas d'autre chemin en service entre {a} et {b} pour le moment.", +"customer_paths.no_other_working_fiber":"Il n'y a pas d'autre fibre en service entre {a} et {b}. Construis-en une et tu pourras y déplacer ce client.", +"customer_paths.not_enough_free_channels":"Pas assez de canaux libres : {free} libres, il en faut {n}", +"customer_paths.now_on":"Actuellement sur", +"customer_paths.only_your_own_fiber_rents_pairs":"Seule ta propre fibre peut louer des paires", +"customer_paths.over_the_ms_budget":"Au-delà du budget de {ms} ms", +"customer_paths.path_facts":"{km} km · {ms} ms", +"customer_paths.pinned_to_path":"Épinglé sur {path}", +"customer_paths.routing_chooses_this_circuit":"Le routage choisit chaque jour le chemin de ce circuit entre {a} et {b}. Le déplacer l'épingle gratuitement sur le chemin de ton choix. Tant qu'un lien de ce chemin est coupé, il suit le routage jusqu'au retour du lien.", +"customer_paths.same_trench":"Même tranchée", +"customer_paths.shares_n_spans":{"one":"Partage {n} tronçon","other":"Partage {n} tronçons"}, +"customer_paths.that_path_is_down":"Ce chemin est coupé, il suit donc le routage pour l'instant", +"customer_paths.this_customer_rides_one_fiber":"Ce client passe par une fibre entre {a} et {b}. Le déplacer vers une autre est gratuit et immédiat.", "customers.attacks_on_city_are_hauled_to":"les attaques sur {city} sont acheminées vers {to} pour le scrubbing : +{ms} ms", "customers.everyone_who_pays_you_happiest_last":"Tous ceux qui te paient, les plus contents en dernier. Sous 60 % ils commencent à râler, sous 30 % ils sont furieux, et à 0 % ils résilient.", "customers.from_unhappy_customers":"venant des clients mécontents", diff --git a/site/i18n/it.js b/site/i18n/it.js index edb8ab5..5497bfb 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1757,6 +1757,30 @@ "core.vendor_zoo":"Zoo dei vendor", "core.your_auto_te_predates_backbones":"Il tuo Auto-TE è stato installato prima che i backbone avessero una tecnologia, quindi funziona come ha sempre fatto. Cambiare il backbone passa alle nuove regole.", "core.your_backbone_now_runs_lv":"Il tuo backbone ora gira su {lv}.", +"customer_paths.fiber_label":"{name} · {km} km", +"customer_paths.fits_only_g_of_bw":"Ci stanno solo {g} su {bw}", +"customer_paths.fully_diverse":"Totalmente diverso", +"customer_paths.its_spare_pairs_are_taken":"Le sue coppie libere sono già affittate", +"customer_paths.let_routing_choose_again":"Lascia di nuovo scegliere al routing", +"customer_paths.move":"Sposta", +"customer_paths.move_name":"Sposta {name}", +"customer_paths.move_to_another_path":"Sposta su un altro percorso", +"customer_paths.name_follows_routing_again":"{name} segue di nuovo il routing.", +"customer_paths.name_moved_to_fiber":"{name} spostato su {fiber}.", +"customer_paths.name_now_rides_path":"{name} ora passa per {path}.", +"customer_paths.no_other_path":"Al momento non c'è un altro percorso funzionante tra {a} e {b}.", +"customer_paths.no_other_working_fiber":"Non c'è un'altra fibra funzionante tra {a} e {b}. Costruiscine una e potrai spostarci questo cliente.", +"customer_paths.not_enough_free_channels":"Canali liberi insufficienti: {free} liberi, ne servono {n}", +"customer_paths.now_on":"Ora su", +"customer_paths.only_your_own_fiber_rents_pairs":"Solo la tua fibra può affittare coppie", +"customer_paths.over_the_ms_budget":"Oltre il budget di {ms} ms", +"customer_paths.path_facts":"{km} km · {ms} ms", +"customer_paths.pinned_to_path":"Fissato su {path}", +"customer_paths.routing_chooses_this_circuit":"Il routing sceglie ogni giorno il percorso di questo circuito tra {a} e {b}. Spostarlo lo fissa gratis sul percorso che scegli. Finché un link di quel percorso è giù, segue il routing fino al suo ritorno.", +"customer_paths.same_trench":"Stessa trincea", +"customer_paths.shares_n_spans":{"one":"Condivide {n} tratta","other":"Condivide {n} tratte"}, +"customer_paths.that_path_is_down":"Quel percorso è giù, quindi per ora segue il routing", +"customer_paths.this_customer_rides_one_fiber":"Questo cliente passa su una fibra tra {a} e {b}. Spostarlo su un'altra è gratis e immediato.", "customers.attacks_on_city_are_hauled_to":"gli attacchi su {city} vengono portati a {to} per lo scrubbing: +{ms} ms", "customers.everyone_who_pays_you_happiest_last":"Tutti quelli che ti pagano, i più contenti in fondo. Sotto il 60% iniziano a brontolare, sotto il 30% sono furiosi, e a 0% disdicono.", "customers.from_unhappy_customers":"dai clienti scontenti", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 08f4586..46bb3fc 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1757,6 +1757,30 @@ "core.vendor_zoo":"Zoológico de fornecedores", "core.your_auto_te_predates_backbones":"Seu Auto-TE foi instalado antes de os backbones terem uma tecnologia, então ele funciona como sempre. Mudar o backbone passa para as regras novas.", "core.your_backbone_now_runs_lv":"Seu backbone agora roda {lv}.", +"customer_paths.fiber_label":"{name} · {km} km", +"customer_paths.fits_only_g_of_bw":"Só cabem {g} de {bw}", +"customer_paths.fully_diverse":"Totalmente diverso", +"customer_paths.its_spare_pairs_are_taken":"Os pares livres já estão alugados", +"customer_paths.let_routing_choose_again":"Deixar o roteamento escolher de novo", +"customer_paths.move":"Mover", +"customer_paths.move_name":"Mover {name}", +"customer_paths.move_to_another_path":"Mover para outro caminho", +"customer_paths.name_follows_routing_again":"{name} volta a seguir o roteamento.", +"customer_paths.name_moved_to_fiber":"{name} movido para {fiber}.", +"customer_paths.name_now_rides_path":"{name} agora passa por {path}.", +"customer_paths.no_other_path":"Agora não há outro caminho funcionando entre {a} e {b}.", +"customer_paths.no_other_working_fiber":"Não há outra fibra funcionando entre {a} e {b}. Construa uma e você poderá mover este cliente para ela.", +"customer_paths.not_enough_free_channels":"Canais livres insuficientes: {free} livres, precisa de {n}", +"customer_paths.now_on":"Agora em", +"customer_paths.only_your_own_fiber_rents_pairs":"Só a sua própria fibra pode alugar pares", +"customer_paths.over_the_ms_budget":"Acima do orçamento de {ms} ms", +"customer_paths.path_facts":"{km} km · {ms} ms", +"customer_paths.pinned_to_path":"Fixado em {path}", +"customer_paths.routing_chooses_this_circuit":"O roteamento escolhe todo dia o caminho deste circuito entre {a} e {b}. Movê-lo o fixa no caminho que você escolher, de graça. Enquanto um link desse caminho estiver fora, ele segue o roteamento até o link voltar.", +"customer_paths.same_trench":"Mesma vala", +"customer_paths.shares_n_spans":{"one":"Compartilha {n} trecho","other":"Compartilha {n} trechos"}, +"customer_paths.that_path_is_down":"Esse caminho está fora, então por enquanto segue o roteamento", +"customer_paths.this_customer_rides_one_fiber":"Este cliente passa por uma fibra entre {a} e {b}. Movê-lo para outra é grátis e imediato.", "customers.attacks_on_city_are_hauled_to":"os ataques em {city} são levados a {to} para scrubbing: +{ms} ms", "customers.everyone_who_pays_you_happiest_last":"Todo mundo que te paga, os mais felizes por último. Abaixo de 60% começam a reclamar, abaixo de 30% ficam furiosos, e em 0% cancelam.", "customers.from_unhappy_customers":"de clientes insatisfeitos", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 266cf70..de2324b 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -262,7 +262,13 @@ const API_CMD={ dropBiz:{args:[['id','entityId']],confirm:'double', doc:'Terminate a signed customer. Rejected once an event contract\'s event has started.'}, setRoute:{args:[['id','entityId'],['m','routeMode']],watch:['biz.#id'], - doc:'How a customer\'s traffic is routed: normal follows metrics, fast takes the lowest latency, scenic the quietest links.'}, + doc:'How a customer\'s traffic is routed: normal follows metrics, fast takes the lowest latency, scenic the quietest links. Clears a pinned path.'}, + pathMove:{args:[['id','entityId'],['link','entityId']],watch:['biz.#id'], + doc:'Move a fiber customer (alien wave, dark fiber pair, fiber pairs) to another working fiber between the same two cities. Free. Rejected if that fiber has no room for it.'}, + pathPin:{args:[['id','entityId'],['via','string']],watch:['biz.#id'], + doc:'Pin a circuit to a path: via is its city ids in order, comma-separated, from the customer\'s city to its city2, every hop a working link. Free. While a link on it is down the circuit follows routing.'}, + pathAuto:{args:[['id','entityId']],watch:['biz.#id'], + doc:'Unpin a circuit, so routing chooses its path again.'}, /* ---------- traffic engineering ---------- */ buyTE:{args:[],quote:a=>({setup:TE_COST,monthly:TE_MO,blocked:coreTE()||(S&&S.te)?[]:[tr('core.auto_te_needs_an_rsvp_te_or')]}), doc:'Buy the Auto-TE controller, which spills overflow onto alternate paths. Level 3+, and it needs an RSVP-TE-or-higher backbone.'}, @@ -491,6 +497,7 @@ const API_VIEW={ focusCity:{args:[['city','cityId']],doc:'Select and centre a city.'}, selLink:{args:[['id','entityId']],doc:'Select a link.'}, custGo:{args:[['id','entityId']],doc:'Jump from the dashboard to a customer.'}, + pathOpen:{args:[['id','entityId']],doc:'Open the window listing the other paths a customer can move to: fibers for a fiber customer, routes for a circuit. pathMove and pathPin make the move.'}, listMore:{args:[['k','listPage']],doc:'Show another page of the dashboard list.'}, custF:{args:[['v','string']],doc:'Filter the customers list.'}, custCity:{args:[['v','string']],doc:'Filter the customers list by city.'}, diff --git a/src/game/60-features/37-customer-paths.js b/src/game/60-features/37-customer-paths.js new file mode 100644 index 0000000..8a0510a --- /dev/null +++ b/src/game/60-features/37-customer-paths.js @@ -0,0 +1,66 @@ +/* ---------- moving a customer to another path between the same two POPs ---------- */ +/* Fiber customers (an alien wave, leased pairs) sit on one fiber, b.link, so they move to a parallel one. Circuits have + no link of their own: routing picks their path every day. Moving one pins it to a list of cities, b.pin. While a link + on the pin is down it follows routing, as a protected wave would, and it comes back by itself. */ +const PATH_ALT=3,PATH_FAR=1000; +const pathKind=b=>{const T=BIZ_T[b.type];if(pzOn()||!T||capPend(b)||!b.city2)return '';return T.fiber?(b.link?'fiber':''):T.l2&&!b.sites?'circuit':'';}; +const trenchOf=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); +const pathCity=c=>CITY[c].name,pathStr=p=>p.map(pathCity).join(' → '); +const samePair=(l,a,b)=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a); +const fibLab=l=>tr('customer_paths.fiber_label',{name:l.cname?esc(l.cname):capName(l),km:Math.round(l.km).toLocaleString()}); +// Why this fiber cannot take this customer, in the same terms as the offers for it. +function fiberNo(b,l){if(b.type==='wwave'){const n=b.slots||1,free=freeCh(l);return free>=n?'':tr('customer_paths.not_enough_free_channels',{free:Math.max(0,free),n});} + if(!l.own)return tr('customer_paths.only_your_own_fiber_rents_pairs'); + if(b.type==='dfpair')return pairFree(l)?'':tr('customer_paths.its_spare_pairs_are_taken'); + return S.biz.some(x=>x!==b&&x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type))?tr('customer_paths.its_spare_pairs_are_taken'):'';} +// The working fibers it could go to, those on another trench first. +function fiberTargets(b){const cur=S.links.find(l=>l.id===b.link),t=cur?trenchOf(cur):''; + return S.links.filter(l=>l.kind==='df'&&l.id!==b.link&&samePair(l,b.city,b.city2)&&l.ready<=S.day&&!(l.cut>S.day)&&!(l.eqDown>S.day)) + .map(l=>({l,diverse:trenchOf(l)!==t,no:fiberNo(b,l)})).sort((x,y)=>(y.diverse-x.diverse)||(!!x.no-!!y.no)||x.l.km-y.l.km);} +// The live backbone by city pair, as compute() sees it: every link of a pair is one edge. +function pathEdges(){const E={},N={};for(const l of S.links){if(linkDown(l)||!popUp(l.a)||!popUp(l.b))continue;const k=edgeKey(l);let e=E[k]; + if(!e){e=E[k]={k,a:l.a,b:l.b,w:Infinity,km:Infinity,lat:Infinity,cap:0,load:0,ts:new Set()};(N[l.a]=N[l.a]||[]).push(e);(N[l.b]=N[l.b]||[]).push(e);} + e.w=Math.min(e.w,pairW(k,l.km));e.km=Math.min(e.km,l.km);e.lat=Math.min(e.lat,linkLat(l));e.cap+=capOf(l);e.load+=(R.load&&R.load[l.id])||0;e.ts.add(trenchOf(l));} + return {E,N};} +const hopKey=(a,b)=>a{const o=[];for(let i=1;i!!pathHops(pathEdges(),b.pin); +// Where the circuit runs today. Scenic circuits remember it; the others take the shortest path of their kind. +function pathNow(b,G){if(b.pin&&pathHops(G,b.pin))return b.pin; + const r=R.l2route&&R.l2route[b.id+'>'+b.city+'>'+b.city2];if(r&&r[0]){const p=r[0].ns.slice();if(p[0]!==b.city)p.reverse();if(pathHops(G,p))return p;} + return pathWalk(G,b.city,b.city2,b.route==='fast'?e=>e.lat+0.05:e=>e.w);} +// Paths that avoid what is in use: each one is priced as if every trench already used were nearly unusable, so the next +// one is the most diverse there is, sharing a trench only if there is no way round it. +function circuitTargets(b){const G=pathEdges(),now=pathNow(b,G);if(!now)return {now:null,alts:[]}; + const hops=pathHops(G,now)||[],used=new Set(),seen=new Set([now.join()]),own=new Set(hops.map(e=>e.k)),got=R.l2&&R.l2[b.id]||0,alts=[]; + const nowT=new Set();for(const e of hops)for(const t of e.ts){nowT.add(t);used.add(t);} + for(let i=0;i{for(const t of e.ts)if(used.has(t))return (e.w+1)*PATH_FAR;return e.w+1;});if(!p)break; + const h=pathHops(G,p);for(const e of h)for(const t of e.ts)used.add(t);if(seen.has(p.join()))continue;seen.add(p.join()); + alts.push({p,shared:h.filter(e=>[...e.ts].some(t=>nowT.has(t))).length,km:h.reduce((a,e)=>a+e.km,0),lat:h.reduce((a,e)=>a+e.lat+0.05,0), + room:Math.max(0,Math.min(...h.map(e=>e.cap-e.load+(own.has(e.k)?got:0))))});} + alts.sort((x,y)=>x.shared-y.shared||x.lat-y.lat);return {now,alts};} +// The pin as compute() walks it. Null while a link on it is down, and routing takes over. +function pinRoute(p,edges){const path=[];for(let i=1;iCIDX[x]),share:1};} +// Under a customer in the panels. +function pathCtl(b){if(!pathKind(b))return ''; + const pin=b.pin?`
${tr('customer_paths.pinned_to_path',{path:esc(pathStr(b.pin))})}${pinUp(b)?'':` · ${tr('customer_paths.that_path_is_down')}`}
`:''; + return `${pin}
${btn(tr('customer_paths.move_to_another_path'),'pathOpen',{id:b.id},'ghost sm')}
`;} +function pathModal(b){const a=pathCity(b.city),z=pathCity(b.city2),k=pathKind(b);let h=`

${tr('customer_paths.move_name',{name:esc(b.name)})}

`; + const row=(nm,meta,tag,button)=>`
${nm}${tag?` ${tag}`:''}
${meta?`
${meta}
`:''}
${button}
`; + if(k==='fiber'){const cur=S.links.find(l=>l.id===b.link),T=fiberTargets(b); + h+=`

${tr('customer_paths.this_customer_rides_one_fiber',{a,b:z})}

`; + if(cur)h+=`
${tr('customer_paths.now_on')}${fibLab(cur)}
`; + if(!T.length)h+=`

${tr('customer_paths.no_other_working_fiber',{a,b:z})}

`; + for(const t of T)h+=row(fibLab(t.l),t.no,t.diverse?tr('customer_paths.fully_diverse'):tr('customer_paths.same_trench'),btn(tr('customer_paths.move'),'pathMove',{id:b.id,link:t.l.id},'sm',!!t.no));} + else{const {now,alts}=circuitTargets(b); + h+=`

${tr('customer_paths.routing_chooses_this_circuit',{a,b:z})}

`; + if(now)h+=`
${tr('customer_paths.now_on')}${esc(pathStr(now))}
`; + if(b.pin)h+=`
${btn(tr('customer_paths.let_routing_choose_again'),'pathAuto',{id:b.id},'ghost sm')}
`; + if(!alts.length)h+=`

${tr('customer_paths.no_other_path',{a,b:z})}

`; + for(const t of alts){const warn=[t.room${tr('customer_paths.fits_only_g_of_bw',{g:fmtG(t.room),bw:fmtG(b.bw)})}`:'',b.latMax&&t.lat>b.latMax?`${tr('customer_paths.over_the_ms_budget',{ms:b.latMax})}`:''].filter(Boolean).join(' · '); + h+=row(esc(pathStr(t.p)),tr('customer_paths.path_facts',{km:Math.round(t.km).toLocaleString(),ms:t.lat.toFixed(1)})+(warn?' · '+warn:''),t.shared?trn('customer_paths.shares_n_spans',t.shared):tr('customer_paths.fully_diverse'),btn(tr('customer_paths.move'),'pathPin',{id:b.id,via:t.p.join()},'sm'));}} + openModal(h);} diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 6b28350..9d632c5 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -146,7 +146,7 @@ function compute(){RW.gen++; if(!seen[b])return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=CIDX[l.a]===v?CIDX[l.b]:CIDX[l.a];}return path;}; const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.map(srlg)));}; for(const k in edges){const e=edges[k];let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;e.pl=ld;} - const l2Routes=(A,B,b)=>{const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B]; + const l2Routes=(A,B,b)=>{if(b.pin){const r=pinRoute(b.pin,edges);if(r)return [r];}const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B]; if(PX&&m==='fast')return pieFast(PX,fastSP,A,B,b,wLat); if(m!=='scenic')return [{...walkI(m==='fast'?(fastSP[A]||(fastSP[A]=dijkstra(adj,Ai,wLat))).P:SPP[A],Ai,Bi),share:1}]; const ek='l2:'+b.id,own=e=>(R.efg&&R.efg[e.id]&&R.efg[e.id].get(ek))||0; diff --git a/src/game/80-simulation/50-sanitize.js b/src/game/80-simulation/50-sanitize.js index 7e33b48..db35e34 100644 --- a/src/game/80-simulation/50-sanitize.js +++ b/src/game/80-simulation/50-sanitize.js @@ -54,7 +54,7 @@ function sanitize(s){ for(const k of Object.keys(s.peers)){const [n,c]=k.split('@');if(!isNet(n)||!isIx(c))delete s.peers[k];} for(const c of Object.keys(s.myIx)){const m=s.myIx[c];if(!isCity(c)||!m||typeof m!=='object'){delete s.myIx[c];continue;}m.members=Array.isArray(m.members)?m.members.filter(isNet):[];m.name=String(m.name||tr('common.your_ix')).slice(0,40);m.next=num(m.next,s.day);m.fab=int(m.fab,0,MYIX_FAB.length-1,0);} const okBiz=b=>b&&own(BIZ_T,b.type)&&(!BIZ_T[b.type].nni||own(FAB,b.prov))&&isCity(b.city)&&(!b.city2||isCity(b.city2))&&(!b.sites||Array.isArray(b.sites)&&b.sites.every(isCity)); - const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;return b;}; + const fixBiz=b=>{b.id=sid(b.id);b.name=String(b.name||tr('common.customer')).slice(0,80);b.bw=num(b.bw,1);b.rate=num(b.rate,0);if(b.fee!==undefined)b.fee=num(b.fee,0);if(b.start!==undefined)b.start=num(b.start,0);if(b.dur!==undefined)b.dur=num(b.dur,1);if(b.slots!==undefined)b.slots=num(b.slots,0);if(b.what!==undefined)b.what=String(b.what).slice(0,200);if(b.broker!==undefined)b.broker=!!b.broker;if(!Array.isArray(b.reqs))b.reqs=[];b.reqs=b.reqs.filter(r=>own(REQS,r));if(b.mood!==undefined)b.mood=num(b.mood,100);if(b.pm!==undefined)b.pm=num(b.pm,b.mood||100);if(b.exp!==undefined)b.exp=num(b.exp,0);if(b.latMax!=null)b.latMax=num(b.latMax,10);if(b.route&&!own(RT,b.route))b.route='normal';if(b.due!==undefined)b.due=num(b.due,0);if(b.win!==undefined)b.win=num(b.win,180);if(b.live!==undefined)b.live=!!b.live;if(b.link!==undefined&&typeof b.link!=='string')delete b.link;if(b.pin!==undefined){const p=b.pin;if(!Array.isArray(p)||p.length<2||p.length>64||!p.every(isCity)||new Set(p).size!==p.length||!BIZ_T[b.type].l2||b.sites||p[0]!==b.city||p[p.length-1]!==b.city2)delete b.pin;}return b;}; {const ids=new Map(s.links.map(l=>[l.id,l]));s.biz=s.biz.filter(okBiz).map(b=>clFix(s,unpackBiz(fixBiz(b),ids)));}s.offers=s.offers.filter(okBiz).map(fixBiz); // Contracts (#178): the bandwidth market an offer was priced in, who referred it, and the month-by-month tally. for(const o of s.offers){if(!(typeof o.mk==='number'&&o.mk>0&&o.mk<=5))delete o.mk;if(typeof o.ref!=='string')delete o.ref;if(o.refN!==undefined)o.refN=String(o.refN).slice(0,80);}clFixState(s);salesFix(s); diff --git a/src/game/90-actions/53-customer-paths.js b/src/game/90-actions/53-customer-paths.js new file mode 100644 index 0000000..c362a64 --- /dev/null +++ b/src/game/90-actions/53-customer-paths.js @@ -0,0 +1,13 @@ +Object.assign(ACT,{ + pathOpen:({id})=>{const b=S.biz.find(x=>x.id===id);if(b&&pathKind(b))pathModal(b);}, + pathMove:({id,link})=>{const b=S.biz.find(x=>x.id===id),l=b&&pathKind(b)==='fiber'&&fiberTargets(b).find(t=>t.l.id===link&&!t.no);if(!l)return; + // A carrier already renting waves on that fiber: one contract, as when it orders more there. + const more=b.type==='wwave'&&S.biz.find(x=>x!==b&&x.type==='wwave'&&x.link===link&&x.name===b.name); + if(more){more.slots=(more.slots||0)+(b.slots||0);more.rate+=b.rate;more.since=Math.min(more.since??0,b.since??0);more.mood=Math.min(more.mood??100,b.mood??100);more.what=wwWhat(l.l,more.slots);S.biz=S.biz.filter(x=>x!==b);} + else{b.link=link;if(b.type==='wwave')b.what=wwWhat(l.l,b.slots||1);} + closeModal();toast(tr('customer_paths.name_moved_to_fiber',{name:esc(b.name),fiber:fibLab(l.l)}),'good');sfx('build');after();}, + pathPin:({id,via})=>{const b=S.biz.find(x=>x.id===id);if(!b||pathKind(b)!=='circuit'||typeof via!=='string')return;const p=via.split(','); + if(p.length<2||p[0]!==b.city||p[p.length-1]!==b.city2||new Set(p).size!==p.length||!pathHops(pathEdges(),p))return; + b.pin=p;closeModal();toast(tr('customer_paths.name_now_rides_path',{name:esc(b.name),path:esc(pathStr(p))}),'good');sfx('build');after();}, + pathAuto:({id})=>{const b=S.biz.find(x=>x.id===id);if(!b||!b.pin)return;delete b.pin;closeModal();toast(tr('customer_paths.name_follows_routing_again',{name:esc(b.name)}),'good');sfx('click');after();}, +}); diff --git a/src/game/90-actions/85-routing-and-routers.js b/src/game/90-actions/85-routing-and-routers.js index 6a6822f..45502f4 100644 --- a/src/game/90-actions/85-routing-and-routers.js +++ b/src/game/90-actions/85-routing-and-routers.js @@ -9,7 +9,7 @@ Object.assign(ACT,{ routingOpen:()=>{if(S&&!pzOn())routingModal();}, coreSet:({v})=>{if(!S.core)return;v=+v;if(!(v>=0&&v<=S.core.lv)||(v===S.core.run&&!S.core.legacy))return;S.core.run=v;delete S.core.legacy;sfx('click');after();}, via:({v})=>{UI.via=v;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, - setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;sfx('click');after();}}, + setRoute:({id,m})=>{if(!own(RT,m))return;const b=S.biz.find(x=>x.id===id);if(b){b.route=m;delete b.pin;sfx('click');after();}}, route:({r})=>{UI.route=r;if(UI.pending)openLinkModal(UI.pending.a,UI.pending.b);}, addParallel:({id})=>{const l=S.links.find(x=>x.id===id);if(l)openLinkModal(l.a,l.b);}, popStdSet:({city})=>{const p=S.pops[city];if(!p||pzOn())return;S.popStd={g:p.rgen||0,rt:p.routers||1};toast(tr('pop_std.new_pops_now_start_with',{n:S.popStd.rt,model:esc(RG[S.popStd.g].n)}),'good');sfx('click');after();}, diff --git a/src/game/93-ui/50-city-panel.js b/src/game/93-ui/50-city-panel.js index ed2eb74..5a89d6a 100644 --- a/src/game/93-ui/50-city-panel.js +++ b/src/game/93-ui/50-city-panel.js @@ -37,7 +37,7 @@ function cityPanel(c){ h+=`

${tr('common.business_customers')}

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

${tr('city_panel.no_businesses_yet_offers_pop_up')}

`; - 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)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('city_panel.fiber_is_down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('common.needs_a_scrubbing_center')+'':''}${S.day-(b.since||0)<15?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}
${tr('common.happiness_p',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.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)}${clTermTxt(b)?' · '+clTermTxt(b):''}${BIZ_T[b.type].l2?` · ${b.sites?tr('city_panel.carrying_g_per_site',{g:fmtG(R.l2[b.id]||0)}):tr('city_panel.carrying_g',{g:fmtG(R.l2[b.id]||0)})}`:''}${BIZ_T[b.type].fiber&&!fiberOk(b)?' · '+tr('city_panel.fiber_is_down')+'':''}${BIZ_T[b.type].event&&eventLive(b)?` · ${tr('city_panel.serving_v',{v:pct(sfOf(R,b.city))})}`:''}${b.type==='scrub'&&!hasScrub()?' · '+tr('common.needs_a_scrubbing_center')+'':''}${S.day-(b.since||0)<15?` · ${tr('common.provisioning_n_d_grace',{n:15-(S.day-(b.since||0))})}`:''}
${bRisk(b)}${reqList(b)}${BIZ_T[b.type].l2?routeCtl(b):''}${pathCtl(b)}
${tr('common.happiness_p',{p:Math.round(b.mood)})}
${btn(UI.confirm===b.id?tr('common.really_drop'):tr('common.drop'),'dropBiz',{id:b.id},'ghost sm')}
`; h+=`
`+offersHere(c); }else if(UI.tab==='up'){ h+=portNote(c)+latNote(c); diff --git a/src/game/93-ui/70-link-panels.js b/src/game/93-ui/70-link-panels.js index 44ab4bb..705313a 100644 --- a/src/game/93-ui/70-link-panels.js +++ b/src/game/93-ui/70-link-panels.js @@ -122,7 +122,7 @@ function dfPanel(l){
${tr('common.latency')}${tr('common.ms_ms_one_way',{ms:linkLat(l).toFixed(1)})}
${l.own?tr('link_panels.right_of_way_upkeep'):tr('common.iru_lease')}${tr('common.price_mo',{price:fmt$(l.mo)})}
${tr('link_panels.n_amp_huts',{n:amps})}${tr('common.price_mo',{price:fmt$(amps*AMP_MO)})}
${!bld&&!(l.ch||[]).length?`

${tr('link_panels.this_fiber_is_dark_add_optics')}

`:''}
`; if(!bld){const sold=S.biz.filter(b=>b.link===l.id&&(b.type==='wwave'||b.type==='mwave'||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('')} +
${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)})}
${pathCtl(b)}
`).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')}
`:brListHtml(l,fc)}
`;} h+=`

${tr('common.optics')}

${tr('link_panels.each_channel_is_a_pair_of')}

`; if(l.own&&l.sub&&!l.seat)h+=subUpgradePanel(l); diff --git a/src/i18n/en.js b/src/i18n/en.js index 5323950..3f82fb1 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1758,6 +1758,30 @@ "core.vendor_zoo":"Vendor zoo", "core.your_auto_te_predates_backbones":"Your Auto-TE was installed before backbones had a technology, so it runs as it always did. Changing the backbone switches to the new rules.", "core.your_backbone_now_runs_lv":"Your backbone now runs {lv}.", +"customer_paths.fiber_label":"{name} · {km} km", +"customer_paths.fits_only_g_of_bw":"Fits only {g} of {bw}", +"customer_paths.fully_diverse":"Fully diverse", +"customer_paths.its_spare_pairs_are_taken":"Its spare pairs are already rented", +"customer_paths.let_routing_choose_again":"Let routing choose again", +"customer_paths.move":"Move", +"customer_paths.move_name":"Move {name}", +"customer_paths.move_to_another_path":"Move to another path", +"customer_paths.name_follows_routing_again":"{name} follows routing again.", +"customer_paths.name_moved_to_fiber":"{name} moved to {fiber}.", +"customer_paths.name_now_rides_path":"{name} now rides {path}.", +"customer_paths.no_other_path":"There is no other working path between {a} and {b} right now.", +"customer_paths.no_other_working_fiber":"There is no other working fiber between {a} and {b}. Build one, and you can move this customer onto it.", +"customer_paths.not_enough_free_channels":"Not enough free channels: {free} free, needs {n}", +"customer_paths.now_on":"Now on", +"customer_paths.only_your_own_fiber_rents_pairs":"Only your own fiber can rent out pairs", +"customer_paths.over_the_ms_budget":"Over the {ms} ms budget", +"customer_paths.path_facts":"{km} km · {ms} ms", +"customer_paths.pinned_to_path":"Pinned to {path}", +"customer_paths.routing_chooses_this_circuit":"Routing chooses this circuit's path between {a} and {b} every day. Moving it pins it to the path you pick, for free. While a link on that path is down, it follows routing until the link is back.", +"customer_paths.same_trench":"Same trench", +"customer_paths.shares_n_spans":{"one":"Shares {n} span","other":"Shares {n} spans"}, +"customer_paths.that_path_is_down":"That path is down, so it follows routing for now", +"customer_paths.this_customer_rides_one_fiber":"This customer rides one fiber between {a} and {b}. Moving it to another one is free and happens at once.", "customers.attacks_on_city_are_hauled_to":"attacks on {city} are hauled to {to} for scrubbing: +{ms} ms", "customers.everyone_who_pays_you_happiest_last":"Everyone who pays you, happiest last. Below 60% they start to grumble, below 30% they are furious, and at 0% they cancel.", "customers.from_unhappy_customers":"from unhappy customers", diff --git a/tests/customer-paths.test.js b/tests/customer-paths.test.js new file mode 100644 index 0000000..2b6c3d2 --- /dev/null +++ b/tests/customer-paths.test.js @@ -0,0 +1,191 @@ +// Moving a customer to another path between the same two POPs: fiber customers to another fiber, circuits by a pin. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// New York and Ashburn, with Boston as the way round, for the test's sake. Fiber a is the direct one, on its own trench; +// b runs beside it in the same trench; c is direct on another trench; d and e go through Boston on trenches of their own. +const fib = (id, a, z, km, trench, n = 8) => `S.links.push({id:'${id}',a:'${a}',b:'${z}',kind:'df',own:true,sys:'roadm',pairs:1,ch:Array(${n}).fill('zr4'),km:${km},sub:false,cable:null,mo:1,trench:'${trench}',cut:0,day:0,ready:0,spares:false});`; +const BASE = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + + "for(const c of ['nyc','ash','bos'])if(!S.pops[c])S.pops[c]={day:0,bb:null,boost:0,down:0,routers:4,gen:false,rgen:RG.length-3};S.links=[];" + + fib('a', 'nyc', 'ash', 350, 'ta') + fib('b', 'nyc', 'ash', 350, 'ta') + fib('c', 'ash', 'nyc', 420, 'tc') + fib('d', 'nyc', 'bos', 130, 'td') + fib('e', 'bos', 'ash', 220, 'te'); +const hasCities = (ev) => ev("['nyc','ash','bos'].every(isCity)"); +const wave = "S.biz.push({id:'w',type:'wwave',name:'Zay-No Fiber',city:'nyc',city2:'ash',link:'a',slots:2,bw:1,rate:9000,reqs:[],mood:80,since:0,day:0,route:'normal',what:'x'});"; +const pair = (type, id = 'p', link = 'a') => `S.biz.push({id:'${id}',type:'${type}',name:'A Customer ${id}',city:'nyc',city2:'ash',link:'${link}',slots:0,bw:1,rate:9000,reqs:[],mood:80,since:0,day:0,route:'normal',what:'x'});`; +const circuit = (bw = 100) => `S.biz.push({id:'k',type:'l2vpn',name:'Big Circuit',city:'nyc',city2:'ash',bw:${bw},rate:10,reqs:[],mood:80,since:0,day:0,route:'normal'});`; +function game(t, extra = '') { const h = load({ seed: 777 }); t.after(() => h.dom.window.close()); + h.ev(BASE); assert.equal(hasCities(h.ev), true); h.ev(extra + 'compute();'); return h; } +const biz = (ev, id, k) => ev(`S.biz.find(b=>b.id===${lit(id)}).${k}`); +const modal = (ev) => ev("document.getElementById('modal').textContent"); + +test('a wave moves to another fiber: free, its channels go with it, and the first choice is on another trench', (t) => { + const { ev, errors } = game(t, wave); + const cash = ev('S.cash'); + assert.deepEqual(JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).map(x=>[x.l.id,x.diverse,x.no]))")), [['c', true, ''], ['b', false, '']]); + assert.equal(ev("soldSlots(S.links.find(l=>l.id==='a'))"), 2); + ev("ACT.pathOpen({id:'w'})"); + assert.match(modal(ev), /Fully diverse/); assert.match(modal(ev), /Same trench/); + ev("ACT.pathMove({id:'w',link:'c'})"); + assert.equal(biz(ev, 'w', 'link'), 'c'); + assert.equal(ev("soldSlots(S.links.find(l=>l.id==='a'))"), 0); + assert.equal(ev("soldSlots(S.links.find(l=>l.id==='c'))"), 2); + assert.equal(ev('S.cash'), cash, 'free'); + assert.equal(biz(ev, 'w', 'rate'), 9000, 'the contract stands'); + assert.equal(ev("document.getElementById('modal').hidden"), true); + assert.deepEqual(errors, []); +}); + +test('a wave needs room on the new fiber; a move is checked again when it is made', (t) => { + const { ev, errors } = game(t, wave + "S.links.find(l=>l.id==='c').ch=Array(63).fill('zr4');"); + const c = JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).find(x=>x.l.id==='c'))")); + assert.match(c.no, /1 free, needs 2/); + ev("ACT.pathMove({id:'w',link:'c'})"); + assert.equal(biz(ev, 'w', 'link'), 'a', 'refused'); + for (const link of ['a', 'd', 'nope']) { ev(`ACT.pathMove({id:'w',link:${lit(link)}})`); assert.equal(biz(ev, 'w', 'link'), 'a', `${link}: not a fiber it can go to`); } + assert.deepEqual(errors, []); +}); + +test('a carrier already renting waves on the new fiber ends up with one contract', (t) => { + const { ev, errors } = game(t, wave + "S.biz.push({id:'w2',type:'wwave',name:'Zay-No Fiber',city:'nyc',city2:'ash',link:'c',slots:3,bw:1,rate:1000,reqs:[],mood:90,since:5,day:0,route:'normal',what:'x'});"); + ev("ACT.pathMove({id:'w',link:'c'})"); + assert.equal(ev("S.biz.filter(b=>b.type==='wwave').length"), 1); + assert.equal(biz(ev, 'w2', 'slots'), 5); assert.equal(biz(ev, 'w2', 'rate'), 10000); assert.equal(biz(ev, 'w2', 'mood'), 80, 'the unhappier of the two'); assert.equal(biz(ev, 'w2', 'since'), 0); + assert.match(biz(ev, 'w2', 'what'), /5/); + assert.deepEqual(errors, []); +}); + +test('fiber pairs follow the same rules as signing them: your own fiber, and pairs still free', (t) => { + for (const type of ['dfpair', 'pairs', 'capfib']) { + const { ev, errors } = game(t, pair(type) + pair('pairs', 'q', 'b') + "S.links.find(l=>l.id==='e').x=1;"); + const T = JSON.parse(ev("JSON.stringify(Object.fromEntries(fiberTargets(S.biz[0]).map(x=>[x.l.id,x.no])))")); + assert.equal(T.c, '', `${type} can go to the free fiber`); + assert.match(T.b, /already rented/, `${type} cannot join a fiber whose pairs are sold`); + ev("ACT.pathMove({id:'p',link:'b'})"); assert.equal(biz(ev, 'p', 'link'), 'a'); + ev("ACT.pathMove({id:'p',link:'c'})"); assert.equal(biz(ev, 'p', 'link'), 'c'); + assert.deepEqual(errors, []); + } + const { ev } = game(t, pair('dfpair') + "S.links.find(l=>l.id==='c').own=false;"); + assert.match(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), /your own fiber/); +}); + +test('only working fibers are offered, and a customer on a cut fiber can be moved off it', (t) => { + const { ev, errors } = game(t, wave + "S.links.find(l=>l.id==='a').cut=S.day+9;S.links.find(l=>l.id==='b').eqDown=S.day+9;" + fib('f', 'nyc', 'ash', 300, 'tf') + "S.links.at(-1).ready=S.day+5;"); + assert.equal(ev("fiberOk(S.biz[0])"), false); + assert.deepEqual(JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).map(x=>x.l.id))")), ['c']); + ev("ACT.pathMove({id:'w',link:'c'})"); + assert.equal(ev("fiberOk(S.biz[0])"), true); + ev("S.links.find(l=>l.id==='c').ready=S.day+5;"); + assert.deepEqual(JSON.parse(ev("JSON.stringify(fiberTargets(S.biz[0]).map(x=>x.l.id))")), [], 'nothing left'); + ev("ACT.pathOpen({id:'w'})"); + assert.match(modal(ev), /no other working fiber/); + assert.deepEqual(errors, []); +}); + +test('a pinned circuit rides its path, and takes the load off the direct fibers', (t) => { + const { ev, errors } = game(t, circuit(100)); + const cash = ev('S.cash'); + const load = () => JSON.parse(ev("JSON.stringify(Object.fromEntries(['a','b','c','d','e'].map(i=>[i,R.load[i]||0])))")); + const direct = load(); + assert.equal(Math.round(direct.a + direct.b + direct.c), 100, 'by default it takes the direct edge'); + assert.equal(Math.round(direct.d), 0); + const T = JSON.parse(ev("JSON.stringify(circuitTargets(S.biz[0]))")); + assert.deepEqual(T.now, ['nyc', 'ash']); + assert.deepEqual(T.alts.map((x) => x.p), [['nyc', 'bos', 'ash']]); + assert.equal(T.alts[0].shared, 0, 'nothing in common with the direct fibers'); + ev("ACT.pathOpen({id:'k'})"); + assert.match(modal(ev), /Fully diverse/); + ev("ACT.pathPin({id:'k',via:'nyc,bos,ash'})"); + const on = load(); + assert.equal(Math.round(on.a + on.b + on.c), 0); + assert.equal(Math.round(on.d), 100); assert.equal(Math.round(on.e), 100); + assert.equal(ev("R.l2.k"), 100); + assert.ok(ev('R.l2lat.k') > 0); + assert.equal(ev('S.cash'), cash, 'free'); + assert.deepEqual(errors, []); +}); + +test('a pin falls back to routing while a link on it is down, comes back by itself, and can be undone', (t) => { + const { ev, errors } = game(t, circuit(100) + "S.biz[0].pin=['nyc','bos','ash'];"); + assert.equal(ev('Math.round(R.load.d)'), 100); + ev("S.links.find(l=>l.id==='e').cut=S.day+9;compute();"); + assert.equal(ev('Math.round(R.load.d||0)'), 0, 'off the broken path'); + assert.equal(ev('R.l2.k'), 100, 'and the customer keeps its service'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz[0].pin)')), ['nyc', 'bos', 'ash'], 'the pin is kept'); + assert.equal(ev('pinUp(S.biz[0])'), false); + assert.match(ev('pathCtl(S.biz[0])'), /That path is down/); + ev("S.links.find(l=>l.id==='e').cut=0;compute();"); + assert.equal(ev('Math.round(R.load.d)'), 100, 'back by itself'); + assert.doesNotMatch(ev('pathCtl(S.biz[0])'), /That path is down/); + ev("ACT.pathOpen({id:'k'})"); + assert.match(modal(ev), /Let routing choose again/); + ev("ACT.pathAuto({id:'k'})"); + assert.equal(ev("S.biz[0].pin===undefined"), true); + assert.equal(ev('Math.round(R.load.d||0)'), 0); + assert.deepEqual(errors, []); +}); + +test('choosing a route mode unpins; a bad path is refused; SD-WANs, pending deals and puzzles have no move', (t) => { + const { ev, errors } = game(t, circuit(100)); + for (const via of ['nyc,ash,bos', 'bos,nyc,ash', 'nyc', 'nyc,nowhere,ash', 'nyc,bos,nyc,ash', 'nyc,ash,ash']) { + ev(`ACT.pathPin({id:'k',via:${lit(via)}})`); + assert.equal(ev('S.biz[0].pin===undefined'), true, via); + } + ev("ACT.pathPin({id:'k',via:null})"); ev("ACT.pathPin({id:'k',via:7})"); ev("ACT.pathPin({id:'nope',via:'nyc,ash'})"); + assert.equal(ev('S.biz[0].pin===undefined'), true); + ev("S.links=S.links.filter(l=>l.id!=='e');compute();ACT.pathPin({id:'k',via:'nyc,bos,ash'})"); + assert.equal(ev('S.biz[0].pin===undefined'), true, 'a hop with no link'); + ev("ACT.pathPin({id:'k',via:'nyc,ash'})"); + assert.equal(ev('S.biz[0].pin.length'), 2); + ev("ACT.setRoute({id:'k',m:'fast'})"); + assert.equal(ev('S.biz[0].pin===undefined'), true); + assert.equal(ev("pathKind({type:'mtrain',city:'nyc',city2:'ash',sites:['nyc','ash']})"), ''); + assert.equal(ev("pathKind({type:'capw',city:'nyc',city2:'ash',due:9,live:false})"), '', 'not delivered yet'); + assert.equal(ev("pathKind({type:'capw',city:'nyc',city2:'ash',due:9,live:true})"), 'circuit'); + assert.equal(ev("pathKind({type:'l2vpn',city:'nyc'})"), '', 'no second city'); + assert.equal(ev("pathKind({type:'wwave',city:'nyc',link:'a'})"), '', 'no second city'); + assert.equal(ev("pathKind({type:'wwave',city:'nyc',city2:'ash'})"), '', 'no fiber yet'); + assert.deepEqual(errors, []); +}); + +test('with no way round, the most diverse path shares what it must and says so', (t) => { + // Boston reaches Ashburn only over the direct fibers' trench. + const { ev, errors } = game(t, circuit(100) + "S.links.find(l=>l.id==='e').trench='ta';S.links=S.links.filter(l=>l.id!=='c');"); + const T = JSON.parse(ev('JSON.stringify(circuitTargets(S.biz[0]))')); + assert.deepEqual(T.alts.map((x) => [x.p, x.shared]), [[['nyc', 'bos', 'ash'], 1]]); + ev("ACT.pathOpen({id:'k'})"); + assert.match(modal(ev), /Shares 1 span/); + assert.deepEqual(errors, []); +}); + +test('the window warns when a path is too small or too slow for the customer', (t) => { + const { ev, errors } = game(t, circuit(1e6) + "S.biz[0].latMax=0.1;"); + ev("ACT.pathOpen({id:'k'})"); + assert.match(modal(ev), /Fits only/); + assert.match(modal(ev), /Over the 0.1 ms budget/); + assert.deepEqual(errors, []); +}); + +test('saves: a pin survives a reload, and a bad one is dropped, leaving old saves alone', (t) => { + const { ev, errors } = game(t, circuit(100) + "S.biz[0].pin=['nyc','bos','ash'];"); + const again = (pin) => ev(`(()=>{const s=JSON.parse(JSON.stringify(packSave(S)));s.biz[0].pin=${lit(pin)};return JSON.stringify(migrate(s).biz[0].pin);})()`); + assert.deepEqual(JSON.parse(again(['nyc', 'bos', 'ash'])), ['nyc', 'bos', 'ash']); + for (const bad of ['nyc', [], ['nyc'], ['nyc', 'nowhere', 'ash'], ['bos', 'ash'], ['nyc', 'bos'], ['nyc', 'bos', 'nyc', 'ash'], [1, 2], { a: 1 }]) + assert.equal(again(bad), undefined, JSON.stringify(bad)); + assert.equal(ev("(()=>{const s=JSON.parse(JSON.stringify(packSave(S)));delete s.biz[0].pin;return migrate(s).biz[0].pin===undefined;})()"), true); + // Not a circuit: no pin. + assert.equal(ev("(()=>{const s=JSON.parse(JSON.stringify(packSave(S)));s.biz[0].type='wwave';s.biz[0].pin=['nyc','ash'];return migrate(s).biz[0].pin===undefined;})()"), true); + // A stale pin (a POP on it was closed) does no harm: routing carries the circuit. + ev("delete S.pops.bos;S.links=S.links.filter(l=>l.a!=='bos'&&l.b!=='bos');compute();"); + assert.equal(ev('R.l2.k'), 100); + assert.deepEqual(errors, []); +}); + +test('the buttons are in the panels: under a customer in its city, and on the fiber it rents', (t) => { + const { ev, errors } = game(t, wave + circuit(100)); + ev("UI.tab='cust';UI.sel={type:'city',id:'nyc'};selectCity('nyc');UI.tab='cust';renderPanel();"); + assert.equal(ev("document.querySelectorAll('#panel [data-act=pathOpen]').length"), 2); + ev("selectLink('a');renderPanel();"); + assert.equal(ev("[...document.querySelectorAll('#panel [data-act=pathOpen]')].length"), 1); + assert.deepEqual(errors, []); +}); From 3554e9f700956908266a988b25f91b7315997051 Mon Sep 17 00:00:00 2001 From: Christopher Hawker Date: Mon, 9 Nov 2026 16:45:08 +1100 Subject: [PATCH 15/20] Moving waves checks the room the broker would sell: bandwidth for managed waves, and what is kept back Managed waves need a channel as big as the wave and their bandwidth spare after your own traffic and the share kept back, on leased fiber too. A move bumps CM_V so their capacity follows them, merging needs the same size, and alien waves leave the kept-back channels alone. Pinned customers' badges share one path graph per routing result. --- CHANGELOG.md | 2 +- site/i18n/de.js | 3 ++ site/i18n/es.js | 3 ++ site/i18n/fr.js | 3 ++ site/i18n/it.js | 3 ++ site/i18n/pt.js | 3 ++ src/game/60-features/37-customer-paths.js | 14 ++++-- src/game/90-actions/53-customer-paths.js | 10 ++-- src/i18n/en.js | 3 ++ tests/customer-paths.test.js | 60 +++++++++++++++++++++++ 10 files changed, 96 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98ecb9a..c8eadb8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ All notable changes to this project are documented here. The project follows - Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. - A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before. - The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before. -- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Alien waves and leased fiber pairs move to another fiber, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. +- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. ## [3.2.0] — 2026-11-07 diff --git a/site/i18n/de.js b/site/i18n/de.js index 39c300f..3d0e0a9 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -1770,9 +1770,12 @@ "customer_paths.name_follows_routing_again":"{name} folgt wieder dem Routing.", "customer_paths.name_moved_to_fiber":"{name} ist auf {fiber} umgezogen.", "customer_paths.name_now_rides_path":"{name} läuft jetzt über {path}.", +"customer_paths.needs_a_g_channel":"Braucht einen Kanal mit {g} oder mehr", "customer_paths.no_other_path":"Zwischen {a} und {b} gibt es gerade keinen anderen funktionierenden Pfad.", "customer_paths.no_other_working_fiber":"Zwischen {a} und {b} gibt es keine andere funktionierende Glasfaser. Bau eine, dann kannst du diesen Kunden darauf umziehen.", "customer_paths.not_enough_free_channels":"Zu wenig freie Kanäle: {free} frei, {n} nötig", +"customer_paths.not_enough_spare_capacity":"Zu wenig freie Kapazität: {free} übrig nach deinem eigenen Traffic und den {hold} %, die du zurückhältst, {g} nötig", +"customer_paths.not_enough_spare_channels":"Zu wenig freie Kanäle: {free} übrig nach den {hold} %, die du für deinen eigenen Traffic zurückhältst, {n} nötig", "customer_paths.now_on":"Aktuell auf", "customer_paths.only_your_own_fiber_rents_pairs":"Nur deine eigene Glasfaser kann Paare vermieten", "customer_paths.over_the_ms_budget":"Über dem Budget von {ms} ms", diff --git a/site/i18n/es.js b/site/i18n/es.js index 06a6d27..4348512 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -1768,9 +1768,12 @@ "customer_paths.name_follows_routing_again":"{name} vuelve a seguir el enrutamiento.", "customer_paths.name_moved_to_fiber":"{name} se ha movido a {fiber}.", "customer_paths.name_now_rides_path":"{name} ahora va por {path}.", +"customer_paths.needs_a_g_channel":"Necesita un canal iluminado a {g} o más", "customer_paths.no_other_path":"Ahora mismo no hay otra ruta operativa entre {a} y {b}.", "customer_paths.no_other_working_fiber":"No hay otra fibra operativa entre {a} y {b}. Construye una y podrás mover a este cliente a ella.", "customer_paths.not_enough_free_channels":"No hay canales libres suficientes: {free} libres, necesita {n}", +"customer_paths.not_enough_spare_capacity":"No hay capacidad libre suficiente: quedan {free} tras tu propio tráfico y el {hold} % que reservas, necesita {g}", +"customer_paths.not_enough_spare_channels":"No hay canales libres suficientes: quedan {free} tras el {hold} % que reservas para tu propio tráfico, necesita {n}", "customer_paths.now_on":"Ahora en", "customer_paths.only_your_own_fiber_rents_pairs":"Solo tu propia fibra puede alquilar pares", "customer_paths.over_the_ms_budget":"Supera el presupuesto de {ms} ms", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 2d7fb90..a3c7813 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -1768,9 +1768,12 @@ "customer_paths.name_follows_routing_again":"{name} suit de nouveau le routage.", "customer_paths.name_moved_to_fiber":"{name} a été déplacé vers {fiber}.", "customer_paths.name_now_rides_path":"{name} passe maintenant par {path}.", +"customer_paths.needs_a_g_channel":"Il faut un canal allumé à {g} ou plus", "customer_paths.no_other_path":"Il n'y a pas d'autre chemin en service entre {a} et {b} pour le moment.", "customer_paths.no_other_working_fiber":"Il n'y a pas d'autre fibre en service entre {a} et {b}. Construis-en une et tu pourras y déplacer ce client.", "customer_paths.not_enough_free_channels":"Pas assez de canaux libres : {free} libres, il en faut {n}", +"customer_paths.not_enough_spare_capacity":"Pas assez de capacité libre : il reste {free} après ton propre trafic et les {hold} % que tu gardes de côté, il en faut {g}", +"customer_paths.not_enough_spare_channels":"Pas assez de canaux libres : il en reste {free} après les {hold} % que tu gardes pour ton propre trafic, il en faut {n}", "customer_paths.now_on":"Actuellement sur", "customer_paths.only_your_own_fiber_rents_pairs":"Seule ta propre fibre peut louer des paires", "customer_paths.over_the_ms_budget":"Au-delà du budget de {ms} ms", diff --git a/site/i18n/it.js b/site/i18n/it.js index 5497bfb..0c57513 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -1768,9 +1768,12 @@ "customer_paths.name_follows_routing_again":"{name} segue di nuovo il routing.", "customer_paths.name_moved_to_fiber":"{name} spostato su {fiber}.", "customer_paths.name_now_rides_path":"{name} ora passa per {path}.", +"customer_paths.needs_a_g_channel":"Serve un canale acceso a {g} o più", "customer_paths.no_other_path":"Al momento non c'è un altro percorso funzionante tra {a} e {b}.", "customer_paths.no_other_working_fiber":"Non c'è un'altra fibra funzionante tra {a} e {b}. Costruiscine una e potrai spostarci questo cliente.", "customer_paths.not_enough_free_channels":"Canali liberi insufficienti: {free} liberi, ne servono {n}", +"customer_paths.not_enough_spare_capacity":"Capacità libera insufficiente: restano {free} dopo il tuo traffico e il {hold}% che tieni da parte, ne servono {g}", +"customer_paths.not_enough_spare_channels":"Canali liberi insufficienti: ne restano {free} dopo il {hold}% che tieni da parte per il tuo traffico, ne servono {n}", "customer_paths.now_on":"Ora su", "customer_paths.only_your_own_fiber_rents_pairs":"Solo la tua fibra può affittare coppie", "customer_paths.over_the_ms_budget":"Oltre il budget di {ms} ms", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 46bb3fc..f915c74 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -1768,9 +1768,12 @@ "customer_paths.name_follows_routing_again":"{name} volta a seguir o roteamento.", "customer_paths.name_moved_to_fiber":"{name} movido para {fiber}.", "customer_paths.name_now_rides_path":"{name} agora passa por {path}.", +"customer_paths.needs_a_g_channel":"Precisa de um canal aceso a {g} ou mais", "customer_paths.no_other_path":"Agora não há outro caminho funcionando entre {a} e {b}.", "customer_paths.no_other_working_fiber":"Não há outra fibra funcionando entre {a} e {b}. Construa uma e você poderá mover este cliente para ela.", "customer_paths.not_enough_free_channels":"Canais livres insuficientes: {free} livres, precisa de {n}", +"customer_paths.not_enough_spare_capacity":"Capacidade livre insuficiente: sobram {free} depois do seu próprio tráfego e dos {hold}% que você reserva, precisa de {g}", +"customer_paths.not_enough_spare_channels":"Canais livres insuficientes: sobram {free} depois dos {hold}% que você reserva para o seu próprio tráfego, precisa de {n}", "customer_paths.now_on":"Agora em", "customer_paths.only_your_own_fiber_rents_pairs":"Só a sua própria fibra pode alugar pares", "customer_paths.over_the_ms_budget":"Acima do orçamento de {ms} ms", diff --git a/src/game/60-features/37-customer-paths.js b/src/game/60-features/37-customer-paths.js index 8a0510a..e6eb4ae 100644 --- a/src/game/60-features/37-customer-paths.js +++ b/src/game/60-features/37-customer-paths.js @@ -8,8 +8,13 @@ const trenchOf=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id); const pathCity=c=>CITY[c].name,pathStr=p=>p.map(pathCity).join(' → '); const samePair=(l,a,b)=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a); const fibLab=l=>tr('customer_paths.fiber_label',{name:l.cname?esc(l.cname):capName(l),km:Math.round(l.km).toLocaleString()}); -// Why this fiber cannot take this customer, in the same terms as the offers for it. -function fiberNo(b,l){if(b.type==='wwave'){const n=b.slots||1,free=freeCh(l);return free>=n?'':tr('customer_paths.not_enough_free_channels',{free:Math.max(0,free),n});} +// Why this fiber cannot take this customer, in the same terms as the market that sold it: waves only where the broker +// could sell them, after the share kept back for your own traffic. +function fiberNo(b,l){const n=b.slots||1,hold=S.cm.hold; + if(b.type==='wwave'){const free=freeCh(l),spare=cmSpare(l,'spec');return spare>=n?'':free=n*g?'':tr('customer_paths.not_enough_spare_capacity',{free:fmtCap(free),g:fmtCap(n*g),hold});} if(!l.own)return tr('customer_paths.only_your_own_fiber_rents_pairs'); if(b.type==='dfpair')return pairFree(l)?'':tr('customer_paths.its_spare_pairs_are_taken'); return S.biz.some(x=>x!==b&&x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type))?tr('customer_paths.its_spare_pairs_are_taken'):'';} @@ -28,7 +33,10 @@ function pathWalk(G,a,b,cost){const dist={[a]:0},prev={},done=new Set();for(;;){ for(const e of G.N[u]||[]){const v=e.a===u?e.b:e.a,nd=ud+cost(e);if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=u;}}} if(dist[b]===undefined)return null;const p=[b];while(p[0]!==a)p.unshift(prev[p[0]]);return p;} const pathHops=(G,p)=>{const o=[];for(let i=1;i!!pathHops(pathEdges(),b.pin); +// The panels ask for every pinned customer: one graph per routing (a new R), not one per customer. +let PIN_G=null; +const pinG=()=>{const c=PIN_G;if(!c||c.R!==R||c.S!==S||c.d!==S.day||c.n!==S.links.length)PIN_G={R,S,d:S.day,n:S.links.length,G:pathEdges()};return PIN_G.G;}; +const pinUp=b=>!!pathHops(pinG(),b.pin); // Where the circuit runs today. Scenic circuits remember it; the others take the shortest path of their kind. function pathNow(b,G){if(b.pin&&pathHops(G,b.pin))return b.pin; const r=R.l2route&&R.l2route[b.id+'>'+b.city+'>'+b.city2];if(r&&r[0]){const p=r[0].ns.slice();if(p[0]!==b.city)p.reverse();if(pathHops(G,p))return p;} diff --git a/src/game/90-actions/53-customer-paths.js b/src/game/90-actions/53-customer-paths.js index c362a64..8f723e7 100644 --- a/src/game/90-actions/53-customer-paths.js +++ b/src/game/90-actions/53-customer-paths.js @@ -1,10 +1,12 @@ Object.assign(ACT,{ pathOpen:({id})=>{const b=S.biz.find(x=>x.id===id);if(b&&pathKind(b))pathModal(b);}, pathMove:({id,link})=>{const b=S.biz.find(x=>x.id===id),l=b&&pathKind(b)==='fiber'&&fiberTargets(b).find(t=>t.l.id===link&&!t.no);if(!l)return; - // A carrier already renting waves on that fiber: one contract, as when it orders more there. - const more=b.type==='wwave'&&S.biz.find(x=>x!==b&&x.type==='wwave'&&x.link===link&&x.name===b.name); - if(more){more.slots=(more.slots||0)+(b.slots||0);more.rate+=b.rate;more.since=Math.min(more.since??0,b.since??0);more.mood=Math.min(more.mood??100,b.mood??100);more.what=wwWhat(l.l,more.slots);S.biz=S.biz.filter(x=>x!==b);} - else{b.link=link;if(b.type==='wwave')b.what=wwWhat(l.l,b.slots||1);} + // A carrier already renting waves of that kind (and size) on that fiber: one contract, as when it orders more there. + const wv=b.type==='wwave'||b.type==='mwave',what=(x,n)=>b.type==='wwave'?wwWhat(l.l,n):cmWhat(l.l,cmWP(x.g),n); + const more=wv&&S.biz.find(x=>x!==b&&x.type===b.type&&x.link===link&&x.name===b.name&&x.g===b.g); + if(more){more.slots=(more.slots||0)+(b.slots||0);more.rate+=b.rate;more.since=Math.min(more.since??0,b.since??0);more.mood=Math.min(more.mood??100,b.mood??100);more.what=what(more,more.slots);S.biz=S.biz.filter(x=>x!==b);} + else{b.link=link;if(wv)b.what=what(b,b.slots||1);} + CM_V++; // managed waves come off their fiber's capacity (mwG()), which caches by fiber closeModal();toast(tr('customer_paths.name_moved_to_fiber',{name:esc(b.name),fiber:fibLab(l.l)}),'good');sfx('build');after();}, pathPin:({id,via})=>{const b=S.biz.find(x=>x.id===id);if(!b||pathKind(b)!=='circuit'||typeof via!=='string')return;const p=via.split(','); if(p.length<2||p[0]!==b.city||p[p.length-1]!==b.city2||new Set(p).size!==p.length||!pathHops(pathEdges(),p))return; diff --git a/src/i18n/en.js b/src/i18n/en.js index 3f82fb1..89e662f 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -1769,9 +1769,12 @@ "customer_paths.name_follows_routing_again":"{name} follows routing again.", "customer_paths.name_moved_to_fiber":"{name} moved to {fiber}.", "customer_paths.name_now_rides_path":"{name} now rides {path}.", +"customer_paths.needs_a_g_channel":"Needs a channel lit at {g} or more", "customer_paths.no_other_path":"There is no other working path between {a} and {b} right now.", "customer_paths.no_other_working_fiber":"There is no other working fiber between {a} and {b}. Build one, and you can move this customer onto it.", "customer_paths.not_enough_free_channels":"Not enough free channels: {free} free, needs {n}", +"customer_paths.not_enough_spare_capacity":"Not enough spare capacity: {free} left after your own traffic and the {hold}% you keep back, needs {g}", +"customer_paths.not_enough_spare_channels":"Not enough spare channels: {free} left after the {hold}% you keep back for your own traffic, needs {n}", "customer_paths.now_on":"Now on", "customer_paths.only_your_own_fiber_rents_pairs":"Only your own fiber can rent out pairs", "customer_paths.over_the_ms_budget":"Over the {ms} ms budget", diff --git a/tests/customer-paths.test.js b/tests/customer-paths.test.js index 2b6c3d2..01d5aae 100644 --- a/tests/customer-paths.test.js +++ b/tests/customer-paths.test.js @@ -55,6 +55,66 @@ test('a carrier already renting waves on the new fiber ends up with one contract assert.deepEqual(errors, []); }); +test('a wave leaves alone the channels kept back for your own traffic', (t) => { + // 47 channels lit of 64: 17 free, but a quarter of the fiber is kept back, so 1 spare. + const { ev, errors } = game(t, wave + "S.cm.hold=25;S.links.find(l=>l.id==='c').ch=Array(47).fill('zr4');"); + assert.match(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), /1 left after the 25% you keep back.*needs 2/); + ev("ACT.pathMove({id:'w',link:'c'})"); + assert.equal(biz(ev, 'w', 'link'), 'a', 'refused'); + ev("S.cm.hold=0;ACT.pathMove({id:'w',link:'c'})"); + assert.equal(biz(ev, 'w', 'link'), 'c', 'nothing kept back: it fits'); + assert.deepEqual(errors, []); +}); + +// Four managed 400G waves, 1.6T in all, carved out of fiber a's lit capacity. +const mwave = (id = 'm', link = 'a', g = 400, slots = 4) => `S.biz.push({id:'${id}',type:'mwave',g:${g},name:'Photon Express',city:'nyc',city2:'ash',link:'${link}',slots:${slots},bw:1,rate:5000,reqs:[],mood:80,since:0,day:0,route:'normal',what:'x'});`; + +test('managed waves need that much spare lit capacity on the new fiber, on leased fiber too, and their capacity moves with them', (t) => { + // c has 1.6T lit, but a quarter is kept back: 1.2T spare, room for three of the four. b has 3.2T: 2.4T spare. + const { ev, errors } = game(t, mwave() + "S.cm.hold=25;S.links.find(l=>l.id==='c').ch=Array(4).fill('zr4');"); + const no = () => JSON.parse(ev("JSON.stringify(Object.fromEntries(fiberTargets(S.biz[0]).map(x=>[x.l.id,x.no])))")); + assert.match(no().c, /Not enough spare capacity/); + assert.equal(no().b, ''); + ev("ACT.pathMove({id:'m',link:'c'})"); + assert.equal(biz(ev, 'm', 'link'), 'a', '1.6T does not fit in 1.2T'); + // A leased fiber is lit capacity like any other: the reason is the room, not whose glass it is. + ev("S.links.find(l=>l.id==='b').own=false;S.links.find(l=>l.id==='c').own=false;"); + assert.equal(no().b, ''); + assert.doesNotMatch(no().c, /own fiber/); + assert.match(no().c, /spare capacity/); + // What the fiber gives your own traffic follows the waves, at once. + assert.equal(ev("mwG(S.links.find(l=>l.id==='a'))"), 1600); + ev("ACT.pathMove({id:'m',link:'b'})"); + assert.equal(biz(ev, 'm', 'link'), 'b'); + assert.equal(ev("mwG(S.links.find(l=>l.id==='a'))"), 0); + assert.equal(ev("mwG(S.links.find(l=>l.id==='b'))"), 1600); + assert.equal(ev("dfCap0(S.links.find(l=>l.id==='a'))"), 3200); + assert.equal(ev("dfCap0(S.links.find(l=>l.id==='b'))"), 1600); + assert.match(biz(ev, 'm', 'what'), /4/); + assert.deepEqual(errors, []); +}); + +test('a managed wave needs a channel as big as it is; a carrier renting the same size there gets one contract, another size does not', (t) => { + { const { ev, errors } = game(t, mwave('m', 'a', 800, 1) + "S.cm.hold=0;"); + assert.match(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), /Needs a channel lit at/, '400G optics only'); + ev("S.links.find(l=>l.id==='c').ch=Array(8).fill('zr8');"); + assert.equal(ev("fiberTargets(S.biz[0]).find(x=>x.l.id==='c').no"), ''); + assert.deepEqual(errors, []); } + { const { ev, errors } = game(t, mwave() + mwave('m2', 'b', 100, 2) + "S.cm.hold=0;"); + ev("ACT.pathMove({id:'m',link:'b'})"); + assert.equal(ev("S.biz.filter(b=>b.type==='mwave'&&b.link==='b').length"), 2, '400G and 100G waves stay apart'); + assert.equal(biz(ev, 'm2', 'slots'), 2); + assert.equal(ev("mwG(S.links.find(l=>l.id==='b'))"), 1800); + assert.deepEqual(errors, []); } + { const { ev, errors } = game(t, mwave() + mwave('m2', 'b', 400, 2) + "S.cm.hold=0;"); + ev("ACT.pathMove({id:'m',link:'b'})"); + assert.equal(ev("S.biz.filter(b=>b.type==='mwave').length"), 1); + assert.equal(biz(ev, 'm2', 'slots'), 6); assert.equal(biz(ev, 'm2', 'rate'), 10000); assert.equal(biz(ev, 'm2', 'g'), 400); + assert.match(biz(ev, 'm2', 'what'), /6/); + assert.equal(ev("mwG(S.links.find(l=>l.id==='b'))"), 2400); + assert.deepEqual(errors, []); } +}); + test('fiber pairs follow the same rules as signing them: your own fiber, and pairs still free', (t) => { for (const type of ['dfpair', 'pairs', 'capfib']) { const { ev, errors } = game(t, pair(type) + pair('pairs', 'q', 'b') + "S.links.find(l=>l.id==='e').x=1;"); From d6b08dded3dd5ff317e012f52f70d1d8dded22b4 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Mon, 9 Nov 2026 10:40:39 +0000 Subject: [PATCH 16/20] Kept exit orders also check each exit's kind An exit that turned from an exchange into a PNI at the same place in the list, city and preference kept the order made for the exchange, which sorts behind a PNI at the same distance, so the cached routing could differ from routing without the cache (#320 review). The exit signature now includes the kind. Also drops the unused e.vis. --- src/game/80-simulation/29-route-cache.js | 3 ++- src/game/80-simulation/30-compute.js | 4 ++-- tests/route-cache.test.js | 16 ++++++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/game/80-simulation/29-route-cache.js b/src/game/80-simulation/29-route-cache.js index 15dc982..a7340e6 100644 --- a/src/game/80-simulation/29-route-cache.js +++ b/src/game/80-simulation/29-route-cache.js @@ -44,7 +44,8 @@ function rcReachPut(X,R2){const r=X.reach;Object.assign(R2.reachable,r.reachable exits, cities and preferences on the same graph keeps the orders it had, and uses them today already. Only the lists that changed start again (scanned today, sorted from tomorrow). */ function rcExitKeep(key,E,okBy,reach,LIST,BRJ,DSEL,RSET,bk=''){const ok=[];for(let j=0;j0?1:0); const P=RC.x&&RC.x.gk===RC.gk&&RC.x.bk===bk&&RC.x.sig?RC.x:null,old=new Map(); if(P)for(const d of P.lists){if(d.cs){for(let k=0;k{for(let i=0;i=P.sig.length||P.sig[x]!==sig[x])return false;}return true;}; diff --git a/src/game/80-simulation/30-compute.js b/src/game/80-simulation/30-compute.js index 1bae9a6..3438f48 100644 --- a/src/game/80-simulation/30-compute.js +++ b/src/game/80-simulation/30-compute.js @@ -22,7 +22,7 @@ function flDefine(R2,c){const {NF,FREM,FCI,FNJ,FCA,FBZ,FGT,FGI,FGP,FGH,FTI,FII,E /* Every exit has the same fields in the same order, whatever its kind, so the routing loop reads them from one object shape (exits of six shapes made each property read there a slow lookup). */ function mkEx(k,id,city,cap,rank,pref,lab,ok,nets,net){return {k,net,id,city,lab,cap,used:0,rank,pref,ok,nets,dir:null,clean:false,prem:false,carry:false,prep:false,sac:false,pnc:false, - ek:'',J:0,byC:null,desc:null,dup:false,told:false,hp:1,dt:0,ci:0,cn:false,vis:0,ts:-1,xi:0,kx:EXK.indexOf(k),fac:undefined};} + ek:'',J:0,byC:null,desc:null,dup:false,told:false,hp:1,dt:0,ci:0,cn:false,ts:-1,xi:0,kx:EXK.indexOf(k),fac:undefined};} // The exit kinds by number (mkEx's kx), for what routing adds up per kind in typed arrays. const EXK=['t','ix','p','c']; function compute(){RW.gen++; @@ -79,7 +79,7 @@ function compute(){RW.gen++; // TSL: a slot per transit port id, for what it carries to each network (R.tNet, added up in TNA). const ekN={},TSL=new Map();(()=>{for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;} // dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last. - for(let i=0;i1;e.told=false;e.hp=e.pref==='high'?0:1;e.dt=e.k==='ix'?PNI_TIE:0;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;e.ts=-1;if(e.k==='t'){let t=TSL.get(e.id);if(t===undefined)TSL.set(e.id,t=TSL.size);e.ts=t;} + for(let i=0;i1;e.told=false;e.hp=e.pref==='high'?0:1;e.dt=e.k==='ix'?PNI_TIE:0;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.ts=-1;if(e.k==='t'){let t=TSL.get(e.id);if(t===undefined)TSL.set(e.id,t=TSL.size);e.ts=t;} if(XC)continue; // Index loops or forEach (same order): for…of here made an iterator result per exit and network. const ns=e.nets||NET_IDS;if(Array.isArray(ns)){for(let q=0;qokAdd(e,n));} diff --git a/tests/route-cache.test.js b/tests/route-cache.test.js index 4a0af1d..b7ad481 100644 --- a/tests/route-cache.test.js +++ b/tests/route-cache.test.js @@ -128,3 +128,19 @@ test('lists an exit change leaves alone keep their orders; routing stays the sam for (let d = 0; d < 3; d++) assert.equal(step(ev, 'for(const c in S.pops)if(S.pops[c].bb)S.pops[c].bb.d*=1.03').same, true, `day ${d + 1} after`); assert.deepEqual(errors, []); }); + +test('an exit that turns from an exchange into a PNI at the same place in the list does not keep its old order', () => { + const { ev, errors } = open(); + // The last exchange with a few networks on it, its city A, and a network m there that also gets a PNI at A. + ev(`(()=>{const ixs=Object.keys(S.ixp).filter(c=>S.pops[ixCity(c)]);let p=null; + for(let k=ixs.length-1;k>=0&&!p;k--){const c=ixs[k],ss=[...ixSessions(c)];if(ss.length>2)p={c,A:ixCity(c),m:ss[0]};} + window.__P=p;for(const c of Object.keys(S.ixp).slice(Object.keys(S.ixp).indexOf(p.c)+1))delete S.ixp[c]; + S.pni.push({id:'pz0',net:p.m,city:p.A,tier:1,n:1,pref:'normal'});})();compute();compute();compute();`); + assert.ok(ev('!!__P'), 'an exchange to drop'); + // The exchange goes and a PNI with m at A comes first: an exit of the same city and preference, but now a PNI. + const r = step(ev, `delete S.ixp[__P.c];S.pni.unshift({id:'pz1',net:__P.m,city:__P.A,tier:1,n:1,pref:'normal'})`); + assert.equal(r.g, false, 'same graph'); + assert.equal(r.x, true, 'the exits changed'); + assert.equal(r.same, true, 'the same routing as without the kept tables'); + assert.deepEqual(errors, []); +}); From f00bc733d000a680b435d213e6531205065fc1b5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Mon, 9 Nov 2026 13:30:28 +0100 Subject: [PATCH 17/20] Two CSS checks read jsdom 31 as well as 30 jsdom 31 (#327) serializes calc() with its terms sorted and expands the overflow shorthand into overflow-y; the diagnostic readout and puzzle dock tests now accept both. --- tests/diagnostic-info.test.js | 3 ++- tests/puzzles-phone.test.js | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/diagnostic-info.test.js b/tests/diagnostic-info.test.js index 6eeae7b..3cee6f8 100644 --- a/tests/diagnostic-info.test.js +++ b/tests/diagnostic-info.test.js @@ -103,7 +103,8 @@ test('on a 360 px phone the readout wraps inside the screen instead of running o try { ev('diagOn(true)'); const st = ev('document.getElementById("diag").style.cssText'); - assert.match(st, /max-width: calc\(100vw - 32px\)/); + // jsdom 31 serializes calc() with its terms sorted (calc(-32px + 100vw)); a browser keeps them as written. + assert.match(st, /max-width: calc\((100vw - 32px|-32px \+ 100vw)\)/); assert.match(st, /white-space: pre-wrap/); assert.match(st, /pointer-events: none/, 'it never takes a tap meant for the map'); } finally { h.done(); } diff --git a/tests/puzzles-phone.test.js b/tests/puzzles-phone.test.js index f693271..45e6736 100644 --- a/tests/puzzles-phone.test.js +++ b/tests/puzzles-phone.test.js @@ -66,7 +66,8 @@ test('a link’s card: sizes first, then what it carries, then its routing', () test('nothing on a phone scrolls by design: the bar and the card’s body have no scroll of their own', () => { const { ev, errors } = load(); const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText)) - .flatMap(m=>[...m.cssRules]).map(r=>({sel:r.selectorText||'',ov:r.style.getPropertyValue('overflow')+r.style.getPropertyValue('overflow-y'),mh:r.style.getPropertyValue('max-height')})))`)); + .flatMap(m=>[...m.cssRules]).map(r=>({sel:r.selectorText||'',ov:r.style.getPropertyValue('overflow-y')||r.style.getPropertyValue('overflow'),mh:r.style.getPropertyValue('max-height')})))`)); + // (jsdom 31 expands the overflow shorthand into overflow-y too; jsdom 30 kept only the shorthand.) const dock = rules.find((r) => r.sel === '#pzBox.dock'); assert.ok(dock && dock.ov === 'visible' && dock.mh === 'none', 'the bar is as tall as it needs, never a scroll box'); assert.ok(!rules.some((r) => /pzd-/.test(r.sel) && /auto|scroll/.test(r.ov)), 'no part of the bar or the cards scrolls'); From 6a44da4017e4a3af26d09414819c694027e3cf2d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:35:14 +0000 Subject: [PATCH 18/20] Tools: Bump jsdom from 30.1.3 to 31.0.0 Bumps [jsdom](https://github.com/jsdom/jsdom) from 30.1.3 to 31.0.0. - [Release notes](https://github.com/jsdom/jsdom/releases) - [Commits](https://github.com/jsdom/jsdom/compare/v30.1.3...v31.0.0) --- updated-dependencies: - dependency-name: jsdom dependency-version: 31.0.0 dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- package-lock.json | 322 ++++++++++++---------------------------------- package.json | 2 +- 2 files changed, 81 insertions(+), 243 deletions(-) diff --git a/package-lock.json b/package-lock.json index c771089..880948c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,7 +11,7 @@ "devDependencies": { "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", - "jsdom": "30.1.3", + "jsdom": "31.0.0", "playwright-core": "1.65.0", "ws": "8.22.1" }, @@ -19,192 +19,6 @@ "node": ">=20" } }, - "node_modules/@asamuzakjp/css-color": { - "version": "7.1.9", - "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-7.1.9.tgz", - "integrity": "sha512-vZ6JQVq8Ivgz6b/IBlAf90wZviXdluY13cQOPO+nJHbmXwGrPl2GcpqUY7a55/8ZVdfONXpCFMpRijOBCHNlcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@csstools/css-calc": "^3.4.3", - "@csstools/css-color-parser": "^4.2.6", - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2", - "lru-cache": "^11.5.3" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, - "node_modules/@asamuzakjp/dom-selector": { - "version": "10.0.5", - "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-10.0.5.tgz", - "integrity": "sha512-EgmJ7oEaGQECTn3H3wmnQpEy4hKY66VvM7VQndwPIQob3p877BgbyOUE3EX0LgXQCciF2H8KMdR+RznqjMNOLw==", - "dev": true, - "license": "MIT", - "dependencies": { - "bidi-js": "^1.1.0", - "css-tree": "^3.2.1", - "is-potential-custom-element-name": "^1.0.1", - "lru-cache": "^11.5.3" - }, - "engines": { - "node": "^22.22.2 || ^24.15.0 || >=26.0.0" - } - }, - "node_modules/@bramus/specificity": { - "version": "2.4.3", - "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", - "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", - "dev": true, - "license": "MIT", - "dependencies": { - "css-tree": "^3.2.1" - }, - "bin": { - "specificity": "bin/cli.js" - } - }, - "node_modules/@csstools/color-helpers": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz", - "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", - "engines": { - "node": ">=20.19.0" - } - }, - "node_modules/@csstools/css-calc": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz", - "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-color-parser": { - "version": "4.2.7", - "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.7.tgz", - "integrity": "sha512-zgm9yjQz5iJB4VL8RyVwd71TWB8Q89FSxt/NzXoWqPSkEBOVtn9L6vAPtSc9hpKfB0Awo/AL2VKFHjYetBLFHQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "dependencies": { - "@csstools/color-helpers": "^6.1.2", - "@csstools/css-calc": "^3.4.3" - }, - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^4.0.2", - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-parser-algorithms": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz", - "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - }, - "peerDependencies": { - "@csstools/css-tokenizer": "^4.0.2" - } - }, - "node_modules/@csstools/css-syntax-patches-for-csstree": { - "version": "1.1.16", - "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.16.tgz", - "integrity": "sha512-LsDbJPP/B8cPasUJyTA5S99F7C4G93ngW8hUluXz8CFeOaaRnBPtBiIlvgcPYU0HmHNz8CXg+1vwFrIB4F6Dgw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT-0", - "peerDependencies": { - "css-tree": "^3.2.1" - }, - "peerDependenciesMeta": { - "css-tree": { - "optional": true - } - } - }, - "node_modules/@csstools/css-tokenizer": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz", - "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=20.19.0" - } - }, "node_modules/@exodus/bytes": { "version": "1.16.0", "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", @@ -280,28 +94,31 @@ "node": ">=20" } }, - "node_modules/bidi-js": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", - "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "node_modules/bcp-47": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bcp-47/-/bcp-47-2.1.2.tgz", + "integrity": "sha512-wsv86UuNFuPnVieKLyECTT+CP1WSAHeoIg5P3xu2kA9Z+7fVPoKt7dxzSeEhtJel0AI+NW3fIW3KtTKQKUCngg==", "dev": true, "license": "MIT", "dependencies": { - "require-from-string": "^2.0.2" + "is-alphabetical": "^2.0.0", + "is-alphanumerical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/css-tree": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", - "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", + "node_modules/bcp-47-match": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/bcp-47-match/-/bcp-47-match-2.0.3.tgz", + "integrity": "sha512-JtTezzbAibu8G0R9op9zb3vcWZd9JF6M0xOYGPn0fNCd7wOpRB1mU2mH9T8gaBGbAAyIIVgB2G7xG0GP98zMAQ==", "dev": true, "license": "MIT", - "dependencies": { - "mdn-data": "2.27.1", - "source-map-js": "^1.2.1" - }, - "engines": { - "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" } }, "node_modules/data-urls": { @@ -361,6 +178,43 @@ "node": "^22.13.0 || >=24.0.0" } }, + "node_modules/is-alphabetical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz", + "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-alphanumerical": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz", + "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-alphabetical": "^2.0.0", + "is-decimal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/is-decimal": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz", + "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, "node_modules/is-potential-custom-element-name": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", @@ -369,41 +223,39 @@ "license": "MIT" }, "node_modules/jsdom": { - "version": "30.1.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-30.1.3.tgz", - "integrity": "sha512-hQMUPvRgN7KxsfIytDQji7bimuJeRQa6Qo5+iuiZQk5CafeRxLIA10/cG5YCBFNpD9RO3oqIiN4CO1Y44kxqXg==", + "version": "31.0.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-31.0.0.tgz", + "integrity": "sha512-xAkhD9z1eyFC5+QUi9K24CaZJgdCQ2GOGLW1GdVDoQvkp/AxEH9TQ0pAplPOlIiV92hfcgnFOADZypbjgbBT6Q==", "dev": true, "license": "MIT", "dependencies": { - "@asamuzakjp/css-color": "^7.1.3", - "@asamuzakjp/dom-selector": "^10.0.3", - "@bramus/specificity": "^2.4.2", - "@csstools/css-syntax-patches-for-csstree": "^1.1.15", "@exodus/bytes": "^1.16.0", - "css-tree": "^3.2.1", + "bcp-47": "^2.1.2", + "bcp-47-match": "^2.0.3", "data-urls": "^8.0.0", "decimal.js": "^10.6.0", "html-encoding-sniffer": "^7.0.0", "is-potential-custom-element-name": "^1.0.1", "lru-cache": "^11.5.3", - "parse5": "^8.0.1", + "parse5": "^8.1.0", + "parse5-parser-stream": "^8.1.0", "saxes": "^6.0.0", "tough-cookie": "^6.0.2", - "undici": "^8.12.1", + "undici": "^8.12.3", "w3c-xmlserializer": "^6.0.0", "webidl-conversions": "^8.0.1", "whatwg-mimetype": "^5.0.0", - "whatwg-url": "^17.2.0", + "whatwg-url": "^17.3.0", "xml-name-validator": "^5.0.0" }, "engines": { "node": "^22.22.2 || ^24.15.0 || >=26.0.0" }, "peerDependencies": { - "canvas": "^3.2.3" + "@napi-rs/canvas": "^1.0.13" }, "peerDependenciesMeta": { - "canvas": { + "@napi-rs/canvas": { "optional": true } } @@ -418,13 +270,6 @@ "node": "20 || >=22" } }, - "node_modules/mdn-data": { - "version": "2.27.1", - "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", - "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", - "dev": true, - "license": "CC0-1.0" - }, "node_modules/parse5": { "version": "8.1.0", "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.0.tgz", @@ -438,6 +283,19 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/parse5-parser-stream": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-8.1.0.tgz", + "integrity": "sha512-58MPfNTA+DsIzro41rU94xghnu/h2N4yEPdPdGPlZVHM/QvA5jlVGYVo7IzlHbFLHYx3cZUnr9s9HBrA0tEYyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "parse5": "^8.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/playwright-core": { "version": "1.65.0", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz", @@ -461,16 +319,6 @@ "node": ">=6" } }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -484,16 +332,6 @@ "node": ">=v12.22.7" } }, - "node_modules/source-map-js": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", - "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/tldts": { "version": "7.4.19", "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", diff --git a/package.json b/package.json index a117b72..2d4a489 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "devDependencies": { "@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/server": "2.4.0", - "jsdom": "30.1.3", + "jsdom": "31.0.0", "playwright-core": "1.65.0", "ws": "8.22.1" } From 4630ba99af8195faa7da1ebcd68e2efad2c907a5 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Mon, 9 Nov 2026 12:36:03 +0000 Subject: [PATCH 19/20] Clear the open code scanning alerts - auto-release.yml: the by-hand test run passes github.sha (what it got anyway) instead of an output that also reads workflow_run.head_sha, so CI never checks out a ref a workflow_run handed over in a job that uses caches (cache poisoning, 7 alerts in ci.yml). - tests/harness.js: the script splitter also matches end tags like (bad HTML filtering regexp). - Tests paste the fixture saves into the page with lit(), which escapes what could end a script or a string, instead of plain JSON.stringify (improper code sanitization). --- .github/workflows/auto-release.yml | 5 +++-- tests/day-steps.test.js | 5 +++-- tests/gameplay-rules.test.js | 2 +- tests/harness.js | 2 +- tests/land-islands.test.js | 3 ++- tests/pie-backhaul.test.js | 3 ++- tests/pie-balance.test.js | 3 ++- tests/pie-routing.test.js | 3 ++- tests/pie-traffic.test.js | 3 ++- 9 files changed, 18 insertions(+), 11 deletions(-) diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 6332c25..765105b 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -70,13 +70,14 @@ jobs: case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac echo "skip=false" >> "$GITHUB_OUTPUT" - # Only when started by hand: after a push, CI has already tested this commit. + # Only when started by hand: after a push, CI has already tested this commit. By hand the commit is main as it is + # (github.sha, what check.outputs.sha is then), named directly so CI never checks out a ref a workflow_run handed over. tests: needs: check if: needs.check.outputs.skip == 'false' && github.event_name == 'workflow_dispatch' uses: ./.github/workflows/ci.yml with: - ref: ${{ needs.check.outputs.sha }} + ref: ${{ github.sha }} release: needs: [check, tests] diff --git a/tests/day-steps.test.js b/tests/day-steps.test.js index b9ad08b..027b065 100644 --- a/tests/day-steps.test.js +++ b/tests/day-steps.test.js @@ -9,12 +9,13 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); // The big network with an intern running every order, a failure and an event due soon, its circuits on scenic // routes, which read yesterday's R.efg, and renewal haggles the sales desk answers (slRenRun() routes after them). Ids come from Date.now(), // so the clock stands still in every page. -const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false; +const SETUP = `Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();autoPause=()=>false; S.cash=1e9;ACT.salesHire({id:'eng'});closeModal();S.slAuto.on=true;S.slAuto.ren=true;window.__ren=0;{const f=slRenOne;slRenOne=function(){__ren++;return f.apply(this,arguments);};} for(const b of S.biz.filter(b=>clOn(b)&&!BIZ_T[b.type].fiber).slice(0,20)){b.te=S.day+28;b.hag={rate:Math.round(b.rate*0.7),until:S.day+28};} S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0; @@ -110,7 +111,7 @@ test('an action while the worker routes stands; another network loaded mid-day g // A new game while a day is in flight: the old day's steps never touch it. p.ev('rwDay()'); const day = p.ev('S.day'); - p.ev(`window.__old=S;S=migrate(JSON.parse(${JSON.stringify(BIG)}));compute();`); + p.ev(`window.__old=S;S=migrate(JSON.parse(${lit(BIG)}));compute();`); const fresh = p.ev('JSON.stringify(S.hist)'); p.pump(); assert.equal(p.ev('JSON.stringify(S.hist)'), fresh); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 38795de..44414ca 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -654,7 +654,7 @@ test('O7: a fresh Tier 1 cannot afford a full Shortcrust in its first year', () // most the Ex-Im Pie Bank lends a rocket company on top. const g = load(); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); - g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`); + g.ev(`S=migrate(JSON.parse(${lit(save)}));compute()`); const rev = g.ev('R.revMo'), loan = g.ev('Math.max(...Object.values(BANKS).map(b=>b.amt[1]))') * rev + g.ev('pieEximCap()'), cash = Math.max(0, g.ev('S.cash')); const year = 12 * rev + loan + Math.min(cash, 12 * rev); const full = g.ev("pieFullCost('short')"); diff --git a/tests/harness.js b/tests/harness.js index 2e5c0a2..f03638e 100644 --- a/tests/harness.js +++ b/tests/harness.js @@ -22,7 +22,7 @@ function split(html) { let s = SPLIT.get(html); if (s) return s; const code = []; - const shell = html.replace(/'; }); diff --git a/tests/land-islands.test.js b/tests/land-islands.test.js index a52e6a1..a9cdbb8 100644 --- a/tests/land-islands.test.js +++ b/tests/land-islands.test.js @@ -6,12 +6,13 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); test('land islands answer "a path without subsea" as walking the links does', () => { const { ev, errors } = load({ seed: 3 }); - ev(`S=migrate(JSON.parse(${JSON.stringify(BIG)}));UI.started=true;closeModal();compute();`); + ev(`S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;closeModal();compute();`); const cmp = () => JSON.parse(ev(`(()=>{const cs=Object.keys(S.pops).concat(['sin','nyc','lon',null,undefined]);let n=0,yes=0;const bad=[]; for(const a of cs.slice(0,60))for(const b of cs){if(!a)continue;TERR=null;const w=terrestrialPath(a,b);TERR={S,gen:RW.gen,m:null};const i=terrestrialPath(a,b);TERR=null; n++;if(w)yes++;if(w!==i)bad.push(a+'-'+b);}return JSON.stringify({n,yes,bad:bad.slice(0,5)});})()`)); diff --git a/tests/pie-backhaul.test.js b/tests/pie-backhaul.test.js index 934ed2e..ea88613 100644 --- a/tests/pie-backhaul.test.js +++ b/tests/pie-backhaul.test.js @@ -5,6 +5,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); // A backbone London – New York – Auckland with transit in London and New York, full dishes with landing rights there, a // full lasered Shortcrust, and Pitcairn (Adamstown): a POP of its own with broadband, no cable, and a dish. @@ -230,7 +231,7 @@ test('the traceroute to and from a cut-off POP shows the orbit hops', () => { test('saves without pies, and pie saves whose POPs are all connected, route as before', () => { const { ev, errors } = load(); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); - ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`); + ev(`S=migrate(JSON.parse(${lit(save)}));compute()`); assert.equal(ev('S.pie'), null); const out = () => ev("JSON.stringify([R.served,R.demand,R.egT,R.load,R.l2,R.l2lat,R.citySrv])"); const a = out(); diff --git a/tests/pie-balance.test.js b/tests/pie-balance.test.js index 05f4c39..ecb1c1a 100644 --- a/tests/pie-balance.test.js +++ b/tests/pie-balance.test.js @@ -9,6 +9,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); const YEARS = +(process.env.PIE_BALANCE_YEARS || 0); @@ -28,7 +29,7 @@ const YEARS = +(process.env.PIE_BALANCE_YEARS || 0); function sim(days, stop = false, seed = 7, gov = false) { const g = load({ seed }); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); - g.ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));S.pieV=1;UI.started=true;UI.pitched=true;UI.speed=0;S.nextFail=1e9;S.nextEvent=1e9; + g.ev(`S=migrate(JSON.parse(${lit(save)}));S.pieV=1;UI.started=true;UI.pitched=true;UI.speed=0;S.nextFail=1e9;S.nextEvent=1e9; isTier1=()=>true;after=()=>{};pieModal=()=>{};compute();pieInit();UI.pieLas=true;ACT.pieFound();ACT.pieFactory();ACT.pieRd({k:'reuse'}); for(const c of Object.keys(S.pops).filter(c=>pieCoast(c)&&piePadOk(c,'short')).sort((a,b)=>Math.abs(CITY[a].lat)-Math.abs(CITY[b].lat)).slice(0,2))ACT.piePad({city:c}); window.__site=()=>{const ds=S.pie.dishes,lic=c=>pieLicOk(CITY[c].cc)?0:pieLicPrice(CITY[c].cc); diff --git a/tests/pie-routing.test.js b/tests/pie-routing.test.js index 40043fe..1374565 100644 --- a/tests/pie-routing.test.js +++ b/tests/pie-routing.test.js @@ -5,6 +5,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); // A sandbox with London and New York joined by a transatlantic wave, Frankfurt 640 km from London, a company, and a // 16-antenna dish with landing rights at each POP. @@ -159,7 +160,7 @@ test('spats: data stays home, and not over my airspace', () => { test('saves without pies route identically, and pay nothing for orbit', () => { const { ev, errors } = load(); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); - ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`); + ev(`S=migrate(JSON.parse(${lit(save)}));compute()`); assert.equal(ev('S.pie'), null); const out = () => ev("JSON.stringify([R.served,R.demand,R.revMo,R.egT,R.load,R.l2,R.l2lat,R.rev])"); const a = out(); diff --git a/tests/pie-traffic.test.js b/tests/pie-traffic.test.js index 5faa9cd..633de79 100644 --- a/tests/pie-traffic.test.js +++ b/tests/pie-traffic.test.js @@ -5,6 +5,7 @@ const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); // London, New York and Frankfurt on one backbone, a company, 16-antenna dishes with landing rights at each. const world = (ev, opt = {}) => { @@ -195,7 +196,7 @@ test('the traceroute shows a circuit through orbit hop by hop', () => { test('saves without pies: no traffic data, the same routing, and an untouched map', () => { const { ev, errors } = load(); const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); - ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));compute()`); + ev(`S=migrate(JSON.parse(${lit(save)}));compute()`); assert.equal(ev('R.pie===undefined'), true); assert.equal(ev("trSkyList().length"), 0); assert.equal(ev("pieFiberMs({k:'c',id:'x'})"), Infinity); From e0671c02bebcdf390736f12bd0b803d698df14a2 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Mon, 9 Nov 2026 13:37:12 +0000 Subject: [PATCH 20/20] Move customers between paths, and big networks route in half the time (3.3.0) --- CHANGELOG.md | 12 +++++++----- package-lock.json | 4 ++-- package.json | 2 +- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d41f66..db3d467 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,16 +6,18 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +## [3.3.0] — 2026-11-09 + +- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. +- Routing a big network's day takes about half the work, with exactly the same results: on a network of 390 POPs with Auto-TE, a day's routing went from about 0.7 to 0.3 seconds on a computer. +- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. +- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. +- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. - Linking to a coast where no subsea cable lands yet, like Iqaluit, now says how you can get there (overland, or with a cable of your own) instead of listing no cities to hop through (#321). - A delay while your own subsea cable is being laid now holds the lay ship where it is, instead of sending it back to port and starting the laying over. The cable already on the seabed stays there, the build simply finishes later, and there is nothing to pay twice (#322). -- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. - A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds. -- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. -- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. - A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before. - The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before. -- Routing a big network's day takes about half the work, with exactly the same results: on a network of 390 POPs with Auto-TE, a day's routing went from about 0.7 to 0.3 seconds on a computer. -- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. ## [3.2.0] — 2026-11-07 diff --git a/package-lock.json b/package-lock.json index 880948c..ecce01c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "seriesoftubes", - "version": "3.2.0", + "version": "3.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "seriesoftubes", - "version": "3.2.0", + "version": "3.3.0", "license": "MIT", "devDependencies": { "@modelcontextprotocol/node": "2.1.2", diff --git a/package.json b/package.json index 2d4a489..105a19a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "seriesoftubes", - "version": "3.2.0", + "version": "3.3.0", "description": "A cartoon browser game about building the internet.", "private": true, "license": "MIT",