seriesoftubes/tests/canonical-state.test.js
jvanvik 6f0c080875 Island Wi-Fi for 18 groups of outer islands, by satellite and spur cable (#83)
Each zone (Vanua Levu & Taveuni off Suva, the Out Islands off Nassau, and
16 more) is a pool of island homes at your POP in its city: no node and no
link on the map, its Gbps join the city's demand. Rent backhaul at the
city's teleport (about 35% sign up over GEO, 75% over MEO, 90% over
Starblink from a gateway there) or, from level 3, lay a spur cable and
everyone may sign up. The first order brings the island kit. Islanders pay
island prices, their homes are IPv6-only in the NAT64 pool, and investors
on a revenue share take their cut. A spur can be cut for weeks (failure
'wspur', chaos only): a satellite kept beside it carries the islands. Zones
are off in puzzles, the Architect, scenarios and below level 2.

The satellite geometry works on points now (satSeesAt, satPairAt, satKmAt;
the city functions wrap them, with the same answers). Starblink serves a
zone only from a gateway in its own city (16 of 18; a gateway anywhere in
reach would serve the same 16), with its storm and rival rule; Nunavut and
Southeast Alaska stay on GEO. Rules W6 and F12.
2026-11-12 02:12:21 +01:00

136 lines
11 KiB
JavaScript

// Canonical live state (the server-sim design, 5.4): the game as it runs is exactly what a reload makes of its save.
// A server-run network's page loads the server's state with migrate() (it never trusts state it did not check), and
// the server checks every action against the save path; both need migrate(live S) to change nothing. A year of a big
// network with everything on (DDoS, failures, events, the intern on every order, the sales desk on auto, IPv6-only, and
// once before the year everything else a network can own: an own exchange, scrubbing centers, teleports, LEO gateways,
// satellites, an island Wi-Fi zone with a circuit and a spur, dark fiber, an own cable, a subsea seat, exchange points,
// the backbone core, the redundancy kit, the bulk orders),
// checked every day. T1_BASE=<git ref> also plays the same year on the page at that ref: the same money, customers,
// incidents, dice and ids every day, so making the state canonical changed no play.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { load } = require('./harness');
const { assembleRef } = require('../scripts/lib/page');
const { lit } = require('../scripts/lib/js-literal');
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
const DAYS = 365;
function open(file) {
const h = load(file ? { file, seed: 4242 } : { seed: 4242 });
h.ev(`Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(BIG)}));S.rng=7;S.rules=makeRules('bgp');UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();
S.lvl=Math.max(S.lvl,6);S.cash+=5e8;ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
ACT.salesHire({id:'shark'});ACT.salesAuto();closeModal();
for(const c of Object.keys(S.pops).filter(c=>S.pops[c].bb).slice(0,3))ACT.ip6Go({city:c});closeModal();`);
// Everything else, each through its own action as a player clicks it (__did: the ones that changed the network).
h.ev(`window.__did=[];const tryA=(n,a)=>{const s0=JSON.stringify(S);try{ACT[n](a);}catch(e){__did.push(n+' threw '+e.message);return;}closeModal();if(JSON.stringify(S)!==s0)__did.push(n);};
const pops=Object.keys(S.pops);
for(const c of pops.slice(0,40)){if(Object.keys(S.myIx).length)break;tryA('foundIx',{city:c});}
for(const c of pops.slice(0,6))tryA('buildScrub',{city:c});
for(const c of pops.slice(0,4))tryA('teleBuild',{city:c});
for(const c of pops.slice(0,4))tryA('teleLeo',{city:c});
{let n=0;for(const a of pops.slice(0,4))for(const b of satTargets(a)){if(n>=1)break;if(!satWhy(a,b,LEO_BIRD,5)){tryA('buySat',{a,b,bird:LEO_BIRD,g:5});n++;}}}
tryA('buildPop',{city:'suv'});tryA('teleBuild',{city:'suv'});tryA('wispSat',{z:'vanualevu',bird:'kac1',g:2});tryA('wispSpur',{z:'vanualevu'});
{let n=0;for(const a of pops.slice(0,12))for(const b of pops.slice(12,30)){if(n>=2)break;for(const bird of Object.keys(SATS))for(const g of [1,2,5,10]){if(n>=2)break;if(!satWhy(a,b,bird,g)){tryA('buySat',{a,b,bird,g});n++;}}}}
{let n=0;for(const a of pops.slice(0,10))for(const b of pops.slice(10,40)){if(n>=2)break;if(kmBetween(a,b)<900&&!noTalk(a,b)){UI.pending={a,b};UI.dfSrc='build';const k=S.links.length;tryA('orderDf');if(S.links.length>k)n++;}}}
{let n=0;for(const a of pops.slice(0,30))for(const b of Object.keys(CITY)){if(n>=1)break;if(S.pops[b]||a===b)continue;UI.pending={a,b};const k=S.links.length;if(!ownCabWhy(a,b)){tryA('orderCable');if(S.links.length>k)n++;}}}
seatConf(null);if(S.seatOff)tryA('seatBuy',{n:SEAT_N[0]});
tryA('ddosAuto');S.ddosAuto={rtbh:true,scrub:true};tryA('coreUp');tryA('coreUp');
for(const c of pops.slice(0,3))tryA('xpBuild',{city:c});
for(const c of pops.slice(0,3))tryA('utilityKit',{city:c,cost:(utilityKit(c)||{}).cost});
tryA('utilityRouteServers');tryA('utilityPeers');tryA('pniAll',{net:null,tier:1,q:(pniBatch(null,1)||{}).cost});
tryA('bstdSet',{k:'gen'});tryA('bstdSet',{k:'site2'});tryA('bstdApply',typeof bstdPlanKey==='function'?{quote:bstdPlanKey(bstdPlan(false)),q:bstdQuote(false).cost}:{});
UI.pending=null;closeModal();compute();`);
return h;
}
const BUILT = ['foundIx', 'buildScrub', 'teleBuild', 'teleLeo', 'buySat', 'wispSat', 'wispSpur', 'orderDf', 'orderCable', 'seatBuy', 'coreUp', 'xpBuild', 'utilityKit', 'pniAll', 'bstdApply'];
// In the page: every top-level key whose JSON differs between live S and what a reload makes of it, both ways a reload
// happens (the full state a page takes, and the save text). uidN and the dice are put back: a reload may draw ids.
const CHECK = `window.__sortK=v=>Array.isArray(v)?v.map(__sortK):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,k)=>(v[k]!==undefined&&(o[k]=__sortK(v[k])),o),{}):v;
window.__canon=()=>{const u0=uidN,r0=S.rng,out=[];
const live=JSON.parse(JSON.stringify(S)),snap=JSON.parse(JSON.stringify(migrate(JSON.parse(JSON.stringify(S)))));uidN=u0;S.rng=r0;
const pl=JSON.parse(JSON.stringify(packSave(S))),pm=JSON.parse(JSON.stringify(packSave(migrate(JSON.parse(JSON.stringify(packSave(S)))))));uidN=u0;S.rng=r0;
for(const k of new Set([...Object.keys(live),...Object.keys(snap)])){
// Exactly, key order included (a page's mirror stays byte for byte the server's), except the order of S.ops's keys,
// which the standing orders' own sanitizing (95-standing-orders.js) writes its way. Its content is checked as it is.
const a=k==='ops'?__sortK(live[k]):live[k],b=k==='ops'?__sortK(snap[k]):snap[k];
if(JSON.stringify(a)!==JSON.stringify(b))out.push('snapshot '+k);}
for(const k of new Set([...Object.keys(pl),...Object.keys(pm)]))if(JSON.stringify(__sortK(pl[k]))!==JSON.stringify(__sortK(pm[k])))out.push('save '+k);
return out;};
window.__diff=k=>{const u0=uidN,r0=S.rng;const a=JSON.parse(JSON.stringify(S))[k],b=JSON.parse(JSON.stringify(migrate(JSON.parse(JSON.stringify(S)))))[k];uidN=u0;S.rng=r0;
const out=[];const walk=(x,y,p)=>{if(out.length>4||JSON.stringify(x)===JSON.stringify(y))return;
if(x&&y&&typeof x==='object'&&typeof y==='object'){for(const kk of new Set([...Object.keys(x),...Object.keys(y)]))walk(x[kk],y[kk],p+'.'+kk);if(!out.length)out.push(p+': key order');return;}
out.push(p+': '+JSON.stringify(x)+' → '+JSON.stringify(y));};walk(a,b,k);return out.join('; ');};`;
const PLAY = `JSON.stringify({day:S.day,cash:S.cash,rng:S.rng,uidN,biz:S.biz.map(b=>b.id+':'+b.mood+':'+b.rate).join(),offers:S.offers.map(o=>o.id).join(),
inc:S.inc.map(i=>i.id+i.type).join(),links:S.links.map(l=>l.id+':'+(l.ch||[]).length).join(),transit:S.transit.map(t=>t.id+':'+t.tier+':'+(t.n||1)).join(),
pni:S.pni.map(p=>p.id+':'+p.tier+':'+(p.n||1)).join(),pops:Object.keys(S.pops).join(),ddos:ddosAll(S,false).map(a=>a.id+':'+a.tgt+':'+a.until).join(),
stats:Object.fromEntries(Object.entries(S.stats).filter(([k])=>k!=='ddT')),served:R.served,lost:S.lost,
ops:JSON.stringify(S.ops.log.map(e=>({...e,r:e.r.map(r=>[r[0],r[1],r[2].slice(0,3)])})))})`;
// (The day's log names at most three places a job now, as a reload always kept it: the base page listed every broken link.)
test(`a year of a big network with everything on: live state is what a reload makes of it, every day${process.env.T1_BASE ? ', and play is as before' : ''}`, (t) => {
const head = open();
t.after(() => head.dom.window.close());
head.ev(CHECK);
let base = null;
if (process.env.T1_BASE) {
const f = path.join(os.tmpdir(), `tubes-canon-base-${process.pid}.html`);
fs.writeFileSync(f, assembleRef(process.env.T1_BASE));
base = open(f);
t.after(() => { base.dom.window.close(); fs.rmSync(f, { force: true }); });
}
assert.equal(head.ev('S.ops.intern'), 'kevin');
const did = JSON.parse(head.ev('JSON.stringify(__did)'));
assert.deepEqual(did.filter((x) => / threw /.test(x)), [], 'nothing threw while building');
for (const a of BUILT) assert.ok(did.includes(a), `${a} built something before the year (${did.join(', ')})`);
assert.ok(head.ev('S.links.some(l=>l.bird===LEO_BIRD)'), 'a LEO circuit before the year');
assert.equal(head.ev('S.slAuto.on'), true);
assert.ok(head.ev("Object.values(S.pops).filter(p=>p.bb&&(p.bb.v6||p.bb.v6e)).length") >= 3, 'IPv6-only homes on the way');
const seen = { ddos: 0, inc: 0, starts: 0 };
for (let d = 1; d <= DAYS; d++) {
head.ev('dayTick()');
const bad = JSON.parse(head.ev('JSON.stringify(__canon())'));
if (bad.length) assert.fail(`day ${d}: ${bad.join(', ')} differ: ${bad.map((k) => head.ev(`__diff(${lit(k.split(' ')[1])})`)).join(' | ')}`);
if (base) { base.ev('dayTick()'); assert.equal(base.ev(PLAY), head.ev(PLAY), `day ${d}: play differs from the base page`); }
seen.ddos = Math.max(seen.ddos, head.ev('ddosAll().length'));
seen.inc = Math.max(seen.inc, head.ev('S.inc.length'));
seen.starts = Math.max(seen.starts, head.ev('S.ddosStarts.length'));
}
// It was a year of trouble, not a quiet one.
assert.ok(seen.ddos >= 1 && seen.starts >= 2, `attacks came (${JSON.stringify(seen)})`);
assert.ok(head.ev('S.stats.incidents') > 50, 'failures and events came');
assert.ok(head.ev('S.ops.log.length') > 0, 'the intern worked');
const kept = JSON.parse(head.ev(`JSON.stringify({myIx:Object.keys(S.myIx).length,scrubs:S.scrubs.length,sat:S.links.filter(l=>l.kind==='sat').length,df:S.links.filter(l=>l.kind==='df').length})`));
assert.ok(kept.myIx && kept.scrubs && kept.sat && kept.df, `what was built lived through the year (${JSON.stringify(kept)})`);
assert.equal(head.ev('S.lost'), false);
assert.deepEqual(head.errors, []);
});
test('fresh Normal games played at random, move by move: everything a player builds is what a reload makes of it', (t) => {
// The moves of the route fuzz (scripts/lib/route-fuzz.js): buttons on panels, windows and the dashboard, links, days.
const { openPage, playGame } = require('../scripts/lib/route-fuzz');
const { assemble } = require('../scripts/lib/page');
const file = path.join(os.tmpdir(), `tubes-canon-fresh-${process.pid}.html`);
fs.writeFileSync(file, assemble().html);
t.after(() => fs.rmSync(file, { force: true }));
for (const seed of [3, 5]) {
const P = { base: openPage(file, 'base'), head: openPage(file, 'head') };
t.after(() => { P.base.dom.window.close(); P.head.dom.window.close(); });
P.head.ev(CHECK);
let checked = 0;
const g = playGame(P, seed, { moves: 120, onMove: () => {
// Only a Normal game runs on a server. The fuzz may open a link from a city to itself, which the game's own drag
// never does (and the server's envelope refuses): such a state is skipped.
if (!P.head.ev("!!S&&!pzOn()&&S.mode==='normal'&&!S.links.some(l=>l.a===l.b)")) return;
const bad = JSON.parse(P.head.ev('JSON.stringify(__canon())'));
if (bad.length) assert.fail(`seed ${seed} after ${checked} moves: ${bad.join(', ')} differ: ${bad.map((k) => P.head.ev(`__diff(${lit(k.split(' ')[1])})`)).join(' | ')}`);
checked++;
} });
assert.equal(g.div, null, `seed ${seed}: the two copies stayed in step`);
assert.ok(checked > 60, `seed ${seed}: ${checked} moves checked in a Normal game`);
assert.deepEqual(g.errors, []);
}
});