Server-run play, part 1: game prerequisites and shared contracts
Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.
- A new network in two halves (beginState/beginShow), the coach split into
tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
once-per-load toasts, the five text actions take their text as an
argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
the base no longer count as divergences.
This commit is contained in:
parent
e25f843526
commit
d1e127da67
60 changed files with 2200 additions and 105 deletions
131
tests/canonical-state.test.js
Normal file
131
tests/canonical-state.test.js
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
// 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, satellites,
|
||||
// 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});
|
||||
{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', 'buySat', '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.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, []);
|
||||
}
|
||||
});
|
||||
|
|
@ -161,11 +161,14 @@ test('saves before 2.2 load: an attack on a city finds its target, and an IX bla
|
|||
assert.equal(ev('S.ev.ddos.tgt'), 'g', 'the most attractive customer in the city');
|
||||
assert.equal(ev('S.ev.ddos.ixbh'), undefined);
|
||||
assert.equal(ev('S.ev.ddos.entry'), undefined);
|
||||
assert.equal(ev('S.ev.ddosMore[0].tgt'), 'g');
|
||||
// A customer target that is no customer here stays as it is: in play that is a customer who left during the day, and
|
||||
// the next morning ends the attack (ddosExpire), so a reload must not aim it at someone else.
|
||||
assert.equal(ev('S.ev.ddosMore[0].tgt'), 'nobody');
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosAuto)')), { rtbh: false, scrub: true });
|
||||
ev("const s=JSON.parse(JSON.stringify(packSave(S)));s.ddosAuto='yes';s.stats.ddT='x';S=migrate(s)");
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ddosAuto)')), { rtbh: false, scrub: true });
|
||||
ev('for(let i=0;i<3;i++)dayTick()');
|
||||
assert.equal(ev("ddosAll(S,false).some(a=>a.id==='o2')"), false, 'and the morning ended it');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
"tests/backbone-core.test.js": 27.5,
|
||||
"tests/badges-variants.test.js": 20.2,
|
||||
"tests/build.test.js": 1.3,
|
||||
"tests/canonical-state.test.js": 64.0,
|
||||
"tests/capacity-deals.test.js": 12.6,
|
||||
"tests/chaos-monkey.test.js": 30.3,
|
||||
"tests/city-size.test.js": 8.5,
|
||||
|
|
@ -31,6 +32,7 @@
|
|||
"tests/modes.test.js": 41.1,
|
||||
"tests/more-cables.test.js": 14.3,
|
||||
"tests/moscow-premium.test.js": 12.0,
|
||||
"tests/mp-sim-contract.test.js": 7.0,
|
||||
"tests/networks-list.test.js": 6.4,
|
||||
"tests/new-game-speed.test.js": 10.1,
|
||||
"tests/optic-counts.test.js": 9.7,
|
||||
|
|
@ -59,6 +61,7 @@
|
|||
"tests/save-slots.test.js": 48.5,
|
||||
"tests/scenarios-playtest.test.js": 113.2,
|
||||
"tests/sea-routing.test.js": 42.6,
|
||||
"tests/server-sim-prereqs.test.js": 16.0,
|
||||
"tests/services.test.js": 15.7,
|
||||
"tests/specialist.test.js": 14.3,
|
||||
"tests/speed.test.js": 144.6,
|
||||
|
|
|
|||
1
tests/fixtures/mp-sim/clock.json
vendored
Normal file
1
tests/fixtures/mp-sim/clock.json
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"t":"clock","speed":1,"eff":1,"run":true,"why":null,"votes":{"efgh5678":4},"tally":{"4":1},"need":2,"active":["abcd1234","efgh5678"],"hold":[],"idle":[],"day":518,"last":1,"max":8,"off":{"abcd1234":-473,"efgh5678":0}}
|
||||
1
tests/fixtures/mp-sim/roster.json
vendored
Normal file
1
tests/fixtures/mp-sim/roster.json
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"t":"roster","code":"K7Q2XD","title":"Friday","preset":"oncall","seed":424242,"created":1730913600000,"players":[{"pid":"abcd1234","name":"Packet Pals","asn":201234,"color":"#3a86ff","card":{"day":45,"name":"Packet Pals","asn":201234,"tier":"t3","t1":false,"lvl":2,"pops":["fra","ams"],"links":[["ams","fra",10]],"ix":[],"transit":["cog"],"ppol":"open","reach":1,"peak":47.3,"served":47.3,"cust":0,"rev":7099,"cashB":5,"score":47},"seen":1731000000000,"joined":1730913600000},{"pid":"efgh5678","name":"Tubular Bells","asn":207777,"color":"#ff4f9a","card":null,"seen":1730999940000,"joined":1730996400000}],"feed":[{"k":"join","pid":"abcd1234","name":"Packet Pals","at":1730913600000},{"k":"join","pid":"efgh5678","name":"Tubular Bells","at":1730996400000},{"k":"chat","pid":"efgh5678","name":"Tubular Bells","at":1730999940000,"text":"peer with me?"}],"on":["abcd1234","efgh5678"]}
|
||||
1
tests/fixtures/mp-sim/snap.json
vendored
Normal file
1
tests/fixtures/mp-sim/snap.json
vendored
Normal file
File diff suppressed because one or more lines are too long
1
tests/fixtures/mp-sim/sub.json
vendored
Normal file
1
tests/fixtures/mp-sim/sub.json
vendored
Normal file
File diff suppressed because one or more lines are too long
1
tests/fixtures/mp-sim/upd-act.json
vendored
Normal file
1
tests/fixtures/mp-sim/upd-act.json
vendored
Normal file
File diff suppressed because one or more lines are too long
1
tests/fixtures/mp-sim/upd-day.json
vendored
Normal file
1
tests/fixtures/mp-sim/upd-day.json
vendored
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -258,7 +258,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => {
|
|||
const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
|
||||
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
|
||||
['dfBuildDays', 'leadDays'], ['dayPreRun', "rule('clock')"], ['snub', "rule('market')"], ['failureRun', 'shipsOn()'],
|
||||
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()'],
|
||||
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toastPop', 'quietOn()'],
|
||||
['ip4On', "rule('ip4')"], ['ip4Fits', 'ip4On()'], ['ip4Money', 'ip4On()'], ['ip4Day', 'ip4On()'],
|
||||
['ip6Day', 'ip4On()'], ['ip6Grow', 'ip4On()'], ['ip6Why', 'ip4On()'], ['ip6Html', 'ip4On()'], ['ip4Can', 'ip4On()']];
|
||||
fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${lit(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)');
|
||||
|
|
|
|||
|
|
@ -7,17 +7,22 @@
|
|||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { JSDOM, VirtualConsole } = require('jsdom');
|
||||
const { assemble } = require('../scripts/lib/page');
|
||||
const { assemble, simId } = require('../scripts/lib/page');
|
||||
|
||||
const PAGE = {};
|
||||
const page = (dev) => PAGE[dev] || (PAGE[dev] = assemble({ dev }).html);
|
||||
const page = (dev, mp) => PAGE[dev + '|' + mp] || (PAGE[dev + '|' + mp] = assemble({ dev, mp }).html);
|
||||
// The build id an MP page carries (scripts/lib/page.js simId()), worked out once per test process.
|
||||
let SIM;
|
||||
const simOf = () => SIM || (SIM = simId(assemble({ mp: true }).html));
|
||||
|
||||
// opts.file: a built or older page to load instead (the perf bench, the release build test).
|
||||
// opts.agent: the development page, with src/agent/.
|
||||
// opts.mp: the page with multiplayer on, as MP_API=… npm run build stamps it; opts.fetch: the page's fetch, from the start.
|
||||
// opts.mp: the page with multiplayer on, as MP_API=… npm run build makes it: the server-play client in it, MP_API
|
||||
// stamped (opts.mp's path, or '/api/mp' for true) and SIM_ID too; opts.fetch: the page's fetch, from the start
|
||||
// (fakeFetch() below fakes the session server, streams included).
|
||||
function load(opts = {}) {
|
||||
let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent);
|
||||
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp));
|
||||
let html = opts.file ? fs.readFileSync(opts.file, 'utf8') : page(!!opts.agent, !!opts.mp);
|
||||
if (opts.mp) html = html.replace("/*__MP_API__*/''", () => JSON.stringify(opts.mp === true ? '/api/mp' : opts.mp)).replace("/*__SIM_ID__*/''", () => JSON.stringify(simOf()));
|
||||
const errors = [];
|
||||
const vc = new VirtualConsole();
|
||||
vc.on('jsdomError', (e) => {
|
||||
|
|
@ -47,6 +52,8 @@ function load(opts = {}) {
|
|||
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(opts.dir || path.join(__dirname, '..', 'site', 'i18n'), opts.lang + '.js'), 'utf8')); }
|
||||
// jsdom has no CompressionStream; {gzip:true} lends the page Node's, the same API browsers have (#176).
|
||||
if (opts.gzip) for (const k of ['CompressionStream', 'DecompressionStream', 'TextEncoder', 'TextDecoder']) window[k] = globalThis[k];
|
||||
// An MP page reads its server's stream through fetch: the decoder and streams it needs, Node's (as browsers have them).
|
||||
if (opts.mp) for (const k of ['TextEncoder', 'TextDecoder', 'ReadableStream']) if (!window[k]) window[k] = globalThis[k];
|
||||
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
|
||||
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
|
||||
const fake = () => { const calls = { n: 0 };
|
||||
|
|
@ -115,4 +122,58 @@ function browser({ locks = true, channel = true } = {}) {
|
|||
}
|
||||
const flush = (n = 3) => new Promise((r) => { const go = (i) => (i ? setTimeout(() => go(i - 1), 2) : r()); go(n); });
|
||||
|
||||
module.exports = { load, seed, browser, flush };
|
||||
/* One server-sent event as it goes over the wire (section 5.1 of the server-sim design): event, optional id, one line
|
||||
of JSON data. */
|
||||
const sse = (event, data, id) => `event: ${event}\n${id === undefined ? '' : `id: ${id}\n`}data: ${JSON.stringify(data)}\n\n`;
|
||||
|
||||
/* A fake session server for an MP page (load({mp: true, fetch: f})). routes: [regexp on "METHOD url", reply |
|
||||
(call) => reply], where a reply is {status, json, headers?}, an Error (the network failed) or a promise of either (an
|
||||
answer still on its way; the page aborting meanwhile rejects it, as fetch does). A GET of …/stream that no route
|
||||
answers opens an event stream the test writes to:
|
||||
f.streams every stream opened, in order; await f.stream(i) the i-th one (0 first), once the page opens it
|
||||
s.send(event, data, id) one event (sse() above); s.comment('hb'); s.close(); s.fail(err)
|
||||
s.aborted the page aborted it (its AbortSignal); s.closed it ended either way; s.call its request
|
||||
Every request is in f.calls: {url, method, path (without MP_API's base), query, headers, raw, body (parsed JSON),
|
||||
keepalive, signal}. Responses are Node's own Headers and ReadableStream, which is what browsers hand a page. */
|
||||
function fakeFetch(routes = [], { base = '/api/mp' } = {}) {
|
||||
const calls = [], streams = [], waiting = [], enc = new TextEncoder();
|
||||
const aborted = () => { const e = new Error('aborted'); e.name = 'AbortError'; return e; };
|
||||
const res = (r) => (r instanceof Error ? Promise.reject(r) : Promise.resolve({ ok: r.status < 400, status: r.status, headers: new Headers(r.headers || { 'content-type': 'application/json' }),
|
||||
body: null, json: () => (r.json === undefined ? Promise.reject(new SyntaxError('no body')) : Promise.resolve(r.json)), text: () => Promise.resolve(r.json === undefined ? '' : JSON.stringify(r.json)) }));
|
||||
function open(c) {
|
||||
let ctl;
|
||||
const s = { call: c, closed: false, aborted: false, sent: [],
|
||||
write(t) { if (!s.closed) ctl.enqueue(enc.encode(t)); return s; },
|
||||
send(event, data, id) { const t = sse(event, data, id); s.sent.push({ event, data, id }); return s.write(t); },
|
||||
comment(text = 'hb') { return s.write(`: ${text}\n\n`); },
|
||||
close() { if (!s.closed) { s.closed = true; ctl.close(); } return s; },
|
||||
fail(e = new Error('network')) { if (!s.closed) { s.closed = true; ctl.error(e); } return s; } };
|
||||
const body = new ReadableStream({ start(k) { ctl = k; }, cancel() { s.closed = true; } });
|
||||
if (c.signal) c.signal.addEventListener('abort', () => { s.aborted = true; s.fail(aborted()); });
|
||||
streams.push(s);
|
||||
for (const w of waiting.filter((x) => x.i < streams.length)) { waiting.splice(waiting.indexOf(w), 1); w.ok(streams[w.i]); }
|
||||
return Promise.resolve({ ok: true, status: 200, headers: new Headers({ 'content-type': 'text/event-stream; charset=utf-8' }), body,
|
||||
json: () => Promise.reject(new SyntaxError('an event stream')), text: () => Promise.reject(new TypeError('an event stream')) });
|
||||
}
|
||||
const f = (url, o = {}) => {
|
||||
const u = new URL(String(url), 'https://tests.invalid/'), method = (o.method || 'GET').toUpperCase();
|
||||
const headers = {}; for (const [k, v] of Object.entries(o.headers || {})) headers[k.toLowerCase()] = v;
|
||||
let body; try { body = typeof o.body === 'string' ? JSON.parse(o.body) : undefined; } catch (e) { body = undefined; }
|
||||
const c = { url: String(url), method, path: u.pathname.startsWith(base) ? u.pathname.slice(base.length) : u.pathname, query: Object.fromEntries(u.searchParams),
|
||||
headers, raw: o.body, body, keepalive: !!o.keepalive, signal: o.signal };
|
||||
calls.push(c);
|
||||
if (o.signal && o.signal.aborted) return Promise.reject(aborted());
|
||||
for (const [re, h] of f.routes) if (re.test(`${method} ${c.url}`)) {
|
||||
const r = typeof h === 'function' ? h(c) : h;
|
||||
if (!r || typeof r.then !== 'function') return res(r);
|
||||
return new Promise((ok, no) => { if (o.signal) o.signal.addEventListener('abort', () => no(aborted())); r.then((x) => res(x).then(ok, no), no); });
|
||||
}
|
||||
if (method === 'GET' && /\/stream$/.test(c.path)) return open(c);
|
||||
return res({ status: 404, json: { error: 'not here' } });
|
||||
};
|
||||
f.routes = routes; f.calls = calls; f.streams = streams;
|
||||
f.stream = (i = 0) => (streams[i] ? Promise.resolve(streams[i]) : new Promise((ok) => waiting.push({ i, ok })));
|
||||
return f;
|
||||
}
|
||||
|
||||
module.exports = { load, seed, browser, flush, sse, fakeFetch };
|
||||
|
|
|
|||
187
tests/lib/mp-sim-fake-engine.js
Normal file
187
tests/lib/mp-sim-fake-engine.js
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
// A stand-in for the server-run engine (scripts/lib/mp-sim-engine.js, track T2), for testing the session host without
|
||||
// worker threads or a game: the same API, every method a promise of the worker reply that section 4.2 of the
|
||||
// server-sim design names, made from the canned stream in tests/fixtures/mp-sim/. Each reply passes
|
||||
// tests/lib/mp-sim-shape.js checkWorker(); an upd or snap inside one passes checkEvent().
|
||||
//
|
||||
// const engine = createFakeEngine();
|
||||
// engine.load(code, nets:[{nid, env?, begin?, lang, prefs}]) → [{t:'loaded', nid, epoch, day, lost, saved?}], one per
|
||||
// net; a network that did not load is {t:'loaded', nid, err} (broken, 4.7)
|
||||
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]:{day, lost,
|
||||
// pause?, err?, retried?, ms}}}
|
||||
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd} (msg: the request body, 5.8)
|
||||
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal:{h, c}, ui?}
|
||||
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?} (views: [{link} | {peer}])
|
||||
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}
|
||||
// engine.prefs(code, nid, {prefs}) → undefined; engine.greet(code, nid) → a pulled
|
||||
// engine.save(code, nid) → {t:'saved', nid, txt, uidN, rt, day, lost}; engine.card(code, nid) → {t:'card', nid, card}
|
||||
// engine.unload(code, nid?) → {t:'unloaded', code, nid?}; engine.stats() → {workers, realms, sessions} (not a promise)
|
||||
//
|
||||
// For the tests of the host: engine.calls (every call, [method, ...args]); engine.outcome = (msg) => outcome to answer
|
||||
// acts with ('applied' unless set); engine.lose(code, nid) / engine.pause(code, nid) (the next day ends bankrupt / asks
|
||||
// for a pause); engine.hold(method) keeps that method's answers back until engine.release(method); engine.exit() is a worker
|
||||
// that died: every pending call rejects and every realm is gone.
|
||||
// Failures, in the shapes the real engine answers them (4.2, 4.3, 4.7): engine.failNext(method, what, nid?) with what
|
||||
// 'timeout' or 'throw' (or 'exit': the call rejects, as when the worker died):
|
||||
// load → that network (every network of the call without nid) answers {t:'loaded', nid, err} and has no realm;
|
||||
// day → the day failed twice: nets[nid] = {day (unchanged), lost, err, retried:true, ms} and the network is broken
|
||||
// (left out of later days; acts answer 'stopped'); without nid, the first network of the day;
|
||||
// other → {t:'err', code, nid, what, msg}.
|
||||
// A timeout leaves a fresh realm behind (4.2): a new epoch, v from 0. engine.breakNext(code, nid): the next load of that
|
||||
// network fails (a save that does not migrate). engine.flaky(code, nid): its next day fails once and passes on the retry
|
||||
// (retried:true, no err).
|
||||
'use strict';
|
||||
const { fixture } = require('./mp-sim-shape');
|
||||
|
||||
function createFakeEngine(opts = {}) {
|
||||
const F = { snap: fixture('snap'), day: fixture('upd-day'), act: fixture('upd-act'), sub: fixture('sub'), roster: fixture('roster') };
|
||||
const realms = new Map(), held = new Map(), fails = new Map(), pending = new Set(), breaks = new Set(), flaky = new Set();
|
||||
const key = (code, nid) => code + '/' + nid;
|
||||
let epochN = 0;
|
||||
const newEpoch = () => 'e' + (++epochN).toString(36);
|
||||
const realm = (code, nid) => { const r = realms.get(key(code, nid)); if (!r) throw new Error(`no realm ${key(code, nid)}`); return r; };
|
||||
// A realm the worker had to build again after a timeout: a new epoch, versions from 0.
|
||||
const rebuilt = (r) => { if (r) { r.epoch = newEpoch(); r.v = 0; r.dirty = false; } };
|
||||
// Every answer goes through here: held back, failed, or rejected when the worker exits meanwhile. failed(f): the reply
|
||||
// for an injected failure, when the method has its own shape for one (load, day); else {t:'err'}.
|
||||
function answer(method, make, code = 'K7Q2XD', nid = 'abcd1234', failed = null) {
|
||||
return new Promise((ok, no) => {
|
||||
const job = { ok, no };
|
||||
const run = () => {
|
||||
pending.delete(job);
|
||||
const f = fails.get(method);
|
||||
if (f) {
|
||||
fails.delete(method);
|
||||
if (f.what === 'exit') return no(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
|
||||
if (failed) { try { return ok(failed(f)); } catch (e) { return no(e); } }
|
||||
if (f.what === 'timeout') rebuilt(realms.get(key(code, f.nid || nid)));
|
||||
return ok({ t: 'err', code, nid: f.nid || nid, what: f.what, msg: `injected ${f.what}` });
|
||||
}
|
||||
try { ok(make()); } catch (e) { no(e); }
|
||||
};
|
||||
job.run = run;
|
||||
pending.add(job);
|
||||
const h = held.get(method);
|
||||
if (h) h.push(job); else if (opts.sync) run(); else setImmediate(run);
|
||||
});
|
||||
}
|
||||
const upd = (r, base, extra = {}) => {
|
||||
const from = r.v, v = ++r.v;
|
||||
const s = { ...base.s, day: r.day };
|
||||
return JSON.stringify({ ...base, from, v, now: Date.now(), day: r.day, s, ...extra });
|
||||
};
|
||||
const snapOf = (code, nid, r) => {
|
||||
const S = { ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } };
|
||||
return JSON.stringify({ ...F.snap, epoch: r.epoch, v: r.v, now: Date.now(), S, keep: r.keep.splice(0) });
|
||||
};
|
||||
const subsOf = (views = []) => {
|
||||
const o = {};
|
||||
for (const w of views) {
|
||||
if (w && typeof w.link === 'string') o['link:' + w.link] = { ef: F.sub.ef, egd: F.sub.egd };
|
||||
if (w && typeof w.peer === 'string') o['peer:' + w.peer] = { pf: { [w.peer]: Object.values(F.sub.pf)[0] || {} } };
|
||||
}
|
||||
return o;
|
||||
};
|
||||
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
|
||||
|
||||
const engine = {
|
||||
calls: [],
|
||||
outcome: () => 'applied',
|
||||
load(code, nets) {
|
||||
engine.calls.push(['load', code, nets]);
|
||||
const one = (n, err) => {
|
||||
if (err) { realms.delete(key(code, n.nid)); return { t: 'loaded', nid: n.nid, err }; }
|
||||
const day = n.begin ? 0 : (n.env && Number.isInteger(n.env.day) ? n.env.day : F.snap.S.day);
|
||||
const r = { epoch: newEpoch(), v: 0, day, lost: false, broken: false, dirty: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
|
||||
realms.set(key(code, n.nid), r);
|
||||
return { t: 'loaded', nid: n.nid, epoch: r.epoch, day, lost: false, ...(n.begin ? { saved: savedOf(code, n.nid, r) } : {}) };
|
||||
};
|
||||
const bad = (n) => { const k = key(code, n.nid); if (!breaks.has(k)) return null; breaks.delete(k); return 'migrate threw: injected'; };
|
||||
return answer('load', () => nets.map((n) => one(n, bad(n))), code, nets[0] && nets[0].nid,
|
||||
(f) => nets.map((n) => one(n, f.nid === undefined || f.nid === n.nid ? `injected ${f.what}` : bad(n))));
|
||||
},
|
||||
day(code, { d, nets = [] } = {}) {
|
||||
engine.calls.push(['day', code, { d, nets }]);
|
||||
const ids = [...nets].sort();
|
||||
const run = (f) => {
|
||||
const out = {};
|
||||
for (const nid of ids) {
|
||||
const r = realm(code, nid);
|
||||
if (r.lost || r.broken) continue;
|
||||
// Failed twice (f names it): back to the mark, broken at its pre-day state.
|
||||
if (f && (f.nid || ids.find((x) => !realm(code, x).lost && !realm(code, x).broken)) === nid) {
|
||||
r.broken = true; if (f.what === 'timeout') rebuilt(r);
|
||||
out[nid] = { day: r.day, lost: r.lost, err: `injected ${f.what}`, retried: true, ms: 2000 };
|
||||
continue;
|
||||
}
|
||||
const again = flaky.delete(key(code, nid));
|
||||
r.day++; r.dirty = true;
|
||||
if (r.loseNext) { r.lost = true; r.loseNext = false; r.keep.push(['modal', 'lose']); }
|
||||
out[nid] = { day: r.day, lost: r.lost, ms: 1, ...(r.pause ? { pause: true } : {}), ...(again ? { retried: true } : {}) };
|
||||
r.pause = false;
|
||||
}
|
||||
return { t: 'dayDone', code, d, nets: out };
|
||||
};
|
||||
return answer('day', () => run(null), code, ids[0], run);
|
||||
},
|
||||
act(code, nid, msg) {
|
||||
engine.calls.push(['act', code, nid, msg]);
|
||||
return answer('act', () => {
|
||||
const r = realm(code, nid);
|
||||
if (r.lost || r.broken) return { t: 'actDone', nid, epoch: r.epoch, rid: msg.rid, outcome: 'stopped', v: r.v, upd: null };
|
||||
const outcome = engine.outcome(msg);
|
||||
r.dirty = false;
|
||||
const u = upd(r, F.act, { acts: [{ rid: msg.rid, dev: msg.dev, ui: {} }] });
|
||||
return { t: 'actDone', nid, epoch: r.epoch, rid: msg.rid, outcome, ...(outcome === 'error' ? { why: 'the game threw' } : {}), v: r.v, upd: u };
|
||||
}, code, nid);
|
||||
},
|
||||
ask(code, nid, msg) {
|
||||
engine.calls.push(['ask', code, nid, msg]);
|
||||
return answer('ask', () => { realm(code, nid); return { t: 'askDone', nid, rid: msg.rid, modal: { h: `<h2>${msg.act}</h2><p>What if…</p>`, c: '' } }; }, code, nid);
|
||||
},
|
||||
pull(code, nid, { snap = false, views } = {}) {
|
||||
engine.calls.push(['pull', code, nid, { snap, views }]);
|
||||
return answer('pull', () => {
|
||||
const r = realm(code, nid), o = { t: 'pulled', nid, epoch: r.epoch };
|
||||
if (r.dirty) { o.upd = upd(r, F.day); r.dirty = false; }
|
||||
o.v = r.v;
|
||||
if (snap) o.snap = snapOf(code, nid, r);
|
||||
if (views) o.subs = subsOf(views);
|
||||
return o;
|
||||
}, code, nid);
|
||||
},
|
||||
sub(code, nid, { views = [] } = {}) {
|
||||
engine.calls.push(['sub', code, nid, { views }]);
|
||||
return answer('sub', () => { const r = realm(code, nid); return { t: 'subbed', nid, epoch: r.epoch, v: r.v, subs: subsOf(views) }; }, code, nid);
|
||||
},
|
||||
prefs(code, nid, { prefs } = {}) { engine.calls.push(['prefs', code, nid, { prefs }]); return answer('prefs', () => { realm(code, nid); return undefined; }, code, nid); },
|
||||
greet(code, nid) {
|
||||
engine.calls.push(['greet', code, nid]);
|
||||
return answer('greet', () => { const r = realm(code, nid); r.dirty = true; const o = { t: 'pulled', nid, epoch: r.epoch, upd: upd(r, F.day, { fx: [['told', 'grace']] }) }; r.dirty = false; o.v = r.v; return o; }, code, nid);
|
||||
},
|
||||
save(code, nid) { engine.calls.push(['save', code, nid]); return answer('save', () => savedOf(code, nid, realm(code, nid)), code, nid); },
|
||||
card(code, nid) { engine.calls.push(['card', code, nid]); return answer('card', () => { realm(code, nid); return { t: 'card', nid, card: F.roster.players[0].card }; }, code, nid); },
|
||||
unload(code, nid) {
|
||||
engine.calls.push(['unload', code, nid]);
|
||||
return answer('unload', () => { for (const k of [...realms.keys()]) if (k.startsWith(code + '/') && (nid === undefined || k === key(code, nid))) realms.delete(k); return { t: 'unloaded', code, ...(nid ? { nid } : {}) }; }, code, nid);
|
||||
},
|
||||
stats() { return { workers: 1, realms: realms.size, sessions: new Set([...realms.keys()].map((k) => k.split('/')[0])).size }; },
|
||||
// Test controls.
|
||||
lose(code, nid) { realm(code, nid).loseNext = true; },
|
||||
pause(code, nid) { realm(code, nid).pause = true; },
|
||||
keep(code, nid, fx) { realm(code, nid).keep.push(fx); },
|
||||
hold(method) { if (!held.has(method)) held.set(method, []); },
|
||||
release(method) { const h = held.get(method) || []; held.delete(method); for (const j of h) j.run(); },
|
||||
failNext(method, what = 'throw', nid) { fails.set(method, { what, nid }); },
|
||||
breakNext(code, nid) { breaks.add(key(code, nid)); },
|
||||
flaky(code, nid) { flaky.add(key(code, nid)); },
|
||||
exit() {
|
||||
const e = Object.assign(new Error('worker exited'), { code: 'EXIT' });
|
||||
for (const j of [...pending]) { pending.delete(j); j.no(e); }
|
||||
held.clear(); realms.clear();
|
||||
},
|
||||
realms,
|
||||
};
|
||||
return engine;
|
||||
}
|
||||
|
||||
module.exports = { createFakeEngine };
|
||||
91
tests/lib/mp-sim-fixtures.js
Normal file
91
tests/lib/mp-sim-fixtures.js
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
// The canned stream of a server-run network (tests/fixtures/mp-sim/*.json): what the session server sends a page, made
|
||||
// here from a real seeded game the way the server's realm will make it (section 5 of the server-sim design): live S,
|
||||
// a top-level key diff per update, slim R, the effects a day and two actions leave. The client tests (and the fake
|
||||
// engine) use these until the integration step records real streams in their place; every one passes
|
||||
// tests/lib/mp-sim-shape.js. Run `node tests/lib/mp-sim-fixtures.js` to write them again.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../harness');
|
||||
|
||||
const DIR = path.join(__dirname, '..', 'fixtures', 'mp-sim');
|
||||
const CODE = 'K7Q2XD', PID = 'abcd1234', PID2 = 'efgh5678', EPOCH = 'k3f9', DEV = '9f8e7d6c', NOW = 1731000000000;
|
||||
const MP = { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
|
||||
|
||||
// In the page: the effects the realm would capture (its epilogue rebinds these the same way), and slim R (5.5).
|
||||
const RIG = `window.__fx=[];
|
||||
toast=(h,k='',a=[],o=null)=>{if(S)logNote(h,k,a,o);__fx.push(['toast',{h,k,a,o,tick:!!UI.tick}]);};
|
||||
sfx=n=>{__fx.push(['sfx',n]);};haptic=n=>{__fx.push(['haptic',n]);};
|
||||
floater=(x,y,t,c)=>{if(__fx.filter(f=>f[0]==='floater').length<40)__fx.push(['floater',[x,y,t,c]]);};
|
||||
window.__slimR=()=>{const {o}=rwPack(R);for(const k of ['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked'])delete o[k];
|
||||
const tn={};for(const id in o.tNet)tn[id]=Object.fromEntries(Object.entries(o.tNet[id]).sort((a,b)=>b[1]-a[1]).slice(0,4));o.tNet=tn;
|
||||
o.tTop8=transitTop(S.transit.map(t=>t.id),8);
|
||||
const r6=v=>typeof v==='number'?(Number.isInteger(v)||!isFinite(v)?v:+v.toPrecision(6)):Array.isArray(v)?v.map(r6):v&&typeof v==='object'?Object.fromEntries(Object.entries(v).map(([k,x])=>[k,r6(x)])):v;
|
||||
return r6(JSON.parse(JSON.stringify(o)));};
|
||||
window.__keys=()=>Object.fromEntries(Object.keys(S).map(k=>[k,JSON.stringify(S[k])]));`;
|
||||
|
||||
function make() {
|
||||
const { ev, errors, dom } = load({ seed: 4242 });
|
||||
ev(`Date.now=()=>${NOW};`);
|
||||
// A network of a server session, built the way the server builds one (beginState, then the server's own marks), with
|
||||
// the intern on every order and a fiber cut it rushes: the snapshot carries a shift's log and the week's tally.
|
||||
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)}});S.mp.sim=1;S.tut=null;compute();beginHello();
|
||||
S.nextFail=S.nextEvent=1e9;UI.speed=0;UI.started=true;ACT.charter({k:'global'});
|
||||
ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});
|
||||
UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();
|
||||
S.lvl=Math.max(S.lvl,2);ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
|
||||
for(let i=0;i<45;i++){if(i===20)dayGo(failureRun('cut'));dayTick();}`);
|
||||
ev(RIG);
|
||||
const snapS = JSON.parse(ev('JSON.stringify(S)'));
|
||||
const r0 = JSON.parse(ev('JSON.stringify(__slimR())'));
|
||||
const diff = (before) => { const now = JSON.parse(ev('JSON.stringify(__keys())')), s = {}, del = [];
|
||||
for (const k of Object.keys(now)) if (now[k] !== before[k]) s[k] = JSON.parse(now[k]);
|
||||
for (const k of Object.keys(before)) if (!(k in now)) del.push(k);
|
||||
return { s, del, keys: now }; };
|
||||
const fx = () => JSON.parse(ev('JSON.stringify(__fx.splice(0))'));
|
||||
const clock = { t: 'clock', speed: 1, eff: 1, run: true, why: null, votes: { [PID2]: 4 }, tally: { 4: 1 }, need: 2, active: [PID, PID2], hold: [], idle: [],
|
||||
day: 518, last: 1, max: 8, off: { [PID]: S0day(snapS) - 518, [PID2]: 0 } };
|
||||
const card = JSON.parse(ev('JSON.stringify(mpCard())'));
|
||||
const roster = { t: 'roster', code: CODE, title: 'Friday', preset: 'oncall', seed: MP.seed, created: NOW - 864e5,
|
||||
players: [{ pid: PID, name: 'Packet Pals', asn: MP.asn, color: MP.color, card, seen: NOW, joined: NOW - 864e5 },
|
||||
{ pid: PID2, name: 'Tubular Bells', asn: 207777, color: '#ff4f9a', card: null, seen: NOW - 6e4, joined: NOW - 36e5 }],
|
||||
feed: [{ k: 'join', pid: PID, name: 'Packet Pals', at: NOW - 864e5 }, { k: 'join', pid: PID2, name: 'Tubular Bells', at: NOW - 36e5 }, { k: 'chat', pid: PID2, name: 'Tubular Bells', at: NOW - 6e4, text: 'peer with me?' }],
|
||||
on: [PID, PID2] };
|
||||
const snap = { t: 'snap', epoch: EPOCH, v: 412, now: NOW, S: snapS, r: r0, clock, roster, since: { days: 37, again: 0 }, keep: [['badge', { id: 'firstpop', v: 'oncall' }]] };
|
||||
|
||||
// A day: the keys it changed, a new R, what it said.
|
||||
let base = JSON.parse(ev('JSON.stringify(__keys())'));
|
||||
ev('UI.tick=false;dayTick();');
|
||||
const d1 = diff(base), dayFx = fx();
|
||||
if (!dayFx.length) dayFx.push(['sfx', 'coin']);
|
||||
const updDay = { t: 'upd', from: 412, v: 413, now: NOW + 2500, day: JSON.parse(ev('S.day')), s: d1.s, del: d1.del, r: JSON.parse(ev('JSON.stringify(__slimR())')), fx: dayFx };
|
||||
|
||||
// Two quick taps in one update: a new POP (the panel moves to it) and a transit port there.
|
||||
base = d1.keys;
|
||||
ev("ACT.buildPop({city:'par'});");
|
||||
const ui1 = { sel: { type: 'city', id: 'par' }, tab: 'cust' };
|
||||
ev("ACT.buyTransit({city:'par',net:'cog',tier:1});");
|
||||
const d2 = diff(base), actFx = fx();
|
||||
const updAct = { t: 'upd', from: 413, v: 414, now: NOW + 3100, day: updDay.day, s: d2.s, del: d2.del, r: JSON.parse(ev('JSON.stringify(__slimR())')), fx: actFx,
|
||||
acts: [{ rid: 'a1b2c3d4e5', dev: DEV, ui: ui1 }, { rid: 'a1b2c3d4e6', dev: DEV, ui: {} }] };
|
||||
|
||||
// A stream's flow records: the link it shows and its traffic's ways in, and a city's Peering tab.
|
||||
const sub = JSON.parse(ev(`(()=>{const l=S.links[0],k=edgeKey(l),rec=R.ef[k],egd={};if(rec)for(const e in rec.eg||{})if(R.egDesc[e])egd[e]=R.egDesc[e];
|
||||
return JSON.stringify({t:'sub',v:414,ef:rec?{[k]:rec}:{},egd,pf:{fra:pniFlows('fra')}});})()`));
|
||||
|
||||
if (errors.length) throw new Error('the game failed while making fixtures: ' + errors.join('; '));
|
||||
dom.window.close();
|
||||
return { snap, 'upd-day': updDay, 'upd-act': updAct, sub, clock, roster };
|
||||
}
|
||||
// The calendar offset of the network in the fixtures: its own date against the session day (open question 1).
|
||||
function S0day(S) { return S.day; }
|
||||
|
||||
function write() {
|
||||
fs.mkdirSync(DIR, { recursive: true });
|
||||
const out = make();
|
||||
for (const [k, v] of Object.entries(out)) fs.writeFileSync(path.join(DIR, k + '.json'), JSON.stringify(v) + '\n');
|
||||
return Object.keys(out);
|
||||
}
|
||||
|
||||
module.exports = { make, write, DIR, CODE, PID, PID2, EPOCH, DEV, NOW };
|
||||
|
||||
if (require.main === module) console.log('wrote', write().map((k) => `tests/fixtures/mp-sim/${k}.json`).join(', '));
|
||||
183
tests/lib/mp-sim-shape.js
Normal file
183
tests/lib/mp-sim-shape.js
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
// The shapes of server-run play on the wire and between host and worker (the server-sim design, sections 4.2 and 5.3),
|
||||
// checked: the session server's real output (its tests run every event they write through checkEvent) and the canned
|
||||
// streams in tests/fixtures/mp-sim/ (the client's tests) must agree on them.
|
||||
//
|
||||
// checkEvent(e) problems with one stream event ([] when fine): snap, upd, sub, clock, roster, bye
|
||||
// checkFx(f) problems with one effect entry, [kind, payload]
|
||||
// checkWorker(m) problems with one worker → host reply: loaded, dayDone, actDone, askDone, pulled, subbed, saved,
|
||||
// card, unloaded, err
|
||||
//
|
||||
// The epoch (5.10): the worker mints a new one at every realm load (a load, a begin, and the fresh realm it builds
|
||||
// after a timeout, 4.2) and puts the realm's current one on every reply that carries versions: loaded, pulled, actDone,
|
||||
// subbed. The host keeps the last one per network and writes it into every event's id (`id: <epoch>.<v>`); a reply with
|
||||
// another epoch than the host holds means the realm was built again, so v started over and every page takes a snapshot.
|
||||
// A network that did not load (loaded.err: its save failed, 4.7) has no realm, so no epoch, day or lost.
|
||||
// A toast effect's k and a may be left out (toastPop's defaults: '' and []): a game call toast(html) has neither.
|
||||
// parseSse(text) the events of an event-stream text: [{event, id, data (parsed)}], comments and heartbeats skipped
|
||||
// fixture(name) tests/fixtures/mp-sim/<name>.json, parsed
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
|
||||
const PID = /^[a-z0-9]{8}$/, RID = /^[a-z0-9]{8,16}$/, EPOCH = /^[a-z0-9]{1,16}$/, CODE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
|
||||
// What slim R never carries (5.5): compute inputs, internals, and what goes on demand in sub events.
|
||||
const R_NEVER = ['ef', 'fl', 'efp', 'flc', 'efg', 'egDesc', 'l2route', 'bbF', 'peered', 'cityBlocked'];
|
||||
const FX_KINDS = ['toast', 'sfx', 'haptic', 'floater', 'track', 'pause', 'modal', 'badge', 'mk', 'told'];
|
||||
const WHY = [null, 'empty', 'hold', 'slow', 'loading', 'vote'];
|
||||
const BYE = ['gone', 'old', 'moved', 'slow', 'shutdown'];
|
||||
const OUTCOMES = ['applied', 'no_effect', 'rejected', 'error', 'stopped'];
|
||||
const UI_KEYS = ['sel', 'tab', 'left', 'confirm', 'closed', 'modal'];
|
||||
|
||||
const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
const int = (v) => Number.isInteger(v);
|
||||
const nat = (v) => Number.isInteger(v) && v >= 0;
|
||||
const num = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
const str = (v) => typeof v === 'string';
|
||||
const bool = (v) => typeof v === 'boolean';
|
||||
|
||||
// fields: {name: test | [test, 'opt']}; extra keys are problems too (a typo on one side is caught by the other).
|
||||
function fields(o, spec, where, out, open = false) {
|
||||
if (!obj(o)) { out.push(`${where}: not an object`); return; }
|
||||
for (const [k, t] of Object.entries(spec)) {
|
||||
const [f, opt] = Array.isArray(t) ? t : [t];
|
||||
if (!(k in o) || o[k] === undefined) { if (!opt) out.push(`${where}.${k}: missing`); continue; }
|
||||
const r = f(o[k], `${where}.${k}`, out);
|
||||
if (r === false) out.push(`${where}.${k}: bad value ${JSON.stringify(o[k]).slice(0, 80)}`);
|
||||
}
|
||||
if (!open) for (const k of Object.keys(o)) if (!(k in spec)) out.push(`${where}.${k}: unknown field`);
|
||||
}
|
||||
const listOf = (t) => (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((x, i) => { if (t(x, `${w}[${i}]`, out) === false) out.push(`${w}[${i}]: bad value ${JSON.stringify(x).slice(0, 60)}`); }); return true; };
|
||||
const mapOf = (kt, vt) => (v, w, out) => { if (!obj(v)) return false; for (const [k, x] of Object.entries(v)) { if (!kt(k)) out.push(`${w}: bad key ${k}`); if (vt(x, `${w}.${k}`, out) === false) out.push(`${w}.${k}: bad value ${JSON.stringify(x).slice(0, 60)}`); } return true; };
|
||||
|
||||
// Live S, as the server's realm holds it: what every page reads first (the full check is the game's own migrate()).
|
||||
function liveS(S, w, out) {
|
||||
if (!obj(S)) return false;
|
||||
if (S.v !== 1 || !nat(S.day) || !num(S.cash) || !obj(S.pops) || !Array.isArray(S.links) || !Array.isArray(S.biz) || !obj(S.stats)) out.push(`${w}: not a game state (v, day, cash, pops, links, biz, stats)`);
|
||||
if (!obj(S.mp) || !CODE.test(S.mp.code) || !PID.test(S.mp.pid) || S.mp.sim !== 1) out.push(`${w}.mp: not a server network (code, pid, sim:1)`);
|
||||
if (S.mode !== 'normal') out.push(`${w}.mode: server networks are Normal games`);
|
||||
return true;
|
||||
}
|
||||
function slimR(r, w, out) {
|
||||
if (!obj(r)) return false;
|
||||
for (const k of R_NEVER) if (k in r) out.push(`${w}.${k}: slim R never carries it`);
|
||||
for (const k of ['served', 'demand', 'reach', 'revMo', 'costMo']) if (!num(r[k])) out.push(`${w}.${k}: missing or not a number`);
|
||||
for (const k of ['load', 'useT', 'tNet', 'cityDem', 'citySrv']) if (!obj(r[k])) out.push(`${w}.${k}: missing`);
|
||||
if (!Array.isArray(r.ddos)) out.push(`${w}.ddos: missing`);
|
||||
else r.ddos.forEach((m, i) => { if (m.attack !== null && !str(m.attack)) out.push(`${w}.ddos[${i}].attack: an attack's id (or null)`); });
|
||||
if (!Array.isArray(r.tTop8) || r.tTop8.length > 8 || !r.tTop8.every((x) => Array.isArray(x) && x.length === 2 && str(x[0]) && num(x[1]))) out.push(`${w}.tTop8: [[net, gbps]] × ≤ 8`);
|
||||
if (obj(r.tNet)) for (const [id, m] of Object.entries(r.tNet)) if (!obj(m) || Object.keys(m).length > 4) out.push(`${w}.tNet.${id}: at most the top 4 networks`);
|
||||
return true;
|
||||
}
|
||||
const sel = (v) => v === null || (obj(v) && (v.type === 'city' || v.type === 'link') && str(v.id) && Object.keys(v).length === 2);
|
||||
function actUi(u, w, out) {
|
||||
fields(u, { sel: [sel, 'opt'], tab: [(v) => v === null || str(v), 'opt'], left: [(v) => v === null || str(v), 'opt'], confirm: [(v) => v === null || str(v), 'opt'],
|
||||
closed: [(v) => v === 1 || v === true, 'opt'], modal: [(v) => obj(v) && str(v.h) && str(v.c) && Object.keys(v).length === 2, 'opt'] }, w, out);
|
||||
return true;
|
||||
}
|
||||
const actEntry = (a, w, out) => { fields(a, { rid: (v) => RID.test(v), dev: (v) => RID.test(v), ui: actUi }, w, out); return true; };
|
||||
|
||||
function checkFx(f, w = 'fx', out = []) {
|
||||
if (!Array.isArray(f) || f.length !== 2 || !str(f[0])) { out.push(`${w}: an effect is [kind, payload]`); return out; }
|
||||
const [k, p] = f;
|
||||
const bad = () => out.push(`${w}: bad ${k} payload ${JSON.stringify(p).slice(0, 80)}`);
|
||||
switch (k) {
|
||||
case 'toast': fields(p, { h: str, k: [str, 'opt'], a: [listOf((x) => obj(x) && str(x.l) && str(x.act)), 'opt'], o: [(v) => v === null || obj(v), 'opt'], tick: [bool, 'opt'] }, `${w}.toast`, out); break;
|
||||
case 'sfx': case 'haptic': if (!str(p)) bad(); break;
|
||||
case 'floater': if (!Array.isArray(p) || p.length !== 4 || !num(p[0]) || !num(p[1]) || !str(p[2]) || !str(p[3])) bad(); break;
|
||||
case 'track': if (!Array.isArray(p) || p.length !== 2 || !str(p[0]) || !(p[1] === undefined || p[1] === null || bool(p[1]))) bad(); break;
|
||||
case 'pause': if (p !== 1) bad(); break;
|
||||
case 'modal': if (!['win', 'lose', 'baron'].includes(p)) bad(); break;
|
||||
case 'badge': if (!obj(p) || !str(p.id) || !(p.v === undefined || str(p.v))) bad(); break;
|
||||
case 'mk': if (!obj(p) || !str(p.e)) bad(); break;
|
||||
case 'told': break;
|
||||
default: out.push(`${w}: unknown effect ${k}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const fxList = (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((f, i) => checkFx(f, `${w}[${i}]`, out)); return true; };
|
||||
|
||||
const CLOCK = { t: (v) => v === 'clock', speed: (v) => SPEEDS.includes(v), eff: (v) => num(v) && v >= 0, run: bool, why: (v) => WHY.includes(v),
|
||||
votes: mapOf((k) => PID.test(k), (v) => v === null || SPEEDS.includes(v)), tally: mapOf((k) => SPEEDS.includes(+k), nat), need: (v) => int(v) && v >= 1,
|
||||
active: listOf((v) => PID.test(v)), hold: listOf((v) => PID.test(v)), idle: listOf((v) => PID.test(v)), day: nat, last: (v) => SPEEDS.includes(v) && v > 0,
|
||||
max: (v) => SPEEDS.includes(v) && v > 0,
|
||||
// The calendar offset of every network of the session: its own S.day minus the session day (open question 1: "own
|
||||
// date"). One field, so a shared date later only means all zeros.
|
||||
off: mapOf((k) => PID.test(k), int) };
|
||||
const PLAYER = { pid: (v) => PID.test(v), name: str, asn: nat, color: (v) => /^#[0-9a-f]{6}$/i.test(v), card: (v) => v === null || obj(v), seen: nat, joined: nat,
|
||||
lost: [bool, 'opt'], broken: [bool, 'opt'] };
|
||||
const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str, preset: str, seed: int, created: nat,
|
||||
players: listOf((p, w, out) => { fields(p, PLAYER, w, out); return true; }),
|
||||
feed: listOf((f, w, out) => { fields(f, { k: str, pid: str, name: str, at: nat, text: [str, 'opt'] }, w, out); return true; }),
|
||||
on: listOf((v) => PID.test(v)) };
|
||||
|
||||
function checkEvent(e) {
|
||||
const out = [];
|
||||
if (!obj(e) || !str(e.t)) return ['an event is an object with t'];
|
||||
const w = e.t;
|
||||
if (e.t === 'snap') fields(e, { t: str, epoch: (v) => EPOCH.test(v), v: nat, now: nat, S: liveS, r: slimR,
|
||||
clock: (v, ww, o) => { fields(v, CLOCK, ww, o); return true; }, roster: (v, ww, o) => { fields(v, ROSTER, ww, o); return true; },
|
||||
since: (v, ww, o) => { fields(v, { days: nat, again: nat }, ww, o); return true; },
|
||||
keep: (v, ww, o) => { if (!Array.isArray(v) || v.length > 32) return false; v.forEach((f, i) => { checkFx(f, `${ww}[${i}]`, o); if (f[0] !== 'badge' && f[0] !== 'modal') o.push(`${ww}[${i}]: keep holds only badge and modal`); }); return true; } }, w, out);
|
||||
else if (e.t === 'upd') {
|
||||
fields(e, { t: str, from: nat, v: nat, now: nat, day: nat, s: obj, del: [listOf(str), 'opt'], r: [slimR, 'opt'], fx: [fxList, 'opt'], acts: [listOf(actEntry), 'opt'] }, w, out);
|
||||
if (nat(e.v) && nat(e.from) && e.v !== e.from + 1) out.push('upd: v is from + 1 (only a pull makes a version)');
|
||||
if (obj(e.s) && Array.isArray(e.del)) for (const k of e.del) if (k in e.s) out.push(`upd: ${k} both changed and deleted`);
|
||||
if (obj(e.s) && 'day' in e.s && e.s.day !== e.day) out.push('upd: day differs from s.day');
|
||||
if (Array.isArray(e.fx) && e.fx.length > 60) out.push('upd: more than 60 effects');
|
||||
} else if (e.t === 'sub') fields(e, { t: str, v: nat, ef: [obj, 'opt'], egd: [obj, 'opt'], pf: [obj, 'opt'] }, w, out);
|
||||
else if (e.t === 'clock') fields(e, CLOCK, w, out);
|
||||
else if (e.t === 'roster') fields(e, ROSTER, w, out);
|
||||
else if (e.t === 'bye') fields(e, { t: str, why: (v) => BYE.includes(v) }, w, out);
|
||||
else out.push(`unknown event ${e.t}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Worker → host replies (4.2). Big payloads (an update, a snapshot) are JSON text, ready to write to every stream.
|
||||
const json = (t) => (v, w, out) => { if (!str(v)) return false; let e; try { e = JSON.parse(v); } catch (x) { return false; } for (const p of checkEvent(e)) out.push(`${w}: ${p}`); if (e.t !== t) out.push(`${w}: not a ${t}`); return true; };
|
||||
const subs = mapOf((k) => /^(link|peer):.{1,40}$/.test(k), (v) => obj(v));
|
||||
const epoch = (v) => EPOCH.test(v);
|
||||
const WORKER = {
|
||||
// epoch, day and lost: required unless err says the network did not load (checkWorker).
|
||||
loaded: { t: str, nid: (v) => PID.test(v), epoch: [epoch, 'opt'], day: [nat, 'opt'], lost: [bool, 'opt'], err: [str, 'opt'], saved: [(v, w, out) => { for (const p of checkWorker(v)) out.push(`${w}: ${p}`); return true; }, 'opt'] },
|
||||
// A day that failed twice: err, retried, and day as it was before (the network is broken at its pre-day state, 4.3).
|
||||
dayDone: { t: str, code: (v) => CODE.test(v), d: nat, nets: mapOf((k) => PID.test(k), (v, w, out) => { fields(v, { day: nat, lost: bool, pause: [bool, 'opt'], err: [str, 'opt'], retried: [bool, 'opt'], ms: (x) => num(x) && x >= 0 }, w, out); return true; }) },
|
||||
actDone: { t: str, nid: (v) => PID.test(v), epoch, rid: (v) => RID.test(v), outcome: (v) => OUTCOMES.includes(v), why: [str, 'opt'], v: nat, upd: [(v, w, out) => v === null || json('upd')(v, w, out), 'opt'] },
|
||||
askDone: { t: str, nid: (v) => PID.test(v), rid: (v) => RID.test(v), modal: [(v) => obj(v) && str(v.h) && str(v.c), 'opt'], ui: [obj, 'opt'], err: [str, 'opt'] },
|
||||
pulled: { t: str, nid: (v) => PID.test(v), epoch, v: nat, upd: [json('upd'), 'opt'], snap: [json('snap'), 'opt'], subs: [subs, 'opt'] },
|
||||
subbed: { t: str, nid: (v) => PID.test(v), epoch, v: nat, subs },
|
||||
saved: { t: str, nid: (v) => PID.test(v), txt: str, uidN: nat, rt: obj, day: nat, lost: bool },
|
||||
card: { t: str, nid: (v) => PID.test(v), card: (v) => v === null || obj(v) },
|
||||
unloaded: { t: str, code: (v) => CODE.test(v), nid: [(v) => PID.test(v), 'opt'] },
|
||||
err: { t: str, code: (v) => CODE.test(v), nid: (v) => PID.test(v), rid: [(v) => RID.test(v), 'opt'], what: (v) => ['timeout', 'throw', 'oom', 'exit', 'load'].includes(v), msg: str },
|
||||
};
|
||||
function checkWorker(m) {
|
||||
const out = [];
|
||||
if (!obj(m) || !str(m.t) || !WORKER[m.t]) return [`unknown worker reply ${obj(m) ? m.t : typeof m}`];
|
||||
fields(m, WORKER[m.t], m.t, out);
|
||||
if (m.t === 'loaded' && m.err === undefined) for (const k of ['epoch', 'day', 'lost']) if (m[k] === undefined) out.push(`loaded.${k}: missing`);
|
||||
if (m.t === 'loaded' && m.err !== undefined && m.saved !== undefined) out.push('loaded: a network that did not load has nothing saved');
|
||||
if (m.t === 'pulled' && m.snap !== undefined && str(m.snap)) { try { const e = JSON.parse(m.snap); if (e.epoch !== m.epoch) out.push('pulled: the snapshot\'s epoch is not the realm\'s'); } catch (x) { /* reported above */ } }
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseSse(text) {
|
||||
const out = [];
|
||||
for (const block of String(text).split('\n\n')) {
|
||||
if (!block.trim()) continue;
|
||||
let event = 'message', id, data = '';
|
||||
for (const line of block.split('\n')) {
|
||||
if (!line || line.startsWith(':')) continue;
|
||||
const i = line.indexOf(':'), k = i < 0 ? line : line.slice(0, i), v = i < 0 ? '' : line.slice(i + 1).replace(/^ /, '');
|
||||
if (k === 'event') event = v; else if (k === 'id') id = v; else if (k === 'data') data += (data ? '\n' : '') + v;
|
||||
}
|
||||
if (data) out.push({ event, id, data: JSON.parse(data) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const DIR = path.join(__dirname, '..', 'fixtures', 'mp-sim');
|
||||
const fixture = (name) => JSON.parse(fs.readFileSync(path.join(DIR, name + '.json'), 'utf8'));
|
||||
const FIXTURES = ['snap', 'upd-day', 'upd-act', 'sub', 'clock', 'roster'];
|
||||
|
||||
module.exports = { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES, FX_KINDS, R_NEVER, SPEEDS };
|
||||
308
tests/mp-sim-contract.test.js
Normal file
308
tests/mp-sim-contract.test.js
Normal file
|
|
@ -0,0 +1,308 @@
|
|||
// The contracts server-run play is built against (the server-sim design, sections 4.2, 5 and 10): the act tables and
|
||||
// the envelope check (scripts/lib/mp-sim-acts.js), the canned stream (tests/fixtures/mp-sim/) and its shape checker
|
||||
// (tests/lib/mp-sim-shape.js), the fake engine (tests/lib/mp-sim-fake-engine.js), and the harness's MP page with its
|
||||
// fake streaming fetch. The engine, the host and the client each test their side against these.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load, fakeFetch, sse, flush } = require('./harness');
|
||||
const { simId } = require('../scripts/lib/page');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
const A = require('../scripts/lib/mp-sim-acts');
|
||||
const { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES } = require('./lib/mp-sim-shape');
|
||||
const { createFakeEngine } = require('./lib/mp-sim-fake-engine');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const SIM = simId();
|
||||
const env = (act, args = {}, more = {}) => ({ rid: 'a1b2c3d4e5', dev: '9f8e7d6c', sim: SIM, act, args, ...more });
|
||||
|
||||
test('every ACT is classified once: SEND, ASK, VOTE, LOCAL or PUZZLE; SEND is the agent\'s game commands, adjusted', (t) => {
|
||||
// The development page of a multiplayer build: every ACT there is, the server-play client's (98-server-play) too.
|
||||
const { ev, errors, dom } = load({ agent: true, mp: true });
|
||||
t.after(() => dom.window.close());
|
||||
const acts = JSON.parse(ev('JSON.stringify(Object.keys(ACT))'));
|
||||
const lists = { SEND: A.SEND, ASK: A.ASK, VOTE: A.VOTE, LOCAL: A.LOCAL, PUZZLE: A.PUZZLE };
|
||||
const where = {};
|
||||
for (const [name, list] of Object.entries(lists)) {
|
||||
assert.deepEqual([...list].sort(), list, `${name} stays sorted, one per line`);
|
||||
for (const a of list) { assert.equal(where[a], undefined, `ACT.${a} is in both ${where[a]} and ${name}`); where[a] = name; }
|
||||
}
|
||||
for (const a of acts) assert.ok(where[a], `ACT.${a} is not classified: add it to SEND, ASK, VOTE or LOCAL in scripts/lib/mp-sim-acts.js`);
|
||||
for (const a of Object.keys(where)) assert.ok(acts.includes(a), `${a} is in scripts/lib/mp-sim-acts.js (${where[a]}) but ACT has no such act`);
|
||||
for (const a of A.PUZZLE) assert.match(a, /^pz[A-Z]/);
|
||||
// SEND, derived again: never counted by hand.
|
||||
const cmd = JSON.parse(ev('JSON.stringify(Object.keys(API_CMD))'));
|
||||
const want = cmd.filter((k) => !/^pz[A-Z]/.test(k) && !['teCheck', 'traceRun', 'closeModal'].includes(k)).concat(['connCancel', 'pieRename', 'tutSkip']).sort();
|
||||
assert.deepEqual(A.SEND, want, 'SEND = API_CMD − pz* − {teCheck, traceRun, closeModal} + {connCancel, pieRename, tutSkip}');
|
||||
// The other tables only name sent acts (asks for ASK), and their own args.
|
||||
for (const a of [...Object.keys(A.CONFIRM), ...Object.keys(A.DRAFTS), ...Object.keys(A.QUOTE)]) assert.ok(A.SEND.includes(a), `${a} is sent`);
|
||||
for (const a of Object.keys(A.TEXT)) assert.ok(A.SEND.includes(a) || A.ASK.includes(a), `${a} is sent or asked`);
|
||||
for (const ks of Object.values(A.DRAFTS)) for (const k of ks) assert.ok(A.DRAFT_TYPES[k], `draft ${k} has a type`);
|
||||
assert.equal(A.armKey('connCancel', { k: 't', id: 'i9' }), 'cc:t:i9');
|
||||
assert.equal(A.armKey('rmSite', { city: 'fra' }), 'sitefra');
|
||||
assert.equal(A.armKey('cancelTransit', { id: 'x' }), null, "an 'arg' act arms with ok:1, not a key");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// Every button and drop-down a rich game shows, as the page would send it: [act, args].
|
||||
function crawl(ev) {
|
||||
ev(`window.__btns=[];window.__grab=()=>{for(const el of document.querySelectorAll('[data-act],[data-chg]')){const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){a={bad:el.dataset.args};}
|
||||
if(el.dataset.chg){a={...a,v:el.value}}__btns.push([act,a]);}};`);
|
||||
const views = [
|
||||
"for(const c of ['fra','ams','nyc','sin','syd']){for(const tab of ['cust','up','peer','infra','links']){UI.sel={type:'city',id:c};UI.tab=tab;renderPanel();__grab();}}",
|
||||
"for(const l of S.links.slice(0,40)){UI.sel={type:'link',id:l.id};renderPanel();__grab();}",
|
||||
"UI.leftOpen=true;for(const k of ['goals','deals','noc','nets']){UI.left=k;renderLeft();__grab();}",
|
||||
"$('dash').hidden=false;for(const k of DTABS){UI.dtab=k;renderDash();__grab();}$('dash').hidden=true;",
|
||||
'ACT.bank();__grab();ACT.bankClose();',
|
||||
"for(const [a,x] of [['opsOpen',{}],['utilities',{city:'fra'}],['bstdOpen',{}],['pniAllOpen',{net:null}],['pniAllOpen',{net:'cog'}],['salesOpen',{}],['routingOpen',{}],['ip4Open',{}],['models',{}],['decomOpen',{}],['teEdit',{}]]){try{ACT[a](x);}catch(e){}__grab();closeModal();}",
|
||||
"openLinkModal('fra','nyc');__grab();closeModal();openLinkModal('fra','ams');__grab();closeModal();",
|
||||
"UI.confirm=null;for(const t of S.transit.slice(0,3)){UI.sel={type:'city',id:t.city};UI.tab='up';UI.confirm=t.id;renderPanel();__grab();}UI.confirm=null;",
|
||||
];
|
||||
for (const v of views) ev(v);
|
||||
return JSON.parse(ev('JSON.stringify(__btns)'));
|
||||
}
|
||||
|
||||
test('the envelope check passes every button a rich game shows for a sent act, as the page sends it', (t) => {
|
||||
const fsx = require('node:fs');
|
||||
const BIG = fsx.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
const { ev, errors, dom } = load({ seed: 77 });
|
||||
t.after(() => dom.window.close());
|
||||
ev(`Date.now=()=>1.7e12;S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.lvl=Math.max(S.lvl,6);
|
||||
ACT.opsHire({id:'kevin'});closeModal();ACT.salesHire({id:'eng'});closeModal();S.popStd=bstdPut({...bstd(),rt:2});compute();renderAll();`);
|
||||
const btns = crawl(ev);
|
||||
const sent = btns.filter(([a]) => A.SEND.includes(a));
|
||||
assert.ok(sent.length > 200, `a real sweep: ${sent.length} sent buttons of ${btns.length}`);
|
||||
const acts = new Set(sent.map(([a]) => a));
|
||||
assert.ok(acts.size > 40, `${acts.size} different acts`);
|
||||
for (const q of ['pniAll', 'bstdApply', 'utilityKit']) assert.ok(acts.has(q), `the sweep found ${q}`);
|
||||
for (const [act, args] of sent) {
|
||||
// The page adds the drafts the act reads, as they are, and confirms a two-click act's second click.
|
||||
const ui = A.DRAFTS[act] ? JSON.parse(ev(`JSON.stringify({pending:UI.pending||{a:'fra',b:'ams'},route:UI.route||'',via:UI.via||'',cnPrem:!!UI.cnPrem,dfSrc:'lease',dfSys:'lite',seaDesign:'standard',
|
||||
seaterminal:false,seaengineering:false,decom:['fra'],slop:false,pieIns:false,pieLas:false})`)) : null;
|
||||
const body = env(act, args, { ...(ui ? { ui: Object.fromEntries(A.DRAFTS[act].map((k) => [k, ui[k]])) } : {}), ...(A.CONFIRM[act] ? { confirmed: true } : {}),
|
||||
ctx: { sel: { type: 'city', id: 'fra' }, tab: 'cust', left: 'noc', modal: false, w: 390, h: 844, coarse: true } });
|
||||
const r = A.checkEnvelope('act', JSON.parse(JSON.stringify(body)), { sim: SIM });
|
||||
assert.ok(r.ok, `${act} ${JSON.stringify(args)}: ${r.error}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the envelope check refuses what section 10 refuses', () => {
|
||||
const ok = (kind, b) => A.checkEnvelope(kind, b, { sim: SIM });
|
||||
assert.equal(ok('act', env('buyTransit', { city: 'fra', net: 'cog', tier: 1 })).ok, true);
|
||||
const no = (kind, b, why) => { const r = ok(kind, b); assert.equal(r.ok, false, `${why}: refused`); assert.equal(r.code, 400, why); };
|
||||
const proto = JSON.parse('{"__proto__":{"polluted":1}}');
|
||||
for (const [b, why] of [
|
||||
[null, 'null'], [[], 'an array'], ['x', 'a string'], [{ ...env('buildPop', { city: 'fra' }), rid: 'AB' }, 'a bad rid'], [{ ...env('buildPop', { city: 'fra' }), dev: 'x'.repeat(17) }, 'a bad dev'],
|
||||
[{ ...env('buildPop', { city: 'fra' }), sim: 'nothex' }, 'a bad sim'], [{ ...env('buildPop', { city: 'fra' }), extra: 1 }, 'an unknown field'],
|
||||
[env('start', {}), 'a session act'], [env('pzStart', {}), 'a puzzle act'], [env('speed', { v: 8 }), 'a vote'], [env('teOpt', {}), 'a local act'],
|
||||
[env('constructor', {}), 'constructor'], [env('__proto__', {}), '__proto__'], [env('toString', {}), 'toString'],
|
||||
[env('buildPop', { city: { id: 'fra' } }), 'a nested object'], [env('buildPop', proto), '__proto__ in args'], [env('buildPop', { constructor: 1 }), 'constructor in args'],
|
||||
[env('buildPop', Object.fromEntries(Array.from({ length: 13 }, (x, i) => ['k' + i, i]))), '13 args'], [env('buildPop', { city: 'x'.repeat(65) }), 'a 65-character string'],
|
||||
[env('buildPop', { city: Array(65).fill('fra') }), 'an array of 65'], [env('buildPop', { city: [{}] }), 'an object in an array'], [env('buildPop', { city: NaN }), 'NaN'],
|
||||
[env('buildPop', { 'bad-key': 1 }), 'a bad arg name'], [env('buildPop', [1, 2]), 'args as an array'],
|
||||
[env('buildLink', { tier: 1 }, { ui: { pending: 'fra-ams' } }), 'a draft of the wrong type'], [env('buildLink', { tier: 1 }, { ui: { decom: ['fra'] } }), 'a draft the act does not read'],
|
||||
[env('buildLink', { tier: 1 }, { ui: { pending: { a: 'fra', b: 'ams', c: 'x' } } }), 'a pair with more'], [env('buildLink', { tier: 1 }, { ui: { pending: { a: 'fra', b: 'fra' } } }), 'a link from a city to itself'], [env('buildPop', { city: 'fra' }, { ui: { pending: { a: 'fra', b: 'ams' } } }), 'drafts on an act without'],
|
||||
[env('decomGo', {}, { ui: { decom: Array(201).fill('fra') } }), '201 cities'],
|
||||
[env('buildPop', { city: 'fra' }, { confirmed: true }), 'confirmed on a one-click act'], [env('rmLink', { id: 'l1' }, { confirmed: false }), 'confirmed false'],
|
||||
[env('buildPop', { city: 'fra' }, { ctx: { sel: { type: 'ix', id: 'fra' } } }), 'a selection of another type'], [env('buildPop', { city: 'fra' }, { ctx: { tab: 'Cust' } }), 'a tab with capitals'],
|
||||
[env('buildPop', { city: 'fra' }, { ctx: { w: 0 } }), 'a viewport of nothing'], [env('buildPop', { city: 'fra' }, { ctx: { h: Infinity } }), 'an endless viewport'], [env('buildPop', { city: 'fra' }, { ctx: { w: '390' } }), 'a viewport as text'],
|
||||
[env('buildPop', { city: 'fra' }, { ctx: { evil: 1 } }), 'an unknown ctx field'], [env('buildPop', { city: 'fra' }, { ctx: [] }), 'ctx as an array'],
|
||||
[env('pniAll', { net: null, tier: 1 }), 'a quote act without its quote'], [env('utilityCaches', { city: 'fra', quote: 5 }), 'a key quote as a number'],
|
||||
[env('bstdApply', { q: 5 }), 'the build standard without its plan'], [env('bstdApply', { quote: 5 }), 'a plan key as a number'],
|
||||
[env('teDeploy', { script: 'x'.repeat(4001) }), 'a script over 4000'], [env('metricSet', { id: 'l1', v: '1'.repeat(17) }), 'a metric over 16'],
|
||||
]) no('act', b, why);
|
||||
assert.equal(ok('act', env('teDeploy', { script: 'x'.repeat(4000) })).ok, true, 'a long script within its cap');
|
||||
// A viewport outside what the layout tells apart is clamped, not refused: a 5120-px monitor, a desktop zoomed out.
|
||||
for (const [w, h, cw, ch] of [[5120, 1440, A.VIEW_MAX, 1440], [100, 50, A.VIEW_MIN, A.VIEW_MIN], [390, 844, 390, 844]]) {
|
||||
const b = env('buildPop', { city: 'fra' }, { ctx: { w, h } });
|
||||
assert.equal(ok('act', b).ok, true, `${w}×${h}`);
|
||||
assert.deepEqual([b.ctx.w, b.ctx.h], [cw, ch], `${w}×${h} clamped into ${A.VIEW_MIN}–${A.VIEW_MAX}`);
|
||||
}
|
||||
assert.equal(ok('act', env('rmLink', { id: 'l1' }, { confirmed: true })).ok, true);
|
||||
const old = ok('act', { ...env('buildPop', { city: 'fra' }), sim: 'ffffffffffff' });
|
||||
assert.deepEqual([old.ok, old.code, old.old], [false, 409, true], 'a page of another build is told it is old');
|
||||
// Asks: only the three what-ifs, without drafts or confirmations.
|
||||
assert.equal(ok('ask', env('teCheck', { script: 'prefer cog at fra' })).ok, true);
|
||||
assert.equal(ok('ask', env('linkCheck', { id: 'l1' })).ok, true);
|
||||
no('ask', env('buildPop', { city: 'fra' }), 'a sent act as an ask');
|
||||
no('ask', env('linkCheck', { id: 'l1' }, { confirmed: true }), 'an ask confirmed');
|
||||
// Votes, presence, settings.
|
||||
for (const s of [0, 0.5, 1, 2, 4, 8, null]) assert.equal(ok('vote', { speed: s, sim: SIM }).ok, true, `vote ${s}`);
|
||||
no('vote', { speed: 3, sim: SIM }, 'a speed that is none'); no('vote', { speed: 1, sim: SIM, x: 1 }, 'a vote with more');
|
||||
assert.equal(ok('vote', { speed: 1, sim: 'ffffffffffff' }).code, 409);
|
||||
assert.equal(ok('here', { dev: '9f8e7d6c', hidden: false, hold: true, view: { link: 'l1' } }).ok, true);
|
||||
no('here', { dev: '9f8e7d6c', view: { link: { x: 1 } } }, 'a view with an object'); no('here', { dev: '9f8e7d6c', hidden: 'yes' }, 'a flag that is no boolean');
|
||||
assert.equal(ok('prefs', { prefs: { pauseFurious: true }, lang: 'de' }).ok, true);
|
||||
no('prefs', { prefs: { muted: true } }, 'a preference that is not the network\'s'); no('prefs', { lang: '../x' }, 'a language that is no code');
|
||||
no('nope', {}, 'an unknown kind');
|
||||
});
|
||||
|
||||
test('the canned stream: every fixture passes the shape checker, and the shape checker catches broken ones', () => {
|
||||
for (const n of FIXTURES) assert.deepEqual(checkEvent(fixture(n)), [], n);
|
||||
const upd = fixture('upd-act');
|
||||
assert.equal(upd.acts.length, 2, 'two actions in one update');
|
||||
assert.equal(upd.v, upd.from + 1);
|
||||
assert.equal(fixture('upd-day').from, fixture('snap').v, 'the day follows the snapshot');
|
||||
assert.equal(upd.from, fixture('upd-day').v, 'the actions follow the day');
|
||||
assert.ok('off' in fixture('clock'), 'the clock carries each network\'s calendar offset');
|
||||
const broken = [
|
||||
[{ ...upd, v: upd.from + 2 }, /from \+ 1/], [{ ...upd, r: { ...upd.r, ef: {} } }, /never carries/], [{ ...upd, fx: [['boom', 1]] }, /unknown effect/],
|
||||
[{ ...upd, acts: [{ rid: 'x', dev: '9f8e7d6c', ui: {} }] }, /rid/], [{ ...fixture('clock'), speed: 3 }, /speed/], [{ ...fixture('roster'), on: ['NOPE'] }, /on/],
|
||||
[{ ...fixture('snap'), S: { ...fixture('snap').S, mp: { ...fixture('snap').S.mp, sim: undefined } } }, /server network/], [{ t: 'bye', why: 'tired' }, /why/], [{ t: 'nope' }, /unknown event/],
|
||||
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/],
|
||||
];
|
||||
for (const [e, re] of broken) assert.match(checkEvent(e).join('\n'), re);
|
||||
assert.deepEqual(checkFx(['floater', [1, 2, 'x', '#fff']]), []);
|
||||
assert.match(checkFx(['toast', { h: 1 }]).join(), /toast/);
|
||||
// Over the wire: sse() writes what parseSse() reads.
|
||||
const text = FIXTURES.map((n, i) => sse(fixture(n).t, fixture(n), i % 2 ? `k3f9.${i}` : undefined)).join(': hb\n\n');
|
||||
const back = parseSse(text);
|
||||
assert.deepEqual(back.map((e) => e.data), FIXTURES.map(fixture));
|
||||
assert.equal(back[1].id, 'k3f9.1');
|
||||
});
|
||||
|
||||
test('the canned state is the game\'s own: migrate() keeps the snapshot and every update applied to it as they are', (t) => {
|
||||
const { ev, errors, dom } = load();
|
||||
t.after(() => dom.window.close());
|
||||
const same = (s) => ev(`(()=>{const a=${lit(JSON.stringify(s))},b=JSON.stringify(migrate(JSON.parse(a)));return a===b?'':b.slice(0,0)+'differs';})()`);
|
||||
let S = fixture('snap').S;
|
||||
assert.equal(same(S), '', 'the snapshot');
|
||||
for (const n of ['upd-day', 'upd-act']) {
|
||||
const u = fixture(n);
|
||||
S = { ...S, ...u.s };
|
||||
for (const k of u.del || []) delete S[k];
|
||||
assert.equal(same(S), '', `after ${n}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the fake engine answers every call in the shapes of section 4.2', async () => {
|
||||
const e = createFakeEngine(), code = 'K7Q2XD', a = 'abcd1234', b = 'efgh5678';
|
||||
const all = [];
|
||||
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false }, lang: 'en', prefs: {} }, { nid: b, env: { day: 40 }, lang: 'de', prefs: {} }]);
|
||||
assert.equal(L.length, 2); assert.ok(L[0].saved, 'a new network is checkpointed at once');
|
||||
assert.ok(L[0].epoch && L[1].epoch && L[0].epoch !== L[1].epoch, 'each realm load has its own epoch');
|
||||
all.push(...L);
|
||||
const D = await e.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [b, a] });
|
||||
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.equal(D.nets[b].day, 41);
|
||||
all.push(D);
|
||||
const P1 = await e.pull(code, a, {}), P2 = await e.pull(code, a, {});
|
||||
assert.ok(P1.upd && !P2.upd, 'a pull sends what changed, once'); assert.equal(P2.v, P1.v, 'only a pull with something to send is a version');
|
||||
const act = await e.act(code, a, env('buildPop', { city: 'par' }));
|
||||
assert.equal(act.v, P1.v + 1); assert.equal(JSON.parse(act.upd).acts[0].rid, 'a1b2c3d4e5');
|
||||
assert.deepEqual([P1.epoch, P2.epoch, act.epoch], [L[0].epoch, L[0].epoch, L[0].epoch], 'every versioned reply names the realm\'s epoch');
|
||||
all.push(P1, P2, act, await e.ask(code, a, env('linkCheck', { id: 'l1' })), await e.pull(code, b, { snap: true, views: [{ link: 'l1' }, { peer: 'fra' }] }),
|
||||
await e.sub(code, a, { views: [{ link: 'l1' }] }), await e.greet(code, a), await e.save(code, b), await e.card(code, a));
|
||||
assert.equal(await e.prefs(code, a, { prefs: { pauseFurious: true } }), undefined);
|
||||
e.lose(code, b);
|
||||
const D2 = await e.day(code, { d: 2, nets: [a, b] });
|
||||
assert.equal(D2.nets[b].lost, true);
|
||||
const D3 = await e.day(code, { d: 3, nets: [a, b] });
|
||||
assert.equal(D3.nets[b], undefined, 'a lost network has no more days');
|
||||
assert.equal((await e.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
|
||||
e.failNext('act', 'timeout');
|
||||
const tmo = await e.act(code, a, env('buildPop', { city: 'par' }));
|
||||
assert.deepEqual([tmo.t, tmo.what], ['err', 'timeout']);
|
||||
// The worker built that realm again: a new epoch, versions from 0, so every page of it takes a snapshot.
|
||||
const P3 = await e.pull(code, a, { snap: true });
|
||||
assert.notEqual(P3.epoch, L[0].epoch); assert.equal(P3.v, 0); assert.equal(JSON.parse(P3.snap).epoch, P3.epoch);
|
||||
all.push(D2, D3, tmo, P3);
|
||||
for (const m of all) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
|
||||
// Held answers wait; a worker that dies rejects everything pending.
|
||||
e.hold('day');
|
||||
let done = false; const p = e.day(code, { d: 4, nets: [a] }).then(() => { done = true; });
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.equal(done, false, 'held');
|
||||
e.release('day'); await p; assert.equal(done, true);
|
||||
e.hold('save');
|
||||
const s1 = e.save(code, a), s2 = e.save(code, b);
|
||||
e.exit();
|
||||
await assert.rejects(s1, /worker exited/); await assert.rejects(s2, /worker exited/);
|
||||
assert.equal(e.stats().realms, 0);
|
||||
e.failNext('load', 'exit');
|
||||
await assert.rejects(e.load(code, [{ nid: a, env: {}, lang: 'en', prefs: {} }]), /worker exited/);
|
||||
assert.deepEqual(checkWorker({ t: 'unloaded', code }), []);
|
||||
assert.ok(e.calls.length > 15);
|
||||
});
|
||||
|
||||
test('the fake engine fails the way the engine does: a network that does not load, a day that fails twice or once', async () => {
|
||||
const a = 'abcd1234', b = 'efgh5678', c = 'ijkl9012', net = (nid) => ({ nid, env: { day: 5 }, lang: 'en', prefs: {} });
|
||||
// A save that does not load (4.7): that network is broken, the others load.
|
||||
const e = createFakeEngine(), code = 'K7Q2XD';
|
||||
e.breakNext(code, b);
|
||||
const L = await e.load(code, [net(a), net(b)]);
|
||||
assert.equal(Array.isArray(L), true);
|
||||
assert.deepEqual([!!L[0].err, !!L[1].err], [false, true]);
|
||||
assert.deepEqual(Object.keys(L[1]).sort(), ['err', 'nid', 't'], 'a broken load has no realm: no epoch, day or lost');
|
||||
e.failNext('load', 'timeout', c);
|
||||
const L2 = await e.load('Q9W8E7', [net(a), net(c)]);
|
||||
assert.deepEqual([!!L2[0].err, !!L2[1].err], [false, true], 'a failed load call names the network it failed');
|
||||
e.failNext('load', 'throw');
|
||||
const L3 = await e.load('Z2X3C4', [net(a), net(b)]);
|
||||
assert.deepEqual(L3.map((l) => !!l.err), [true, true], 'without a network, every network of the call');
|
||||
// Days: one that fails once and passes on the retry, one that fails twice (broken at its pre-day state).
|
||||
e.flaky(code, a);
|
||||
const D1 = await e.day(code, { d: 1, nets: [a] });
|
||||
assert.deepEqual([D1.nets[a].day, D1.nets[a].retried, D1.nets[a].err], [6, true, undefined]);
|
||||
const E = createFakeEngine();
|
||||
await E.load(code, [net(a), net(b)]);
|
||||
E.failNext('day', 'throw', b);
|
||||
const D2 = await E.day(code, { d: 1, nets: [a, b] });
|
||||
assert.equal(D2.nets[a].day, 6);
|
||||
assert.deepEqual([D2.nets[b].day, D2.nets[b].retried, typeof D2.nets[b].err], [5, true, 'string']);
|
||||
const D3 = await E.day(code, { d: 2, nets: [a, b] });
|
||||
assert.equal(D3.nets[b], undefined, 'a broken network has no more days');
|
||||
assert.equal((await E.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
|
||||
// A day that timed out twice leaves a fresh realm (a new epoch) as well.
|
||||
const ep = (await E.pull(code, a, {})).epoch;
|
||||
E.failNext('day', 'timeout');
|
||||
const D4 = await E.day(code, { d: 3, nets: [a] });
|
||||
assert.equal(typeof D4.nets[a].err, 'string');
|
||||
assert.notEqual((await E.pull(code, a, {})).epoch, ep);
|
||||
for (const m of [...L, ...L2, ...L3, D1, D2, D3, D4]) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
|
||||
// The checker holds the host to it.
|
||||
assert.match(checkWorker({ t: 'loaded', nid: a, day: 1, lost: false }).join(), /epoch: missing/);
|
||||
assert.match(checkWorker({ t: 'pulled', nid: a, v: 1 }).join(), /epoch: missing/);
|
||||
assert.match(checkWorker({ t: 'loaded', nid: a, err: 'x', saved: { t: 'saved' } }).join(), /nothing saved/);
|
||||
assert.deepEqual(checkFx(['toast', { h: 'one argument', tick: false }]), [], 'toast(html): k and a may be left out');
|
||||
});
|
||||
|
||||
test('the harness: load({mp:true}) is a stamped MP page, and fakeFetch streams events the page reads through fetch', async (t) => {
|
||||
const f = fakeFetch([[/^POST \/api\/mp\/sessions\/K7Q2XD\/act$/, (c) => ({ status: 200, json: { rid: c.body.rid, outcome: 'applied', v: 414 } })]]);
|
||||
const { ev, errors, dom } = load({ mp: true, fetch: f });
|
||||
t.after(() => dom.window.close());
|
||||
assert.equal(ev('MP_API'), '/api/mp');
|
||||
assert.equal(ev('SIM_ID'), SIM);
|
||||
// A stream, read the way a page reads one.
|
||||
ev(`window.__got=[];window.__end='';window.__ac=new AbortController();
|
||||
fetch(MP_API+'/sessions/K7Q2XD/stream?dev=9f8e7d6c&sim='+SIM_ID,{headers:{Authorization:'Bearer abcd1234.x'},signal:__ac.signal}).then(r=>{
|
||||
if(!r.ok||!/event-stream/.test(r.headers.get('content-type')))return;const rd=r.body.getReader(),dc=new TextDecoder();let buf='';
|
||||
const go=()=>rd.read().then(({done,value})=>{if(done){__end='done';return;}buf+=dc.decode(value,{stream:true});let i;
|
||||
while((i=buf.indexOf('\\n\\n'))>=0){const blk=buf.slice(0,i);buf=buf.slice(i+2);const d=blk.split('\\n').filter(l=>l.startsWith('data: ')).map(l=>l.slice(6)).join('\\n');if(d)__got.push(JSON.parse(d).t);}go();},e=>{__end=e.name;});go();});`);
|
||||
const s = await f.stream(0);
|
||||
assert.equal(s.call.path, '/sessions/K7Q2XD/stream');
|
||||
assert.deepEqual(s.call.query, { dev: '9f8e7d6c', sim: SIM });
|
||||
assert.equal(s.call.headers.authorization, 'Bearer abcd1234.x');
|
||||
s.send('snap', fixture('snap'), 'k3f9.412').comment().send('upd', fixture('upd-day'), 'k3f9.413');
|
||||
await flush(5);
|
||||
assert.deepEqual(JSON.parse(ev('JSON.stringify(__got)')), ['snap', 'upd']);
|
||||
ev('__ac.abort()');
|
||||
await flush(5);
|
||||
assert.equal(s.aborted, true, 'the page aborted it');
|
||||
assert.equal(ev('__end'), 'AbortError');
|
||||
// A second stream that the server ends.
|
||||
ev(`fetch(MP_API+'/sessions/K7Q2XD/stream?dev=9f8e7d6c&sim='+SIM_ID).then(r=>r.body.getReader().read()).then(x=>{window.__d2=x.done;})`);
|
||||
(await f.stream(1)).close();
|
||||
await flush(5);
|
||||
assert.equal(ev('__d2'), true);
|
||||
// A POST answered by a route; the call is recorded with its parsed body.
|
||||
ev(`fetch(MP_API+'/sessions/K7Q2XD/act',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({rid:'a1b2c3d4e5'})}).then(r=>r.json()).then(j=>{window.__j=j;})`);
|
||||
await flush(5);
|
||||
assert.equal(ev('__j.outcome'), 'applied');
|
||||
assert.equal(f.calls.at(-1).body.rid, 'a1b2c3d4e5');
|
||||
ev(`fetch(MP_API+'/sessions/K7Q2XD/vote',{method:'POST',body:'{}'}).then(r=>{window.__st=r.status;})`);
|
||||
await flush(5);
|
||||
assert.equal(ev('__st'), 404, 'anything else is not here');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -72,6 +72,29 @@ test('pages: the build carries no agent code, and is the page assembled without
|
|||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('pages: the build carries nothing of server-run play; only a multiplayer build has it, with its build id', () => {
|
||||
// src/game/98-server-play/ and its CSS are for self-hosted multiplayer copies (MP_API): left out of this page whole,
|
||||
// and the SIM_ID placeholder stays as it is. Lines of those files (long enough to be theirs, and without labels,
|
||||
// which the build turns into ids) are looked for in both builds.
|
||||
const page = require('../scripts/lib/page');
|
||||
const mp = page.assemble({ mp: true }), lines = mp.html.split('\n'), mine = [];
|
||||
for (const m of mp.map) if (page.MP_ONLY.some((p) => (p.endsWith('/') ? m.file.startsWith(p) : m.file === p)))
|
||||
for (let i = m.from; i <= m.to; i++) { const l = lines[i - 1].trim(); if (l.length >= 40 && !/\b(tr|trn|N_)\(/.test(l)) mine.push(l); }
|
||||
assert.ok(mine.length >= 2, 'the server-play files have lines to look for');
|
||||
const html = read('index.html');
|
||||
for (const l of mine) assert.equal(html.includes(l), false, `the page has no "${l.slice(0, 60)}…"`);
|
||||
assert.match(html, /const SIM_ID=\/\*__SIM_ID__\*\/'';/, 'and no build id');
|
||||
assert.equal('simId' in JSON.parse(read('version.json')), false);
|
||||
const MPOUT = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-pages-mp-'));
|
||||
try {
|
||||
execFileSync(process.execPath, ['scripts/build.js'], { cwd: root, stdio: 'pipe', env: { ...process.env, OUT: MPOUT, VERSION: '1.2.3', BUILD_DATE: '2026-10-27', MP_API: '/api/mp' } });
|
||||
const mph = fs.readFileSync(path.join(MPOUT, 'index.html'), 'utf8'), id = page.simId(mp.html);
|
||||
for (const l of mine) assert.ok(mph.includes(l), `the multiplayer page has "${l.slice(0, 60)}…"`);
|
||||
assert.match(mph, new RegExp(`const SIM_ID='${id}';`), 'stamped with its build id');
|
||||
assert.equal(JSON.parse(fs.readFileSync(path.join(MPOUT, 'version.json'), 'utf8')).simId, id, 'which version.json names too');
|
||||
} finally { fs.rmSync(MPOUT, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('pages: only the release workflow deploys, and only with the GitHub Pages actions', () => {
|
||||
const dir = path.join(root, '.github', 'workflows');
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ test('the global batch, now in the Ops sheet, preserves scope, keyboard focus an
|
|||
select.dispatchEvent(new dom.window.Event('change', { bubbles: true }));
|
||||
assert.equal(doc.activeElement, doc.querySelector('#modalCard select'));
|
||||
const submit = doc.querySelector('#modalCard [data-act="pniAll"]');
|
||||
assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0 }, lang);
|
||||
assert.deepEqual(JSON.parse(submit.dataset.args), { net: null, tier: 0, q: ev('pniBatch(null,0).cost') }, lang);
|
||||
assert.equal(submit.disabled, false, lang);
|
||||
assert.ok(doc.querySelectorAll('#modalCard details').length > 0, 'long lists are collapsed');
|
||||
assert.equal(ev('S.cash'), cash, 'preview does not buy anything');
|
||||
|
|
|
|||
389
tests/server-sim-prereqs.test.js
Normal file
389
tests/server-sim-prereqs.test.js
Normal file
|
|
@ -0,0 +1,389 @@
|
|||
// What server-run play needs from the game before it is built (the server-sim design, track T1): new games in two
|
||||
// halves (beginState/beginHello/beginShow), the tutorial's state apart from its box (tutAdvance/coachDom), a toast on
|
||||
// screen without its log line (toastPop), the boot's one-shot notes in bootNotes(), the five acts that read a typed
|
||||
// field taking the text as an argument, srvOn() and its two checks in the loop, mpSanitize keeping sim, the quote checks,
|
||||
// and the multiplayer-only client folder left out of every other page. None of it changes play in any build.
|
||||
// T1_BASE=<git ref> also compares the refactors with the page at that ref (before them): same state, same screen.
|
||||
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 { assemble, assembleRef, simId, MP_ONLY, ROOT } = require('../scripts/lib/page');
|
||||
const { lit } = require('../scripts/lib/js-literal');
|
||||
|
||||
const BASE = process.env.T1_BASE;
|
||||
let baseHtml = null;
|
||||
const baseFile = () => { if (!baseHtml) { baseHtml = path.join(os.tmpdir(), `tubes-t1-base-${process.pid}.html`); fs.writeFileSync(baseHtml, assembleRef(BASE)); } return baseHtml; };
|
||||
// The pages to compare: this one, and the base page when T1_BASE is set.
|
||||
const pages = (opts = {}) => [load(opts), ...(BASE ? [load({ ...opts, file: baseFile() })] : [])];
|
||||
const pin = 'Date.now=()=>1.7e12;';
|
||||
// What the player sees: the toasts (without their birth time), the panel, the HUD, a window, the coach. (Without the
|
||||
// label ids the shipped base page writes into data-i18n attributes: the words are compared.)
|
||||
const screen = (ev) => ev(`JSON.stringify({toasts:$('toasts').innerHTML,panel:$('panel').innerHTML,hud:$('hud').innerHTML,
|
||||
modal:$('modal').hidden?'':$('modalCard').innerHTML,coach:$('coach').hidden?'':$('coach').innerHTML,glow:document.querySelectorAll('.coach-glow').length})`)
|
||||
.replace(/ data-born=\\"[^"\\]*\\"/g, '').replace(/ data-i18n[-a-z]*=\\"[^"\\]*\\"/g, '');
|
||||
// The game as a reload makes it, keys in order: what "the same game as before" means across this change, which writes
|
||||
// the fields a reload fills in when it creates things (tests/canonical-state.test.js).
|
||||
// stamp: false leaves out when log lines were written and their ids (a boot runs before a test can pin the clock).
|
||||
const canon = (ev, stamp = true) => ev(`(()=>{const u=uidN,r=S.rng,k=v=>Array.isArray(v)?v.map(k):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,x)=>(o[x]=k(v[x]),o),{}):v;
|
||||
try{const s=migrate(JSON.parse(JSON.stringify(S)));if(!${stamp})for(const e of s.log)delete e.at,delete e.id;return JSON.stringify(k(s));}finally{uidN=u;S.rng=r;}})()`);
|
||||
const M = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'bgp', color: '#3a86ff', title: 'Friday' };
|
||||
|
||||
test('a new network in halves: the server path (beginState, compute, beginHello, then beginShow with srv) gives the page the same game and screen as beginGame', (t) => {
|
||||
const A = load(), B = load();
|
||||
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
|
||||
for (const h of [A, B]) h.ev(pin + 'UI.pitched=true;UI.asnTxt="";');
|
||||
A.ev(`beginGame('Packet Pals','fra',{mode:'normal',preset:'bgp',mp:${lit(M)}})`);
|
||||
// The server: the state, its marks, its routing and its welcome; no screen, no storage.
|
||||
const keys0 = B.ev('Object.keys(localStorage).sort().join()'), toasts0 = B.ev("$('toasts').children.length"), started0 = B.ev('UI.started');
|
||||
B.ev(`beginState('Packet Pals','fra',{mode:'normal',preset:'bgp',mp:${lit(M)},asn:201234})`);
|
||||
assert.equal(B.ev('Object.keys(localStorage).sort().join()'), keys0, 'beginState stores nothing');
|
||||
assert.equal(B.ev("$('toasts').children.length"), toasts0, 'and shows nothing');
|
||||
assert.equal(B.ev('UI.started'), started0, 'nor starts the clock');
|
||||
B.ev('S.mp.sim=1;S.tut=null;compute();beginHello();');
|
||||
// The page: makes its slot for the network, then shows it, without routing it again, a second welcome or a tutorial.
|
||||
B.ev(`slotLeave();slotNew();window.__c=0;const c0=compute;compute=()=>{__c++;c0();};beginShow('fra',{mode:'normal',preset:'bgp',mp:${lit(M)},srv:true});compute=c0;`);
|
||||
assert.equal(B.ev('__c'), 0, 'the page does not route a server network');
|
||||
const plain = (ev) => ev('JSON.stringify({...S,tut:undefined,mp:{...S.mp,sim:undefined}})');
|
||||
assert.equal(plain(B.ev), plain(A.ev), 'the same game');
|
||||
assert.equal(B.ev("S.log.filter(e=>/Welcome/.test(e.t)).length"), 1, 'one welcome in the log');
|
||||
assert.equal(screen(B.ev), screen(A.ev), 'the same screen');
|
||||
assert.equal(B.ev('S.mp.sim'), 1);
|
||||
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
|
||||
});
|
||||
|
||||
test('a new game from the title still starts as it did: Normal, sandbox, a scenario', (t) => {
|
||||
for (const how of ["UI.preset='bgp';ACT.start({})", "ACT.modeSet({m:'sandbox'});ACT.start({})", 'ACT.startScn({id:SCN[0].id})']) {
|
||||
const P = pages();
|
||||
t.after(() => P.forEach((h) => h.dom.window.close()));
|
||||
for (const h of P) h.ev(pin + `UI.pitched=true;${how};`);
|
||||
assert.ok(P[0].ev('!!S&&UI.started'), how);
|
||||
for (const h of P.slice(1)) {
|
||||
assert.equal(canon(h.ev), canon(P[0].ev), `${how}: the same game as before`);
|
||||
assert.equal(screen(h.ev), screen(P[0].ev), `${how}: the same screen as before`);
|
||||
}
|
||||
for (const h of P) assert.deepEqual(h.errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('the coach: tutAdvance moves S.tut on and draws nothing, coachDom draws and changes nothing; renderCoach is the two', (t) => {
|
||||
const P = pages();
|
||||
t.after(() => P.forEach((h) => h.dom.window.close()));
|
||||
const steps = ["ACT.launchBB({city:'fra'})", "ACT.buyTransit({city:'fra',net:'cog',tier:1})", "ACT.buyIx({city:'fra',tier:0,signed:true});ACT.rs({city:'fra'})",
|
||||
'for(let i=0;i<6;i++)dayTick();renderAll()', "ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0})", "for(let i=0;i<40&&!S.biz.length;i++){dayTick();if(S.offers[0])ACT.accept({id:S.offers[0].id});}renderAll()"];
|
||||
for (const h of P) h.ev(pin + "window.__TUBES_TUT__=true;UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;UI.speed=0;S.cash=1e7;");
|
||||
assert.equal(P[0].ev('S.tut'), 0, 'the tutorial started');
|
||||
const coach = (ev) => ev("$('coach').hidden+'|'+$('coach').innerHTML+'|'+document.querySelectorAll('.coach-glow').length");
|
||||
for (const s of steps) {
|
||||
for (const h of P) h.ev(s);
|
||||
const ev = P[0].ev;
|
||||
// The two halves on their own, on this page.
|
||||
const box = coach(ev), st = ev('JSON.stringify(S)');
|
||||
ev('coachDom()');
|
||||
assert.equal(ev('JSON.stringify(S)'), st, `${s}: coachDom changes no state`);
|
||||
const tut = ev('S.tut');
|
||||
ev("window.__box=$('coach').innerHTML;tutAdvance()");
|
||||
assert.equal(ev("$('coach').innerHTML===__box"), true, `${s}: tutAdvance draws nothing`);
|
||||
assert.equal(ev('S.tut'), tut, `${s}: renderAll already advanced it`);
|
||||
assert.equal(coach(ev), box);
|
||||
for (const h of P.slice(1)) {
|
||||
assert.equal(h.ev('S.tut'), tut, `${s}: the same step as before`);
|
||||
assert.equal(coach(h.ev), box, `${s}: the same coach as before`);
|
||||
}
|
||||
}
|
||||
assert.equal(P[0].ev('S.tut'), null, 'the tutorial ran to its end');
|
||||
assert.match(P[0].ev('S.log[0].t+S.log[1].t+S.log[2].t'), /basics/, 'and said so');
|
||||
for (const h of P) assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
||||
test('toastPop shows a toast without its log line; toast() is the log line and toastPop, quiet days included', (t) => {
|
||||
const { ev, errors, dom } = load();
|
||||
t.after(() => dom.window.close());
|
||||
ev(pin + "UI.pitched=true;ACT.start({});closeModal();$('toasts').innerHTML='';");
|
||||
const n0 = ev('S.log.length');
|
||||
ev("toastPop('<b>Hi</b> there','good',[{l:'Open',act:'leftTab',args:{t:'noc'}}])");
|
||||
assert.equal(ev('S.log.length'), n0, 'no log line');
|
||||
assert.match(ev("$('toasts').innerHTML"), /<b>Hi<\/b> there.*data-act="leftTab"/);
|
||||
ev("toast('Logged too','good')");
|
||||
assert.equal(ev('S.log.length'), n0 + 1);
|
||||
// Quiet notifications: what a day says (tick) pops up only for trouble and milestones.
|
||||
ev("$('toasts').innerHTML='';window.__q=PREFS.quiet;PREFS.quiet=true;toastPop('a day note','',[],true);toastPop('not a day','',[],false);toastPop('trouble','bad',[],true);PREFS.quiet=__q");
|
||||
assert.equal(ev("$('toasts').children.length"), 2, 'the quiet day note stays in the log only');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
// A save that has both boot notes to say: new networks on the map since it was saved, and Australia's prices.
|
||||
function notesSave() {
|
||||
const { ev, dom } = load();
|
||||
try {
|
||||
ev(pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();ACT.buildPop({city:'syd'});for(let i=0;i<5;i++)dayTick();S.seen=S.seen.slice(3);delete S.auV;");
|
||||
return ev('JSON.stringify(packSave(S))');
|
||||
} finally { dom.window.close(); }
|
||||
}
|
||||
|
||||
test('bootNotes: a reopened network says once that new networks are on the map and that Australia changed, as the boot always did', (t) => {
|
||||
const txt = notesSave();
|
||||
const P = pages({ storage: { 'sot-save-v1': txt } });
|
||||
t.after(() => P.forEach((h) => h.dom.window.close()));
|
||||
const ev = P[0].ev;
|
||||
assert.equal(ev('typeof bootNotes'), 'function');
|
||||
assert.equal(ev('S.grace.told'), 1, 'the courtesy route was announced');
|
||||
assert.equal(ev("'auNews' in S"), false, 'Australia was announced');
|
||||
const said = ev("S.log.slice(0,3).map(e=>e.t).join(' | ')");
|
||||
assert.match(said, /new networks/i);
|
||||
assert.match(said, /Australia/i);
|
||||
ev('bootNotes()');
|
||||
assert.equal(ev("S.log.slice(0,3).map(e=>e.t).join(' | ')"), said, 'once only');
|
||||
for (const h of P.slice(1)) {
|
||||
assert.equal(canon(h.ev, false), canon(ev, false), 'the same as before');
|
||||
assert.equal(screen(h.ev), screen(ev));
|
||||
}
|
||||
// Declared before the multiplayer client's folder, so that folder can rebind it.
|
||||
const { map } = assemble({ mp: true });
|
||||
const where = map.find((m) => fs.readFileSync(path.join(ROOT, 'src', m.file), 'utf8').includes('function bootNotes('));
|
||||
assert.ok(where && where.file < 'game/98-server-play/', `bootNotes() is in ${where && where.file}`);
|
||||
for (const h of P) assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
||||
test('the five acts that read a typed field take the text as an argument first: the same game either way', (t) => {
|
||||
const setup = pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e8;S.lvl=4;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});" +
|
||||
"ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();S.te={on:true,day:0};compute();";
|
||||
const script = 'prefer cog at fra';
|
||||
const cases = [
|
||||
['renameGo', "ACT.rename();$('rnIn').value=' Tubular Bells ';ACT.renameGo({})", "closeModal();ACT.renameGo({name:' Tubular Bells '})", 'S.name'],
|
||||
['metricSet', "ACT.setMetric({id:S.links[0].id,v:'custom'});UI.sel={type:'link',id:S.links[0].id};renderPanel();$('metIn').value='2.5';ACT.metricSet({id:S.links[0].id})",
|
||||
"ACT.setMetric({id:S.links[0].id,v:'custom'});ACT.metricSet({id:S.links[0].id,v:'2.5'})", 'JSON.stringify(S.pairMet)'],
|
||||
['teDeploy', `ACT.teEdit();$('teSrc').value=${lit(script)};ACT.teDeploy({})`, `closeModal();ACT.teDeploy({script:${lit(script)}})`, 'JSON.stringify(S.te)'],
|
||||
];
|
||||
for (const [act, field, arg, pick] of cases) {
|
||||
const A = load(), B = load();
|
||||
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
|
||||
A.ev(setup); B.ev(setup);
|
||||
A.ev(field); B.ev(arg);
|
||||
assert.equal(B.ev(pick), A.ev(pick), `${act}: what it changed`);
|
||||
assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'), `${act}: the whole game`);
|
||||
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
|
||||
}
|
||||
{
|
||||
const D = load();
|
||||
t.after(() => D.dom.window.close());
|
||||
assert.equal(D.ev(setup + "ACT.rename();$('rnIn').value='Tubular Bells';ACT.renameGo({});S.name"), 'Tubular Bells');
|
||||
}
|
||||
// teCheck: the same report from the argument as from the editor.
|
||||
{
|
||||
const A = load(), B = load();
|
||||
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
|
||||
A.ev(setup + `ACT.teEdit();$('teSrc').value=${lit(script)};ACT.teCheck({})`);
|
||||
B.ev(setup + `closeModal();ACT.teCheck({script:${lit(script)}})`);
|
||||
assert.match(A.ev("$('modalCard').textContent"), /rule/);
|
||||
assert.equal(B.ev("$('modalCard').querySelector('pre').textContent"), A.ev("$('modalCard').querySelector('pre').textContent"));
|
||||
assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'));
|
||||
}
|
||||
// pieRename: the rocket company's name, in a sandbox (where anyone may found one).
|
||||
{
|
||||
const pie = pin + "UI.pitched=true;ACT.modeSet({m:'sandbox'});ACT.start({});closeModal();ACT.pieFound();closeModal();";
|
||||
const A = load(), B = load();
|
||||
t.after(() => { A.dom.window.close(); B.dom.window.close(); });
|
||||
A.ev(pie); B.ev(pie);
|
||||
assert.ok(A.ev('!!(S.pie&&S.pie.co)'), 'a rocket company');
|
||||
A.ev("UI.pieTab='co';ACT.pieOpen()");
|
||||
assert.ok(A.ev("!!$('pieNm')"), 'the name field is on screen');
|
||||
A.ev("$('pieNm').value=' Orbit Pie ';ACT.pieRename({})");
|
||||
B.ev("closeModal();ACT.pieRename({name:' Orbit Pie '})");
|
||||
assert.equal(A.ev('S.pie.co.name'), 'Orbit Pie');
|
||||
assert.equal(B.ev('JSON.stringify(S)'), A.ev('JSON.stringify(S)'));
|
||||
assert.deepEqual(A.errors, []); assert.deepEqual(B.errors, []);
|
||||
}
|
||||
// Without the argument and without the field, nothing happens, as before.
|
||||
const C = load();
|
||||
t.after(() => C.dom.window.close());
|
||||
C.ev(setup + "closeModal();window.__s=JSON.stringify(S);ACT.renameGo({});ACT.metricSet({id:S.links[0].id});ACT.pieRename({});");
|
||||
assert.equal(C.ev('JSON.stringify(S)===__s'), true);
|
||||
});
|
||||
|
||||
test('the field paths of the five acts play as before', { skip: !BASE && 'set T1_BASE to compare with the page before' }, (t) => {
|
||||
const setup = pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e8;S.lvl=4;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});" +
|
||||
"ACT.buildPop({city:'ams'});UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();S.te={on:true,day:0};compute();" +
|
||||
"ACT.rename();$('rnIn').value='Tubular Bells';ACT.renameGo({});ACT.setMetric({id:S.links[0].id,v:'custom'});UI.sel={type:'link',id:S.links[0].id};renderPanel();$('metIn').value='2.5';ACT.metricSet({id:S.links[0].id});" +
|
||||
"ACT.teEdit();$('teSrc').value='prefer cog at fra';ACT.teCheck({});ACT.teDeploy({});";
|
||||
const P = pages();
|
||||
t.after(() => P.forEach((h) => h.dom.window.close()));
|
||||
for (const h of P) h.ev(setup);
|
||||
assert.equal(canon(P[1].ev), canon(P[0].ev));
|
||||
});
|
||||
|
||||
test('srvOn(): false in every page this track ships; a server-play folder that says yes keeps the loop and the boot from running the network', (t) => {
|
||||
// The plain page and the MP page with only the folder's placeholder: the stub, and a network with sim plays locally.
|
||||
for (const opts of [{}, { mp: true }]) {
|
||||
const { ev, errors, dom } = load(opts);
|
||||
t.after(() => dom.window.close());
|
||||
assert.equal(ev('srvOn()'), false);
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
// A page whose folder rebinds srvOn (as the real client will) and opens a server network's mirror.
|
||||
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-srv-src-'));
|
||||
t.after(() => fs.rmSync(src, { recursive: true, force: true }));
|
||||
fs.cpSync(path.join(ROOT, 'src'), src, { recursive: true });
|
||||
fs.writeFileSync(path.join(src, 'game', '98-server-play', '50-t1-test.js'), 'srvOn=()=>!!(S&&S.mp&&S.mp.sim===1);bootNotes=()=>{window.__notes=(window.__notes||0)+1;};\n');
|
||||
const file = path.join(src, 'page.html');
|
||||
fs.writeFileSync(file, assemble({ src, mp: true }).html.replace("/*__MP_API__*/''", "'/api/mp'"));
|
||||
const mk = load();
|
||||
t.after(() => mk.dom.window.close());
|
||||
mk.ev(pin + `UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${lit(M)}});S.mp.sim=1;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});compute();`);
|
||||
const txt = mk.ev('JSON.stringify(packSave(S))');
|
||||
const run = (ev) => { ev("closeModal();UI.speed=8;let t=performance.now();for(let i=0;i<40;i++){t+=200;frame(t);}"); return ev('S.day'); };
|
||||
{
|
||||
const { ev, errors, dom } = load({ file, storage: { 'sot-save-v1': txt } });
|
||||
t.after(() => dom.window.close());
|
||||
assert.equal(ev('S.mp.sim'), 1, 'mpSanitize kept sim');
|
||||
assert.equal(ev('srvOn()'), true);
|
||||
assert.equal(ev('R.served'), 0, 'the boot did not route it (the server does)');
|
||||
assert.equal(ev('window.__notes'), 1, 'the boot called the rebound bootNotes');
|
||||
const d0 = ev('S.day');
|
||||
assert.equal(run(ev), d0, 'no day ran on this page');
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
{
|
||||
// The same save in the page this track ships: a sim network nobody runs for it plays here, as phase 1 does.
|
||||
const { ev, errors, dom } = load({ storage: { 'sot-save-v1': txt } });
|
||||
t.after(() => dom.window.close());
|
||||
assert.ok(ev('R.served') > 0, 'routed at boot');
|
||||
const d0 = ev('S.day');
|
||||
assert.ok(run(ev) > d0, 'and days run');
|
||||
assert.deepEqual(errors, []);
|
||||
}
|
||||
});
|
||||
|
||||
test('mpSanitize keeps sim:1 and nothing else in its place', (t) => {
|
||||
const { ev, errors, dom } = load();
|
||||
t.after(() => dom.window.close());
|
||||
ev(pin + `UI.pitched=true;ACT.start({});closeModal();S.mp=${lit({ ...M, seq: 3 })};`);
|
||||
const back = (sim) => JSON.parse(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.mp.sim=${lit(sim)};return JSON.stringify(migrate(s).mp);})()`));
|
||||
assert.equal(back(1).sim, 1);
|
||||
for (const v of [2, '1', true, null, { x: 1 }]) assert.equal('sim' in back(v), false, JSON.stringify(v));
|
||||
assert.equal('sim' in JSON.parse(ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))).mp)')), false, 'a phase-1 network has none');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('quote checks: a bulk order whose total changed under its window is shown again, not bought', (t) => {
|
||||
const { ev, errors, dom } = load();
|
||||
t.after(() => dom.window.close());
|
||||
ev(pin + "UI.pitched=true;ACT.start({});S.nextFail=S.nextEvent=1e9;closeModal();S.cash=1e9;S.lvl=6;for(const c of ['fra','ams','lon','par'])ACT.buildPop({city:c});compute();");
|
||||
// pniAll: the sheet's button carries the total it shows.
|
||||
ev("ACT.pniAllOpen({net:null})");
|
||||
const args = JSON.parse(ev(`$('modalCard').querySelector('[data-act="pniAll"]').dataset.args`));
|
||||
assert.equal(args.q, ev(`pniBatch(null,${args.tier}).cost`), 'the button carries the quoted total');
|
||||
const n0 = ev('S.pni.length'), c0 = ev('S.cash');
|
||||
ev(`ACT.pniAll(${lit({ ...args, q: args.q + 1 })})`);
|
||||
assert.equal(ev('S.pni.length'), n0, 'a changed total buys nothing');
|
||||
assert.equal(ev('S.cash'), c0);
|
||||
assert.match(ev("$('modalCard').textContent"), /quote changed/i, 'the sheet says why, with the new total');
|
||||
ev(`ACT.pniAll(${lit(args)})`);
|
||||
assert.ok(ev('S.pni.length') > n0, 'the shown total buys');
|
||||
// Without q (the agent, older callers): as before.
|
||||
ev("closeModal();ACT.buildPop({city:'nyc'});window.__n=S.pni.length;ACT.pniAll({net:null,tier:1})");
|
||||
assert.ok(ev('S.pni.length') > ev('__n'));
|
||||
// A sheet whose batch was ordered meanwhile (another tap, the intern): shown again, not a silent nothing.
|
||||
ev("ACT.pniAllOpen({net:null})");
|
||||
const gone = JSON.parse(ev(`$('modalCard').querySelector('[data-act="pniAll"]').dataset.args`));
|
||||
ev(`closeModal();ACT.pniAll(${lit({ net: gone.net, tier: gone.tier })});window.__n=S.pni.length;ACT.pniAll(${lit(gone)})`);
|
||||
assert.equal(ev('S.pni.length'), ev('__n'));
|
||||
assert.match(ev("$('modal').hidden?'':$('modalCard').textContent"), /quote changed/i, 'an emptied plan says so');
|
||||
// bstdApply: the build standard's "Bring everything up now" carries the plan it shows (its key) and its total.
|
||||
ev("closeModal();S.popStd=bstdPut({...bstd(),rt:2});ACT.bstdOpen()");
|
||||
const b = JSON.parse(ev(`$('modalCard').querySelector('[data-act="bstdApply"]').dataset.args`));
|
||||
assert.deepEqual(b, JSON.parse(ev('JSON.stringify({quote:bstdPlanKey(bstdPlan(false)),q:bstdQuote(false).cost})')));
|
||||
const rts = "JSON.stringify(Object.values(S.pops).map(p=>p.routers))", r0 = ev(rts);
|
||||
ev(`ACT.bstdApply(${lit({ ...b, quote: b.quote + 'x' })})`);
|
||||
assert.equal(ev(rts), r0, 'another plan builds nothing');
|
||||
assert.match(ev("$('modalCard').textContent"), /quote changed/i);
|
||||
ev(`closeModal();ACT.bstdApply(${lit({ ...b, q: Math.round(b.q * 0.9) })})`);
|
||||
assert.equal(ev(rts), r0, 'a total 10% away builds nothing');
|
||||
assert.match(ev("$('modalCard').textContent"), /quote changed/i);
|
||||
// Hardware prices drift a little every day under the market rule: the same plan a day later still builds.
|
||||
ev(`closeModal();ACT.bstdApply(${lit({ ...b, q: b.q + 1 })})`);
|
||||
assert.notEqual(ev(rts), r0, 'the shown plan builds, at today\'s prices');
|
||||
ev(`ACT.bstdApply(${lit(b)})`);
|
||||
assert.match(ev("$('modal').hidden?'':$('modalCard').textContent"), /quote changed/i, 'and once it is all done, the old sheet is shown again');
|
||||
// The two that always checked: utilityKit (cost) and utilityCaches (quote).
|
||||
ev("closeModal();window.__s=JSON.stringify(S);ACT.utilityKit({city:'fra',cost:-1,modal:true});ACT.utilityCaches({city:'fra',quote:'nope',modal:true})");
|
||||
assert.equal(ev('JSON.stringify(S)===__s'), true);
|
||||
// utilityKit takes a day's drift too (the kit's router is priced by the market), not a whole part of the kit.
|
||||
ev("closeModal();ACT.buildPop({city:'mad'});window.__k=utilityKit('mad').cost;ACT.utilityKit({city:'mad',cost:__k+GEN_COST})");
|
||||
assert.equal(ev('S.pops.mad.gen'), false);
|
||||
ev('ACT.utilityKit({city:\'mad\',cost:__k+1})');
|
||||
assert.equal(ev('S.pops.mad.gen&&S.pops.mad.site2&&S.pops.mad.routers===2'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('quote checks hold on a server-run day: the build standard\'s plan a few days old still builds, while hardware prices drift', (t) => {
|
||||
// The review's case: routers on the big network, the market rule on; every day moves the total a little.
|
||||
const BIG = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
|
||||
const { ev, errors, dom } = load({ seed: 77 });
|
||||
t.after(() => dom.window.close());
|
||||
ev(`${pin}S=migrate(JSON.parse(${lit(BIG)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.lvl=Math.max(S.lvl,6);S.rules=makeRules('oncall');
|
||||
S.nextFail=S.nextEvent=1e9;S.day=400;S.cash=1e10;compute();S.popStd=bstdPut({...bstd(),rt:8});ACT.bstdOpen();`);
|
||||
assert.equal(ev("rule('market')"), true);
|
||||
const b = JSON.parse(ev(`$('modalCard').querySelector('[data-act="bstdApply"]').dataset.args`));
|
||||
ev('closeModal();for(let i=0;i<3;i++){S.cash=1e10;dayTick();}');
|
||||
assert.notEqual(ev('bstdQuote(false).cost'), b.q, 'the total moved');
|
||||
assert.equal(ev('bstdPlanKey(bstdPlan(false))'), b.quote, 'the plan did not');
|
||||
const r0 = ev("Object.values(S.pops).reduce((a,p)=>a+(p.routers||1),0)");
|
||||
ev(`ACT.bstdApply(${lit(b)})`);
|
||||
assert.ok(ev("Object.values(S.pops).reduce((a,p)=>a+(p.routers||1),0)") > r0, 'and it builds');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the multiplayer client folder and its CSS are in an MP page only, and SIM_ID is its build id', (t) => {
|
||||
const plain = assemble(), mp = assemble({ mp: true });
|
||||
const only = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p));
|
||||
assert.deepEqual(plain.map.filter((m) => only(m.file)), [], 'the plain page has none of it');
|
||||
const mine = mp.map.filter((m) => only(m.file));
|
||||
assert.ok(mine.some((m) => m.file.startsWith('game/98-server-play/')) && mine.some((m) => m.file === 'styles/43-server-play.css'), 'the MP page has both');
|
||||
// The MP page is the plain page plus exactly those files.
|
||||
const lines = mp.html.split('\n'), drop = new Set();
|
||||
for (const m of mine) for (let i = m.from; i <= m.to; i++) drop.add(i);
|
||||
assert.equal(lines.filter((l, i) => !drop.has(i + 1)).join('\n'), plain.html);
|
||||
assert.equal(assemble({ dev: true }).map.filter((m) => only(m.file)).length, 0, 'nor the development page without mp');
|
||||
// The build id: 12 hex digits of the MP page, a new one for any change.
|
||||
assert.match(simId(), /^[0-9a-f]{12}$/);
|
||||
assert.equal(simId(), simId(mp.html));
|
||||
assert.notEqual(simId(mp.html + ' '), simId(mp.html));
|
||||
assert.match(plain.html, /const SIM_ID=\/\*__SIM_ID__\*\/'';/, 'unstamped in the source');
|
||||
const h = load({ mp: true });
|
||||
t.after(() => h.dom.window.close());
|
||||
assert.equal(h.ev('SIM_ID'), simId(), 'load({mp:true}) is a stamped MP page');
|
||||
assert.equal(h.ev('MP_API'), '/api/mp');
|
||||
assert.deepEqual(h.errors, []);
|
||||
});
|
||||
|
||||
test('the translation check reads the server-play client too: a label used only there counts as used', (t) => {
|
||||
const { page, sourceLabels } = require('../scripts/i18n-check');
|
||||
const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-srv-i18n-'));
|
||||
t.after(() => fs.rmSync(src, { recursive: true, force: true }));
|
||||
fs.cpSync(path.join(ROOT, 'src'), src, { recursive: true });
|
||||
fs.writeFileSync(path.join(src, 'game', '98-server-play', '50-t1-label.js'), "function srvProbe(){return tr('zzsrv.probe_label');}\n");
|
||||
assert.equal(sourceLabels(page(src)).labels.has('zzsrv.probe_label'), true, 'the checked page has the MP-only folder');
|
||||
assert.equal(assemble({ src }).html.includes('zzsrv.probe_label'), false, 'and the plain page still has none of it');
|
||||
});
|
||||
|
||||
test('a new POP has its router in its state from the start: a reload keeps the one play had, even under a port it cannot take', (t) => {
|
||||
// Before canonical state a POP had no rgen until a reload inferred one from its ports: founding an exchange (a tier-2
|
||||
// port, which foundIx does not check against the router) and reloading gave a free router upgrade. Play always read
|
||||
// the basic router (RG[p.rgen||0]); now the state says so, and a reload keeps it.
|
||||
const { ev, errors, dom } = load({ seed: 9 });
|
||||
t.after(() => dom.window.close());
|
||||
const out = JSON.parse(ev(`${pin}UI.pitched=true;ACT.start({});closeModal();S.cash=1e8;S.lvl=6;let c=null;
|
||||
for(const x of Object.keys(CITY)){if(S.pops[x]||!cityOn(x)||cnCity(x))continue;ACT.buildPop({city:x});closeModal();if(S.pops[x]&&!foundIxWhy(x)){c=x;break;}}
|
||||
ACT.foundIx({city:c});closeModal();const u=uidN,r=S.rng,back=migrate(JSON.parse(JSON.stringify(packSave(S))));uidN=u;S.rng=r;
|
||||
JSON.stringify({c,live:S.pops[c].rgen,ix:S.ixp[c],reload:back.pops[c].rgen,maxP:RG[0].maxP})`));
|
||||
assert.ok(out.c, 'a city to found an exchange in');
|
||||
assert.equal(out.live, 0, 'the basic router, written down');
|
||||
assert.ok(out.ix > out.maxP, 'an exchange port above what that router takes (foundIx does not check it: its own owner\'s to decide)');
|
||||
assert.equal(out.reload, 0, 'a reload keeps the router play had');
|
||||
// An old save's POP without the field still gets the router its ports need.
|
||||
assert.equal(ev(`(()=>{const s=JSON.parse(JSON.stringify(S));delete s.pops[${lit(out.c)}].rgen;const u=uidN,r=S.rng;try{return migrate(s).pops[${lit(out.c)}].rgen;}finally{uidN=u;S.rng=r;}})()`) > 0, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
|
@ -37,7 +37,8 @@ test('kit is all-or-nothing, rejects stale quotes and handles missing PoPs', t =
|
|||
ev("ACT.utilityKit({city:'fra',cost:quote})");
|
||||
assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
|
||||
assert.equal(ev('S.cash'), ev('quote-1'));
|
||||
ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+1,modal:true})");
|
||||
// A quote a whole part of the kit away is stale (a day's price drift, within 1%, is not: server-sim-prereqs).
|
||||
ev("S.cash=1e8;ACT.utilityKit({city:'fra',cost:quote+GEN_COST,modal:true})");
|
||||
assert.equal(ev('JSON.stringify(S.pops.fra)'), before);
|
||||
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
|
||||
ev("ACT.utilityKit({city:'not-a-city',cost:0});ACT.utilityKit({city:'ams',cost:0})");
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue