Server-run engine: review fixes
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.
This commit is contained in:
parent
3b8c331556
commit
9597d89079
11 changed files with 879 additions and 211 deletions
|
|
@ -3,28 +3,36 @@
|
|||
// 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();
|
||||
// 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)
|
||||
// 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}}}
|
||||
// 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}]);
|
||||
// snap is the realm's half (t, epoch, v, now, S, r, keep): engine.snapWith(snap, {clock,
|
||||
// roster, since}) makes the stream event
|
||||
// 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
|
||||
// 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.stats() → {workers, realms, sessions} (not a promise);
|
||||
// engine.close() → stops it (every pending call rejects)
|
||||
// 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):
|
||||
// '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;
|
||||
|
|
@ -36,18 +44,26 @@
|
|||
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;
|
||||
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 new Error(`no realm ${key(code, nid)}`); return r; };
|
||||
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 = () => {
|
||||
|
|
@ -55,7 +71,7 @@ function createFakeEngine(opts = {}) {
|
|||
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 (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}` });
|
||||
|
|
@ -88,15 +104,27 @@ function createFakeEngine(opts = {}) {
|
|||
};
|
||||
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 : (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' };
|
||||
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) } : {}) };
|
||||
};
|
||||
|
|
@ -106,14 +134,18 @@ function createFakeEngine(opts = {}) {
|
|||
},
|
||||
day(code, { d, nets = [] } = {}) {
|
||||
engine.calls.push(['day', code, { d, nets }]);
|
||||
const ids = [...nets].sort();
|
||||
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 = realm(code, nid);
|
||||
if (r.lost || r.broken) continue;
|
||||
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) => !realm(code, x).lost && !realm(code, x).broken)) === nid) {
|
||||
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;
|
||||
|
|
@ -136,12 +168,12 @@ function createFakeEngine(opts = {}) {
|
|||
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 };
|
||||
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: '' } }; }, code, nid);
|
||||
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 }]);
|
||||
|
|
@ -151,6 +183,7 @@ function createFakeEngine(opts = {}) {
|
|||
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);
|
||||
},
|
||||
|
|
@ -161,16 +194,25 @@ function createFakeEngine(opts = {}) {
|
|||
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);
|
||||
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(); return Promise.resolve(); },
|
||||
close() { engine.exit(); closed = true; return Promise.resolve(); },
|
||||
snapWith,
|
||||
// Test controls.
|
||||
lose(code, nid) { realm(code, nid).loseNext = true; },
|
||||
|
|
@ -182,9 +224,14 @@ function createFakeEngine(opts = {}) {
|
|||
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' });
|
||||
const e = coded('worker exited', 'EXIT');
|
||||
for (const j of [...pending]) { pending.delete(j); j.no(e); }
|
||||
held.clear(); realms.clear();
|
||||
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,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -5,7 +5,10 @@
|
|||
// bigScenic() the big fixture as a server network (session marks, dice, its L2 customers on scenic routes),
|
||||
// as live S text; the route-memory problem only shows with scenic circuits (design 4.7, 11)
|
||||
// msg(act, args, more) an act or ask request as a page sends it (envelope-checked, ctx clamped)
|
||||
// ctxOf(ev) the page's ctx: its selection, tab and left list, a desktop viewport
|
||||
// ctxOf(ev, o) the page's ctx: its selection, tab and left list, a desktop viewport; with modal:true also the
|
||||
// open window as the page names it (winOf)
|
||||
// winOf(ev) the page's ctx.win: the open window by mp-sim-acts.js WINDOWS (the first entry whose class is
|
||||
// the window's and whose marker, when it has one, is inside it), with its view state; or null
|
||||
// begin(nid, o) a new network's begin entry for engine.load()
|
||||
// RSIG R with its lazy parts read out, attacks by id (as tests/route-worker.test.js reads it)
|
||||
// checked(r) r, after checkWorker (and checkEvent of the upd/snap inside) found nothing
|
||||
|
|
@ -58,7 +61,15 @@ function msg(act, args = {}, more = {}) {
|
|||
assert.ok(r.ok, `${act}: the page would not send this (${r.error})`);
|
||||
return body;
|
||||
}
|
||||
const ctxOf = (ev, o = {}) => ({ sel: JSON.parse(ev('JSON.stringify(UI.sel)')), tab: ev('UI.tab'), left: ev('UI.left'), modal: false, w: 1024, h: 768, coarse: false, ...o });
|
||||
const winOf = (ev) => JSON.parse(ev(`(()=>{const W=${JSON.stringify(A.WINDOWS)},m=$('modal'),c=$('modalCard');if(m.hidden)return 'null';
|
||||
for(const [k,w] of Object.entries(W))if(m.className===w.c&&(!w.sel||c.querySelector(w.sel))){const ui={};for(const u of w.ui||[])if(typeof UI[u]==='string')ui[u]=UI[u];
|
||||
return JSON.stringify(Object.keys(ui).length?{k,ui}:{k});}
|
||||
return 'null';})()`));
|
||||
const ctxOf = (ev, o = {}) => {
|
||||
const c = { sel: JSON.parse(ev('JSON.stringify(UI.sel)')), tab: ev('UI.tab'), left: ev('UI.left'), modal: false, w: 1024, h: 768, coarse: false, ...o };
|
||||
if (c.modal && !('win' in o)) { const w = winOf(ev); if (w) c.win = w; }
|
||||
return c;
|
||||
};
|
||||
const begin = (nid, o = {}) => ({ nid, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: MP.asn, mp: { ...MP, pid: nid }, tut: false, ...o }, lang: 'en', prefs: {} });
|
||||
|
||||
const RSIG = "(()=>{const o={};for(const k in R)o[k]=R[k];o.ef={};for(const k in R.ef)o.ef[k]=R.ef[k];o.fl=(R.fl||[]).map(f=>[f.c,f.n,f.junk,f.rem,f.gt,f.gi,f.gp,f.gh,f.ti,f.ii]);return JSON.stringify(o,(k,v)=>k==='attack'?(v&&v.id):k==='ports'?undefined:v);})()";
|
||||
|
|
@ -77,4 +88,4 @@ function differs(a, b) {
|
|||
.slice(0, 4).map((k) => `${k}: ${String(JSON.stringify(A2[k])).slice(0, 300)} ≠ ${String(JSON.stringify(B2[k])).slice(0, 300)}`).join('\n');
|
||||
}
|
||||
|
||||
module.exports = { CODE, PID, DEV, MP, T0, STEP, TEST, ROOMY, sim, page, bigScenic, msg, ctxOf, begin, RSIG, checked, differs };
|
||||
module.exports = { CODE, PID, DEV, MP, T0, STEP, TEST, ROOMY, sim, page, bigScenic, msg, ctxOf, winOf, begin, RSIG, checked, differs };
|
||||
|
|
|
|||
|
|
@ -145,14 +145,17 @@ const json = (t) => (v, w, out) => { if (!str(v)) return false; let e; try { e =
|
|||
const snapPart = (v, w, out) => { if (!str(v)) return false; let e; try { e = JSON.parse(v); } catch (x) { return false; } if (!obj(e) || e.t !== 'snap') { out.push(`${w}: not a snap`); return true; } fields(e, SNAP_REALM, w, out); return true; };
|
||||
const subs = mapOf((k) => /^(link|peer):.{1,40}$/.test(k), (v) => obj(v));
|
||||
const epoch = (v) => EPOCH.test(v);
|
||||
const ms = (v) => num(v) && v >= 0;
|
||||
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: [snapPart, 'opt'], subs: [subs, 'opt'] },
|
||||
// ms: the worker's time for the call (mark, realm, update), not the wait behind other calls: the rate limit's measure.
|
||||
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'], ms: [ms, 'opt'] },
|
||||
// Neither modal nor err: the what-if opened nothing (a link that is gone, say); the page shows nothing new.
|
||||
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'], ms: [ms, 'opt'] },
|
||||
pulled: { t: str, nid: (v) => PID.test(v), epoch, v: nat, upd: [json('upd'), 'opt'], snap: [snapPart, 'opt'], subs: [subs, 'opt'], ms: [ms, '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) },
|
||||
|
|
|
|||
|
|
@ -12,7 +12,9 @@ const { lit } = require('../scripts/lib/js-literal');
|
|||
const A = require('../scripts/lib/mp-sim-acts');
|
||||
const { createEngine } = require('../scripts/lib/mp-sim-engine');
|
||||
const { crawl } = require('./lib/mp-sim-crawl');
|
||||
const { TEST, ROOMY, page, bigScenic, msg, ctxOf, begin, checked, differs } = require('./lib/mp-sim-play');
|
||||
const { MP, TEST, ROOMY, page, bigScenic, msg, ctxOf, begin, checked, differs } = require('./lib/mp-sim-play');
|
||||
// A local game made a server network, as the host's import does (5.2): the session's marks, then the save path.
|
||||
const STAMP = `S.mp={...${JSON.stringify(MP)},seq:0,sim:1};`;
|
||||
|
||||
const E = createEngine({ workers: 1, test: TEST, timeouts: ROOMY });
|
||||
test.after(() => E.close());
|
||||
|
|
@ -44,7 +46,7 @@ function pieCo() {
|
|||
P.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e11;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;delete S.done.t1;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=500");
|
||||
P.ev("S.transit=[];S.ixp={};S.peers={};S.pni=[];S.grace=null;for(const n of t1Need())S.pni.push({id:'p'+n.id,net:n.id,city:'fra',tier:2});S.nextFail=1e9;S.nextEvent=1e9;compute()");
|
||||
P.ev("for(const n of NETS)if(!R.reachable[n.id]){if(!S.pops[n.pops[0]])S.pops[n.pops[0]]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S.pni.push({id:'i'+n.id,net:n.id,city:n.pops[0],tier:0});}compute();checkGoals();");
|
||||
P.ev("ACT.buildPop({city:'sin'});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});S.pie.stock=400;closeModal();S.rng=99;uidN=1000;S=migrate(JSON.parse(JSON.stringify(S)));compute();");
|
||||
P.ev("ACT.buildPop({city:'sin'});ACT.pieFound();ACT.pieFactory();ACT.piePad({city:'sin'});S.pie.stock=400;closeModal();S.rng=99;uidN=1000;" + STAMP + "S=migrate(JSON.parse(JSON.stringify(S)));compute();");
|
||||
return P;
|
||||
}
|
||||
// A small network with one transit port, Auto-TE and a script slot: a cap on that transit drops most of its traffic
|
||||
|
|
@ -52,13 +54,13 @@ function pieCo() {
|
|||
function oneUp() {
|
||||
const P = page();
|
||||
P.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=3000");
|
||||
P.ev("ACT.buyTransit({city:'fra',net:NETS.filter(n=>sellsAt(n,'fra')&&n.price)[0].id,tier:1});ACT.coreUp();ACT.coreUp();S.te={on:true,day:S.day,script:''};closeModal();S.rng=99;uidN=1000;S=migrate(JSON.parse(JSON.stringify(S)));compute();");
|
||||
P.ev("ACT.buyTransit({city:'fra',net:NETS.filter(n=>sellsAt(n,'fra')&&n.price)[0].id,tier:1});ACT.coreUp();ACT.coreUp();S.te={on:true,day:S.day,script:''};closeModal();S.rng=99;uidN=1000;" + STAMP + "S=migrate(JSON.parse(JSON.stringify(S)));compute();");
|
||||
P.cap = `cap transit ${P.ev('NETS.find(n=>n.id===S.transit[0].net).name')} at 5 gbps`;
|
||||
return P;
|
||||
}
|
||||
// A Hong Kong and a Shanghai POP and a mainland license: a link between them crosses the border, and may cross it premium.
|
||||
const CROSS = "S.cnLic={state:'ok'};for(const c of ['hkg','sha'])if(!S.pops[c])S.pops[c]={day:0,bb:null,boost:0,down:0,routers:1,gen:false};S=migrate(JSON.parse(JSON.stringify(S)));compute();";
|
||||
const loadInto = async (code, nid, P) => checked((await E.load(code, [{ nid, env: { s: P.ev('JSON.stringify(S)'), uidN: +P.ev('uidN'), rt: null }, lang: 'en', prefs: {} }]))[0]);
|
||||
const loadInto = async (code, nid, P) => { const L = checked((await E.load(code, [{ nid, env: { s: P.ev('JSON.stringify(S)'), uidN: +P.ev('uidN'), rt: null }, lang: 'en', prefs: {} }]))[0]); assert.equal(L.err, undefined, L.err); return L; };
|
||||
|
||||
test('two-click buttons: the first click arms SRV_ARM\'s key (or waits for ok), and confirmed:true on the server is both clicks', async (t) => {
|
||||
const P = rich();
|
||||
|
|
@ -122,9 +124,11 @@ test('repayLoan: armed by its id, repaid by the second click (a network small en
|
|||
});
|
||||
|
||||
/* The UI values an act reads, recorded while it runs (its redraw, after(), and windows left out: they read the page's
|
||||
own state to draw it). Every page-held value it reads must be one of its DRAFTS; each of its DRAFTS is read on one of
|
||||
the paths played here. */
|
||||
const PAGE_HELD = [...new Set([...Object.keys(A.DRAFT_TYPES), 'lmode', 'dfMode', 'drag', 'snap', 'hover', 'vp', 'nf', 'dtab'])];
|
||||
own state to draw it). Every page-held value it reads must be one of its DRAFTS, or the view state of a window (ctx.win,
|
||||
WINDOWS: the window it redraws reads it); each of its DRAFTS is read on one of the paths played here. Page-held: what
|
||||
the drafts are, what only LOCAL acts write (the windows' view state, the PNI sheet's plan), and the map's own. */
|
||||
const WIN_UI = [...new Set(Object.values(A.WINDOWS).flatMap((w) => w.ui || []))];
|
||||
const PAGE_HELD = [...new Set([...Object.keys(A.DRAFT_TYPES), ...WIN_UI, 'pniAll', 'lmode', 'dfMode', 'drag', 'snap', 'hover', 'vp', 'nf', 'dtab'])];
|
||||
test('DRAFTS: the page-held UI values each act reads, all of them', (t) => {
|
||||
const P = rich();
|
||||
t.after(() => P.close());
|
||||
|
|
@ -158,7 +162,7 @@ test('DRAFTS: the page-held UI values each act reads, all of them', (t) => {
|
|||
reads[act] = new Set([...(reads[act] || []), ...JSON.parse(ev('JSON.stringify(__unspy())'))]);
|
||||
ev('[after,openModal,renderAll,renderPanel,renderLeft,renderHUD,renderHint,renderDash,renderBank]=__keep;closeModal();');
|
||||
}
|
||||
const extra = [...reads[act]].filter((k) => PAGE_HELD.includes(k) && !A.DRAFTS[act].includes(k));
|
||||
const extra = [...reads[act]].filter((k) => PAGE_HELD.includes(k) && !A.DRAFTS[act].includes(k) && !WIN_UI.includes(k));
|
||||
assert.deepEqual(extra, [], `${act} reads page-held UI that is not in its DRAFTS`);
|
||||
}
|
||||
for (const act of Object.keys(A.DRAFTS)) {
|
||||
|
|
@ -213,6 +217,65 @@ test('drafts and texts: the server\'s run of each draft and text act leaves the
|
|||
assert.equal(T.ev("S.log.slice(0,3).some(x=>/AI apologises/.test(x.t))"), true, 'the slop path');
|
||||
assert.deepEqual(T.errors, []);
|
||||
});
|
||||
/* A click inside a window (the page sends it with ctx.modal, and ctx.win names the window): the server redraws that
|
||||
window as the page does, never another one (a stand-in that said every window is open had a rocket company's click
|
||||
answer with the routing window, and the intern's with the build standard), with the view state only the page holds
|
||||
(the intern's POP, the pie window's tab and POP). Every sent button in the windows: the window the page shows after
|
||||
its own click against the act's ui.modal or ui.closed, and the network after it. */
|
||||
test('a click inside a window: the server answers with the window the page shows, its view state and all', async (t) => {
|
||||
const P = rich(), Q = pieCo();
|
||||
t.after(() => { P.close(); Q.close(); });
|
||||
await loadInto('W1NDW5', 'wind0001', P);
|
||||
await loadInto('P1EW1N', 'piew0001', Q);
|
||||
const lastPop = "Object.keys(S.pops).sort((a,b)=>CITY[a].name.localeCompare(CITY[b].name)).at(-1)";
|
||||
const sets = [
|
||||
[P, 'W1NDW5', 'wind0001', [['opsOpen', {}, ''], ['opsOpen', {}, `ACT.opsCity({v:${lastPop}})`], ['utilities', { city: 'fra' }, ''], ['bstdOpen', {}, ''],
|
||||
['pniAllOpen', { net: null }, ''], ['salesOpen', {}, ''], ['routingOpen', {}, ''], ['models', {}, ''], ['teEdit', {}, ''], ['ip4Open', {}, '']]],
|
||||
[Q, 'P1EW1N', 'piew0001', ['traffic', 'co', 'fly', 'dish'].map((tab) => ['pieOpen', {}, `ACT.pieTab({t:'${tab}'});ACT.pieCity({v:${lastPop}})`])],
|
||||
];
|
||||
const kind = (h) => (/data-routing/.test(h) ? 'routing' : /data-sheet="bstd"/.test(h) ? 'bstd' : (/<h2[^>]*>([^<]{0,40})/.exec(h) || [, '?'])[1].trim());
|
||||
let n = 0;
|
||||
const wins = new Set(), seenUi = new Set();
|
||||
for (const [X, code, nid, openers] of sets) {
|
||||
const { ev } = X;
|
||||
ev("window.__mh=null;{const om=openModal;openModal=function(h,c){__mh=String(h);return om.apply(this,arguments);};}");
|
||||
const open = (o, x, setup) => ev(`closeModal();UI.confirm=null;ACT[${JSON.stringify(o)}](${JSON.stringify(x)});${setup};__mh=null;`);
|
||||
for (const [o, x, setup] of openers) {
|
||||
open(o, x, setup);
|
||||
if (ev("$('modal').hidden")) continue;
|
||||
const seen = new Set();
|
||||
const btns = JSON.parse(ev("JSON.stringify([...$('modal').querySelectorAll('[data-act],[data-chg]')].map(el=>{const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){}if(el.dataset.chg)a={...a,v:el.value};return [act,a];}))"));
|
||||
for (const [act, args] of btns) {
|
||||
// (Two-click, draft and text acts have their own tests: a text button reads its field, which the page sends.)
|
||||
if (!A.SEND.includes(act) || A.CONFIRM[act] || A.DRAFTS[act] || (A.TEXT[act] && Object.keys(A.TEXT[act]).some((k) => !(k in args))) || seen.has(act)) continue;
|
||||
seen.add(act);
|
||||
open(o, x, setup);
|
||||
const ctx = ctxOf(ev, { modal: true });
|
||||
if (ctx.win) { wins.add(ctx.win.k); for (const k of Object.keys(ctx.win.ui || {})) seenUi.add(k); }
|
||||
try { ev(`ACT[${JSON.stringify(act)}](${JSON.stringify(args)})`); } catch (e) { /* compared all the same */ }
|
||||
const pageWin = ev("$('modal').hidden") ? 'closed' : ev('__mh') || 'unchanged';
|
||||
const r = checked(await E.act(code, nid, msg(act, args, { ctx })));
|
||||
const ui = r.upd ? JSON.parse(r.upd).acts[0].ui : {};
|
||||
const srvWin = ui.modal ? ui.modal.h : ui.closed ? 'closed' : 'unchanged';
|
||||
n++;
|
||||
const name = (w) => (w === 'closed' || w === 'unchanged' ? w : kind(w));
|
||||
assert.ok(srvWin === pageWin, `${o} → ${act} ${JSON.stringify(args)}: the page shows ${name(pageWin)}, the server ${name(srvWin)}${name(pageWin) === name(srvWin) ? ' (another drawing of it)' : ''}`);
|
||||
const want = ev('JSON.stringify(S)'), got = (await E.eval(code, nid, 'return JSON.stringify(S)')).value;
|
||||
assert.ok(want === got, `${act}:\n${want === got ? '' : differs(want, got)}`);
|
||||
}
|
||||
}
|
||||
// The stand-in is no window once the act is done.
|
||||
assert.deepEqual((await E.eval(code, nid, "return [$('modal').hidden,$('modal').className,$('modalCard').innerHTML]")).value, [true, '', '']);
|
||||
assert.deepEqual(X.errors, []);
|
||||
}
|
||||
t.diagnostic(`${n} buttons inside windows sent`);
|
||||
assert.ok(n >= 30, `${n} buttons`);
|
||||
assert.deepEqual([...wins].sort(), ['bstd', 'ops', 'pie', 'routing'], 'the windows the page named');
|
||||
assert.deepEqual([...seenUi].sort(), [...WIN_UI].sort(), 'and their view state');
|
||||
// Every view state a window carries is checked in the realm before it is set.
|
||||
assert.deepEqual((await E.eval('W1NDW5', 'wind0001', 'return Object.keys(SIM_WINOK).sort()')).value, [...WIN_UI].sort());
|
||||
});
|
||||
|
||||
async function play(code, nid, ev, plays) {
|
||||
for (const [act, args, before, ui] of plays) {
|
||||
ev(before);
|
||||
|
|
|
|||
|
|
@ -16,6 +16,8 @@ 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.
|
||||
|
|
@ -94,8 +96,26 @@ test('the envelope check refuses what section 10 refuses', () => {
|
|||
[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'],
|
||||
// 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'],
|
||||
]) 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');
|
||||
// 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 } });
|
||||
|
|
@ -163,7 +183,7 @@ test('the canned state is the game\'s own: migrate() keeps the snapshot and ever
|
|||
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: {} }]);
|
||||
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: { s: sv(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);
|
||||
|
|
@ -215,7 +235,7 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
|
|||
});
|
||||
|
||||
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: {} });
|
||||
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);
|
||||
|
|
@ -254,6 +274,27 @@ test('the fake engine fails the way the engine does: a network that does not loa
|
|||
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) => {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@
|
|||
// - Retry: a day that fails once (a throw, and a timeout, both after the day's DDoS step with an attack on, the networks
|
||||
// busy) leaves the same network as no failure.
|
||||
// - Order: three networks of a session, in two different realm orders, each the same.
|
||||
// - Routing memory: a checkpoint taken between an act and the next day, and an act rolled back, keep what the game
|
||||
// remembers of its last routing (UI.rk, UI.rkR): the next click that changes nothing routing reads routes in neither,
|
||||
// as in the network that kept going (compute() is not always a fixed point, so a routing there could change R).
|
||||
// - Market and moved customers (3.2.0, 3.3.0): the market's settings and a customer moved to another fiber or pinned
|
||||
// to a path, then days of sales, against the page and under the strict gate; a checkpoint of it plays on the same.
|
||||
// - Timer audit and gate: days with failures, events, the intern on every order and the sales desk on auto, then every
|
||||
|
|
@ -195,6 +198,35 @@ test('retry: a day that throws, or times out, once after the DDoS step with an a
|
|||
await E.unload(code);
|
||||
});
|
||||
|
||||
test('routing memory: after a checkpoint between an act and the next day, or an act rolled back, a click that changes nothing routing reads routes in neither network', async () => {
|
||||
const code = 'RKMEM0', base = 'rkbs0001', copy = 'rkcp0002';
|
||||
const ev = async (nid, src) => (await E.eval(code, nid, src)).value;
|
||||
checked((await E.load(code, [begin(base)]))[0]);
|
||||
await day(code, 1, [base]);
|
||||
assert.equal(checked(await E.act(code, base, msg('launchBB', { city: 'fra' }))).outcome, 'applied');
|
||||
// The checkpoint, right after an act that routed, in a fresh realm.
|
||||
const sv = checked(await E.save(code, base));
|
||||
assert.equal(sv.rt.rk, true, 'the checkpoint says R is the routing of S as it is');
|
||||
checked((await E.load(code, [{ nid: copy, env: { s: sv.txt, uidN: sv.uidN, rt: sv.rt }, lang: 'en', prefs: {} }]))[0]);
|
||||
await ev(copy, `__srvClock(${await ev(base, 'return __srvClock()')});return 1;`);
|
||||
const COUNT = '{const c=compute;compute=function(){__cc++;return c.apply(this,arguments);};}window.__cc=0;return 1;';
|
||||
for (const n of [base, copy]) await ev(n, COUNT);
|
||||
for (const n of [base, copy]) assert.equal(checked(await E.act(code, n, msg('renameGo', { name: 'Tubular Bells' }))).outcome, 'applied');
|
||||
assert.deepEqual([await ev(base, 'return __cc'), await ev(copy, 'return __cc')], [0, 0], 'a click that changes nothing routing reads');
|
||||
{ const x = await realmS(code, base), y = await realmS(code, copy); assert.ok(x === y, differs(x, y)); }
|
||||
// An act that routes, then throws: back in place, what the game remembers of its routing with it.
|
||||
const net = await ev(base, "return NETS.filter(n=>sellsAt(n,'fra')&&!S.transit.some(t=>t.city==='fra'&&t.net===n.id))[0].id");
|
||||
await ev(base, "{const f=ACT.buyTransit;ACT.buyTransit=a=>{f(a);throw new Error('after its routing');};}return 1;");
|
||||
const r = checked(await E.act(code, base, msg('buyTransit', { city: 'fra', net, tier: 1 })));
|
||||
assert.equal(r.outcome, 'error');
|
||||
assert.ok(await ev(base, 'return __cc') > 0, 'the act that failed had routed');
|
||||
for (const n of [base, copy]) await ev(n, '__cc=0;return 1;');
|
||||
for (const n of [base, copy]) checked(await E.act(code, n, msg('renameGo', { name: 'Packet Pals' })));
|
||||
assert.deepEqual([await ev(base, 'return __cc'), await ev(copy, 'return __cc')], [0, 0], 'nor after an act rolled back');
|
||||
{ const x = await realmS(code, base), y = await realmS(code, copy); assert.ok(x === y, differs(x, y)); }
|
||||
await E.unload(code);
|
||||
});
|
||||
|
||||
test('order: three networks of a session play the same in either realm order', async () => {
|
||||
// The same three networks under ids that sort the other way round: X, Y, Z here are Z, Y, X there.
|
||||
const X = { home: 'fra' }, Y = { home: 'nyc', preset: 'bgp' }, Z = { home: 'sin', preset: 'freeze' };
|
||||
|
|
|
|||
|
|
@ -5,8 +5,17 @@
|
|||
// everything back; actions report only the UI they changed; a session's day holds back loads; unwatched networks stay
|
||||
// bounded; realms do not share their intrinsics; every call is answered, whatever a load holds; and a session whose load
|
||||
// takes its worker down gets a worker of its own, then is given up, while the others keep their places.
|
||||
// Review fixes: an arg that names a built-in is refused, and a realm whose built-ins changed is replaced; a mark that
|
||||
// runs out of time undoes nothing; a fresh realm takes over the fx waiting for a page; a network whose realm cannot be
|
||||
// built again is dropped and the host told; a day with bad lists is refused, never the worker's end; an exit blames the
|
||||
// session that was running; a worker that cannot start backs off, then SIM_DOWN; the game is read once (a src/ that
|
||||
// does not compile fails at start, a respawned worker runs the same game); a damaged route memory still loads, a save
|
||||
// that is no server network does not; and the fake engine answers the same edge calls with the same codes.
|
||||
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 { createEngine, snapWith } = require('../scripts/lib/mp-sim-engine');
|
||||
const { checkEvent, checkFx, fixture } = require('./lib/mp-sim-shape');
|
||||
const { MP, TEST, ROOMY, bigScenic, msg, begin, checked } = require('./lib/mp-sim-play');
|
||||
|
|
@ -44,6 +53,7 @@ test('a new network: begin, a snapshot, its welcome, actions, days, a what-if, v
|
|||
// Actions: the update with the result is version v; the tutorial moves on the server.
|
||||
const a1 = checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
|
||||
assert.deepEqual([a1.outcome, a1.v, a1.epoch], ['applied', 2, L.epoch]);
|
||||
assert.ok(a1.ms > 0 && G.ms >= 0, 'the worker time of a call, for the rate limit');
|
||||
const u1 = updOf(a1);
|
||||
assert.equal(u1.from, 1);
|
||||
assert.deepEqual(u1.acts.map((x) => x.rid), [JSON.parse(JSON.stringify(a1.rid))]);
|
||||
|
|
@ -369,17 +379,236 @@ test('a session whose load takes its worker down: twice, a worker of its own; on
|
|||
} finally { await W.close(); }
|
||||
});
|
||||
|
||||
test('a polluted prototype stays in its own realm', async () => {
|
||||
test('a polluted prototype stays in its own realm, and that realm is replaced at its next call', async () => {
|
||||
const code = 'P0WWVT', a = 'poll0001', b = 'poll0002';
|
||||
(await E.load(code, [begin(a), begin(b)])).forEach(checked);
|
||||
const ep = checked(await E.pull(code, a, {})).epoch;
|
||||
assert.equal(await ev(code, a, 'Object.prototype.polluted=1;Array.prototype.evil=()=>1;return ({}).polluted'), 1);
|
||||
assert.deepEqual(await ev(code, b, 'return [({}).polluted===undefined,[].evil===undefined]'), [true, true]);
|
||||
assert.equal(({}).polluted, undefined, 'nor the host');
|
||||
const D = await day(code, 1, [a, b]);
|
||||
assert.deepEqual([D.nets[a].day, D.nets[b].day], [1, 1]);
|
||||
assert.deepEqual([D.nets[a].day, D.nets[a].retried, D.nets[b].day, D.nets[b].retried], [1, true, 1, undefined]);
|
||||
assert.notEqual(checked(await E.pull(code, a, {})).epoch, ep, 'a fresh realm');
|
||||
assert.deepEqual(await ev(code, a, 'return [({}).polluted===undefined,[].evil===undefined]'), [true, true]);
|
||||
await E.unload(code);
|
||||
});
|
||||
|
||||
test('an arg that names a built-in is refused; an act that changes the built-ins all the same leaves a fresh realm and the network as before', async () => {
|
||||
const code = 'PR0T0S', nid = 'prot0001';
|
||||
checked((await E.load(code, [begin(nid)]))[0]);
|
||||
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
|
||||
const ep = checked(await E.pull(code, nid, {})).epoch;
|
||||
// The envelope refuses it (tests/mp-sim-contract.test.js); a body that got past it, the realm refuses too.
|
||||
const r0 = checked(await E.act(code, nid, { ...msg('launchBB', { city: 'ams' }), args: { city: '__proto__' } }));
|
||||
assert.deepEqual([r0.outcome, r0.why], ['rejected', 'an arg names a built-in']);
|
||||
assert.equal(await ev(code, nid, 'for(const k in {})return k;return null;'), null);
|
||||
// An act that writes through a prototype all the same (by hand here): the reply says so, the realm that saw it is
|
||||
// never used again, and the network is as it was before the act.
|
||||
const s0 = await ev(code, nid, 'return JSON.stringify(S)');
|
||||
await ev(code, nid, '{const f=ACT.buildPop;ACT.buildPop=a=>{f(a);Object.prototype.bb={d:null};};}return 1;');
|
||||
const r1 = checked(await E.act(code, nid, msg('buildPop', { city: 'ams' })));
|
||||
assert.deepEqual([r1.t, r1.what, /built-ins of the realm changed: Object\.prototype\.bb/.test(r1.msg)], ['err', 'throw', true]);
|
||||
const P = checked(await E.pull(code, nid, { snap: true }));
|
||||
assert.notEqual(P.epoch, ep, 'a fresh realm');
|
||||
assert.equal(await ev(code, nid, 'return JSON.stringify(S)'), s0, 'the act undone');
|
||||
assert.equal(await ev(code, nid, "for(const k in {})return k;return ACT.buildPop.toString().includes('prototype')"), false, 'clean, with the game\'s own act');
|
||||
assert.equal(checked(await E.act(code, nid, msg('buildPop', { city: 'ams' }))).outcome, 'applied', 'and it plays on');
|
||||
// One that also throws (its finally blocks ran: S went back in place, the prototype did not): the same.
|
||||
await ev(code, nid, "{const f=ACT.buildPop;ACT.buildPop=a=>{f(a);Array.prototype.evil=1;throw new Error('and threw');};}return 1;");
|
||||
const r2 = checked(await E.act(code, nid, msg('buildPop', { city: 'dus' })));
|
||||
assert.deepEqual([r2.t, /Array\.prototype\.evil/.test(r2.msg)], ['err', true]);
|
||||
assert.deepEqual(await ev(code, nid, "for(const k in [])return k;return [!!S.pops.ams,!!S.pops.dus]"), [true, false]);
|
||||
await E.unload(code);
|
||||
});
|
||||
|
||||
test('a mark that runs out of time changes nothing: no applied action or day is undone, and the reply names the mark', async (t) => {
|
||||
const W = createEngine({ workers: 1, test: TEST, timeouts: { ...ROOMY, mark: 300 } });
|
||||
t.after(() => W.close());
|
||||
const { ev } = on(W);
|
||||
const code = 'MARKT0', nid = 'mark0001';
|
||||
checked((await W.load(code, [begin(nid)]))[0]);
|
||||
assert.equal(checked(await W.act(code, nid, msg('buildPop', { city: 'ams' }))).outcome, 'applied');
|
||||
checked(await W.day(code, { d: 1, nets: [nid] }));
|
||||
const ep = checked(await W.pull(code, nid, {})).epoch;
|
||||
await ev(code, nid, 'srvMark=function(){for(;;){}};return 1;');
|
||||
const r = checked(await W.act(code, nid, msg('buildPop', { city: 'dus' })));
|
||||
assert.deepEqual([r.t, r.what, r.msg], ['err', 'timeout', 'marking the network took longer than 300 ms']);
|
||||
assert.deepEqual(await ev(code, nid, 'return [S.day,!!S.pops.ams,!!S.pops.dus]'), [1, true, false], 'what was applied stays');
|
||||
assert.notEqual(checked(await W.pull(code, nid, {})).epoch, ep, 'built again from its own save');
|
||||
// A day whose mark runs out of time: built again from its own save, and the day plays in the fresh realm.
|
||||
await ev(code, nid, 'srvMark=function(){for(;;){}};return 1;');
|
||||
const D = checked(await W.day(code, { d: 2, nets: [nid] }));
|
||||
assert.deepEqual([D.nets[nid].day, D.nets[nid].retried, D.nets[nid].err], [2, true, undefined]);
|
||||
assert.deepEqual(await ev(code, nid, 'return [S.day,!!S.pops.ams]'), [2, true]);
|
||||
});
|
||||
|
||||
test('a fresh realm after a timeout takes over the fx waiting for a page: badges, windows and toasts', async (t) => {
|
||||
const W = createEngine({ workers: 1, test: TEST, timeouts: { ...ROOMY, day: 600, act: 400 } });
|
||||
t.after(() => W.close());
|
||||
const { ev } = on(W);
|
||||
const code = 'FXKEEP', nid = 'fxkp0001';
|
||||
checked((await W.load(code, [begin(nid)]))[0]);
|
||||
checked(await W.pull(code, nid, { snap: true }));
|
||||
const ep = checked(await W.pull(code, nid, {})).epoch;
|
||||
const waiting = (id) => `srvFx(['badge',{id:'${id}',v:'oncall'}]);showWin();toast('still waiting');`;
|
||||
const kept = (P) => { const k = JSON.parse(P.snap).keep.map((f) => (f[0] === 'badge' ? 'badge:' + f[1].id : f[0] + ':' + f[1])); return k; };
|
||||
// A day that runs out of time once (the fx were waiting before it), then plays in a fresh realm.
|
||||
await ev(code, nid, waiting('probe') + '{const f=ddosTick;let once=true;ddosTick=function(){f();if(once){once=false;for(;;){}}};}return 1;');
|
||||
const D = checked(await W.day(code, { d: 1, nets: [nid] }));
|
||||
assert.deepEqual([D.nets[nid].day, D.nets[nid].retried], [1, true]);
|
||||
const P = checked(await W.pull(code, nid, { snap: true }));
|
||||
assert.notEqual(P.epoch, ep);
|
||||
assert.ok(kept(P).includes('badge:probe') && kept(P).includes('modal:win'), `kept: ${kept(P)}`);
|
||||
assert.ok(JSON.parse(P.upd).fx.some(([k, p]) => k === 'toast' && p.h === 'still waiting'), 'and the toast');
|
||||
// An action that runs out of time: the same, and its own fx are not among them.
|
||||
await ev(code, nid, waiting('probe2') + "ACT.buildPop=()=>{toast('mine');for(;;){}};return 1;");
|
||||
const r = checked(await W.act(code, nid, msg('buildPop', { city: 'ams' })));
|
||||
assert.deepEqual([r.t, r.what], ['err', 'timeout']);
|
||||
const P2 = checked(await W.pull(code, nid, { snap: true }));
|
||||
assert.notEqual(P2.epoch, P.epoch);
|
||||
assert.deepEqual(kept(P2), ['badge:probe2', 'modal:win']);
|
||||
const fx2 = JSON.parse(P2.upd).fx;
|
||||
assert.ok(fx2.some(([k, p]) => k === 'toast' && p.h === 'still waiting') && !fx2.some(([k, p]) => k === 'toast' && p.h === 'mine'));
|
||||
});
|
||||
|
||||
test('a network whose realm cannot be built again is dropped: the host is told, its calls answer NO_REALM, the others play on', async (t) => {
|
||||
const lost = [];
|
||||
const W = createEngine({ workers: 1, test: TEST, timeouts: { ...ROOMY, act: 400 }, onLost: (c, nids, why) => lost.push([c, nids, why]) });
|
||||
t.after(() => W.close());
|
||||
const { ev } = on(W);
|
||||
const code = 'DR0PPD', a = 'lost0001', b = 'lost0002';
|
||||
(await W.load(code, [begin(a), begin(b)])).forEach(checked);
|
||||
// Its marks are no saves that load (as a corrupt state would be), and an act runs for ever inside opsQuiet.
|
||||
await ev(code, a, "{const m0=srvMark;srvMark=function(i){const r=m0(i);return r.slice(0,r.indexOf('\\n'))+'\\n{\"cash\":';};}ACT.buildPop=()=>opsQuiet(()=>{for(;;){}});return 1;");
|
||||
const r = checked(await W.act(code, a, msg('buildPop', { city: 'ams' })));
|
||||
assert.deepEqual([r.t, r.what, /the network was dropped/.test(r.msg)], ['err', 'timeout', true]);
|
||||
assert.deepEqual(lost.map(([c, nids]) => [c, nids]), [[code, [a]]]);
|
||||
assert.match(lost[0][2], /rebuilding the realm failed/);
|
||||
assert.deepEqual([W.has(code, a), W.has(code, b)], [false, true]);
|
||||
await assert.rejects(W.pull(code, a, {}), (e) => e.code === 'NO_REALM');
|
||||
await assert.rejects(W.act(code, a, msg('buildPop', { city: 'ams' })), (e) => e.code === 'NO_REALM');
|
||||
assert.deepEqual(Object.keys(checked(await W.day(code, { d: 1, nets: [a, b] })).nets), [b], 'stopped, not playing; the other plays on');
|
||||
// The host loads it again from its checkpoint.
|
||||
checked((await W.load(code, [begin(a)]))[0]);
|
||||
assert.equal(W.has(code, a), true);
|
||||
});
|
||||
|
||||
test('a day with lists that are not lists is refused whole; the worker and its other sessions go on', async () => {
|
||||
const code = 'B4DDAY', nid = 'alon0001', other = 'BYSTD1', o = 'byst0009';
|
||||
checked((await E.load(code, [begin(nid)]))[0]);
|
||||
checked((await E.load(other, [begin(o)]))[0]);
|
||||
const w = E.stats().workers;
|
||||
for (const bad of [{ alone: {} }, { alone: 5 }, { nets: 'x' }]) await assert.rejects(within(E.day(code, { d: 1, nets: [nid], ...bad })), (e) => e.code === 'ERR', JSON.stringify(bad));
|
||||
assert.equal(checked(await within(E.day(code, { d: 1, nets: [nid], alone: [nid, 7] }))).nets[nid].day, 1);
|
||||
checked(await within(E.pull(other, o, {})));
|
||||
assert.deepEqual([E.stats().workers, E.has(other, o)], [w, true]);
|
||||
await E.unload(code); await E.unload(other);
|
||||
});
|
||||
|
||||
test('an exit counts against the session the worker was running, not one whose load waited behind it; own workers are capped', async (t) => {
|
||||
const W = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, maxOwn: 1 });
|
||||
t.after(() => W.close());
|
||||
// Twice: the hog's call runs for ever while another session's load waits behind it, and the worker dies.
|
||||
const hog = async (code, nid) => {
|
||||
for (let i = 0; i < 2; i++) {
|
||||
checked((await W.load(code, [begin(nid)]))[0]);
|
||||
const p = W.eval(code, nid, 'for(;;){}', 60000), q = W.load('J01NER', [begin('join0001')]);
|
||||
for (let k = 0; k < 300 && W.running(0) !== code; k++) await wait(10);
|
||||
assert.equal(W.running(0), code, 'the worker runs the hog');
|
||||
W.kill(0);
|
||||
await assert.rejects(p, (e) => e.code === 'EXIT');
|
||||
await assert.rejects(q, (e) => e.code === 'EXIT');
|
||||
}
|
||||
};
|
||||
await hog('H0G001', 'hogg0001');
|
||||
checked((await W.load('H0G001', [begin('hogg0001')]))[0]);
|
||||
checked((await W.load('J01NER', [begin('join0001')]))[0]);
|
||||
assert.deepEqual([W.dedicated('H0G001'), W.dedicated('J01NER')], [true, false], 'the hog has a worker of its own, the joiner none');
|
||||
// Another like it: no third worker (maxOwn 1), given up.
|
||||
await hog('H0G002', 'hogg0002');
|
||||
await assert.rejects(W.load('H0G002', [begin('hogg0002')]), (e) => e.code === 'GAVE_UP');
|
||||
assert.equal(W.stats().workers, 2);
|
||||
checked(await within(W.pull('J01NER', 'join0001', {}).catch(() => W.load('J01NER', [begin('join0001')]).then((r) => r[0]))));
|
||||
});
|
||||
|
||||
test('a worker that cannot start is not started again at once: after a few tries every call answers SIM_DOWN', async (t) => {
|
||||
const logs = [];
|
||||
const W = createEngine({ workers: 1, test: { ...TEST, startFail: true }, startBackoffMs: 10, log: (l, x) => logs.push(String(x)) });
|
||||
t.after(() => W.close());
|
||||
await assert.rejects(W.load('D0WN00', [begin('down0001')]), (e) => e.code === 'EXIT' || e.code === 'SIM_DOWN');
|
||||
for (let k = 0; k < 200 && !logs.some((x) => /server-run play is down/.test(x)); k++) await wait(50);
|
||||
await assert.rejects(W.load('D0WN00', [begin('down0001')]), (e) => e.code === 'SIM_DOWN');
|
||||
await assert.rejects(W.pull('D0WN00', 'down0001', {}), (e) => e.code === 'SIM_DOWN');
|
||||
await assert.rejects(W.day('D0WN00', { d: 1, nets: [] }), (e) => e.code === 'SIM_DOWN');
|
||||
await wait(300);
|
||||
assert.deepEqual([logs.filter((x) => /could not start/.test(x)).length, logs.filter((x) => /is down/.test(x)).length], [4, 1], 'five starts, then said once');
|
||||
});
|
||||
|
||||
test('the game is read once: a src/ that does not compile fails at start, and a worker started later runs the same game', async (t) => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-sim-src-'));
|
||||
t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
|
||||
fs.cpSync(path.join(__dirname, '..', 'src'), path.join(tmp, 'src'), { recursive: true });
|
||||
const W = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, root: tmp });
|
||||
t.after(() => W.close());
|
||||
assert.equal(W.simId, E.simId, 'the same src/, the same build id');
|
||||
checked((await W.load('SAMEG4', [begin('same0001')]))[0]);
|
||||
// The checkout changes under a running engine (a pull before the restart), and its worker dies.
|
||||
fs.appendFileSync(path.join(tmp, 'src', 'game', '99-loop.js'), '\n;globalThis.__pulled=1;\n');
|
||||
W.kill(0);
|
||||
for (let k = 0; k < 200 && W.stats().realms; k++) await wait(10);
|
||||
checked((await W.load('SAMEG4', [begin('same0001')]))[0]);
|
||||
assert.equal((await W.eval('SAMEG4', 'same0001', 'return typeof globalThis.__pulled')).value, 'undefined', 'the game the engine names, not the one on disk');
|
||||
fs.appendFileSync(path.join(tmp, 'src', 'game', '99-loop.js'), '\n}}}(\n');
|
||||
assert.throws(() => createEngine({ workers: 1, root: tmp }), /does not compile/);
|
||||
});
|
||||
|
||||
test('a checkpoint whose route memory is damaged still loads; a save that is no server network does not', async () => {
|
||||
const code = 'RTDAMG', a = 'rtdm0001';
|
||||
const [L] = await E.load(code, [begin(a)]);
|
||||
checked(L);
|
||||
const s = L.saved.txt, net = (nid, env) => ({ nid, env: { uidN: L.saved.uidN, ...env }, lang: 'en', prefs: {} });
|
||||
const R = await E.load(code, [
|
||||
net('rtdm0002', { s, rt: { efg: { x: { g: [1, 2], v: [1] } } } }),
|
||||
net('rtdm0003', { s: JSON.stringify({ ...JSON.parse(s), mp: null }), rt: null }),
|
||||
net('rtdm0004', { s: JSON.stringify({ ...JSON.parse(s), mode: 'sandbox' }), rt: null }),
|
||||
]);
|
||||
R.forEach(checked);
|
||||
assert.equal(R[0].err, undefined, R[0].err);
|
||||
assert.match(R[1].err, /not a server network/);
|
||||
assert.match(R[2].err, /server networks are Normal games/);
|
||||
assert.equal(checked(await E.day(code, { d: 1, nets: ['rtdm0002'] })).nets.rtdm0002.day, 1);
|
||||
await E.unload(code);
|
||||
});
|
||||
|
||||
test('the fake engine fails as the engine does: the same edge calls, the same codes', async (t) => {
|
||||
const { createFakeEngine } = require('./lib/mp-sim-fake-engine');
|
||||
const lostR = [], lostF = [];
|
||||
const R = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, onLost: (c, n, w) => lostR.push([c, n, w]) });
|
||||
const F = createFakeEngine({ onLost: (c, n, w) => lostF.push([c, n, w]) });
|
||||
t.after(() => R.close());
|
||||
const code = 'PAR1TY', a = 'pari0001', b = 'pari0002';
|
||||
const out = (p) => p.then((r) => (Array.isArray(r) ? r.map((x) => x.err || 'ok') : r && r.t === 'dayDone' ? Object.keys(r.nets) : 'ok'), (e) => 'rejected ' + e.code);
|
||||
const same = async (what, f) => { const x = await out(f(R)), y = await out(f(F)); assert.deepEqual(y, x, what); return x; };
|
||||
assert.equal(await same('an act with no realm', (X) => X.act(code, a, msg('buildPop', { city: 'ams' }))), 'rejected NO_REALM');
|
||||
await same('a load of nothing', (X) => X.load(code, []));
|
||||
await same('a network twice', (X) => X.load(code, [begin(a), begin(a)]));
|
||||
await same('neither a save nor a begin', (X) => X.load(code, [{ nid: a, env: { day: 5 }, lang: 'en', prefs: {} }]));
|
||||
await same('a day of a session that is not here', (X) => X.day('N0SVCH', { d: 1, nets: [a] }));
|
||||
await same('a load', (X) => X.load(code, [begin(a)]));
|
||||
await same('a day naming a network that is not loaded', (X) => X.day(code, { d: 1, nets: [a, b] }));
|
||||
await same('nets that is no list', (X) => X.day(code, { d: 2, nets: 'x' }));
|
||||
assert.deepEqual([R.has(code, a), F.has(code, a)], [true, true]);
|
||||
// A worker that dies: a session with nothing pending loses its realms all the same; its next call answers NO_REALM.
|
||||
R.kill(0); F.exit();
|
||||
for (let k = 0; k < 200 && !lostR.length; k++) await wait(10);
|
||||
assert.deepEqual(lostR, lostF);
|
||||
assert.deepEqual(lostR, [[code, [a], 'exit']]);
|
||||
assert.equal(await same('a call after the worker died', (X) => X.pull(code, a, {})), 'rejected NO_REALM');
|
||||
await R.close(); await F.close();
|
||||
await same('a load after close', (X) => X.load(code, [begin(a)]));
|
||||
assert.equal(await same('a pull after close', (X) => X.pull(code, a, {})), 'rejected CLOSED');
|
||||
});
|
||||
|
||||
test('a worker that exits rejects every call pending on it; the engine goes on with a new one', async () => {
|
||||
const W = createEngine({ workers: 1, test: TEST, timeouts: ROOMY });
|
||||
try {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue