One calendar for a server session (the user's answer to Q1): a network that joins begins on the session's date, and one that joins after day 180, when the shared market starts to move, gets a head start (answered 2026-11-11). Dormant until the host (T3) passes a start day: in the plain build and in single-device play S.day0 is 0 and the game is as before. - S.day0, the calendar day a network began: 0 in newGame(), repaired in sanitize() (at most S.day), so old saves load. netAge() is the network's age; the first-days rules count it: the charter window (and specSanitize), the tutorial's five days, the DDoS grace and early size cap, route leaks, RPKI, the world's bad news, shortages and control-plane events, sold-out routes, the scrubbing customers, loan offers, the broker's first calls, the Speedrun and Blitz badges and the day counts in the win, lose and Glass Baron windows. The market, the calendar and world events stay on the session's date. - beginState() takes o.day for a session network in Normal mode (lateStart()): the day, the first outage and event, the home POP and the first IPv4 block are stamped with it, so the block cannot be sold on day one at the session's price. - The head start (60-features/81-late-joiners.js): starting cash topped up by the rise in hardware prices (START_CASH x (hwTrend - 1), to $1,000, at most $60k, with the market rule only) and the first 365 days of home broadband matched (R.rev.late: what homes pay after the Australian wholesale cut or levy; outside investors' share, inside revMo). A second welcome with a button to the bank, a Goals card, a bank section, a line in a city's broadband pitch and a toast when the year is over; every label in all six dictionaries. - The "since you started" lines (supply chain, bandwidth market, wave prices) measure from the network's own start. - Server-run engine: srvBegin takes begin.day (an integer from 0, else the begin fails), the fake engine begins there and keeps day0 in its saves, CLOCK.off leaves the shape checker and the contract test, and the fixtures' network begins on day 473 (written again with tests/lib/mp-sim-fixtures.js; a second run changes nothing). - Gameplay rule F11, the agent's day0 doc and status age, ARCHITECTURE and the plans (Q1's game side built, open question 1 answered). - tests/late-joiners.test.js; F11 in tests/gameplay-rules.test.js; a late begin in tests/mp-sim-engine.test.js; one calendar in tests/mp-sim-contract.test.js. Merged onto Starblink and Island Wi-Fi: revMo counts both the islands (V.wisp) and the match (V.late), the revenue share base keeps V.wisp and leaves V.late out; F11 sits before F12 in the gameplay rules and their test; the mp-sim fixtures were written again with tests/lib/mp-sim-fixtures.js (a second run changes nothing).
347 lines
28 KiB
JavaScript
347 lines
28 KiB
JavaScript
// 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 { crawl } = require('./lib/mp-sim-crawl');
|
||
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 });
|
||
// A checkpoint as the host hands it to load(): the save text (the canned network on that day).
|
||
const sv = (day) => JSON.stringify({ ...fixture('snap').S, day });
|
||
|
||
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, []);
|
||
});
|
||
|
||
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', 'mktCfg', 'pathPin']) 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'],
|
||
// Values that name a built-in: written through as a key (S.pops[city]) they reach a prototype.
|
||
[env('launchBB', { city: '__proto__' }), '__proto__ as a city'], [env('addGen', { city: 'constructor' }), 'constructor as a city'], [env('buildPop', { city: 'prototype' }), 'prototype as a city'],
|
||
[env('buildPop', { city: ['fra', '__proto__'] }), '__proto__ in an array'], [env('buildLink', { tier: 1 }, { ui: { pending: { a: '__proto__', b: 'ams' } } }), '__proto__ in a draft'],
|
||
[env('decomGo', {}, { ui: { decom: ['fra', 'constructor'] } }), 'constructor among the cities to close'], [env('orderDf', {}, { ui: { dfSys: 'constructor' } }), 'constructor as a system'],
|
||
// Any name Object.prototype has reads as something there (S.pops.toString is a function, so a POP).
|
||
[env('ptSave', { city: 'toString', k: 'micro' }), 'toString as a city'], [env('popStdSet', { city: 'valueOf' }), 'valueOf as a city'],
|
||
[env('buildPop', { city: ['fra', 'hasOwnProperty'] }), 'hasOwnProperty in an array'], [env('decomGo', {}, { ui: { decom: ['fra', 'toString'] } }), 'toString among the cities to close'],
|
||
// The open window: one the server knows by name, with only its own view state.
|
||
[env('opsTpl', { k: 'bb' }, { ctx: { modal: true, win: { k: 'nope' } } }), 'a window that is none'], [env('opsTpl', { k: 'bb' }, { ctx: { win: 'ops' } }), 'a window as text'],
|
||
[env('opsTpl', { k: 'bb' }, { ctx: { win: { k: 'ops', ui: { pieTab: 'co' } } } }), 'another window\'s view state'], [env('opsTpl', { k: 'bb' }, { ctx: { win: { k: 'ops', x: 1 } } }), 'a window with more'],
|
||
[env('opsTpl', { k: 'bb' }, { ctx: { win: { k: 'ops', ui: { opsCity: '__proto__' } } } }), '__proto__ as the intern\'s POP'], [env('opsTpl', { k: 'bb' }, { ctx: { win: { k: 'ops', ui: { opsCity: { a: 1 } } } } }), 'a POP as an object'],
|
||
[env('opsTpl', { k: 'bb' }, { ctx: { win: { k: 'constructor' } } }), 'constructor as a window'],
|
||
[env('opsTpl', { k: 'bb' }, { ctx: { win: { k: 'ops', ui: { opsCity: 'toString' } } } }), 'toString as the intern\'s POP'],
|
||
]) no('act', b, why);
|
||
assert.equal(ok('act', env('teDeploy', { script: 'x'.repeat(4000) })).ok, true, 'a long script within its cap');
|
||
// Free text may say them: a network named for a word.
|
||
assert.equal(ok('act', env('renameGo', { name: 'constructor' })).ok, true, 'a name is no key');
|
||
assert.equal(ok('act', env('renameGo', { name: 'toString' })).ok, true, 'nor this one');
|
||
// An express of six spans: six link ids as the game mints them (10 or 11 characters each), joined by commas.
|
||
const ids = Array.from({ length: 6 }, (x, i) => 'i' + (2e7 + i).toString(36).slice(-5) + (12345 + i));
|
||
assert.equal(ids.join(',').length > 64, true);
|
||
assert.equal(ok('act', env('xpBuild', { via: ids.join(',') })).ok, true, 'the longest express a player can build');
|
||
for (const win of [{ k: 'ops', ui: { opsCity: 'zrh' } }, { k: 'pie', ui: { pieTab: 'co', pieCity: 'fra' } }, { k: 'routing' }, { k: 'bstd' }, { k: 'charter' }, { k: 'pie', ui: { pieTab: null } }]) {
|
||
assert.equal(ok('act', env('opsTpl', { k: 'bb' }, { ctx: { modal: true, win } })).ok, true, JSON.stringify(win));
|
||
}
|
||
// 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');
|
||
// One calendar for the session: no offsets, and the network in the snapshot is on the clock's day (it joined late).
|
||
assert.ok(!('off' in fixture('clock')), 'the clock carries no calendar offsets');
|
||
assert.equal(fixture('snap').S.day, fixture('clock').day);
|
||
assert.ok(fixture('snap').S.day0 > 0 && fixture('snap').S.day0 < fixture('snap').S.day, 'the canned network began on the session\'s date');
|
||
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/], [{ ...fixture('clock'), off: {} }, /unknown field/],
|
||
];
|
||
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 = [];
|
||
// A network that joins the session on its day 40 begins on it, beside one loaded at 40: one calendar.
|
||
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false, day: 40 }, lang: 'en', prefs: {} }, { nid: b, env: { s: sv(40) }, lang: 'de', prefs: {} }]);
|
||
assert.equal(L.length, 2); assert.ok(L[0].saved, 'a new network is checkpointed at once');
|
||
assert.deepEqual([L[0].day, L[1].day, JSON.parse(L[0].saved.txt).day0], [40, 40, 40]);
|
||
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: 41, speed: 1, last: 1, alone: [], nets: [b, a] });
|
||
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.deepEqual([D.nets[a].day, D.nets[b].day], [41, 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: 42, nets: [a, b] });
|
||
assert.equal(D2.nets[b].lost, true);
|
||
const D3 = await e.day(code, { d: 43, 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);
|
||
// A pulled snapshot is the realm's half; with the host's clock, roster and since it is the stream event.
|
||
const host = { clock: fixture('clock'), roster: fixture('roster'), since: { days: 0, again: 0 } };
|
||
assert.match(checkEvent(JSON.parse(P3.snap)).join(), /clock: missing/, 'the realm\'s half alone is no stream event');
|
||
assert.deepEqual(checkEvent(JSON.parse(e.snapWith(P3.snap, host))), []);
|
||
assert.deepEqual(JSON.parse(e.snapWith(P3.snap, host)).clock, host.clock);
|
||
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: 44, 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: { s: sv(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');
|
||
// Refused the way the engine refuses, with its codes (tests/mp-sim-engine.test.js holds the two to each other).
|
||
const lost = [], X = createFakeEngine({ onLost: (cd, nids, why) => lost.push([cd, ...nids, why].join(' ')) });
|
||
await assert.rejects(X.load(code, []), (x) => x.code === 'ERR');
|
||
await assert.rejects(X.load(code, [net(a), net(a)]), (x) => x.code === 'ERR' && /twice/.test(x.message));
|
||
const [nl] = await X.load(code, [{ nid: a, env: { day: 5 }, lang: 'en', prefs: {} }]);
|
||
assert.equal(nl.err, 'no save to load', 'a checkpoint without its save text');
|
||
await assert.rejects(X.act(code, a, env('buildPop', { city: 'par' })), (x) => x.code === 'NO_REALM');
|
||
await assert.rejects(X.day('N0SVCH', { d: 1, nets: [a] }), (x) => x.code === 'NO_REALM');
|
||
await X.load(code, [net(a)]);
|
||
assert.deepEqual(Object.keys((await X.day(code, { d: 1, nets: [a, b] })).nets), [a], 'a network that is not loaded is left out');
|
||
const G1 = await X.greet(code, a), G2 = await X.greet(code, a);
|
||
assert.deepEqual([typeof G1.upd, G2.upd], ['string', undefined], 'the one-shots of a greet are said once');
|
||
X.failNext('load', 'gaveUp');
|
||
await assert.rejects(X.load('Q9W8E7', [net(c)]), (x) => x.code === 'GAVE_UP');
|
||
// A worker that dies takes every realm, also of a session with nothing pending: its next call answers NO_REALM.
|
||
X.exit();
|
||
assert.deepEqual(lost, [`${code} ${a} exit`]);
|
||
await assert.rejects(X.pull(code, a, {}), (x) => x.code === 'NO_REALM');
|
||
await X.close();
|
||
await assert.rejects(X.load(code, [net(a)]), (x) => x.code === 'CLOSED');
|
||
await assert.rejects(X.pull(code, a, {}), (x) => x.code === 'CLOSED');
|
||
});
|
||
|
||
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, []);
|
||
});
|