The intern can keep PNI and IX ports ahead of their traffic (closes #234)

A new standing order, Keep peering headroom, works like the transit one: it
keeps each PNI and IX port above a multiple of today's traffic (1.25x to 3x).
A single port at a POP with several routers gets a second port in a LAG; any
other port moves up to the smallest port size that fits, or the biggest the
router takes. If the preferred move cannot be done it tries the other one.

It pays through the same actions as a click (ACT.pni, ACT.lagP, ACT.buyIx,
ACT.lagIx), is off by default, has the Headroom and Budget dials and the
per-POP switch, and keeps to the cash floor. A PNI augment on order is waited
for, router ports an augment will take are not promised twice, and nothing
is bought while a DDoS flood is live, since the flood counts as port usage.

The intern's monthly bill figure (opsMoNow) now counts IX ports too.
This commit is contained in:
Christopher Hawker 2026-11-03 22:54:54 +11:00
parent 48ba0048da
commit 62c242c9a7
9 changed files with 226 additions and 2 deletions

View file

@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- The NOC intern has a new order, Keep peering headroom, that adds capacity to your PNI and IX ports before they fill up (#234). A single port at a POP with several routers gets a second port in a LAG, so no router is its only way out; any other port moves up to the smallest port size that fits. It has the same Headroom and Budget dials as the transit order, can be switched off per POP, waits out a DDoS flood instead of buying ports for it, and a PNI with an augment already on order waits for it to land. The monthly figure in the intern's log now counts IX ports too.
- You can pay to hurry the survey, permits and factory of your own subsea cable, 30 days at a time (#258). Money only goes so far: the cable still has to be made, about two months plus a day for every 80 km, before the lay ships sail.
- Three new cities in northern Australia: Port Hedland, Townsville and Alice Springs (#255). Port Hedland lands a new cable up the coast to Darwin and a branch of Darwin's cable out to Singapore; Alice Springs has no sea at all. In the wet season, November to April, fiber cuts in the tropical north, Darwin included, take twice as long to reach.
- Traceroute no longer shows an "embedded cache in your rack" hop on paths that leave over transit, an exchange or a PNI. Only traffic that really ends at one of your cache boxes shows it now.

View file

@ -2894,6 +2894,7 @@
"ops.l_paid":"Kosten: {cost} einmalig, {mo}/Monat.",
"ops.l_peer":{"one":"hat mit einem Netz an {where} gepeert","other":"hat mit {n} Netzen an {where} gepeert"},
"ops.l_pni":{"one":"hat einen PNI in {where} bestellt","other":"hat {n} PNIs bestellt ({where})"},
"ops.l_ports":{"one":"hat einen Peering-Port in {where} aufgestockt","other":"hat {n}-mal Peering-Ports aufgestockt ({where})"},
"ops.l_quiet":"{name} hat auf die Graphen geschaut. Nichts zu tun.",
"ops.l_repair":{"one":"hat eine Reparatur beschleunigt","other":"hat {n} Reparaturen beschleunigt"},
"ops.l_routers":{"one":"hat Router in {where} aufgerüstet","other":"hat Router an {n} Orten aufgerüstet ({where})"},
@ -2926,6 +2927,8 @@
"ops.o_optics_d":"Optiken auf heiß laufende Dark Fiber stecken und neue Glasfaser am Tag der Übergabe beleuchten.",
"ops.o_pni":"PNI mit den Großen",
"ops.o_pni_d":"Jede Woche: mit jedem willigen Netz, das an deinen POPs genug Traffic schickt, einen PNI bestellen, in der jeweils kleinsten Größe des Netzes.",
"ops.o_ports":"Peering-Reserve halten",
"ops.o_ports_d":"PNI- und IX-Ports über einem Vielfachen des heutigen Traffics halten: ein einzelner Port an einem POP mit mehreren Routern bekommt einen zweiten im LAG, alle anderen eine Portgröße hoch.",
"ops.o_repair":"Reparaturen beschleunigen",
"ops.o_repair_d":"Für jeden Ausfall mit Eil-Reparatur zahlen, solange das Budget reicht.",
"ops.o_routers":"Router voraus halten",

View file

@ -2892,6 +2892,7 @@
"ops.l_paid":"Coste: {cost} de entrada, {mo}/mes.",
"ops.l_peer":{"one":"hizo peering con una red en {where}","other":"hizo peering con {n} redes en {where}"},
"ops.l_pni":{"one":"pidió un PNI en {where}","other":"pidió {n} PNIs ({where})"},
"ops.l_ports":{"one":"amplió un puerto de peering en {where}","other":"amplió puertos de peering {n} veces ({where})"},
"ops.l_quiet":"{name} miró las gráficas. No había nada que hacer.",
"ops.l_repair":{"one":"aceleró una reparación","other":"aceleró {n} reparaciones"},
"ops.l_routers":{"one":"mejoró los routers en {where}","other":"mejoró los routers en {n} sitios ({where})"},
@ -2924,6 +2925,8 @@
"ops.o_optics_d":"Añadir ópticas a la fibra oscura que va caliente y encender la fibra nueva el día que te la entregan.",
"ops.o_pni":"PNI con los grandes",
"ops.o_pni_d":"Cada semana: pedir un PNI a cada red dispuesta que envíe suficiente tráfico en tus POPs, con el tamaño mínimo de cada red.",
"ops.o_ports":"Margen en puertos de peering",
"ops.o_ports_d":"Mantener los puertos PNI e IX por encima de un múltiplo del tráfico de hoy: un puerto único en un POP con varios routers recibe un segundo en LAG, todos los demás suben un tamaño de puerto.",
"ops.o_repair":"Acelerar reparaciones",
"ops.o_repair_d":"Pagar la reparación urgente de cada caída que la tenga, mientras dure el presupuesto.",
"ops.o_routers":"Routers por delante",

View file

@ -2892,6 +2892,7 @@
"ops.l_paid":"Coût : {cost} d'entrée, {mo}/mois.",
"ops.l_peer":{"one":"a peeré avec un réseau à {where}","other":"a peeré avec {n} réseaux à {where}"},
"ops.l_pni":{"one":"a commandé un PNI à {where}","other":"a commandé {n} PNI ({where})"},
"ops.l_ports":{"one":"a renforcé un port de peering à {where}","other":"a renforcé des ports de peering {n} fois ({where})"},
"ops.l_quiet":"{name} a surveillé les graphes. Rien à faire.",
"ops.l_repair":{"one":"a accéléré une réparation","other":"a accéléré {n} réparations"},
"ops.l_routers":{"one":"a mis à niveau les routeurs à {where}","other":"a mis à niveau les routeurs à {n} endroits ({where})"},
@ -2924,6 +2925,8 @@
"ops.o_optics_d":"Ajouter des optiques sur la fibre noire qui chauffe, et allumer la nouvelle fibre le jour de sa livraison.",
"ops.o_pni":"PNI avec les gros",
"ops.o_pni_d":"Chaque semaine : commander un PNI avec chaque réseau partant qui envoie assez de trafic sur tes POP, à la taille minimale de chaque réseau.",
"ops.o_ports":"Garder de la marge sur les ports de peering",
"ops.o_ports_d":"Garder les ports PNI et IX au-dessus d'un multiple du trafic du jour : un port unique dans un POP à plusieurs routeurs en reçoit un deuxième en LAG, tous les autres passent à une taille de port au-dessus.",
"ops.o_repair":"Accélérer les réparations",
"ops.o_repair_d":"Payer la réparation express de chaque panne qui en a une, tant que le budget suit.",
"ops.o_routers":"Garder les routeurs en avance",

View file

@ -2892,6 +2892,7 @@
"ops.l_paid":"Costo: {cost} subito, {mo}/mese.",
"ops.l_peer":{"one":"ha fatto peering con una rete a {where}","other":"ha fatto peering con {n} reti a {where}"},
"ops.l_pni":{"one":"ha ordinato un PNI a {where}","other":"ha ordinato {n} PNI ({where})"},
"ops.l_ports":{"one":"ha aumentato una porta di peering a {where}","other":"ha aumentato le porte di peering {n} volte ({where})"},
"ops.l_quiet":"{name} ha guardato i grafici. Niente da fare.",
"ops.l_repair":{"one":"ha accelerato una riparazione","other":"ha accelerato {n} riparazioni"},
"ops.l_routers":{"one":"ha potenziato i router a {where}","other":"ha potenziato i router in {n} posti ({where})"},
@ -2924,6 +2925,8 @@
"ops.o_optics_d":"Aggiungi ottiche alla dark fiber che scotta e accendi la fibra nuova il giorno della consegna.",
"ops.o_pni":"PNI con i grandi",
"ops.o_pni_d":"Ogni settimana: ordina un PNI con ogni rete disponibile che manda abbastanza traffico nei tuoi POP, alla taglia minima di ciascuna rete.",
"ops.o_ports":"Margine sulle porte di peering",
"ops.o_ports_d":"Tieni le porte PNI e IX sopra un multiplo del traffico di oggi: una porta singola in un POP con più router ne riceve una seconda in LAG, tutte le altre passano a una porta più grande.",
"ops.o_repair":"Accelera le riparazioni",
"ops.o_repair_d":"Paga la riparazione urgente di ogni guasto che ce l'ha, finché il budget regge.",
"ops.o_routers":"Router sempre avanti",

View file

@ -2892,6 +2892,7 @@
"ops.l_paid":"Custo: {cost} de entrada, {mo}/mês.",
"ops.l_peer":{"one":"fez peering com uma rede em {where}","other":"fez peering com {n} redes em {where}"},
"ops.l_pni":{"one":"pediu um PNI em {where}","other":"pediu {n} PNIs ({where})"},
"ops.l_ports":{"one":"reforçou uma porta de peering em {where}","other":"reforçou portas de peering {n} vezes ({where})"},
"ops.l_quiet":"{name} ficou olhando os gráficos. Nada a fazer.",
"ops.l_repair":{"one":"acelerou um reparo","other":"acelerou {n} reparos"},
"ops.l_routers":{"one":"melhorou os roteadores em {where}","other":"melhorou os roteadores em {n} lugares ({where})"},
@ -2924,6 +2925,8 @@
"ops.o_optics_d":"Adicionar ópticas à fibra escura que está esquentando e acender a fibra nova no dia da entrega.",
"ops.o_pni":"PNI com os grandes",
"ops.o_pni_d":"Toda semana: pedir um PNI com cada rede disposta que mande tráfego suficiente nos seus POPs, no tamanho mínimo de cada rede.",
"ops.o_ports":"Folga nas portas de peering",
"ops.o_ports_d":"Manter as portas PNI e IX acima de um múltiplo do tráfego de hoje: uma porta única num POP com vários roteadores ganha uma segunda em LAG, todas as outras sobem um tamanho de porta.",
"ops.o_repair":"Acelerar reparos",
"ops.o_repair_d":"Pagar o reparo urgente de cada queda que tenha um, enquanto o orçamento durar.",
"ops.o_routers":"Roteadores à frente",

View file

@ -12,6 +12,7 @@ const INTERNS={
// fees, or (mo) of the running costs the order adds, for caches, which are free to rack but cost rent every month.
const OPS=[
{k:'transit',i:'📈',pop:1,cap:50000,t:N_('ops.o_transit'),d:N_('ops.o_transit_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'},prov:{d:'cheap',ok:v=>v==='cheap'||v==='have'||(isNet(v)&&!!NET[v].price),l:N_('ops.p_prov')}}},
{k:'ports',i:'🔌',pop:1,cap:50000,t:N_('ops.o_ports'),d:N_('ops.o_ports_d'),p:{x:{d:1.5,v:[1.25,1.5,2,3],l:N_('ops.p_x'),f:v=>v+'×'}}},
{k:'routers',i:'🧠',pop:1,cap:250000,t:N_('ops.o_routers'),d:N_('ops.o_routers_d'),p:{at:{d:80,v:[60,70,80,90],l:N_('ops.p_at'),f:v=>v+'%'},how:{d:'auto',v:['auto','add','swap'],l:N_('ops.p_how'),f:v=>tr({auto:N_('ops.how_auto'),add:N_('ops.how_add'),swap:N_('ops.how_swap')}[v])}}},
{k:'caches',i:'📦',pop:1,cap:5000,mo:1,t:N_('ops.o_caches'),d:N_('ops.o_caches_d'),p:{g:{d:5,v:[1,5,10,25,50],l:N_('ops.p_g'),f:v=>fmtG(v)}}},
{k:'ix',i:'🔀',t:N_('ops.o_ix'),d:N_('ops.o_ix_d'),p:{}},
@ -24,7 +25,7 @@ const OPS=[
const OPSK=Object.fromEntries(OPS.map(o=>[o.k,o])),OPS_POP=OPS.filter(o=>o.pop).map(o=>o.k);
const OPS_TPL=['bb','transit','ix','kit'];
// What the shift log can say. One line per day: "{name} did this, that and the other."
const OPS_SAY={transit:N_('ops.l_transit'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')};
const OPS_SAY={transit:N_('ops.l_transit'),ports:N_('ops.l_ports'),routers:N_('ops.l_routers'),caches:N_('ops.l_caches'),rs:N_('ops.l_rs'),peer:N_('ops.l_peer'),pni:N_('ops.l_pni'),sales:N_('ops.l_sales'),decline:N_('ops.l_decline'),repair:N_('ops.l_repair'),optics:N_('ops.l_optics'),decom:N_('ops.l_decom'),broke:N_('ops.l_broke'),snag:N_('ops.l_snag')};
// Fat fingers: rare, visible, harmless. Only the LAG one costs anything, and only a little.
const OPS_FF=[N_('ops.ff_desc'),N_('ops.ff_hostname'),N_('ops.ff_typo'),N_('ops.ff_lag'),N_('ops.ff_ping')];
const OPS_TRIALS=1,OPS_FF_RATE={oncall:1/150,bgp:1/60};
@ -90,6 +91,7 @@ function opsMoNow(){let m=cachesMo();
for(const l of S.links)m+=(l.mo||0)+(l.kind==='df'?(l.spares?Math.round(150+(l.ch||[]).length*80):0)+(l.regen|0)*REGEN_MO:0);
for(const t of S.transit)m+=transitMo(t,0);
for(const p of S.pni){const q=p.up||p,N=NET[p.net];m+=(q.g1?Math.round(PORT[0].pni/2):PORT[q.tier].pni)*(q.n||1)+(N.pol==='paid'&&!paidFree(N)?N.paidFee:0);}
for(const c in S.ixp)if(!S.myIx[c])m+=ixPortMo(c,S.ixp[c])*((S.ixn||{})[c]||1);
return m;}
const opsFFLine=e=>tr('ops.ff_line',{name:tr(INTERNS[e.i].s),what:tr(OPS_FF[e.f],{city:CITY[e.c].name})});
// Mute what a click would show (toasts, sounds, floaters, the full redraw) and keep the player's selection.
@ -154,6 +156,28 @@ const OPS_RUN={
if(i!==undefined)job={cost:PORT[i].setup,go:()=>ACT.buyTransit({city:c,net:n.id,tier:i}),w:'+'+PORT[i].n};}}
if(!job||!X.can('transit',job.cost)||!X.pay('transit',job.go))break;
X.did('transit',c+' '+job.w);ts=S.transit.filter(t=>t.city===c);}}},
// PNIs and IX ports keep Headroom times today's traffic, hottest first. One port at a POP with several routers gets a
// second in a LAG, so it is not the only way out; anything else moves up to the smallest port size that fits. A PNI
// augment lands weeks later, so that port waits for it. A flood fills ports for a day or two: not worth buying for.
ports(X){if(ddosAll().length)return;const N=opsP('ports','x'),L=[],
// Router ports that pending PNI augments will take when they land are spoken for.
resv=c=>S.pni.reduce((a,p)=>p.up&&p.city===c?a+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):a,0),room=c=>portsMax(c)-portsUsed(c)+1e-9-resv(c);
// Each port: cap() now, use today, lag() and ups() the jobs it could have as {cost, cap after, w for the log, go}, sig() to see a job took.
for(const p of S.pni){const c=p.city,use=R.usePni[p.id]||0,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,use,u:use/cap(),cap,n,rt:(S.pops[c]||{}).routers||1,busy:()=>!!p.up,sig:()=>[p.tier,n(),!!p.g1,!!p.up].join(),
lag:()=>n()<LAG_MAX&&!msfNope(p.net,c)&&PORT_SLOT(p.tier)<=room(c)?{cost:1500+PORT[p.tier].setup/2,cap:lagCap(pniG(p),n()+1),w:'+1×'+pniPN(p),go:()=>ACT.lagP({id:p.id,d:1})}:null,
ups:()=>{const out=[];for(let t=p.g1?0:p.tier+1;t<PORT.length&&portShown(t);t++){const q=pniQuote(c,p.net,t,resv(c));if(q&&!q.why)out.push({cost:q.cost,cap:lagCap(PORT[t].g,n()),w:pniPN(p)+'→'+PORT[t].n,go:()=>ACT.pni({city:c,net:p.net,tier:t})});}return out;}});}
for(const x in S.ixp){const c=ixCity(x),use=R.useIx[x]||0,cap=()=>ixCap(x),n=()=>(S.ixn||{})[x]||1,pop=S.pops[c];if(S.myIx[x]||!(use>0)||!(cap()>0)||cap()>=N*use||!opsHere('ports',c))continue;
const g=()=>PORT[S.ixp[x]].g;
L.push({city:c,use,u:use/cap(),cap,n,rt:pop?pop.routers||1:1,busy:()=>false,sig:()=>S.ixp[x]+','+n(),
lag:()=>pop&&n()<LAG_MAX&&PORT_SLOT(S.ixp[x])<=room(c)?{cost:ixPortMo(x,S.ixp[x]),cap:cap()*lagCap(g(),n()+1)/lagCap(g(),n()),w:'+1×'+PORT[S.ixp[x]].n,go:()=>ACT.lagIx({city:x,d:1})}:null,
// A remote port (no POP there) stops at 100G; at a POP the router has to take the bigger port.
ups:()=>{const out=[],t0=S.ixp[x];for(let t=t0+1;t<PORT.length&&portShown(t);t++){if(pop?!portOk(c,t)||(PORT_SLOT(t)-PORT_SLOT(t0))*n()>room(c):t>1)continue;
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()<N*o.use;step++){
const lag=o.lag(),ups=o.ups(),fit=ups.find(u=>u.cap>=N*o.use)||ups.at(-1),job=o.n()<2&&o.rt>1?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.city+' '+job.w);}},
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;
@ -197,7 +221,7 @@ const OPS_RUN={
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 OPS_ORDER=['repair','sales','routers','transit','optics','caches','ix','pni','decom'];
const OPS_ORDER=['repair','sales','routers','transit','ports','optics','caches','ix','pni','decom'];
// The shift: once per game day from dayTick, after outages and events have had their turn.
function opsDay(d){if(!opsHired())return;const O=S.ops,m=monthIdx(d);if(m!==O.mon){O.mon=m;for(const k in O.spent)O.spent[k]=0;O.addMo={};}
// A new week: last week's tally becomes the shift report, and the one NOC notice of the week.

View file

@ -2893,6 +2893,7 @@
"ops.l_paid":"Cost: {cost} up front, {mo}/mo.",
"ops.l_peer":{"one":"peered with a network at {where}","other":"peered with {n} networks at {where}"},
"ops.l_pni":{"one":"ordered a PNI in {where}","other":"ordered {n} PNIs ({where})"},
"ops.l_ports":{"one":"topped up a peering port in {where}","other":"topped up peering ports {n} times ({where})"},
"ops.l_quiet":"{name} watched the graphs. Nothing needed doing.",
"ops.l_repair":{"one":"rushed a repair","other":"rushed {n} repairs"},
"ops.l_routers":{"one":"upgraded routers in {where}","other":"upgraded routers in {n} places ({where})"},
@ -2925,6 +2926,8 @@
"ops.o_optics_d":"Add optics to dark fiber that runs hot, and light new fiber the day it is handed over.",
"ops.o_pni":"PNI with the big ones",
"ops.o_pni_d":"Every week: order a PNI with every willing network sending enough traffic at your POPs, at each network's own minimum size.",
"ops.o_ports":"Keep peering headroom",
"ops.o_ports_d":"Keep PNI and IX ports above a multiple of today's traffic: a single port at a POP with several routers gets a second one in a LAG, anything else moves up a port size.",
"ops.o_repair":"Rush repairs",
"ops.o_repair_d":"Pay for the rush repair on every outage that has one, while the budget lasts.",
"ops.o_routers":"Keep routers ahead",

181
tests/intern-ports.test.js Normal file
View file

@ -0,0 +1,181 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
// The intern's "Keep peering headroom" order: PNI and IX ports above a multiple of today's traffic. One port at a POP with
// several routers gets a second in a LAG; anything else moves up a port size. Same setup as the other standing-order tests:
// a small network, a hired intern, no cash floor, no fat fingers (Change Freeze).
const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=3;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" +
"ACT.launchBB({city:'fra'});S.pops.fra.bb.d=300;S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()";
function game(t, extra = '') {
const h = load();
t.after(() => h.dom.window.close());
h.ev(BASE);
if (extra) h.ev(extra);
return h;
}
const hire = ev => ev("ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal()");
// Hiring recomputes, which would wipe the traffic a case stages: hire first, then stage.
function hired(t, extra) { const h = game(t); hire(h.ev); h.ev(extra); return h; }
const on = (ev, p = { x: 1.5 }, cap) => ev(`S.ops.on.ports=true;S.ops.p.ports=${JSON.stringify(p)};${cap === undefined ? '' : `S.ops.cap.ports=${cap};`}`);
const shift = ev => ev('opsDay(S.day)');
const cash = ev => ev('S.cash');
// A 10G PNI with a small network at Frankfurt, carrying `use` Gbps today. PNIs are up the moment they are ordered, so the
// outcome does not wait on a lead time.
const pni = (tier, use, n = 1) => `S.rules.pnis='instant';S.pni.push({id:'p1',city:'fra',net:'drz',tier:${tier},n:${n},ready:0});compute();R.usePni.p1=${use}`;
const ix = (tier, use) => `S.rules.pnis='instant';ACT.buyIx({city:'fra',tier:${tier},signed:true});compute();R.useIx.fra=${use}`;
const PNIS = "JSON.stringify(S.pni.map(p=>[p.net,p.tier,p.n||1,!!p.up]))";
const IXP = "JSON.stringify([S.ixp.fra,(S.ixn||{}).fra||1])";
// The same game twice: the intern's shift in one, the player's own clicks in the other. Both must cost the same and end the same.
function twins(t, extra, manual, pick, x = 1.5) {
const A = game(t), B = game(t);
hire(A.ev); hire(B.ev);
A.ev(extra); B.ev(extra);
on(A.ev, { x });
const a0 = cash(A.ev); shift(A.ev); const a1 = cash(A.ev);
const b0 = cash(B.ev); B.ev(manual); const b1 = cash(B.ev);
assert.ok(a0 - a1 > 0, 'the order did some paid work');
assert.equal(a0 - a1, b0 - b1, 'the shift cost exactly what the clicks cost');
assert.equal(A.ev(pick), B.ev(pick), 'and left the network the same');
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
return A;
}
test('a hot PNI at a one-router POP moves up a port size, exactly as the click would', t => {
const A = twins(t, pni(0, 9), "ACT.pni({city:'fra',net:'drz',tier:1})", PNIS);
assert.equal(A.ev('S.pni[0].tier'), 1);
assert.equal(A.ev('S.pni[0].n||1'), 1, 'one port, not a LAG');
assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up a peering port in Frankfurt 10G→100G/);
});
test('a single PNI port at a POP with several routers gets a second port in a LAG', t => {
const A = twins(t, pni(0, 9) + ";S.pops.fra.routers=2;compute();R.usePni.p1=9", "ACT.lagP({id:'p1',d:1})", PNIS);
assert.equal(A.ev('S.pni[0].tier'), 0, 'same size');
assert.equal(A.ev('S.pni[0].n'), 2);
assert.match(A.ev('opsEntry(S.ops.log[0])'), /Kevin topped up a peering port in Frankfurt \+1×10G/);
});
test('a PNI that is already a LAG moves up a port size, whatever the routers', t => {
const A = twins(t, pni(0, 15, 2) + ";S.pops.fra.routers=2;compute();R.usePni.p1=15", "ACT.pni({city:'fra',net:'drz',tier:1})", PNIS);
assert.equal(A.ev('S.pni[0].tier'), 1);
assert.equal(A.ev('S.pni[0].n'), 2, 'the LAG keeps its members');
});
test('the same two rules for an IX port', t => {
const up = twins(t, ix(0, 9), "ACT.buyIx({city:'fra',tier:1})", IXP);
assert.equal(up.ev(IXP), '[1,1]', 'one router: a bigger port');
assert.match(up.ev('opsEntry(S.ops.log[0])'), /topped up a peering port in Frankfurt 10G→100G/);
const lag = twins(t, ix(0, 9) + ";S.pops.fra.routers=2;compute();R.useIx.fra=9", "ACT.lagIx({city:'fra',d:1})", IXP);
assert.equal(lag.ev(IXP), '[0,2]', 'several routers: a second port in a LAG');
const big = twins(t, ix(0, 15) + ";S.ixn={fra:2};S.pops.fra.routers=2;compute();R.useIx.fra=15", "ACT.buyIx({city:'fra',tier:1})", IXP);
assert.equal(big.ev(IXP), '[1,2]', 'a LAG moves up as a whole');
});
test('it picks the smallest port that gives the headroom, and the biggest the router takes when none does', t => {
// 120G of traffic at 1.5× needs 180G: 100G is too small, 400G fits.
const A = twins(t, pni(1, 99) + ";R.usePni.p1=99", "ACT.pni({city:'fra',net:'drz',tier:2})", PNIS);
assert.equal(A.ev('S.pni[0].tier'), 2);
// A router that tops out at 100G cannot take a bigger port: another member of the LAG instead.
const B = twins(t, "S.pops.fra.rgen=0;" + pni(1, 95), "ACT.lagP({id:'p1',d:1})", PNIS);
assert.equal(B.ev('S.pni[0].tier'), 1);
assert.equal(B.ev('S.pni[0].n'), 2);
// 380G of traffic at 3× needs 1140G: the next size up (800G) is still too small, so it skips to 1.6T in one order.
const C = twins(t, "S.pops.fra.rgen=3;" + pni(2, 380), "ACT.pni({city:'fra',net:'drz',tier:4})", PNIS, 3);
assert.equal(C.ev('S.pni[0].tier'), 4);
});
test('it leaves ports with their headroom alone, and does nothing when switched off', t => {
const { ev, errors } = hired(t, pni(1, 20) + ";" + ix(0, 5));
on(ev);
const s0 = ev(`${PNIS}+${IXP}`), c0 = cash(ev);
shift(ev);
assert.equal(ev(`${PNIS}+${IXP}`), s0);
assert.equal(cash(ev), c0);
assert.equal(ev('S.ops.log[0].r.length'), 0, 'a quiet shift');
ev('R.usePni.p1=95;R.useIx.fra=9;S.ops.on.ports=false');
shift(ev);
assert.equal(cash(ev), c0, 'off: hot ports stay as they are');
assert.deepEqual(errors, []);
});
test('a PNI augment on order is waited for, not ordered twice', t => {
const { ev, errors } = hired(t, "S.rules.pnis='wait';S.pni.push({id:'p1',city:'fra',net:'drz',tier:0,ready:0});compute();R.usePni.p1=9");
on(ev);
shift(ev);
assert.equal(ev('S.pni[0].up&&S.pni[0].up.tier'), 1, 'the augment is ordered');
assert.equal(ev('S.pni[0].tier'), 0, 'and lands later');
const c1 = cash(ev), up = ev('JSON.stringify(S.pni[0].up)');
ev('R.usePni.p1=9'); shift(ev);
assert.equal(cash(ev), c1, 'a second shift buys nothing');
assert.equal(ev('JSON.stringify(S.pni[0].up)'), up);
assert.deepEqual(errors, []);
});
test('the router ports an augment on order will take are not promised twice', t => {
// A hot 100G PNI, a hot 10G PNI and a hot IX port, two routers, one free port: the hottest gets its second member and nobody else can have a port.
const { ev, errors } = hired(t, "S.rules.pnis='wait';S.pops.fra.routers=2;S.transit.push({id:'fill',city:'fra',net:'ntt',tier:1,n:43,down:0},{id:'fill2',city:'fra',net:'ntt',tier:0,n:6,down:0});ACT.buyIx({city:'fra',tier:0,signed:true});" +
"S.pni.push({id:'p1',city:'fra',net:'drz',tier:1,ready:0},{id:'p2',city:'fra',net:'vdp',tier:0,ready:0});compute();R.usePni.p1=95;R.usePni.p2=9;R.useIx.fra=9");
on(ev);
assert.equal(ev("portsMax('fra')-portsUsed('fra')"), 1);
shift(ev);
assert.equal(ev('S.pni[0].up&&S.pni[0].up.n'), 2, 'the hotter PNI is the one that gets the port');
assert.ok(!ev('S.pni[1].up'), 'the 10G one gets neither a member nor a bigger port');
assert.equal(ev(IXP), '[0,1]', 'and neither does the exchange port');
assert.ok(ev("portsUsed('fra')+S.pni.reduce((a,p)=>a+(p.up?Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1)):0),0)") <= ev("portsMax('fra')"), 'and the POP is not over-booked');
assert.deepEqual(errors, []);
});
test('it keeps to the monthly budget, the cash floor and the per-POP switch', t => {
const { ev, errors } = hired(t, pni(0, 9));
on(ev, { x: 1.5 }, 10000);
ev('S.ops.spent.ports=9000');
shift(ev);
assert.equal(ev('S.pni[0].tier'), 0, 'over the budget: left alone');
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Keep peering headroom/);
ev('S.ops.spent.ports=0;S.ops.floor=1e8');
ev('R.usePni.p1=9'); shift(ev);
assert.equal(ev('S.pni[0].tier'), 0, 'under the cash floor: left alone');
ev("S.ops.floor=0;ACT.opsPop({k:'ports',city:'fra'});closeModal();R.usePni.p1=9");
shift(ev);
assert.equal(ev('S.pni[0].tier'), 0, 'switched off at this POP');
ev("ACT.opsPop({k:'ports',city:'fra'});closeModal();R.usePni.p1=9");
shift(ev);
assert.equal(ev('S.pni[0].tier'), 1, 'and on again');
assert.deepEqual(errors, []);
});
test('it waits out a flood instead of buying ports for it', t => {
const { ev, errors } = hired(t, pni(0, 9));
on(ev);
ev("S.ev.ddos={id:'a',city:'fra',tgt:'bb:fra',vec:'http',gbps:20,start:S.day,until:S.day+3};compute();R.usePni.p1=9");
const c0 = cash(ev);
shift(ev);
assert.equal(cash(ev), c0);
assert.equal(ev('S.pni[0].tier'), 0);
ev("S.ev.ddos=null;compute();R.usePni.p1=9"); shift(ev);
assert.equal(ev('S.pni[0].tier'), 1, 'the day after, it gets on with it');
assert.deepEqual(errors, []);
});
test('the monthly bill the intern reports includes IX ports', t => {
const { ev, errors } = hired(t, ix(0, 9));
on(ev);
const m0 = ev('opsMoNow()');
shift(ev);
assert.equal(ev('S.ixp.fra'), 1);
assert.equal(ev('opsMoNow()') - m0, ev('ixPortMo("fra",1)-ixPortMo("fra",0)'));
assert.equal(ev('S.ops.log[0].mo'), ev('opsMoNow()') - m0, 'and the log says so');
assert.deepEqual(errors, []);
});
test('an old save has the order off, and a new save keeps its dials', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, { x: 2 }, 250000);
ev("S.ops.skip.fra=['ports'];save();S=migrate(JSON.parse(slotRaw(UI.slot)))");
assert.equal(ev("S.ops.on.ports&&S.ops.p.ports.x===2&&S.ops.cap.ports===250000&&S.ops.skip.fra[0]==='ports'"), true);
ev("delete S.ops.on.ports;delete S.ops.p.ports;delete S.ops.cap.ports;delete S.ops.spent.ports;S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('S.ops.on.ports'), false, 'an intern hired before the order existed does not start doing it');
assert.equal(ev('opsP("ports","x")'), 1.5);
assert.equal(ev('S.ops.spent.ports'), 0);
assert.deepEqual(errors, []);
});