The review of track T2 found these; each has a test in tests/mp-sim-*.
- Built-ins: an arg, array entry or draft that is '__proto__', 'constructor'
or 'prototype' is refused by the envelope check and again by the realm
(free text may still say them). After every realm call the trampoline
checks the realm's built-ins against what they were at load; a realm
whose built-ins changed answers {srvErr, polluted} and is replaced from
the worker's mark like one that timed out. S as one JSON per key is a
null-prototype object, so the epilogue's for…in never reads a prototype.
- A realm that cannot be built again is never used again: rebuild() tries
once more without the packed R, and when that fails too the network is
dropped (NO_REALM), and the engine tells the host (opts.onLost).
- A mark that fails or runs out of time changes nothing: it clears the old
mark first, the realm is built again from its own save, never from an
older mark, and the reply names the mark. A day rebuilds only from its
own attempt's mark.
- A day whose alone or nets is not a list is refused whole (ERR); a throw
in a load or day step answers that call, never ends the worker.
- An exit counts against the session the worker was running (the worker
says so before each job and step), else as before. Workers of their own
are capped (opts.maxOwn, 4): past that a session is given up.
- A worker that exits before it is ready is started again after a pause
that doubles; after 5 in a row every call answers SIM_DOWN.
- The game text is read and compiled once, in createEngine: a src/ that
does not compile throws there, and every worker, also one started after
an exit, runs the game engine.simId names.
- A damaged route memory never breaks a save that loads (routed from
nothing, logged), and only a server network loads (S.mp.sim, Normal).
- Routing memory (UI.rk, UI.rkR) is kept by the in-place restore and
carried in rt (rk), so a reloaded or rolled-back network skips the same
routings as the one that kept going.
- A fresh realm takes over the fx of the one it replaces (the mark's after
a failed call, all of them after a read): badges, windows and toasts
waiting for a page are not lost to a timeout.
- Windows: the stand-in elements answer querySelector from what was
written (a [data-x] marker) and have a working classList, never the
inert proxy that said every window is open. A request's ctx may name the
open window, ctx.win = {k, ui} (mp-sim-acts.js WINDOWS: bstd, routing,
charter, ops, pie), with the view state only the page holds (the
intern's POP, the pie window's tab and POP), checked in the realm. This
is an addition to the contract of design 5.8 that the page (T4) sends.
The stand-in is hidden again after an act.
- xpBuild's via is a TEXT arg (256): a six-span express fits.
- actDone, askDone and pulled carry ms, the worker time of the call;
engine.mem() and engine.has(code, nid) are public; prefs() passes a
realm's err through; after close() every call rejects CLOSED.
- The fake engine fails as the engine does (NO_REALM, ERR, a load without
a save, a day of an unknown session or naming an unloaded network,
GAVE_UP, SIM_DOWN, CLOSED, onLost), its greet says its one-shots once and
never 'told'; a test runs the same edge calls on both.
- SIM_DRAFT is built from DRAFT_TYPES.
241 lines
16 KiB
JavaScript
241 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'
|
|
// 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; } };
|
|
// 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, 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 ? 0 : Number.isInteger(n.env.day) ? n.env.day : dayOf(n.env.s);
|
|
const r = { epoch: newEpoch(), v: 0, 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 };
|