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).
244 lines
16 KiB
JavaScript
244 lines
16 KiB
JavaScript
// 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({onLost});
|
|
// 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): one with
|
|
// neither a save (env.s, the save text) nor a begin answers err 'no save to load'; a begin
|
|
// starts on begin.day (the session's date; 0 when it is none)
|
|
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]:{day, lost,
|
|
// pause?, err?, retried?, ms}}}; a network of nets that is not loaded is left out
|
|
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (msg: the request body, 5.8)
|
|
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal:{h, c}, ui?, ms} (the real one may answer neither modal
|
|
// nor err: a what-if that opened nothing)
|
|
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?, ms} (views: [{link} |
|
|
// {peer}]); snap is the realm's half (t, epoch, v, now, S, r, keep): engine.snapWith(snap,
|
|
// {clock, roster, since}) makes the stream event
|
|
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}
|
|
// engine.prefs(code, nid, {prefs}) → undefined; engine.greet(code, nid) → a pulled (an update the first time only:
|
|
// the one-shots a page says on opening)
|
|
// 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.has(code, nid); engine.mem()
|
|
// engine.stats() → {workers, realms, sessions} (not a promise); engine.close() → stops it (every pending call
|
|
// rejects EXIT, every later one CLOSED); engine.simId the build id of src/
|
|
// Rejections, with the real engine's codes: NO_REALM (a network or session that is not loaded: after an exit too, which
|
|
// is how a host learns a network it believes loaded must load again), ERR (a load of nothing, or of a network twice;
|
|
// a day whose nets is not a list), EXIT, GAVE_UP, SIM_DOWN, CLOSED.
|
|
//
|
|
// 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; 'gaveUp' and 'down': it rejects GAVE_UP or
|
|
// SIM_DOWN):
|
|
// 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');
|
|
const { snapWith } = require('../../scripts/lib/mp-sim-engine');
|
|
|
|
const coded = (msg, code) => Object.assign(new Error(msg), { code });
|
|
const CODES = { exit: ['worker exited', 'EXIT'], gaveUp: ['session kept failing its worker', 'GAVE_UP'], down: ['server-run play is down', 'SIM_DOWN'] };
|
|
let SIM = null;
|
|
|
|
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, closed = false;
|
|
const newEpoch = () => 'e' + (++epochN).toString(36);
|
|
const realm = (code, nid) => { const r = realms.get(key(code, nid)); if (!r) throw coded(`no realm ${key(code, nid)}`, 'NO_REALM'); return r; };
|
|
const hasSession = (code) => [...realms.keys()].some((k) => k.startsWith(code + '/'));
|
|
// The day of a save text (the real engine reads the save); else the canned one.
|
|
const dayOf = (s) => { try { const d = JSON.parse(s).day; return Number.isInteger(d) ? d : F.snap.S.day; } catch (e) { return F.snap.S.day; } };
|
|
// The day a save's network began (S.day0), at most its day; 0 for a save that does not say.
|
|
const day0Of = (s, day) => { try { const d = JSON.parse(s).day0; return Number.isInteger(d) && d >= 0 ? Math.min(d, day) : 0; } catch (e) { return 0; } };
|
|
// 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) {
|
|
if (closed) return Promise.reject(coded('engine closed', 'CLOSED'));
|
|
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 (CODES[f.what]) return no(coded(...CODES[f.what]));
|
|
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 });
|
|
};
|
|
// The realm's half of a snapshot: the host adds clock, roster and since with snapWith().
|
|
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({ t: 'snap', epoch: r.epoch, v: r.v, now: Date.now(), S, r: F.snap.r, 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, day0: r.day0, 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 CLOSED = () => Promise.reject(coded('engine closed', 'CLOSED'));
|
|
const engine = {
|
|
calls: [],
|
|
outcome: () => 'applied',
|
|
get simId() { return SIM || (SIM = require('../../scripts/lib/page').simId()); },
|
|
load(code, nets) {
|
|
engine.calls.push(['load', code, nets]);
|
|
if (closed) return CLOSED();
|
|
// Refused whole, as the real engine refuses it: nothing to load, a network without a nid, or one twice.
|
|
if (!Array.isArray(nets) || !nets.length) return Promise.reject(coded('load: give the networks to load', 'ERR'));
|
|
const seen = new Set();
|
|
for (const n of nets) {
|
|
if (!n || typeof n !== 'object' || typeof n.nid !== 'string' || !n.nid) return Promise.reject(coded('load: each network needs a nid', 'ERR'));
|
|
if (seen.has(n.nid)) return Promise.reject(coded(`load: ${n.nid} is there twice`, 'ERR'));
|
|
seen.add(n.nid);
|
|
}
|
|
const one = (n, err) => {
|
|
if (!err && !n.begin && !(n.env && typeof n.env === 'object' && typeof n.env.s === 'string')) err = 'no save to load';
|
|
if (err) { realms.delete(key(code, n.nid)); return { t: 'loaded', nid: n.nid, err }; }
|
|
const day = n.begin ? (Number.isInteger(n.begin.day) ? n.begin.day : 0) : Number.isInteger(n.env.day) ? n.env.day : dayOf(n.env.s);
|
|
const r = { epoch: newEpoch(), v: 0, day, day0: n.begin ? day : day0Of(n.env.s, day), lost: false, broken: false, dirty: false, greeted: 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 }]);
|
|
if (closed) return CLOSED();
|
|
if (!hasSession(code)) return Promise.reject(coded(`no session ${code} here`, 'NO_REALM'));
|
|
if (!Array.isArray(nets)) return Promise.reject(coded('day: nets must be a list', 'ERR'));
|
|
// The networks of the day are fixed when it starts: the loaded ones, in sorted order (others are left out).
|
|
const ids = [...new Set(nets)].filter((n) => typeof n === 'string' && realms.has(key(code, n))).sort();
|
|
const run = (f) => {
|
|
const out = {};
|
|
for (const nid of ids) {
|
|
const r = realms.get(key(code, nid));
|
|
if (!r || 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) => realms.has(key(code, 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, ms: 4 };
|
|
}, 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: '' }, ms: 12 }; }, 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);
|
|
o.ms = 1;
|
|
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), o = { t: 'pulled', nid, epoch: r.epoch };
|
|
// The one-shots a page says on opening (bootNotes) are said once: an update the first time, as a toast.
|
|
if (!r.greeted || r.dirty) o.upd = upd(r, F.day, r.greeted ? {} : { fx: [['toast', { h: 'A courtesy route is up.', k: 'good', a: [], o: null, tick: false }]] });
|
|
r.greeted = true; r.dirty = false; o.v = r.v; o.ms = 1;
|
|
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]);
|
|
if (closed) return CLOSED();
|
|
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);
|
|
},
|
|
has(code, nid) { return realms.has(key(code, nid)); },
|
|
mem() { return Promise.resolve([{ heapUsed: 36e6, heapTotal: 48e6, external: 1e6, rss: 120e6, realms: realms.size }]); },
|
|
stats() { return { workers: 1, realms: realms.size, sessions: new Set([...realms.keys()].map((k) => k.split('/')[0])).size }; },
|
|
close() { engine.exit(); closed = true; return Promise.resolve(); },
|
|
snapWith,
|
|
// 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 = coded('worker exited', 'EXIT');
|
|
for (const j of [...pending]) { pending.delete(j); j.no(e); }
|
|
held.clear();
|
|
// Every realm is gone, also of sessions with no call pending: their next call answers NO_REALM.
|
|
const lost = new Map();
|
|
for (const k of realms.keys()) { const [c, n] = k.split('/'); lost.set(c, [...(lost.get(c) || []), n]); }
|
|
realms.clear();
|
|
if (typeof opts.onLost === 'function') for (const [c, ns] of lost) opts.onLost(c, ns, 'exit');
|
|
},
|
|
realms,
|
|
};
|
|
return engine;
|
|
}
|
|
|
|
module.exports = { createFakeEngine };
|