From 92536606ddbc0ba4b3f133b0ef72adbc5ae22812 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 21:41:28 +0100 Subject: [PATCH] Tests, CHANGELOG and docs for the peering desk --- .claude/skills/gameplay-rules/SKILL.md | 4 +- CHANGELOG.md | 3 +- docs/ARCHITECTURE.md | 2 +- docs/adr/0003-translations-by-label.md | 2 +- scripts/lib/compile-labels.js | 2 +- tests/eyeballs.test.js | 2 +- tests/game.test.js | 4 - tests/gameplay-rules.test.js | 11 +- tests/i18n.test.js | 4 +- tests/inbox.test.js | 252 ------------------------- tests/peering-desk.test.js | 117 ++++++++++++ tests/peering.test.js | 7 +- tests/pnis-and-sold-out.test.js | 127 +++++++++++++ tests/puzzles.test.js | 2 +- tests/rules.test.js | 5 +- tests/utilities.test.js | 2 +- 16 files changed, 266 insertions(+), 280 deletions(-) delete mode 100644 tests/inbox.test.js create mode 100644 tests/peering-desk.test.js create mode 100644 tests/pnis-and-sold-out.test.js diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index ecb01ed..770d3ce 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -43,8 +43,8 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | Id | Rule | Why | | --- | --- | --- | | M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | -| M2 | Presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market, inbox; and a seeded year of incidents). | The names promise it. | -| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| M2 | Presets are ordered: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). | The names promise it. | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | | M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | | M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c98686..ebdfd49 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to this project are documented here. The project follows ## [2.0.0] — 2026-10-29 +- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. - Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. - Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. - Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. @@ -19,7 +20,7 @@ All notable changes to this project are documented here. The project follows - A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands in. - Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177). - Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. -- Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips the peering inbox, hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. +- Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. - Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. - Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. - Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7af5613..3b2f4af 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -30,7 +30,7 @@ hoisted across files, and top-level statements run in path order. Find code by n | `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()`) | -| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank | +| `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, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service | | `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` | | `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` | diff --git a/docs/adr/0003-translations-by-label.md b/docs/adr/0003-translations-by-label.md index 19a2c32..a75c209 100644 --- a/docs/adr/0003-translations-by-label.md +++ b/docs/adr/0003-translations-by-label.md @@ -35,7 +35,7 @@ fell back to English. Long sentences as keys made dictionary diffs hard to read - **`npm run i18n:check`** verifies that every label used in `src/` is defined in English, every English label is used, every translation keeps its English's placeholders, HTML tags and plural forms, and every dictionary is sorted. -- **Saves:** a few things in a save hold text to show later (the peering inbox log, sold-out reasons, +- **Saves:** a few things in a save hold text to show later (sold-out reasons, attack names). New saves hold labels. Saves from before labels (1.34 and older) hold the English text; `tr()` maps it back to its label the first time it sees one, so old saves still show the player's language. - **Translators** read `src/i18n/en.js` next to their file; both are sorted by the same labels, so the diff --git a/scripts/lib/compile-labels.js b/scripts/lib/compile-labels.js index 597adfd..a78cf4e 100644 --- a/scripts/lib/compile-labels.js +++ b/scripts/lib/compile-labels.js @@ -6,7 +6,7 @@ // static markup, in the inlined English and in every translation file, and the page ends up about the // size it was when the English text itself was the key. // -// Labels passed to N_() are kept whole: those are the ones the game stores (in saves, in the inbox log) +// Labels passed to N_() are kept whole: those are the ones the game stores (in saves) // and shows later, and an id would mean something else in the next release. const { CALL } = require('../legacy/labels'); const D = require('./dict'); diff --git a/tests/eyeballs.test.js b/tests/eyeballs.test.js index b5a4543..d2922d5 100644 --- a/tests/eyeballs.test.js +++ b/tests/eyeballs.test.js @@ -47,7 +47,7 @@ test('Coax gets Spectre-um’d a year in, and Final Frontear joins Very-Zone a y start(ev2); ev2("ACT.buildPop({city:'chi'});S.pni.push({id:'a',net:'cxc',city:'chi',tier:1,ready:0},{id:'b',net:'spc',city:'chi',tier:1,ready:0});S.day=400;dayTick()"); assert.equal(ev2("S.pni.filter(p=>p.city==='chi').map(p=>p.net).join()"), 'spc'); - // the inbox never brings requests from a brand that no longer exists, and saves keep the record + // saves keep the record of who merged ev("const o=JSON.parse(JSON.stringify(S));S=migrate(o)"); assert.equal(ev("merged('cxc')&&merged('ftr')"), true); ev("S.merged={cxc:'x',zzz:3};S=migrate(JSON.parse(JSON.stringify(S)))"); diff --git a/tests/game.test.js b/tests/game.test.js index 6f5d817..246a769 100644 --- a/tests/game.test.js +++ b/tests/game.test.js @@ -469,10 +469,6 @@ test('notifications: the NOC keeps the last ten minutes, folds repeats and opens const os = JSON.parse(ev("JSON.stringify(S.log.map(e=>e.o))")); assert.deepEqual(os, [null, { a: 'city', v: 'lon' }, { a: 'link', v: linkId }, { a: 'city', v: 'fra' }]); assert.equal(ev("S.log[0].h"), 'Raffle'); assert.equal(ev("S.log[0].t"), 'Raffle You won a T-shirt.'); - // the peering inbox's own button opens the peering inbox - ev("toast('Peering request
From a small network.','',[{l:'Inbox',act:'inbox',args:{}}])"); - assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'inbox' }); - ev('ACT.logOpen({id:S.log[0].id})'); assert.equal(ev("$('modal').hidden"), false, 'the inbox opens');ev('closeModal();S.log.shift()'); // an incident points at what broke assert.deepEqual(JSON.parse(ev(`JSON.stringify(incOpen({ref:'${linkId}'}))`)), { a: 'link', v: linkId }); assert.deepEqual(JSON.parse(ev("JSON.stringify(incOpen({ref:S.links[0].trench||S.links[0].id}))")), { a: 'link', v: ev('S.links[0].id') }); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index ce95537..76cf1ba 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -215,8 +215,8 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at const P = J('PRESETS'), C = J('CHAOS'), lead = { quick: 0, real: 1 }; assert.ok(C[P.freeze.chaos].m <= C[P.oncall.chaos].m && C[P.oncall.chaos].m <= C[P.bgp.chaos].m, 'M2: chaos'); assert.ok(lead[P.freeze.lead] <= lead[P.oncall.lead] && lead[P.oncall.lead] <= lead[P.bgp.lead], 'M2: lead times'); - for (const k of ['market', 'inbox']) assert.ok(!P.freeze[k] || P.oncall[k], `M2: ${k}`); - assert.ok(P.bgp.market && P.bgp.inbox && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship'); + assert.ok(!P.freeze.market || P.oncall.market, 'M2: market'); + assert.ok(P.bgp.market && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship'); // seeded: the same network for a year under each preset const n = {}; for (const p of ['freeze', 'oncall', 'bgp']) { @@ -230,15 +230,14 @@ test('M2: presets are ordered: Change Freeze never harsher than On-call, BGP at test('M3: every subsystem that can annoy the player reads a rule', () => { // [function, what it must read] - const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['inboxDay', "rule('inbox')"], + const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); - // and in play: no chaos, no market, no inbox means a quiet year + // and in play: no chaos and no market means a quiet year const g = load(); - g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false,inbox:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()"); + g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()"); assert.equal(g.ev('S.inc.length+(S.stats.incidents||0)'), 0, 'M3: nothing breaks without chaos'); - assert.equal(g.ev('S.inbox.items.length+S.inbox.seq'), 0, 'M3: no mail without the inbox'); assert.equal(g.ev("hwMul('rt')"), 1, 'M3: no hardware inflation without the market'); assert.equal(g.ev("CITIES.slice(0,40).some(c=>soldOut('fra',c.id,1))"), false, 'M3: no sold-out routes without the market'); assert.deepEqual(g.errors, []); diff --git a/tests/i18n.test.js b/tests/i18n.test.js index ef9da0b..29729c2 100644 --- a/tests/i18n.test.js +++ b/tests/i18n.test.js @@ -36,8 +36,8 @@ function tour(ev) { ['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"], ['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src); const failSrc = ev('fireFailure.toString()'); - for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) { - const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t; + for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) { + const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t; const patched = failSrc.replace(/^function fireFailure/, 'function') .replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`) .replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`); diff --git a/tests/inbox.test.js b/tests/inbox.test.js deleted file mode 100644 index 7acb7f3..0000000 --- a/tests/inbox.test.js +++ /dev/null @@ -1,252 +0,0 @@ -const test = require('node:test'); -const assert = require('node:assert/strict'); -const { load } = require('./harness'); - -function setup(ev) { - ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()"); -} - -test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => { - const { ev, errors } = load(); - setup(ev); - ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})"); - assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill'); - assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/); - // one order in seven gets lost in provisioning for months - ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})"); - const p = JSON.parse(ev('JSON.stringify(S.pni[0])')); - assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`); - ev('compute()'); - assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery'); - assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed'); - ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()'); - assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day'); - // an upgrade is an augment on order: the old port keeps working meanwhile - ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})"); - assert.equal(ev('S.pni[0].tier'), 1); - assert.equal(ev('S.pni[0].up.tier'), 2); - ev('ACT.lagP({id:S.pni[0].id,d:1})'); - assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time'); - ev('S.day=S.pni[0].up.ready-1;dayTick()'); - assert.equal(ev('S.pni[0].tier'), 2); - assert.equal(ev('S.pni[0].up'), undefined); - // chasing it does nothing, mostly - ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]"); - const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)')); - assert.equal(r0, r1); - // most orders arrive in about a month - ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})"); - assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30); - ev("S.pni=S.pni.filter(p=>p.net!=='ggl')"); - // a beer at a conference halves the wait - ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}"); - assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved'); - ev('Math.random=()=>0.1'); - assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved'); - ev('Math.random=()=>0.99'); - ev('S.conf=null'); - // a small network: a few weeks - const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id"); - ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`); - const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`); - assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`); - assert.deepEqual(errors, []); -}); - -test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => { - const { ev, errors } = load(); - setup(ev); - ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})"); - assert.equal(ev('S.pni.length'), 0); - assert.equal(ev("peerOk('dtk','pni','fra').ok"), true); - ev("ACT.pni({city:'fra',net:'dtk',tier:-1})"); - assert.equal(ev('S.pni[0].g1'), true); - ev('S.pni[0].ready=S.day;compute()'); - assert.equal(ev('pniG(S.pni[0])'), 1); - assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1); - assert.equal(ev('pniPN(S.pni[0])'), '1G'); - // and 1G grows into 10G - ev("ACT.pni({city:'fra',net:'dtk',tier:0})"); - assert.equal(ev('S.pni[0].up.tier'), 0); - ev('S.day=S.pni[0].up.ready-1;dayTick()'); - assert.equal(ev('S.pni[0].g1'), undefined); - assert.equal(ev('pniG(S.pni[0])'), 10); - ev("selectCity('fra');ACT.tab({t:'peer'})"); - assert.deepEqual(errors, []); -}); - -test('Microsnoft has no capacity on the US east coast, at any price', () => { - const { ev, errors } = load(); - setup(ev); - ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5"); - for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) { - assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c); - assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c); - } - assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i); - assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine'); - ev("ACT.pni({city:'ash',net:'msf',tier:1})"); - assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0); - assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni*repMul())"), 'other networks are not affected'); - assert.deepEqual(errors, []); -}); - -test('the peering inbox fills up, wants answers, and max-prefix alerts are growth or a leak', () => { - const { ev, errors } = load(); - setup(ev); - ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});S.inbox.pol='selective';compute()"); - ev('for(let i=0;i<60;i++)dayTick()'); - assert.ok(ev('S.inbox.items.length') >= 2, 'mail arrives with an exchange port'); - assert.ok(ev('S.inbox.rep') < 0, 'and ignoring it has a price'); - // accept a real network's request: a bilateral session - const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006&&!ixSessions('ams').has(id);})"); - assert.ok(net); - ev(`S.inbox.items=[{id:901,k:'req',ix:'ams',net:'${net}',day:S.day,stale:false,yrs:1,say:0},{id:902,k:'req',ix:'ams',nm:'Bob’s Bits',asn:212345,day:S.day,stale:true,yrs:7,say:3}];ACT.inbox()`); - assert.match(ev("document.getElementById('modalCard').textContent"), /Bob’s Bits/); - ev("ACT.inboxAct({id:901,a:'accept'});ACT.inboxAct({id:902,a:'accept'})"); - assert.equal(ev(`!!S.peers['${net}@ams']`), true); - assert.equal(ev('S.inbox.tiny[212345].nm'), 'Bob’s Bits'); - ev('compute()'); - assert.equal(ev(`ixSessions('ams').has('${net}')`), true); - // growth: raising the limit brings the session back - ev(`S.inbox.items.push({id:903,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4});S.inbox.down['${net}@ams']=1e9`); - assert.equal(ev(`ixSessions('ams').has('${net}')`), false, 'down on max-prefix'); - ev("ACT.inboxAct({id:903,a:'raise'})"); - assert.equal(ev(`ixSessions('ams').has('${net}')`), true); - // a leak: raising the limit is a route leak, keeping it down is right - ev(`S.inbox.items.push({id:904,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:904,a:'raise'})`); - assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'a route leak'); - assert.ok(ev("S.inc.some(i=>i.type==='leak')")); - ev(`S.inbox.items.push({id:905,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:987654,leak:true,yrs:4});S.inbox.down['${net}@ams']=1e9;ACT.inboxAct({id:905,a:'keep'})`); - const back = ev(`S.inbox.down['${net}@ams']`); - assert.ok(back > ev('S.day') && back < ev('S.day') + 12, 'back on its own in a few days'); - // unanswered requests expire, and the reputation makes selective networks pickier - ev("S.inbox.items=[{id:906,k:'req',ix:'ams',net:'" + net + "',day:S.day-31,stale:false,yrs:1,say:0}];S.inbox.rep=0;inboxDay(S.day)"); - assert.equal(ev('S.inbox.items.some(x=>x.id===906)'), false); - assert.ok(ev('S.inbox.rep') < 0); - ev('S.inbox.rep=-10'); - assert.ok(ev('repMul()') > 1.05 && ev('repMul()') <= 1.1, 'pickier, but never a wall'); - // an alert nobody answers clears itself once the other side notices - ev(`S.inbox.items=[{id:910,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:100,got:180,leak:false,yrs:4}];S.inbox.down['${net}@ams']=S.day+1;inboxDay(S.day+1)`); - assert.equal(ev('S.inbox.items.some(x=>x.id===910)'), false); - // bulk answers - ev("S.inbox.items=[{id:907,k:'req',ix:'ams',nm:'A',asn:1,day:S.day,say:0,yrs:1},{id:908,k:'req',ix:'ams',nm:'B',asn:2,day:S.day,say:0,yrs:1}];ACT.inboxAll({a:'decline'})"); - assert.equal(ev('S.inbox.items.length'), 0); - // the Networks tab says how much mail is waiting - ev("S.inbox.items=[{id:909,k:'req',ix:'ams',nm:'C',asn:3,day:S.day,say:1,yrs:1}];closeModal();UI.left='nets';UI.leftOpen=true;renderLeft()"); - assert.match(ev("document.getElementById('left').textContent"), /Peering inbox/); - assert.deepEqual(errors, []); -}); - -test('the AI agent answers everything, costs $20M a year and gets it wrong a lot', () => { - const { ev, errors } = load(); - setup(ev); - ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()"); - const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})"); - const cash = ev('S.cash'); - ev("ACT.inboxBot({on:1});compute()"); - assert.equal(ev('S.inbox.bot'), true); - assert.ok(cash - ev('S.cash') >= ev('AI_MO')); - assert.ok(ev('R.cost.extras') >= ev('AI_MO'), 'billed every month'); - assert.ok(Math.abs(ev('AI_MO*12') - 20e6) < 12); - // it always gets a leak wrong when the dice say so - ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}];S.inbox.down['${net}@ams']=1e9`); - ev('Math.random=()=>0.1;inboxBot()'); - assert.equal(ev('S.inbox.items.length'), 0, 'inbox zero'); - assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'and a route leak'); - assert.ok(ev("S.inbox.log.some(e=>/They seemed nice/.test(tr(e.m,e.a)))"), 'the log keeps a label, read in the language of the player'); - ev('ACT.inbox()'); - assert.match(ev("document.getElementById('modalCard').textContent"), /They seemed nice/); - // and sometimes it gets it right - ev(`S.inbox.items=[{id:3,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3}];S.ev.leak=null;Math.random=()=>0.9;inboxBot()`); - assert.ok(!ev('S.ev.leak')); - ev('ACT.inboxBot({on:0});compute()'); - assert.equal(ev('S.inbox.bot'), false); - assert.ok(ev('R.cost.extras') < ev('AI_MO')); - assert.deepEqual(errors, []); -}); - -test('saves: the inbox and PNIs on order survive, and garbage is repaired', () => { - const { ev, errors } = load(); - setup(ev); - ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})"); - ev("S.inbox={items:[{id:1,k:'req',ix:'ams',nm:'Ok',asn:5,day:1,say:99},{k:'evil',ix:'ams'},{id:2,k:'mp',ix:'nowhere',key:'a'},'x'],down:{'a@b':'7'},tiny:{'12':{nm:'T',ix:'ams'},'no':{ix:'ams'}},rep:99,bot:'yes',log:[{d:1,m:'hi',a:{who:{x:1}}},5],seq:'z'}"); - ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); - assert.equal(ev('__o.inbox.items.length'), 1); - assert.equal(ev('__o.inbox.items[0].say'), ev('REQ_SAY.length-1')); - assert.equal(ev('__o.inbox.rep'), 5); - assert.equal(ev('__o.inbox.bot'), true); - assert.equal(ev("__o.inbox.down['a@b']"), 7); - assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(__o.inbox.tiny))')), ['12']); - assert.equal(ev('typeof __o.inbox.log[0].a.who'), 'string'); - assert.equal(ev('__o.inbox.seq'), 1); - assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX')); - assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true); - assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G'); - // an old save without an inbox loads with an empty one - ev('const p=JSON.parse(JSON.stringify(S));delete p.inbox;sanitize(p);window.__p=p'); - assert.equal(ev('__p.inbox.items.length'), 0); - assert.equal(ev('__p.inbox.bot'), false); - assert.deepEqual(errors, []); -}); - -test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => { - const { ev, errors } = load(); - setup(ev); - ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3"); - assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days'); - // find a day when 400G is sold out between Frankfurt and Amsterdam - const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()"); - assert.ok(day > 0, 'it happens'); - ev(`S.day=${day}`); - const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))")); - assert.ok(so.until > day && so.until - day <= 90); - assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window'); - ev(`S.day=${day}`); - const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()"); - assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`); - ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`); - assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/); - const n = ev('S.links.length'); - ev('ACT.buildLink({tier:2})'); - assert.equal(ev('S.links.length'), n, 'no 400G today'); - assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/); - assert.deepEqual(errors, []); -}); - -test('peering policy: open accepts everyone, selective is quieter but manual, closed scares customers; raise all limits at once', () => { - const { ev, errors } = load(); - setup(ev); - ev("S.nextFail=S.nextEvent=1e9;ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});ACT.rs({city:'ams'});compute()"); - assert.equal(ev("ppol()"), 'open', 'open by default, as before'); - const rsOpen = ev("ixSessions('ams').size"); - assert.ok(rsOpen > 0, 'the route server works'); - // open: requests are accepted as they come in - ev("Math.random=()=>0.01;inboxDay(S.day+1)"); - assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0); - assert.ok(ev("Object.keys(S.inbox.tiny).length+Object.keys(S.peers).length") > 0, 'and they become sessions'); - // selective: the route server stops counting, you ask yourself, and requests wait for you - ev("ACT.inboxPol({p:'selective'});compute()"); - assert.ok(ev("ixSessions('ams').size") < rsOpen, 'no route server sessions'); - ev("selectCity('ams');ACT.tab({t:'peer'})"); - assert.match(ev("document.getElementById('panelBody').textContent"), /Off while your peering policy is Selective/); - ev("closeModal();S.inbox.items=[];inboxDay(S.day+1)"); - assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 1, 'it waits for an answer'); - // closed: no requests, a sinking reputation, fewer customers calling - ev("ACT.inboxPol({p:'closed'});S.inbox.items=[];S.inbox.rep=0;for(let i=0;i<10;i++)inboxDay(S.day+1)"); - assert.equal(ev("S.inbox.items.filter(x=>x.k==='req').length"), 0); - assert.ok(ev('S.inbox.rep') < 0); - // raise all: every alert at once, leaks included - const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})"); - ev(`S.peers['${net}@ams']=true;S.inbox.items=[{id:71,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:80,leak:false,yrs:2},{id:72,k:'mp',key:'t9',nm:'X',asn:9,ix:'ams',day:S.day,lim:50,got:990000,leak:true,yrs:2}];S.inbox.down['${net}@ams']=1e9;ACT.inbox()`); - assert.match(ev("document.getElementById('modalCard').textContent"), /Raise all max-prefix limits/); - ev('ACT.inboxRaiseAll()'); - assert.equal(ev("S.inbox.items.length"), 0); - assert.equal(ev(`!!S.inbox.down['${net}@ams']`), false); - assert.ok(ev('S.ev.leak&&S.ev.leak.until>S.day'), 'one was a leak'); - assert.match(ev("document.getElementById('toasts').textContent"), /One of them was a route leak/); - // saves keep the policy - ev("const o=JSON.parse(JSON.stringify(S));o.inbox.pol='weird';sanitize(o);window.__o=o"); - assert.equal(ev('__o.inbox.pol'), 'open'); - assert.deepEqual(errors, []); -}); diff --git a/tests/peering-desk.test.js b/tests/peering-desk.test.js new file mode 100644 index 0000000..c5de75e --- /dev/null +++ b/tests/peering-desk.test.js @@ -0,0 +1,117 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;ACT.buyIx({city:'ams',tier:1});compute()"); +} +// Math.random returns these, then 0.5: [ask?, which IX, a real network?, (which one), fresh PeeringDB?] +const seq = (ev, a) => ev(`(()=>{const q=${JSON.stringify(a)};Math.random=()=>q.length?q.shift():0.5;})()`); +const REAL = [0.01, 0.01, 0.01, 0.01, 0.01], STALE = [0.01, 0.01, 0.9, 0.1], FRESH = [0.01, 0.01, 0.9, 0.9]; + +test('peering requests are answered by policy: Open accepts all, Selective the worthwhile ones, Closed none', () => { + const { ev, errors } = load(); + setup(ev); + assert.equal(ev('ppol()'), 'open', 'open by default, as before'); + const day = () => ev('peeringDeskDay(S.day)'); + const peers = () => ev("Object.keys(S.peers).filter(k=>k.endsWith('@ams')).length"); + let n = peers(); + seq(ev, REAL); day(); + assert.equal(peers(), n + 1, 'Open: a real network on the exchange gets its session at once'); + assert.ok(ev("ixSessions('ams').size") > 0); + seq(ev, STALE); day(); + assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [2, 0], 'Open even takes the stale newcomer'); + ev("ACT.peerPol({p:'selective'})"); + assert.equal(ev('ppol()'), 'selective'); + n = peers(); seq(ev, REAL); day(); + assert.equal(peers(), n + 1, 'Selective: a real small network is worth it'); + seq(ev, STALE); day(); + seq(ev, FRESH); day(); + assert.deepEqual(JSON.parse(ev('JSON.stringify([S.pdesk.a,S.pdesk.d])')), [4, 1], 'stale PeeringDB declined, up-to-date one accepted'); + ev("ACT.peerPol({p:'closed'})"); + n = peers(); seq(ev, REAL); day(); seq(ev, FRESH); day(); + assert.equal(peers(), n, 'Closed: nobody gets a session'); + assert.equal(ev('S.pdesk.d'), 3); + ev("ACT.peerPol({p:'nope'})"); + assert.equal(ev('ppol()'), 'closed', 'junk is ignored'); + assert.deepEqual(errors, []); +}); + +test('once a week the NOC log gets one folded peering desk line', () => { + const { ev, errors } = load(); + setup(ev); + ev("ACT.buyIx({city:'fra',tier:1,signed:true});ACT.peerPol({p:'selective'})"); + seq(ev, [0.99]); ev('S.day=Math.ceil(S.day/7)*7+7;S.pdesk=null;peeringDeskDay(S.day)'); + const w = ev('Math.floor(S.day/7)'); + for (let i = 0; i < 6; i++) { seq(ev, i % 3 === 2 ? STALE : [0.01, i % 2 ? 0.01 : 0.99, 0.9, 0.9]); ev(`peeringDeskDay(S.day+${i})`); } + assert.equal(ev('S.pdesk.w'), w); + const logs = ev('S.log.length'); + seq(ev, [0.99]); ev('peeringDeskDay(S.day+7)'); + assert.equal(ev('S.log.length'), logs + 1, 'one line for the week'); + const line = ev('S.log[0].t'); + assert.match(line, /^Peering desk: 4 new sessions at .+ and .+, 2 declined \(Selective\)\.$/); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.log[0].o)')), { a: 'tab', v: 'nets' }); + assert.equal(ev('S.pdesk.w'), w + 1); + // a quiet week says nothing + ev('peeringDeskDay(S.day+14)'); + assert.equal(ev('S.log.length'), logs + 1); + // the Networks tab has the policy picker, what it does, and last week's line; it fits a phone + ev("window.innerWidth=360;UI.left='nets';UI.leftOpen=true;S.pdeskRep.w=Math.floor(S.day/7)-1;renderLeft()"); + const left = ev("document.getElementById('left').textContent"); + assert.match(left, /Peering policy: Selective/); + assert.match(left, /newcomers with an up-to-date PeeringDB/); + assert.match(left, /Peering desk: 4 new sessions/); + assert.doesNotMatch(left, /inbox/i); + ev("document.querySelector('#left [data-act=peerPol][data-args*=closed]').click()"); + assert.equal(ev('ppol()'), 'closed'); + assert.match(ev("document.getElementById('left').textContent"), /Every peering request is declined/); + // more than four exchanges fold into "and N more" + ev("S.pdeskRep={w:0,a:9,d:0,p:'open',ix:['ams','fra','lon','par','nyc']}"); + assert.match(ev('pdeskLine(S.pdeskRep)'), /9 new sessions at .+, .+, .+ and 2 more exchanges \(Open to all\)/); + assert.match(ev("pdeskLine({a:0,d:1,p:'closed',ix:[]})"), /^Peering desk: 1 request declined \(Closed\)\.$/); + assert.deepEqual(errors, []); +}); + +test('old saves with inbox, max-prefix and Large Peering Model state load and play', () => { + const { ev, errors } = load(); + setup(ev); + const net = ev("ixMembers('ams').find(id=>{const n=NET[id];return n.type!=='cdn'&&n.type!=='t1'&&n.pol!=='paid'&&n.share<=0.006;})"); + ev(`S.peers['${net}@ams']=true;delete S.ppol;delete S.pdesk;delete S.pdeskRep; + S.inbox={items:[{id:1,k:'mp',key:'${net}@ams',net:'${net}',ix:'ams',day:S.day,lim:50,got:999999,leak:true,yrs:3},{id:2,k:'req',ix:'ams',nm:'D',asn:4,day:S.day,say:0,yrs:1}], + down:{'${net}@ams':S.day+30},tiny:{'4':{nm:'D',ix:'ams'}},rep:-8,bot:true,pol:'selective',log:[{d:1,m:'peering_inbox.fire_the_ai',a:{}}],seq:2}; + S.rules={...S.rules,inbox:true};S.ev.ixdown={ams:S.day+2}; + S.inc.push({id:'m1',type:'maxpfx',ref:'ams',until:S.day+2,msg:'A member leaked the table.',cost:0,start:S.day}); + S.log.unshift({id:'l1',t:'Peering request',h:'Peering request',k:'',o:{a:'inbox'},ts:Date.now()})`); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('S.inbox'), undefined, 'the inbox is gone'); + assert.equal(ev('ppol()'), 'selective', 'the policy is kept'); + assert.equal(ev("'inbox' in S.rules"), false); + assert.equal(ev("S.inc.find(i=>i.id==='m1').type"), 'ixloop', 'a max-prefix outage in flight becomes an ordinary IX outage'); + assert.equal(ev("S.inc.some(i=>i.type==='maxpfx')"), false); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.log.find(e=>e.id==='l1').o)")), { a: 'tab', v: 'nets' }); + assert.equal(ev(`ixSessions('ams').has('${net}')`), true, 'no session stays down on an old max-prefix limit'); + const extras = ev('R.cost.extras'); + assert.ok(extras < 20e6 / 12, 'the Large Peering Model no longer bills'); + ev("ACT.logOpen({id:'l1'})"); + assert.equal(ev('UI.left'), 'nets'); + ev('for(let i=0;i<40;i++)dayTick()'); + assert.ok(ev('S.inc.every(i=>i.type!=="maxpfx")')); + assert.ok(ev('S.pdesk&&S.pdesk.w>=0')); + // garbage in the new fields is repaired + ev("const o=JSON.parse(JSON.stringify(S));o.ppol='weird';o.pdesk={w:'x',a:-5,d:1e9,ix:['ams','ams','nowhere',3]};o.pdeskRep=[1];sanitize(o);window.__o=o"); + assert.equal(ev('__o.ppol'), 'open'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__o.pdesk)')), { w: 0, a: 0, d: 1e5, ix: ['ams'] }); + assert.equal(ev('__o.pdeskRep'), null); + assert.deepEqual(errors, []); +}); + +test('max-prefix incidents can no longer fire', () => { + const { ev, errors } = load(); + setup(ev); + assert.equal(ev("fireFailure.toString().includes('maxpfx')"), false); + ev("S.day=100;const src=fireFailure.toString().replace(/^function fireFailure/,'function').replace('let tot=opts.reduce',\"opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce\");window.__ff=eval('('+src+')')"); + ev("__reseed(7);for(let i=0;i<200;i++){__ff();S.inc=S.inc.filter(x=>x.type!=='maxpfx'||(window.__mp=1,0));}"); + assert.equal(ev('!!window.__mp'), false); + assert.equal(ev("typeof inboxDay+typeof ibx+typeof ACT.inboxRaiseAll+typeof ACT.inboxBot"), 'undefinedundefinedundefinedundefined'); + assert.deepEqual(errors, []); +}); diff --git a/tests/peering.test.js b/tests/peering.test.js index 4e1d185..9377df9 100644 --- a/tests/peering.test.js +++ b/tests/peering.test.js @@ -200,15 +200,14 @@ test('a peer at a rival exchange can de-peer you without stopping the game', () assert.deepEqual(errors, []); }); -test('an IX meltdown at a rival exchange names the city, and a failing day tick does not stop the game', () => { +test('an IX meltdown at a rival exchange names it, and a failing day tick does not stop the game', () => { const { ev, errors } = load(); ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'ams'});ACT.buyIx({city:'ams~2',tier:1});S.day=100"); const src = ev('fireFailure.toString()').replace(/^function fireFailure/, 'function') - .replace('let tot=opts.reduce', "opts.splice(0,opts.length,['funny',1]);let tot=opts.reduce") - .replace('type=pick(f);}', "type='maxpfx';}"); + .replace('let tot=opts.reduce', "opts.splice(0,opts.length,['ixloop',1]);let tot=opts.reduce"); ev('window.__ff=' + src); ev('__ff()'); - assert.match(ev("S.inc.find(i=>i.type==='maxpfx').msg"), /in Amsterdam, is down/); + assert.ok(ev("S.inc.find(i=>i.type==='ixloop').msg.includes(ixName('ams~2'))")); // a tick that throws is caught, reported once, and the loop keeps going ev("const dt0=dayTick;window.dayTick=()=>{throw new Error('boom')};UI.speed=1;acc=DAY_MS;last=0;frame(16);window.dayTick=dt0"); assert.equal(ev('UI.tickErr'), true); diff --git a/tests/pnis-and-sold-out.test.js b/tests/pnis-and-sold-out.test.js new file mode 100644 index 0000000..485482f --- /dev/null +++ b/tests/pnis-and-sold-out.test.js @@ -0,0 +1,127 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +function setup(ev) { + ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()"); +} + +test('PNIs with the big networks take a month, now and then 6 to 12, and start at 100G; small ones take weeks', () => { + const { ev, errors } = load(); + setup(ev); + ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:0})"); + assert.equal(ev('S.pni.length'), 0, 'no 10G PNI with NetChill'); + assert.match(ev("document.getElementById('toasts').textContent"), /does not do 10G/); + // one order in seven gets lost in provisioning for months + ev("Math.random=()=>0.1;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})"); + const p = JSON.parse(ev('JSON.stringify(S.pni[0])')); + assert.ok(p.ready - ev('S.day') >= 180 && p.ready - ev('S.day') <= 365, `six to twelve months (${p.ready - ev('S.day')} days)`); + ev('compute()'); + assert.equal(ev('R.usePni[S.pni[0].id]||0'), 0, 'nothing flows before delivery'); + assert.equal(ev('R.cost.pni'), 0, 'and nothing is billed'); + ev('S.nextFail=S.nextEvent=1e9;S.pni[0].ready=S.day+1;dayTick();compute()'); + assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'delivered on the day'); + // an upgrade is an augment on order: the old port keeps working meanwhile + ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})"); + assert.equal(ev('S.pni[0].tier'), 1); + assert.equal(ev('S.pni[0].up.tier'), 2); + ev('ACT.lagP({id:S.pni[0].id,d:1})'); + assert.equal(ev('S.pni[0].up.n'), 1, 'one augment at a time'); + ev('S.day=S.pni[0].up.ready-1;dayTick()'); + assert.equal(ev('S.pni[0].tier'), 2); + assert.equal(ev('S.pni[0].up'), undefined); + // chasing it does nothing, mostly + ev("Math.random=()=>0.5;R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:3});const r0=S.pni[0].up.ready;ACT.pniChase({id:S.pni[0].id});window.__r=[r0,S.pni[0].up.ready]"); + const [r0, r1] = JSON.parse(ev('JSON.stringify(__r)')); + assert.equal(r0, r1); + // most orders arrive in about a month + ev("Math.random=()=>0.5;S.pni=[];R.demTo.ggl=1e4;ACT.pni({city:'fra',net:'ggl',tier:1})"); + assert.equal(ev("S.pni.find(p=>p.net==='ggl').ready-S.day"), 30); + ev("S.pni=S.pni.filter(p=>p.net!=='ggl')"); + // a beer at a conference halves the wait + ev("Math.random=()=>0.99;S.conf={until:S.day+10,reg:'EU',name:'RIPE'}"); + assert.equal(ev("pniLead('ggl')"), 15, 'the usual month, halved'); + ev('Math.random=()=>0.1'); + assert.equal(ev("pniLead('ggl')"), Math.round((180 + Math.floor(0.1 * 186)) / 2), 'a slow one, halved'); + ev('Math.random=()=>0.99'); + ev('S.conf=null'); + // a small network: a few weeks + const small = ev("NETS.find(n=>n.pops.includes('fra')&&!pniBig(n.id)&&n.pol==='open'&&n.type!=='cdn').id"); + ev(`Math.random=()=>0.99;ACT.pni({city:'fra',net:'${small}',tier:0})`); + const lead = ev(`S.pni.find(p=>p.net==='${small}').ready-S.day`); + assert.ok(lead >= 14 && lead <= 42, `weeks, not months (${lead})`); + assert.deepEqual(errors, []); +}); + +test('Doitsche Telekomm sells 1G PNIs; nobody else does', () => { + const { ev, errors } = load(); + setup(ev); + ev("S.lvl=10;ACT.pni({city:'fra',net:'nfx',tier:-1})"); + assert.equal(ev('S.pni.length'), 0); + assert.equal(ev("peerOk('dtk','pni','fra').ok"), true); + ev("ACT.pni({city:'fra',net:'dtk',tier:-1})"); + assert.equal(ev('S.pni[0].g1'), true); + ev('S.pni[0].ready=S.day;compute()'); + assert.equal(ev('pniG(S.pni[0])'), 1); + assert.equal(ev("liveCap(pniG(S.pni[0]),'fra','a',1)"), 1); + assert.equal(ev('pniPN(S.pni[0])'), '1G'); + // and 1G grows into 10G + ev("ACT.pni({city:'fra',net:'dtk',tier:0})"); + assert.equal(ev('S.pni[0].up.tier'), 0); + ev('S.day=S.pni[0].up.ready-1;dayTick()'); + assert.equal(ev('S.pni[0].g1'), undefined); + assert.equal(ev('pniG(S.pni[0])'), 10); + ev("selectCity('fra');ACT.tab({t:'peer'})"); + assert.deepEqual(errors, []); +}); + +test('Microsnoft has no capacity on the US east coast, at any price', () => { + const { ev, errors } = load(); + setup(ev); + ev("for(const c of ['ash','nyc','hou'])ACT.buildPop({city:c});R.demTo.msf=1e5"); + for (const c of ['ash', 'nyc', 'bos', 'atn', 'mia']) { + assert.equal(ev(`peerOk('msf','pni','${c}').ok`), false, c); + assert.equal(ev(`peerOk('msf','ix','${c}').ok`), false, c); + } + assert.match(ev("peerOk('msf','pni','ash').why"), /capacity|sold out|coming online/i); + assert.equal(ev("peerOk('msf','pni','hou').ok"), true, 'Houston is fine'); + ev("ACT.pni({city:'ash',net:'msf',tier:1})"); + assert.equal(ev("S.pni.filter(p=>p.city==='ash').length"), 0); + assert.equal(ev("peerOk('ggl','pni','ash').ok"), ev("R.demTo.ggl>=Math.round(NET.ggl.minPni)"), 'other networks are not affected'); + assert.deepEqual(errors, []); +}); + +test('saves: PNIs on order survive, and garbage is repaired', () => { + const { ev, errors } = load(); + setup(ev); + ev("S.pni.push({id:'x',city:'fra',net:'dtk',tier:0,g1:true,ready:S.day+30,up:{tier:'9',n:99,ready:'x'}},{id:'y',city:'fra',net:'nfx',tier:1,g1:true})"); + ev('const o=JSON.parse(JSON.stringify(S));sanitize(o);window.__o=o'); + assert.equal(ev("__o.pni.find(p=>p.id==='x').up.n"), ev('LAG_MAX')); + assert.equal(ev("__o.pni.find(p=>p.id==='x').g1"), true); + assert.equal(ev("__o.pni.find(p=>p.id==='y').g1"), undefined, 'only Doitsche Telekomm does 1G'); + assert.deepEqual(errors, []); +}); + +test('now and then a route is sold out of a wave size, for a while, and asking again does not reroll it', () => { + const { ev, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3"); + assert.equal(ev("S.day=10;!!soldOut('fra','ams',3,null)||!!soldOut('fra','ams',1,null)"), false, 'never in the first 90 days'); + // find a day when 400G is sold out between Frankfurt and Amsterdam + const day = ev("(()=>{for(let d=90;d<20000;d++){S.day=d;if(soldOut('fra','ams',2,null))return d;}return -1;})()"); + assert.ok(day > 0, 'it happens'); + ev(`S.day=${day}`); + const so = JSON.parse(ev("JSON.stringify(soldOut('fra','ams',2,null))")); + assert.ok(so.until > day && so.until - day <= 90); + assert.equal(ev(`S.day=${so.until - 1};!!soldOut('fra','ams',2,null)`), true, 'the same verdict for the whole window'); + ev(`S.day=${day}`); + const share = ev("(()=>{let n=0;for(let d=90;d<20090;d++){S.day=d;if(soldOut('ams','fra',5,null))n++;}return n/20000;})()"); + assert.ok(share > 0.02 && share < 0.2, `rare, a bit more for big waves (${share})`); + ev(`S.day=${day};UI.via=null;openLinkModal('fra','ams')`); + assert.match(ev("document.getElementById('modalCard').textContent"), /sold out for \d+ days/); + const n = ev('S.links.length'); + ev('ACT.buildLink({tier:2})'); + assert.equal(ev('S.links.length'), n, 'no 400G today'); + assert.match(ev("document.getElementById('toasts').textContent"), /No 400G capacity on this route/); + assert.deepEqual(errors, []); +}); diff --git a/tests/puzzles.test.js b/tests/puzzles.test.js index 1ba9ef3..5dfddd8 100644 --- a/tests/puzzles.test.js +++ b/tests/puzzles.test.js @@ -488,7 +488,7 @@ test('main-game toasts and leftover buttons do nothing in a puzzle', () => { ev("ACT.pzPop({city:'lon'})"); const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})"); const s0 = st(); - for (const a of ["opsOpen({})", "inbox({})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})", + for (const a of ["opsOpen({})", "peerPol({p:'closed'})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})", "exportSave({})", "launchBB({city:'lon'})", "ad({city:'lon'})", "addRouter({city:'lon'})", "upRouter({city:'lon'})", "addSite({city:'lon'})", "buyTE({})", "buildScrub({city:'lon',tier:0})", "buildPop({city:'par'})", "buyTransit({city:'lon',net:'cog',tier:1})", "scenarios({})", "share({})", "importGo({})", "cont({})", "start({})", "newgame({})"]) { ev('ACT.' + a); diff --git a/tests/rules.test.js b/tests/rules.test.js index 9d24992..413ad74 100644 --- a/tests/rules.test.js +++ b/tests/rules.test.js @@ -159,11 +159,10 @@ test('quick lead times: PNIs, dark fiber and own builds arrive in days (#151)', assert.deepEqual(errors, []); }); -test('Change Freeze: no peering inbox, no hardware market, no sold-out routes', () => { +test('Change Freeze: no hardware market, no sold-out routes', () => { const { ev, errors } = load(); start(ev, { mode: 'normal', preset: 'freeze' }); - ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<60;i++)inboxDay(S.day+i)"); - assert.equal(ev('S.inbox.items.length+S.inbox.seq'), 0, 'no mail'); + ev("S.cash=1e9;ACT.buyIx({city:'fra',tier:1,signed:true})"); ev('S.day=2000'); assert.equal(ev("hwMul('rt')"), 1, 'no inflation'); assert.equal(ev("hwCard()"), ''); diff --git a/tests/utilities.test.js b/tests/utilities.test.js index dae73a8..415925f 100644 --- a/tests/utilities.test.js +++ b/tests/utilities.test.js @@ -127,7 +127,7 @@ test('route-server batch leaves peering policy and player-owned exchanges alone' const { ev, errors } = setup(t); ev('ACT.utilityRouteServers()'); assert.equal(ev('Object.keys(S.rs).length'), 0, 'does not join an IX without a port'); - ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.inboxPol({p:'closed'});ACT.utilityRouteServers()"); + ev("ACT.buyIx({city:'fra',tier:0,signed:true});ACT.peerPol({p:'closed'});ACT.utilityRouteServers()"); assert.equal(ev('ppol()'), 'closed'); assert.equal(ev('S.rs.fra'), true); assert.equal(ev("ixSessions('fra').has('drz')"), false, 'does not bypass closed policy');