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:
jvanvik 2026-11-09 22:16:52 +01:00
parent 3b8c331556
commit 9597d89079
11 changed files with 879 additions and 211 deletions

View file

@ -458,6 +458,8 @@ const TEXT = {
teCheck: { script: 4000 },
teDeploy: { script: 4000 },
utilityCaches: { quote: 1024 },
// An express's spans, as link ids joined by ',' (up to XP_HOPS = 6 ids of about 10 characters).
xpBuild: { via: 256 },
};
/* Acts that charge a total the player saw in a window, planned again at the click: the arg that carries what the window
@ -472,6 +474,21 @@ const QUOTE = {
utilityKit: 'cost',
};
/* The windows a request's ctx.win may name: the one the page has open when the click came from inside it. The game asks
which window is open by its class and by a marker inside it (pieRe: class 'pie'; bstdShown: [data-sheet="bstd"];
routingRefresh: [data-routing]; charter), so the realm's stand-in has to be that window, or a redraw on the server
opens another one. c: its class (#modal's className); sel: the marker inside #modalCard, if it has one; ui: the view
state it draws from that only the page holds (set by LOCAL acts: the intern window's POP, the pie window's tab and
POP), each checked against the game in the realm. The page names the first entry, in this order, whose c is the open
window's class and whose sel (when it has one) matches inside it; a window none names is sent as ctx.modal alone. */
const WINDOWS = {
bstd: { c: 'ops', sel: '[data-sheet="bstd"]' },
routing: { c: '', sel: '[data-routing]' },
charter: { c: 'charter' },
ops: { c: 'ops', ui: ['opsCity'] },
pie: { c: 'pie', ui: ['pieCity', 'pieTab'] },
};
const ID_RE = /^[a-z0-9]{8,16}$/, SIM_RE = /^[0-9a-f]{12}$/, KEY_RE = /^[A-Za-z][A-Za-z0-9]{0,15}$/, VIEW_RE = /^[a-z0-9]{1,16}$/, SHORT_RE = /^[A-Za-z0-9_.:|~-]{1,40}$/;
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
// The viewport a request's ctx may set on the realm, in CSS pixels: checkEnvelope clamps ctx.w and ctx.h into it.
@ -481,8 +498,10 @@ const SETS = { SEND: new Set(SEND), ASK: new Set(ASK), CONFIRM: new Set(Object.k
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const plain = (o) => !!o && typeof o === 'object' && !Array.isArray(o) && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null);
const prim = (v, cap) => v === null || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= cap);
// Keys a request object may never carry, whatever the regex says.
// Keys a request object may never carry, whatever the regex says; nor values, where a value names something: written
// through as a key (S.pops[city]), they reach a prototype. Free text (TEXT) may say them.
const BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
const badVal = (v) => (typeof v === 'string' ? BAD_KEY.has(v) : Array.isArray(v) ? v.some(badVal) : !!v && typeof v === 'object' && Object.keys(v).some((k) => BAD_KEY.has(k) || badVal(v[k])));
function bad(error, code = 400, extra = {}) { return { ok: false, code, error, ...extra }; }
@ -494,6 +513,7 @@ function checkArgs(act, args) {
for (const k of keys) {
if (!KEY_RE.test(k) || BAD_KEY.has(k)) return `bad arg name ${JSON.stringify(k).slice(0, 40)}`;
const v = args[k], cap = own(caps, k) ? caps[k] : 64;
if (!own(caps, k) && badVal(v)) return `bad arg ${k}`;
if (Array.isArray(v)) { if (v.length > 64 || !v.every((x) => prim(x, 64))) return `bad arg ${k}`; continue; }
if (!prim(v, cap)) return `bad arg ${k}`;
}
@ -502,6 +522,7 @@ function checkArgs(act, args) {
}
function checkDraft(k, v) {
const t = DRAFT_TYPES[k];
if (badVal(v)) return false;
if (Array.isArray(t)) return t.includes(v);
if (t === 'boolean') return typeof v === 'boolean';
if (t === 'string') return typeof v === 'string' && v.length <= 64;
@ -521,6 +542,12 @@ function checkCtx(c) {
// The page sends its innerWidth/innerHeight as they are: a 5120-px monitor, or a desktop zoomed out, is wider than
// anything the layout tells apart (isPhone() and the like only ask whether it is under about 760). Clamped, not refused.
else if (k === 'w' || k === 'h') { if (!(typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1e5)) return `bad ctx.${k}`; c[k] = Math.min(VIEW_MAX, Math.max(VIEW_MIN, v)); }
// The open window, by name, with its view state (WINDOWS): {k, ui?}.
else if (k === 'win') {
const W = plain(v) && typeof v.k === 'string' && own(WINDOWS, v.k) ? WINDOWS[v.k] : null;
if (!W || !Object.keys(v).every((x) => x === 'k' || x === 'ui')) return 'bad ctx.win';
if (v.ui !== undefined && !(plain(v.ui) && Object.keys(v.ui).every((u) => (W.ui || []).includes(u) && (v.ui[u] === null || (typeof v.ui[u] === 'string' && SHORT_RE.test(v.ui[u]) && !BAD_KEY.has(v.ui[u])))))) return 'bad ctx.win.ui';
}
else return `unknown ctx.${String(k).slice(0, 20)}`;
}
return null;
@ -586,4 +613,4 @@ function checkEnvelope(kind, body, opts = {}) {
// Body size caps per kind, in bytes (section 10), for the host's readJson.
const BODY_MAX = { act: 16384, ask: 8192, here: 2048, prefs: 1024, vote: 256 };
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, WINDOWS, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };

View file

@ -3,7 +3,7 @@
// (scripts/lib/mp-sim.js) keeps the clock, presence and votes, and asks this for days, actions, what-ifs and pulls.
// tests/lib/mp-sim-fake-engine.js has the same API with canned answers.
//
// const engine = createEngine({workers: 2, heapMb: 1536, root, log});
// const engine = createEngine({workers: 2, heapMb: 1536, root, log, maxOwn: 4, onLost});
// engine.load(code, [{nid, env?, begin?, lang, prefs, rng?}]) → [{t:'loaded', nid, epoch, day, lost, saved?} |
// {t:'loaded', nid, err}], one per network, in order. env: the checkpoint envelope {s, uidN, rt, last,
// day} (s: the save text; rt: what the realm needs besides it to play on exactly as before, opaque
@ -14,36 +14,53 @@
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]: {day, lost,
// pause?, err?, retried?, ms}}}. Each network in sorted order; one that failed twice answers err and
// its day as it was, and is broken from then on (no more days; actions answer 'stopped').
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd} (upd: the update with the result,
// version v; null when stopped) | {t:'err', code, nid, rid, what:'timeout'|'throw', msg}
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal?, ui?, err?} | {t:'err', …}
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?}. snap is the realm's half
// of a snapshot: snapWith(snap, {clock, roster, since}) makes the stream event.
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (upd: the update with the
// result, version v; null when stopped) | {t:'err', code, nid, rid, what:'timeout'|'throw', msg}
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal?, ui?, err?, ms} (neither modal nor err: the what-if
// opened nothing) | {t:'err', …}
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?, ms}. snap is the realm's
// half of a snapshot: snapWith(snap, {clock, roster, since}) makes the stream event.
// ms: the worker's time for the call (the mark, the realm, the update), without the wait behind other calls: what
// the host's rate limit of worker time counts (section 10).
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}; engine.greet(code, nid) → a pulled
// engine.prefs(code, nid, {prefs}) → undefined; 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 the workers
// engine.simId the build id this engine's game belongs to (SIM_ID of the multiplayer page from the same src/)
// engine.prefs(code, nid, {prefs}) → undefined (or the {t:'err'} of a realm that failed);
// 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) → whether that network has a realm
// engine.stats() → {workers, realms, sessions} (not a promise); engine.mem() → each pool worker's heap and rss
// engine.close() → stops the workers
// engine.simId the build id this engine's game belongs to (SIM_ID of the multiplayer page from the same src/). The
// game text is read once, here: every worker, also one started after an exit, runs that game, and
// a src/ that does not compile makes createEngine throw.
//
// Rejections: a call for a network that is not loaded (code 'NO_REALM'), a malformed call (code 'ERR': a load that
// names no network, or one twice, changes nothing), and every call pending on a worker that exits (out of memory, a
// crash): Error('worker exited'), code 'EXIT'; that worker's sessions are gone and the host loads them again (4.7). Every
// call is answered or rejected; none waits for ever. An exit counts against the sessions whose load was under way on
// that worker (a save that crashes or overflows it), or, when none was, against every session it held. A session with
// two exits against it within an hour gets a worker of its own; when that one exits too, its loads reject with code
// 'GAVE_UP' until the engine is made again (the server restarts). A session stays on its worker while a load of it is
// under way, so an unload and a load sent back to back (a language change) land on the same worker.
// names no network, or one twice, changes nothing), every call pending on a worker that exits (out of memory, a crash):
// Error('worker exited'), code 'EXIT', and every call while no worker can start (code 'SIM_DOWN', 503 for the host).
// Every call is answered or rejected; none waits for ever.
// Lost networks. A worker that exits takes the realms of every session on it, also of those with no call pending, and
// the worker drops a network whose realm cannot be built again after a failure. Such a network answers NO_REALM: for a
// network the host believes loaded, NO_REALM means "load it again from its checkpoint" (4.7). opts.onLost(code, nids,
// why) says it as it happens ('exit', or the worker's reason).
// Blame. An exit counts against the session the worker was running (a call or a step that crashed or overflowed it),
// else against those whose load was under way, else against every session it held; a worker that never started
// blames nobody. A session with two exits against it within an hour gets a worker of its own (at most opts.maxOwn of
// them, 4 by default: past that it is given up); when that one exits too, its loads reject with code 'GAVE_UP' until
// the engine is made again (the server restarts). A worker that exits before it is ready is started again after a
// pause that doubles; after 5 such starts in a row the engine is down (SIM_DOWN). A session stays on its worker while
// a load of it is under way, so an unload and a load sent back to back (a language change) land on the same worker.
// Epochs: every realm load mints one (a load, a begin, the fresh realm after a timeout); loaded, pulled, actDone and
// subbed carry the realm's current one. Versions are the realm's: only a pull (or an action's own pull) makes one.
//
// Tests only, with createEngine({test: {seed, now, step} | true}): engine.eval(code, nid, src) runs code in a realm
// ({value} | {error} | {timeout, epoch}); engine.mem() reports each worker's heap; engine.kill(i) ends pool worker i,
// engine.killOf(code) the worker of that session; engine.workerOf(code) is its pool index (-1: none, or its own),
// engine.dedicated(code) whether it has a worker of its own.
// ({value} | {error} | {timeout, epoch}); engine.kill(i) ends pool worker i, engine.killOf(code) the worker of that
// session; engine.workerOf(code) is its pool index (-1: none, or its own), engine.dedicated(code) whether it has a
// worker of its own, engine.running(i) the session pool worker i is running as far as the engine knows.
// opts.test.startFail: no worker starts; opts.startBackoffMs: the first pause before starting one again (1000).
'use strict';
const path = require('node:path');
const vm = require('node:vm');
const { Worker } = require('node:worker_threads');
const page = require('./page');
const { gameSource } = require('./mp-sim-realm');
const FILE = path.join(__dirname, 'mp-sim-worker.js');
const HOUR = 3600e3;
@ -61,10 +78,21 @@ function createEngine(opts = {}) {
}
const N = Math.max(1, Math.floor(+opts.workers || 2));
const heapMb = Math.max(64, Math.floor(+opts.heapMb || 1536));
const maxOwn = Math.max(0, Math.floor(opts.maxOwn !== undefined ? +opts.maxOwn || 0 : 4));
const backoff = Math.max(1, +opts.startBackoffMs || 1000);
const log = typeof opts.log === 'function' ? opts.log : () => {};
const lostTo = (code, nids, why) => { if (typeof opts.onLost === 'function' && nids.length) try { opts.onLost(code, nids, why); } catch (e) { log('error', 'mp-sim: onLost threw: ' + (e && e.message)); } };
const test = opts.test || null;
const W = { root: opts.root, page: opts.page, test, strict: opts.strict !== undefined ? !!opts.strict : process.env.SIM_STRICT === '1', timeouts: opts.timeouts };
let seq = 0, closed = false;
// The game, read once, here: a src/ that does not compile throws now, and every worker runs the game simId names.
const root = opts.root || page.ROOT, src = gameSource({ root, page: opts.page });
try { new vm.Script(src, { filename: 'game.js' }); } catch (e) { throw new Error(`mp-sim: the game in ${path.join(root, 'src')} does not compile: ${e.message}`); }
const simId = page.simId(page.assemble({ src: path.join(root, 'src'), mp: true }).html);
const W = { root: opts.root, page: opts.page, src, simId, test, strict: opts.strict !== undefined ? !!opts.strict : process.env.SIM_STRICT === '1', timeouts: opts.timeouts };
let seq = 0, closed = false, down = null, fails = 0;
const DOWN = () => Object.assign(new Error(`server-run play is down: ${down}`), { code: 'SIM_DOWN' });
const CLOSED = () => Object.assign(new Error('engine closed'), { code: 'CLOSED' });
// Why no call can go out now: closed, or down (else null).
const shut = () => (closed ? CLOSED() : down ? DOWN() : null);
const pool = [], own = new Map(), placed = new Map(), exits = new Map(), gaveUp = new Set();
// A worker's realms (sessions: code → its loaded nids), and for placement the networks of its loads under way too
// (loading: code → how many).
@ -72,12 +100,16 @@ function createEngine(opts = {}) {
const count = (w) => size(w) + [...w.loading.values()].reduce((a, b) => a + b, 0);
function spawn(dedicated = false) {
const w = { worker: null, pending: new Map(), sessions: new Map(), loading: new Map(), dedicated, dead: false };
const w = { worker: null, pending: new Map(), sessions: new Map(), loading: new Map(), dedicated, dead: false, ready: false, fatal: null, running: null };
w.worker = new Worker(FILE, { workerData: { mpSim: W }, resourceLimits: { maxOldGenerationSizeMb: heapMb } });
w.worker.on('message', (m) => {
if (m.log) { log(m.log[0], m.log[1]); return; }
if (m.fatal) { log('error', 'mp-sim worker could not start: ' + m.fatal); return; }
if (m.ready) return;
if (m.fatal) { w.fatal = String(m.fatal).split('\n')[0].slice(0, 300); return; }
if (m.ready) { w.ready = true; fails = 0; return; }
// The session it runs from now until its next reply: whose doing an exit then is.
if ('run' in m) { w.running = m.run; return; }
if (m.lost) { const s = w.sessions.get(m.lost.code); if (s) s.delete(m.lost.nid); lostTo(m.lost.code, [m.lost.nid], m.lost.why); return; }
w.running = null;
const p = w.pending.get(m.id);
if (!p) return;
w.pending.delete(m.id);
@ -94,25 +126,36 @@ function createEngine(opts = {}) {
function died(w, c) {
if (w.dead) return;
w.dead = true;
// Whose exit it is: the sessions whose load was under way (a save that crashes or overflows its worker), else every
// session it held. The others lose their realms (the host loads them again) without an exit against them.
const held = new Set([...w.sessions.keys(), ...w.loading.keys()]), blamed = new Set(w.loading.size ? w.loading.keys() : held);
// Whose exit it is: the session it was running (a call or a step that crashed or overflowed it), else those whose
// load was under way, else every session it held; nobody's when it never started. The others lose their realms
// (the host loads them again) without an exit against them.
const held = new Set([...w.sessions.keys(), ...w.loading.keys()]);
const blamed = new Set(!w.ready ? [] : w.running && held.has(w.running) ? [w.running] : w.loading.size ? w.loading.keys() : held);
const e = Object.assign(new Error('worker exited'), { code: 'EXIT', exitCode: c });
for (const p of w.pending.values()) p.no(e);
w.pending.clear();
const t = Date.now();
for (const code of held) {
if (placed.get(code) === w) placed.delete(code);
lostTo(code, [...(w.sessions.get(code) || [])], 'exit');
if (!blamed.has(code)) continue;
if (w.dedicated) { gaveUp.add(code); own.delete(code); log('error', `mp-sim: session ${code} took down its own worker too; not loading it again until a restart`); continue; }
exits.set(code, (exits.get(code) || []).filter((x) => t - x < HOUR).concat(t));
}
w.sessions.clear(); w.loading.clear();
if (!closed) {
log('warn', `mp-sim: a worker exited (code ${c}); its sessions load again from their checkpoints`);
for (const [k, x] of own) if (x === w) own.delete(k);
if (closed) return;
const i = pool.indexOf(w);
if (i >= 0) pool[i] = spawn();
if (!w.ready) {
// It never started (the game does not run in a worker): not again at once, but after a pause that doubles; after
// 5 such starts in a row, server-run play is down until the engine is made again.
if (++fails >= 5) { if (!down) { down = w.fatal || `a worker exited before it started (code ${c})`; log('error', `mp-sim: no worker can start (${down}); server-run play is down until a restart`); } return; }
log('warn', `mp-sim: a worker could not start (${w.fatal || 'code ' + c}); trying again in ${backoff * 2 ** (fails - 1)} ms`);
if (i >= 0) setTimeout(() => { if (!closed && !down && pool[i] === w) pool[i] = spawn(); }, backoff * 2 ** (fails - 1)).unref();
return;
}
log('warn', `mp-sim: a worker exited (code ${c}); its sessions load again from their checkpoints`);
if (i >= 0) pool[i] = spawn();
}
for (let i = 0; i < N; i++) pool.push(spawn());
@ -121,15 +164,25 @@ function createEngine(opts = {}) {
let w = placed.get(code);
if (w && !w.dead) return w;
if (!create) return null;
if (down) throw DOWN();
if (gaveUp.has(code)) throw Object.assign(new Error(`session ${code} kept failing its worker`), { code: 'GAVE_UP' });
if ((exits.get(code) || []).filter((x) => Date.now() - x < HOUR).length >= 2) {
if (own.size >= maxOwn) {
gaveUp.add(code);
log('error', `mp-sim: session ${code} keeps failing its worker, and ${own.size} sessions have workers of their own already; not loading it again until a restart`);
throw Object.assign(new Error(`session ${code} kept failing its worker`), { code: 'GAVE_UP' });
}
w = spawn(true); own.set(code, w);
} else w = pool.reduce((a, b) => (count(b) < count(a) ? b : a));
} else {
const live = pool.filter((x) => !x.dead);
if (!live.length) throw Object.assign(new Error('no worker is up yet: try again'), { code: 'SIM_DOWN' });
w = live.reduce((a, b) => (count(b) < count(a) ? b : a));
}
placed.set(code, w);
return w;
}
function send(w, m) {
if (closed) return Promise.reject(Object.assign(new Error('engine closed'), { code: 'CLOSED' }));
if (closed) return Promise.reject(CLOSED());
if (!w || w.dead) return Promise.reject(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
const id = ++seq;
return new Promise((ok, no) => {
@ -140,12 +193,13 @@ function createEngine(opts = {}) {
});
}
const noRealm = (code, nid) => Promise.reject(Object.assign(new Error(`no realm ${code}/${nid}`), { code: 'NO_REALM' }));
const to = (code, nid, m) => { const w = workerOf(code, false); return w ? send(w, { code, nid, ...m }) : noRealm(code, nid); };
const to = (code, nid, m) => { const x = shut(); if (x) return Promise.reject(x); const w = workerOf(code, false); return w ? send(w, { code, nid, ...m }) : noRealm(code, nid); };
const mine = (w, code) => { let s = w.sessions.get(code); if (!s) w.sessions.set(code, s = new Set()); return s; };
const engine = {
simId: null,
simId,
load(code, nets) {
{ const x = shut(); if (x) return Promise.reject(x); }
if (!Array.isArray(nets) || !nets.length) return Promise.reject(Object.assign(new Error('load: give the networks to load'), { code: 'ERR' }));
let w;
try { w = workerOf(code, true); } catch (e) { return Promise.reject(e); }
@ -160,6 +214,7 @@ function createEngine(opts = {}) {
}, (e) => { done(); throw e; });
},
day(code, { d, speed = 1, last = 1, alone = [], nets = [], mute = false } = {}) {
{ const x = shut(); if (x) return Promise.reject(x); }
const w = workerOf(code, false);
if (!w) return Promise.reject(Object.assign(new Error(`no session ${code} here`), { code: 'NO_REALM' }));
return send(w, { t: 'day', code, d, speed, last, alone, nets, mute });
@ -168,11 +223,12 @@ function createEngine(opts = {}) {
ask(code, nid, msg) { return to(code, nid, { t: 'ask', msg }); },
pull(code, nid, { snap = false, views } = {}) { return to(code, nid, { t: 'pull', snap: !!snap, ...(views ? { views } : {}) }); },
sub(code, nid, { views = [] } = {}) { return to(code, nid, { t: 'sub', views }); },
prefs(code, nid, { prefs } = {}) { return to(code, nid, { t: 'prefs', prefs }).then(() => undefined); },
prefs(code, nid, { prefs } = {}) { return to(code, nid, { t: 'prefs', prefs }).then((r) => (r && r.t === 'err' ? r : undefined)); },
greet(code, nid) { return to(code, nid, { t: 'greet' }); },
save(code, nid) { return to(code, nid, { t: 'save' }); },
card(code, nid) { return to(code, nid, { t: 'card' }); },
unload(code, nid) {
if (closed) return Promise.reject(CLOSED());
const w = workerOf(code, false);
if (!w) return Promise.resolve({ t: 'unloaded', code, ...(nid !== undefined ? { nid } : {}) });
return send(w, { t: 'unload', code, ...(nid !== undefined ? { nid } : {}) }).then((r) => {
@ -185,6 +241,8 @@ function createEngine(opts = {}) {
return r;
});
},
has(code, nid) { const w = placed.get(code), s = w && !w.dead && w.sessions.get(code); return !!(s && s.has(nid)); },
mem() { return Promise.all(pool.filter((w) => !w.dead).map((w) => send(w, { t: 'mem' }))); },
stats() {
const ws = [...pool, ...own.values()].filter((w) => !w.dead);
return { workers: ws.length, realms: ws.reduce((a, w) => a + size(w), 0), sessions: ws.reduce((a, w) => a + w.sessions.size, 0) };
@ -198,13 +256,12 @@ function createEngine(opts = {}) {
};
if (test) {
engine.eval = (code, nid, src, ms) => to(code, nid, { t: 'eval', src: String(src), ...(ms ? { ms } : {}) });
engine.mem = () => Promise.all(pool.filter((w) => !w.dead).map((w) => send(w, { t: 'mem' })));
engine.kill = (i = 0) => { const w = pool[i]; if (w && !w.dead) w.worker.terminate(); };
engine.killOf = (code) => { const w = placed.get(code); if (w && !w.dead) w.worker.terminate(); };
engine.workerOf = (code) => pool.indexOf(placed.get(code));
engine.dedicated = (code) => !!(placed.get(code) && placed.get(code).dedicated);
engine.running = (i = 0) => (pool[i] ? pool[i].running : null);
}
{ const page = require('./page'); engine.simId = page.simId(page.assemble({ src: path.join(opts.root || page.ROOT, 'src'), mp: true }).html); }
return engine;
}

View file

@ -9,13 +9,16 @@
// (globalThis.__in), the answer comes back as one string, and no object crosses between host and realm. An answer is
// a JSON header, optionally followed by more parts, each on its own line (JSON text never holds a raw newline):
// srvPull answers `{"v":3,"parts":["upd","snap"]}\n<upd JSON>\n<snap JSON>`, ready to write to a stream.
// A call that throws inside the realm answers {"srvErr": stack}; a call that runs over its time limit throws
// ERR_SCRIPT_EXECUTION_TIMEOUT here, and the realm must not be used for play again (a timeout skips finally blocks).
// A call that throws inside the realm answers {"srvErr": stack}; a call after which the realm's built-ins are not what
// they were at load (a prototype written through) answers {"srvErr", "polluted":1}, and the realm must not be used for
// play again; a call that runs over its time limit throws ERR_SCRIPT_EXECUTION_TIMEOUT here, and the realm must not be
// used for play again either (a timeout skips finally blocks).
//
// gameSource({root, page}) the game script (the largest inline <script> of the assembled page)
// dictSource(lang, root) the source dictionary of a language, or null for English
// prelude(opts), EPILOGUE the realm's own code around the game, as plain strings
// compileCode({root, page}) {game, epilogue, simId} as vm.Scripts, once per process (a worker)
// compileCode({root, page, src, simId}) {game, epilogue, simId} as vm.Scripts, once per process (a worker); src and
// simId: the game text and build id the engine read once (every worker runs the same)
// new Realm({code, lang, dict, test, log, nid}) a realm, the game loaded; .call(name, input, ms), .raw(...)
// parts(text) [header, ...parts] of an answer
'use strict';
@ -74,8 +77,22 @@ const _txt=h=>String(h).replace(/<[^>]*>/g,'').replace(/&(#x[0-9a-f]+|#\\d+|[a-z
const _el=(tag,init)=>{const t={tagName:String(tag||'div').toUpperCase(),_h:'',hidden:true,value:'',firstChild:null,lastChild:null,nextSibling:null,previousSibling:null,parentNode:null,children:[],childNodes:[],attributes:[],...init};
return new Proxy(t,{get(o,k){if(k==='innerHTML')return o._h;if(k==='textContent')return _txt(o._h);
if(k==='firstElementChild'){const m=/^\\s*<([a-zA-Z][a-zA-Z0-9]*)\\b[^>]*>([\\s\\S]*?)<\\/\\1>/.exec(o._h);return m?_el(m[1],{_h:m[2]}):null;}
if(k==='querySelector'||k==='querySelectorAll')return s=>_q(o._h,s,k==='querySelectorAll');if(k==='classList')return _cls(o);
if(k in o)return o[k];return _n;},
set(o,k,v){if(k==='innerHTML')o._h=String(v);else if(k==='textContent')o._h=String(v).replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'})[c]);else o[k]=v;return true;}});};
// Which window is open, as the game asks it (pieRe, bstdShown, routingRefresh, the sea survey: a class, or a [data-x] /
// [data-x="v"] marker inside the card), is answered from what was written, never with the inert proxy, which would say
// every window is open. Other selectors match nothing; matches carry their data-* attributes. (closest() stays inert:
// a stand-in has no ancestors, and the page's own start asks one for its chip.)
const _cls=o=>{const g=()=>String(o.className||'').split(/\\s+/).filter(Boolean),p=a=>{o.className=a.join(' ');};
return new Proxy({contains:c=>g().includes(String(c)),add:(...c)=>p([...new Set([...g(),...c.map(String)])]),remove:(...c)=>{const x=c.map(String);p(g().filter(y=>!x.includes(y)));},
toggle:(c,f)=>{c=String(c);const on=f===undefined?!g().includes(c):!!f;p(on?[...new Set([...g(),c])]:g().filter(y=>y!==c));return on;}},{get:(t,k)=>k in t?t[k]:_n});};
const _cc=x=>x.replace(/-([a-z])/g,(q,c)=>c.toUpperCase());
const _ds=a=>{const d=Object.create(null);a.replace(/\\sdata-([a-z0-9-]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+)))?/gi,(m,k,x,y,z)=>{d[_cc(k.toLowerCase())]=_txt(x??y??z??'');return m;});return d;};
const _q=(h,sel,all)=>{const m=/^\\[data-([a-z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\\]"']*)))?\\]$/i.exec(String(sel).trim()),out=[];
if(m){const k=_cc(m[1].toLowerCase()),v=m[2]??m[3]??m[4],re=/<([a-zA-Z][a-zA-Z0-9]*)(\\s[^>]*)?>/g;let t;
while((t=re.exec(h))){const d=_ds(t[2]||'');if(Object.hasOwn(d,k)&&(v===undefined||d[k]===v)){out.push(_el(t[1],{dataset:d}));if(!all)break;}}}
return all?out:out[0]||null;};
const _byId=new Map();
const _doc=new Proxy({},{get(o,k){if(k==='createElement')return tag=>_el(tag);if(k==='getElementById')return id=>{if(!_byId.has(id))_byId.set(id,_el('div',{id}));return _byId.get(id);};return _n;},set:()=>true});
self.__srvEl=_byId;self.__srvCoarse=false;
@ -94,11 +111,11 @@ for(const [k,v] of Object.entries({document:_doc,localStorage:_store(),sessionSt
/* The epilogue: the server's side of a network, in the game's global scope. It only uses the game's own functions and
the tables of mp-sim-acts.js, written in as data. Everything a page needs to know comes out as fx or in the answers. */
const TABLES = JSON.stringify({ SEND: ACTS.SEND, ASK: ACTS.ASK, CONFIRM: ACTS.CONFIRM, DRAFTS: ACTS.DRAFTS, PREFS: ACTS.PREFS });
const TABLES = JSON.stringify({ SEND: ACTS.SEND, ASK: ACTS.ASK, CONFIRM: ACTS.CONFIRM, DRAFTS: ACTS.DRAFTS, DRAFT_TYPES: ACTS.DRAFT_TYPES, PREFS: ACTS.PREFS, TEXT: ACTS.TEXT, WINDOWS: ACTS.WINDOWS });
const EPILOGUE = `'use strict';
const SIMT=${TABLES},SIM_SEND=new Set(SIMT.SEND),SIM_ASK=new Set(SIMT.ASK),SIM_KEEP=new Set(['badge','modal']);
const SIM_RNEVER=new Set(['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked']);
const SIM_DRAFT=['pending','route','via','cnPrem','dfSrc','dfSys','seaDesign','seaterminal','seaengineering','decom','slop','pieIns','pieLas'];
const SIM_DRAFT=Object.keys(SIMT.DRAFT_TYPES);
// The realm's own memory: epoch and version of what it sent (5.10), the last keys sent, the fx and actions since the
// last pull, the marks, and what the running call saw (a window opened or closed, a refusal toast, an auto-pause).
const SIMR={epoch:'',v:0,seen:false,base:null,rSent:null,fx:[],acts:[],floats:0,alone:false,last:1,pause:false,modal:null,closed:false,bad:false,
@ -106,6 +123,17 @@ const SIMR={epoch:'',v:0,seen:false,base:null,rSent:null,fx:[],acts:[],floats:0,
const srvOwn=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
const srvOut=(h,...p)=>[JSON.stringify(h),...p].join('\\n');
function srvLog(t){console.warn(String(t).slice(0,600));}
/* The realm's built-ins as the game left them at load. A click that writes through a prototype (a city named
__proto__ or constructor) changes them, and every for…in, the game's and this file's, would carry that from then on.
The trampoline checks after every call; a realm whose built-ins changed is replaced like one that timed out. */
const srvFp=(()=>{const n=Object.getOwnPropertyNames,L=[Object,Object.prototype,Array,Array.prototype,Function.prototype,String.prototype,Number.prototype,Boolean.prototype,Map.prototype,Set.prototype];
return ()=>{for(const k in {})return 'Object.prototype.'+k;for(const k in [])return 'Array.prototype.'+k;return L.map(o=>n(o).length).join(',');};})();
const SIM_FP0=srvFp();
function srvDirty(){const f=srvFp();return f===SIM_FP0?'':/^(Object|Array)\\./.test(f)?f:'a built-in has a new property';}
// Strings no arg names: written through as a key, they reach a prototype. Free text (TEXT) may say them.
const SIM_BADV=new Set(['__proto__','constructor','prototype']);
const srvBadV=v=>typeof v==='string'?SIM_BADV.has(v):Array.isArray(v)?v.some(srvBadV):!!v&&typeof v==='object'&&Object.keys(v).some(k=>SIM_BADV.has(k)||srvBadV(v[k]));
const srvBadArgs=(act,a)=>{const t=srvOwn(SIMT.TEXT,act)?SIMT.TEXT[act]:{};return Object.keys(a).some(k=>SIM_BADV.has(k)||(!srvOwn(t,k)&&srvBadV(a[k])));};
/* fx: a ring of 200; when it overflows, the oldest go first, but badges and windows (win, lose) stay, at most 32. */
function srvFx(f){const q=SIMR.fx;q.push(f);
@ -149,7 +177,7 @@ srvOn=function(){return false;};
UI.clockLocked=true;UI.started=true;UI.pitched=true;UI.speed=1;
/* ---- S as top-level keys, R as the page gets it ---- */
function srvKeyJson(){const o={};for(const k of Object.keys(S)){const j=JSON.stringify(S[k]);if(j!==undefined)o[k]=j;}return o;}
function srvKeyJson(){const o=Object.create(null);for(const k of Object.keys(S)){const j=JSON.stringify(S[k]);if(j!==undefined)o[k]=j;}return o;}
function srvJoin(K){let t='{',f=true;for(const k in K){t+=(f?'':',')+JSON.stringify(k)+':'+K[k];f=false;}return t+'}';}
// Slim R (5.5): rwPack's view without the flow tables, routing's own inputs and what goes on demand; the top 4 networks
// per transit port, the top 8 over all of them, numbers to 6 significant digits. Packed once per R object.
@ -194,11 +222,15 @@ function srvOrdOut(txt,K){const u0=uidN,r0=S.rng;let B;
function srvOrdIn(o){if(!o||typeof o!=='object'||Array.isArray(o))return;for(const k of Object.keys(o))if(srvOwn(S,k)&&srvSame(o[k],S[k]))S[k]=o[k];}
// rt as JSON text: R's own route memory, its routing point against S as K holds it (when R was routed here), ord when
// given, and the desk's memory sl.
function srvRtText(r,K,ord,sl){const p=K&&SIM_RIN.get(r);let t=JSON.stringify(srvRtOut(r)).slice(0,-1);
function srvRtText(r,K,ord,sl,rk){const p=K&&SIM_RIN.get(r);let t=JSON.stringify(srvRtOut(r)).slice(0,-1);
if(p){const at=[],gone=[];for(const k in p.k)if(K[k]!==p.k[k])at.push(JSON.stringify(k)+':'+p.k[k]);for(const k in K)if(!srvOwn(p.k,k))gone.push(k);
t+=',"pt":'+p.rt.slice(0,-1)+',"at":{'+at.join(',')+'},"gone":'+JSON.stringify(gone)+'}';}
return t+(ord?',"ord":'+ord:'')+',"sl":'+JSON.stringify(sl||[])+'}';}
const srvKeysOf=s=>{const o=JSON.parse(s),K={};for(const k of Object.keys(o)){const j=JSON.stringify(o[k]);if(j!==undefined)K[k]=j;}return K;};
return t+(ord?',"ord":'+ord:'')+(rk?',"rk":true':'')+',"sl":'+JSON.stringify(sl||[])+'}';}
// rk: R is the routing of S as it is (routeIfChanged's memory, UI.rk and UI.rkR, against K: routeKey() is the join of
// K without RK_SKIP). A fresh realm given it skips the routing of a click that changes nothing routing reads, as this
// one would; without it that click routes again, and compute() is not always a fixed point.
const srvRkOk=(r,K,rk,rkR)=>{if(!K||rkR!==r||typeof rk!=='string')return false;let t='{',f=true;for(const k in K){if(RK_SKIP.has(k))continue;t+=(f?'':',')+JSON.stringify(k)+':'+K[k];f=false;}return t+'}'===rk;};
const srvKeysOf=s=>{const o=JSON.parse(s),K=Object.create(null);for(const k of Object.keys(o)){const j=JSON.stringify(o[k]);if(j!==undefined)K[k]=j;}return K;};
// The S of a routing point (pt), one JSON per key: the loaded S with the keys of at put back and those of gone left out.
function srvAtK(pt){if(!pt||typeof pt!=='object'||!pt.at||typeof pt.at!=='object'||Array.isArray(pt.at)||!Array.isArray(pt.gone))return null;
const K=srvKeyJson();for(const k of Object.keys(pt.at))K[k]=JSON.stringify(pt.at[k]);for(const k of pt.gone)if(typeof k==='string')delete K[k];return K;}
@ -214,8 +246,10 @@ function srvPointIn(r,pt){const K=srvAtK(pt);if(K)SIM_RIN.set(r,{k:K,rt:JSON.str
function srvAttacks(){if(!R||!Array.isArray(R.ddos))return;const as=ddosAll(S,false);for(const x of R.ddos)if(x.attack)x.attack=as.find(a=>a.id===x.attack.id)||null;}
// mark: rt of the marked R against the marked S (a day's mark has it at once); else of R against S now.
function srvRt(inp){const m=inp?JSON.parse(inp):{},k=SIMR.mark;
if(!m.mark)return srvRtText(R,srvKeyJson(),'',srvSlOut());
return SIMR.markRt||(k?srvRtText(k.R,SIMR.markK||srvKeysOf(k.s),'',k.sl):srvRtText(R,null,'',[]));}
if(!m.mark){const K=srvKeyJson();return srvRtText(R,K,'',srvSlOut(),srvRkOk(R,K,UI.rk,UI.rkR));}
if(SIMR.markRt)return SIMR.markRt;
if(!k)return srvRtText(R,null,'',[]);
const K=SIMR.markK||srvKeysOf(k.s);return srvRtText(k.R,K,'',k.sl,srvRkOk(k.R,K,k.ui.rk,k.ui.rkR));}
/* R itself, whole, for the fresh realm that replaces this one after a timeout (routing it again from its point costs a
routing; the old realm still answers), the way the route worker sends it (rwPack/rwUnpack), as text: Maps, Sets, typed
arrays and non-finite numbers tagged. A checkpoint carries the point instead: 20 KB gzip, where R is 375 KB. */
@ -225,16 +259,30 @@ const srvDec=(k,v)=>!v||typeof v!=='object'||Array.isArray(v)?v:'__n' in v?Numbe
function srvRPack(inp){const m=inp?JSON.parse(inp):{},r=m.mark&&SIMR.mark?SIMR.mark.R:R;if(!r||!r.efp||!r.flc)return '';const {o,p}=rwPack(r);return JSON.stringify({o,p},srvEnc);}
function srvSetPrefs(p){if(!p||typeof p!=='object')return;for(const k of SIMT.PREFS)if(typeof p[k]==='boolean')PREFS[k]=p[k];}
/* The window the page has open (ctx.modal; ctx.win names it, mp-sim-acts.js WINDOWS): the stand-in #modal is that
window as the game asks it (its class, its marker), with the view state it draws from (checked here). No win: no
window, or one nothing asks about. The view state of an earlier request never stays. */
const SIM_WINUI=[...new Set(Object.values(SIMT.WINDOWS).flatMap(w=>w.ui||[]))];
const SIM_WINOK={opsCity:v=>srvOwn(S.pops,v),pieCity:v=>srvOwn(S.pops,v),pieTab:v=>PIE_TABS.includes(v)};
function srvWin(c){const w=c&&c.win&&typeof c.win==='object'?c.win:null,W=w&&typeof w.k==='string'&&srvOwn(SIMT.WINDOWS,w.k)?SIMT.WINDOWS[w.k]:null,m=$('modal');
for(const k of SIM_WINUI)delete UI[k];
m.hidden=!((c&&c.modal===true)||W);m.className=W?W.c:'';$('modalCard').innerHTML=W&&W.sel?'<div '+W.sel.slice(1,-1)+'></div>':'';
if(W&&W.ui&&w.ui&&typeof w.ui==='object')for(const k of W.ui){const v=w.ui[k];if(typeof v==='string'&&srvOwn(SIM_WINOK,k)&&SIM_WINOK[k](v))UI[k]=v;}}
function srvWinOff(){const m=$('modal');m.hidden=true;m.className='';$('modalCard').innerHTML='';}
function srvFresh(epoch){SIMR.epoch=String(epoch||'');SIMR.v=0;SIMR.seen=false;SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.rSent=new WeakRef(R);SIMR.base=srvKeyJson();SIMR.mark=null;SIMR.markK=null;SIMR.markRt=null;
UI.sel=null;UI.confirm=null;UI.pending=null;UI.started=true;UI.pitched=true;UI.clockLocked=true;$('modal').hidden=true;}
UI.sel=null;UI.confirm=null;UI.pending=null;UI.started=true;UI.pitched=true;UI.clockLocked=true;srvWinOff();}
/* srvLoad: a network from its save (a checkpoint, or the mark of a realm that timed out) and its rt: S in its live key
order, R routed again from its routing point, the desk's memory; then the days to come are the ones the old realm
had. A realm that replaces one that timed out gets the old realm's R itself when it could still pack it (rpack); live:
the save is the old realm's own S as text (a mark), key order and all. An rt without a point (an older checkpoint)
seeds R with its memory before compute(), the way the route worker does: close, not always the same. */
seeds R with its memory before compute(), the way the route worker does: close, not always the same. A damaged rt
never breaks a save that loads: R is routed from nothing then (close, logged). fx: the fx a fresh realm takes over
from the one it replaces (srvFxOut). Only a server network loads: a Normal game with the session's marks (S.mp.sim;
a local save is stamped on its way in, 5.2), else the load fails with the reason. */
function srvLoad(inp){const m=JSON.parse(inp),rt=m.rt&&typeof m.rt==='object'?m.rt:{};SIMR.strict=!!m.strict;
S=migrate(JSON.parse(m.save));
{const no=S.mode!=='normal'||S.scn?'server networks are Normal games':!S.mp||S.mp.sim!==1?'not a server network (S.mp.sim)':'';if(no)throw new Error('srvLoad: '+no);}
if(typeof S.rng!=='number')S.rng=(m.rng|0)||1;
if(Number.isInteger(m.uidN)&&m.uidN>0)uidN=m.uidN;
srvSetPrefs(m.prefs);
@ -242,9 +290,11 @@ function srvLoad(inp){const m=JSON.parse(inp),rt=m.rt&&typeof m.rt==='object'?m.
if(self.__srvClock&&typeof m.clock==='number')__srvClock(m.clock);
srvOrdIn(m.live?JSON.parse(m.save):rt.ord);
if(typeof m.rpack==='string'&&m.rpack){const x=JSON.parse(m.rpack,srvDec);R=rwUnpack(x.o,x.p);UI.hotMap=hotByCity();srvPointIn(R,rt.pt);}
else if(!srvReroute(rt.pt)){R=srvRtIn(rt);compute();}
else if(!srvReroute(rt.pt)){try{R=srvRtIn(rt);compute();}catch(e){srvLog('the route memory does not load ('+String(e&&e.message||e).slice(0,200)+'): routed from nothing');R=emptyR();compute();}}
if(rt.rk===true){UI.rk=routeKey();UI.rkR=R;}
srvSlIn(rt.sl);
srvFresh(m.epoch);
if(m.fx&&typeof m.fx==='object'&&Array.isArray(m.fx.fx)){SIMR.fx=m.fx.fx.filter(f=>Array.isArray(f)&&typeof f[0]==='string').slice(-200);SIMR.floats=Math.min(40,Math.max(0,m.fx.floats|0));}
// Whatever a loaded network says before its first snapshot (days nobody watched) is older than that snapshot: the
// first pull handles it like any (5.11). Only a new network's welcome waits for its first page (srvBegin).
SIMR.seen=true;
@ -269,9 +319,9 @@ function srvPrefs(inp){const m=JSON.parse(inp);srvSetPrefs(m.prefs);return '{}';
function srvMark(inp){const m=inp?JSON.parse(inp):{};let s,K=null;
if(m.keys||m.day){K=srvKeyJson();s=srvJoin(K);}else s=JSON.stringify(S);
SIMR.markK=m.keys?K:null;const sl=srvSlOut();
SIMR.mark={s,uidN,rng:S.rng,R,sl,...srvClockNow(),fx:SIMR.fx.slice(),floats:SIMR.floats,ui:{sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm,pending:UI.pending}};
SIMR.mark={s,uidN,rng:S.rng,R,sl,...srvClockNow(),fx:SIMR.fx.slice(),floats:SIMR.floats,ui:{sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm,pending:UI.pending,rk:UI.rk,rkR:UI.rkR}};
// As text: nothing the day does reaches it.
const rtJ=m.day?srvRtText(R,K,'',sl):'';SIMR.markRt=rtJ||null;const h=JSON.stringify({uidN,day:S.day,...srvClockNow()});
const rtJ=m.day?srvRtText(R,K,'',sl,srvRkOk(R,K,UI.rk,UI.rkR)):'';SIMR.markRt=rtJ||null;const h=JSON.stringify({uidN,day:S.day,...srvClockNow()});
return (rtJ?h.slice(0,-1)+',"rt":'+rtJ+'}':h)+'\\n'+s;}
/* srvRestore: back to the mark, in place (after a throw: the finally blocks ran). S is parsed back only when it
changed, so the S object stays on every normal path; R is the marked object, its attacks looked up again in a parsed
@ -284,8 +334,11 @@ function srvRestore(inp){const k=SIMR.mark;if(!k)return '{"none":1}';
// so the marked one is still the R the network had: route memory and compute() would only give one close to it.
R=k.R;if(parsed)srvAttacks();
UI.hotMap=hotByCity();UI.slTried=k.sl.length?{s:S,m:new Map(k.sl)}:null;
Object.assign(UI,k.ui);SIMR.fx=k.fx.slice();SIMR.floats=k.floats;SIMR.modal=null;SIMR.closed=false;$('modal').hidden=true;
Object.assign(UI,k.ui);SIMR.fx=k.fx.slice();SIMR.floats=k.floats;SIMR.modal=null;SIMR.closed=false;srvWinOff();
return JSON.stringify({parsed});}
// The fx a fresh realm takes over from this one: the mark's after a failed call (its own fx are dropped, 4.3), else
// (a read that ran out of time) all of them. Badges and windows wait for a page for days; a timeout does not lose them.
function srvFxOut(inp){const m=inp?JSON.parse(inp):{},k=SIMR.mark;return JSON.stringify(m.mark&&k?{fx:k.fx,floats:k.floats}:{fx:SIMR.fx,floats:SIMR.floats});}
/* srvDay: one day of this network, as the page runs it (dayTick, then the day's end render), then the tutorial. mute:
a catch-up day, whose fx are dropped (badges and windows stay). */
@ -339,10 +392,11 @@ function srvAct(inp){const m=JSON.parse(inp),act=String(m.act),ent={rid:String(m
let outcome,why;const K0=SIMR.markK;
const done=(o,w)=>{outcome=o;why=w;};
if(!SIM_SEND.has(act)||!srvOwn(ACT,act)||typeof ACT[act]!=='function')done('rejected','not an act the server runs');
else if(srvBadArgs(act,args)||srvBadV(m.ui))done('rejected','an arg names a built-in');
else{const w=srvDrafts(act,m.ui,args);
if(w)done('rejected',w);
else{const c=m.ctx&&typeof m.ctx==='object'?m.ctx:{};
UI.sel=srvSel(c.sel);if(typeof c.tab==='string')UI.tab=c.tab;if(typeof c.left==='string')UI.left=c.left;srvView(c);$('modal').hidden=!c.modal;
UI.sel=srvSel(c.sel);if(typeof c.tab==='string')UI.tab=c.tab;if(typeof c.left==='string')UI.left=c.left;srvView(c);srvWin(c);
let a2=args;UI.confirm=null;
if(m.confirmed===true&&srvOwn(SIMT.CONFIRM,act)){if(SIMT.CONFIRM[act]==='arg')a2={...args,ok:1};else UI.confirm=srvArm(act,args);}
const sent={sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm};
@ -358,7 +412,7 @@ function srvAct(inp){const m=JSON.parse(inp),act=String(m.act),ent={rid:String(m
else done('applied');}
if(outcome!=='error'){for(const k of ['sel','tab','left','confirm'])if(JSON.stringify(UI[k]??null)!==JSON.stringify(sent[k]??null))ent.ui[k]=UI[k]??null;
if(SIMR.closed)ent.ui.closed=1;if(SIMR.modal)ent.ui.modal=SIMR.modal;}}}}
SIMR.mark=null;SIMR.markK=null;SIMR.acts.push(ent);
srvWinOff();SIMR.mark=null;SIMR.markK=null;SIMR.acts.push(ent);
const p=srvPullParts({});
return srvOut({outcome,...(why?{why}:{}),v:SIMR.v},p.upd);}
@ -366,14 +420,15 @@ function srvAct(inp){const m=JSON.parse(inp),act=String(m.act),ent={rid:String(m
function srvAsk(inp){const m=JSON.parse(inp),k=SIMR.mark,act=String(m.act),out={};
if(!SIM_ASK.has(act)||!srvOwn(ACT,act))return JSON.stringify({err:'not a what-if the server answers'});
const args=m.args&&typeof m.args==='object'&&!Array.isArray(m.args)?m.args:{},td=UI.teDraft,sl=UI.slop,fx0=SIMR.fx.slice(),fl=SIMR.floats,hot=UI.hotMap;
srvView(m.ctx);$('modal').hidden=!(m.ctx&&m.ctx.modal);SIMR.modal=null;
if(srvBadArgs(act,args))return JSON.stringify({err:'an arg names a built-in'});
srvView(m.ctx);srvWin(m.ctx);SIMR.modal=null;
try{ACT[act](args);}catch(e){out.err='the game threw: '+String(e&&e.message||e).slice(0,200);srvLog('ask '+act+' threw: '+String(e&&e.stack||e));}
if(SIMR.modal)out.modal=SIMR.modal;
if(act==='teCheck'||act==='teSlop'){out.ui={teDraft:typeof UI.teDraft==='string'?UI.teDraft:null};if(act==='teSlop')out.ui.slop=typeof UI.slop==='string'?UI.slop:null;}
R=k.R;UI.hotMap=hot;uidN=k.uidN;S.rng=k.rng;
if(JSON.stringify(S)!==k.s){srvLog('ask '+act+' changed the game: put back');srvRestore('{}');}
else Object.assign(UI,k.ui);
SIMR.mark=null;UI.teDraft=td;UI.slop=sl;SIMR.fx=fx0;SIMR.floats=fl;SIMR.modal=null;$('modal').hidden=true;
SIMR.mark=null;UI.teDraft=td;UI.slop=sl;SIMR.fx=fx0;SIMR.floats=fl;SIMR.modal=null;srvWinOff();
return JSON.stringify(out);}
/* ---- pulls (5.3-5.6, 5.10): the only place the version moves ---- */
@ -389,7 +444,7 @@ function srvPullParts(m,K){K=K||srvKeyJson();const now=Date.now();
// make; what happened meanwhile (a new network's welcome) waits for the first one, which that page will get.
if(m.snap&&!SIMR.seen){SIMR.seen=true;SIMR.base=K;SIMR.rSent=new WeakRef(R);
return {upd:'',snap:'{"t":"snap","epoch":'+JSON.stringify(SIMR.epoch)+',"v":'+SIMR.v+',"now":'+now+',"S":'+srvJoin(K)+',"r":'+srvSlimR()+',"keep":[]}',subs:m.views?srvSubs(m.views):null};}
const B=SIMR.base||{},s=[],del=[];
const B=SIMR.base||Object.create(null),s=[],del=[];
for(const k in K)if(B[k]!==K[k])s.push(k);for(const k in B)if(!(k in K))del.push(k);
const rNew=!SIMR.rSent||SIMR.rSent.deref()!==R,fx=SIMR.fx,acts=SIMR.acts;let upd='';
if(s.length||del.length||rNew||fx.length||acts.length){const from=SIMR.v,v=++SIMR.v;
@ -414,28 +469,35 @@ function srvSub(inp){const m=inp?JSON.parse(inp):{};return JSON.stringify({v:SIM
function srvGreet(inp){bootNotes();return srvPull(inp);}
// A checkpoint: the save and its rt, ord included.
function srvSave(){const txt=JSON.stringify(packSave(S)),K=srvKeyJson(),h=JSON.stringify({uidN,day:S.day,lost:!!S.lost,...srvClockNow()});
return h.slice(0,-1)+',"rt":'+srvRtText(R,K,srvOrdOut(txt,K),srvSlOut())+'}\\n'+txt;}
return h.slice(0,-1)+',"rt":'+srvRtText(R,K,srvOrdOut(txt,K),srvSlOut(),srvRkOk(R,K,UI.rk,UI.rkR))+'}\\n'+txt;}
function srvCard(){return JSON.stringify({card:mpCard()});}
`;
// The realm API: one precompiled trampoline per name. Input in __in, a string out; a throw comes back as {srvErr}.
const API = ['srvLoad', 'srvBegin', 'srvPrefs', 'srvMark', 'srvRestore', 'srvRt', 'srvRPack', 'srvDay', 'srvAct', 'srvAsk', 'srvPull', 'srvSub', 'srvGreet', 'srvSave', 'srvCard'];
let TRAMP = null;
const tramps = () => TRAMP || (TRAMP = Object.fromEntries(API.map((n) => [n, new vm.Script(
`(()=>{try{return ${n}(globalThis.__in);}catch(e){return JSON.stringify({srvErr:String(e&&e.stack||e).slice(0,4000)});}})()`, { filename: `srv-${n}.js` })])));
// The realm API: one precompiled trampoline per name. Input in __in, a string out; a throw comes back as {srvErr}, and
// changed built-ins as {srvErr, polluted}. The unchecked ones only read what a fresh realm needs from one that is done
// (its save, rt, R and fx): the worker's recovery after a timeout or a pollution.
const API = ['srvLoad', 'srvBegin', 'srvPrefs', 'srvMark', 'srvRestore', 'srvRt', 'srvRPack', 'srvFxOut', 'srvDay', 'srvAct', 'srvAsk', 'srvPull', 'srvSub', 'srvGreet', 'srvSave', 'srvCard'];
const PEEK = ['srvRt', 'srvRPack', 'srvFxOut', 'srvSave'];
let TRAMP = null, TRAMP0 = null;
const tramp = (n, check) => new vm.Script(`(()=>{let r;try{r=${n}(globalThis.__in);}catch(e){r=JSON.stringify({srvErr:String(e&&e.stack||e).slice(0,4000)});}`
+ (check ? `const d=srvDirty();return d?JSON.stringify({srvErr:'the built-ins of the realm changed: '+d,polluted:1}):r;})()` : 'return r;})()'), { filename: `srv-${n}.js` });
const tramps = (check = true) => (check ? TRAMP || (TRAMP = Object.fromEntries(API.map((n) => [n, tramp(n, true)])))
: TRAMP0 || (TRAMP0 = Object.fromEntries(PEEK.map((n) => [n, tramp(n, false)]))));
// Tests only (createEngine({test})): run a piece of code in a realm, answer its value as JSON.
const EVAL = new vm.Script('(()=>{const f=new Function(globalThis.__in);const v=f();return v===undefined?"null":JSON.stringify(v);})()', { filename: 'srv-test-eval.js' });
/* The game, the epilogue and the build id, compiled once per process. */
function compileCode({ root = ROOT, page = REALM_PAGE } = {}) {
/* The game, the epilogue and the build id, compiled once per process. The engine passes the game text and its build
id (read once, in the main thread), so a worker started later runs the game the engine names, whatever src/ holds by
then; without them they are read from root. */
function compileCode({ root = ROOT, page = REALM_PAGE, src = null, simId: id = null } = {}) {
if (!vm.constants || vm.constants.DONT_CONTEXTIFY === undefined) {
throw new Error(`server-run play needs Node 22.8 or newer (vm.constants.DONT_CONTEXTIFY); this is ${process.version}`);
}
const src = gameSource({ root, page });
const game = typeof src === 'string' && src ? src : gameSource({ root, page });
return {
game: new vm.Script(src, { filename: 'game.js' }),
game: new vm.Script(game, { filename: 'game.js' }),
epilogue: new vm.Script(EPILOGUE, { filename: 'srv-epilogue.js' }),
simId: simId(assemble({ src: path.join(root, 'src'), mp: true }).html),
simId: id || simId(assemble({ src: path.join(root, 'src'), mp: true }).html),
root,
};
}
@ -469,9 +531,10 @@ class Realm {
this.ctx = ctx;
this.ms = performance.now() - t0;
}
// The answer as the realm gave it (a string). Throws ERR_SCRIPT_EXECUTION_TIMEOUT past ms.
raw(name, input, ms = 1000) {
const s = tramps()[name];
// The answer as the realm gave it (a string). Throws ERR_SCRIPT_EXECUTION_TIMEOUT past ms. check false: one of PEEK,
// whatever the built-ins are now (recovery only).
raw(name, input, ms = 1000, check = true) {
const s = tramps(check)[name];
if (!s) throw new Error(`mp-sim-realm: no realm call ${name}`);
this.ctx.__in = input === undefined ? '' : JSON.stringify(input);
try { const r = s.runInContext(this.ctx, { timeout: ms }); return typeof r === 'string' ? r : ''; } finally { this.ctx.__in = ''; }

View file

@ -5,31 +5,40 @@
// network order, with a turn for other messages between two networks: an action for network X lands between days of
// other networks, never inside X's own day. The networks of a day are fixed when it starts. Loads, new networks and
// unloads of a session wait for its day; actions for a network that is still loading wait for it. Every message is
// answered: a load that names no network (or one twice) is refused whole and changes nothing; a network in it that
// has no save, or whose save does not load, answers err (broken) and the others load.
// answered: a load that names no network (or one twice), or a day whose lists are not lists, is refused whole and
// changes nothing; a network in a load that has no save, or whose save does not load, answers err (broken) and the
// others load. Nothing a message holds, and nothing a step throws, takes the worker down.
//
// Failures. Every realm call has a time limit (a day 2 s, an action 1 s, a what-if 3 s, a pull or a save 1 s). Before
// a day or an action the realm is marked (its S as text, uidN, the dice, and for a day its rt: route memory and routing
// point), and the worker keeps the mark. A call that throws has run its finally blocks: the realm goes back to the mark
// in place. A call that times out has not (vm skips them), so that realm is never used again: a fresh one is built from
// the mark, with a new epoch. A failed day runs once more; failing again, the network is broken at its state before
// the day.
// point), and the worker keeps the mark. A mark changes nothing: one that fails leaves the realm as it was, and one
// that runs out of time has the realm built again from its own save, never from an older mark (that would undo what
// came after it). A call that throws has run its finally blocks: the realm goes back to the mark in place. A call that
// times out has not (vm skips them), and one after which the realm's built-ins changed (a prototype written through)
// left them changed: such a realm is never called again for play. A fresh one is built from the mark, with a new
// epoch, and takes over the fx the mark held. A failed day runs once more; failing again, the network is broken at its
// state before the day. When not even a fresh realm can be built, the network is dropped: its calls answer NO_REALM,
// and the engine is told ({lost}), so the host loads it again from its checkpoint (4.7).
//
// The worker → host replies are the shapes of tests/lib/mp-sim-shape.js checkWorker(), sent as {id, ok, reply} (or
// {id, ok:false, error}) for the engine to match its promises; logs go up as {log:[level, text]}.
// {id, ok:false, error}) for the engine to match its promises; logs go up as {log:[level, text]}, a dropped network as
// {lost:{code, nid, why}}, and before each job or step that runs a realm {run: code}, the session it runs (the engine
// forgets it at the next reply): a worker that dies then is that session's doing.
'use strict';
const { isMainThread, parentPort, workerData } = require('node:worker_threads');
const crypto = require('node:crypto');
const v8 = require('node:v8');
const { compileCode, Realm, isTimeout } = require('./mp-sim-realm');
const { compileCode, Realm, isTimeout, parts } = require('./mp-sim-realm');
const TIMEOUTS = { day: 2000, act: 1000, ask: 3000, pull: 1000, save: 1000, mark: 1000, small: 1000, load: 30000 };
const now = () => performance.now();
const MSG = (e) => String((e && (e.stack || e.message)) || e).slice(0, 2000);
const LINE = (e) => String((e && e.message) || e).split('\n')[0].slice(0, 300);
const msOf = (t0) => +(now() - t0).toFixed(2);
/* opts: {root, page, test: {seed, now, step} | true | null, strict, timeouts, log(level, text), post(message)}. */
/* opts: {root, page, src, simId, test: {seed, now, step} | true | null, strict, timeouts, log(level, text), post(message)}. */
function createCore(opts = {}) {
const code = compileCode({ root: opts.root, page: opts.page });
const code = compileCode({ root: opts.root, page: opts.page, src: opts.src, simId: opts.simId });
const T = { ...TIMEOUTS, ...(opts.timeouts || {}) };
const test = opts.test ? (typeof opts.test === 'object' ? opts.test : {}) : null;
const log = opts.log || (() => {});
@ -39,52 +48,97 @@ function createCore(opts = {}) {
const key = (c, n) => c + '/' + n;
const epochOf = () => crypto.randomBytes(4).toString('hex') + (++epochN).toString(36);
const session = (c) => { let s = sessions.get(c); if (!s) sessions.set(c, s = { code: c, day: null, load: null }); return s; };
const running = (c) => post({ run: c });
/* ---- realms ---- */
function build(nid, lang) {
return new Realm({ code, lang, test: test && { seed: test.seed, now: test.now, step: test.step }, loadMs: T.load,
log: (lvl, txt) => log(lvl === 'log' || lvl === 'info' || lvl === 'debug' ? 'info' : 'warn', `[${nid}] ${txt}`) });
}
// A realm call: [header, ...parts]; a throw inside the realm comes back as {srvErr}, a timeout throws.
const call = (e, name, input, ms) => e.realm.call(name, input, ms);
/* A fresh realm in place of one that timed out, from {s, uidN, rt, live}: same network, new epoch, versions from 0. R
comes from the old realm, which still answers after a timeout: the marked R (mark) or its current one, packed whole.
When it cannot, R is routed again from rt's routing point. live: s is a mark, the realm's own S as text. */
// A realm call: [header, ...parts]; a throw inside the realm comes back as {srvErr}, a timeout throws. A realm whose
// built-ins changed is marked polluted: the caller replaces it.
const call = (e, name, input, ms) => { const r = e.realm.call(name, input, ms); if (r[0] && r[0].polluted) e.polluted = true; return r; };
// What a fresh realm takes from one that is done (its save, rt, R, fx), whatever its built-ins are now.
const peek = (e, name, input, ms) => (e.realm ? parts(e.realm.raw(name, input, ms, false)) : [{ srvErr: 'gone' }]);
/* A fresh realm in place of one that is done (timed out, polluted, or could not go back in place), from {s, uidN, rt,
live}: same network, new epoch, versions from 0, the fx the old one held (the mark's, or after a read all of them).
R comes from the old realm, which still answers after a timeout: the marked R (mark) or its current one, packed
whole; when it cannot (or is polluted), or that R does not load, R is routed again from rt's routing point. The old
realm is never called again, even when this throws. */
function rebuild(e, from, mark = true) {
let rpack = null;
try { const s = e.realm && e.realm.raw('srvRPack', { mark }, T.load); if (typeof s === 'string' && s.startsWith('{"o"')) rpack = s; } catch (x) { /* gone */ }
const r = build(e.nid, e.lang), epoch = epochOf();
const [h] = r.call('srvLoad', { save: from.s, uidN: from.uidN, rt: from.rt, rpack, live: !!from.live, prefs: e.prefs, epoch, strict: !!opts.strict, clock: from.clock }, T.load);
if (h.srvErr) throw new Error('rebuilding the realm failed: ' + h.srvErr);
e.realm = r; e.epoch = epoch; e.v = 0; e.day = h.day; e.lost = h.lost;
log('warn', `[${e.nid}] realm rebuilt after a timeout (epoch ${epoch}${rpack ? '' : ', R routed again'})`);
if (!from || typeof from.s !== 'string') { e.realm = null; throw new Error('rebuilding the realm failed: nothing to build from'); }
let rpack = null, fx = null;
if (!e.polluted) try { const s = e.realm && e.realm.raw('srvRPack', { mark }, T.load, false); if (typeof s === 'string' && s.startsWith('{"o"')) rpack = s; } catch (x) { /* gone */ }
try { const [h] = peek(e, 'srvFxOut', { mark }, T.small); if (h && Array.isArray(h.fx)) fx = h; } catch (x) { /* gone */ }
e.realm = null;
const epoch = epochOf();
const load = (rp) => {
const r = build(e.nid, e.lang);
const [h] = r.call('srvLoad', { save: from.s, uidN: from.uidN, rt: from.rt, rpack: rp, fx, live: !!from.live, prefs: e.prefs, epoch, strict: !!opts.strict, clock: from.clock }, T.load);
if (h.srvErr) throw new Error(h.srvErr);
return [r, h];
};
let r, h;
try { [r, h] = load(rpack); } catch (x) {
if (!rpack) throw new Error('rebuilding the realm failed: ' + LINE(x));
log('warn', `[${e.nid}] R as it was did not load (${LINE(x)}): routed again`);
rpack = null;
try { [r, h] = load(null); } catch (y) { throw new Error('rebuilding the realm failed: ' + LINE(y)); }
}
e.realm = r; e.polluted = false; e.epoch = epoch; e.v = 0; e.day = h.day; e.lost = h.lost;
log('warn', `[${e.nid}] realm rebuilt (epoch ${epoch}${rpack ? '' : ', R routed again'})`);
}
// The network cannot go on: dropped (later calls answer NO_REALM), and the engine tells the host (4.7).
function lose(e, why) {
e.realm = null; e.broken = true;
if (realms.get(key(e.code, e.nid)) === e) realms.delete(key(e.code, e.nid));
log('error', `[${e.nid}] dropped, its realm could not be built again: ${why}`);
post({ lost: { code: e.code, nid: e.nid, why: String(why).slice(0, 300) } });
}
// A recovery: true when the network has a realm to play on again, else it is dropped.
const recover = (e, f) => { try { f(); return true; } catch (x) { lose(e, LINE(x)); return false; } };
const gone = (e) => (e.realm ? '' : '; the network was dropped: load it again');
// The rt of the old realm's mark, if it still answers; else the last day's, whose routing point belongs to that day's
// S: with another mark only its route memory counts (a close R).
function markRt(e) {
try { const [h] = call(e, 'srvRt', { mark: true }, 200); if (h && !h.srvErr && h.load) return h; } catch (x) { /* gone */ }
return e.dayMark ? (e.dayMark === e.mark ? e.dayMark.rt : { ...e.dayMark.rt, pt: undefined }) : null;
try { const [h] = peek(e, 'srvRt', { mark: true }, 200); if (h && !h.srvErr && h.load) return h; } catch (x) { /* gone */ }
return e.dayMark ? (e.dayMark === e.mark ? e.dayMark.rt : { ...e.dayMark.rt, pt: undefined, rk: undefined }) : null;
}
// The restore point of the next day or action. A failed mark throws {mark:true} and changed nothing applied; one that
// ran out of time has the realm built again from its own save first (or the network dropped).
function mark(e, input) {
const [h, s] = call(e, 'srvMark', input, T.mark);
if (h.srvErr) throw new Error('mark failed: ' + h.srvErr);
e.mark = null;
if (input.day) e.dayMark = null;
let h, s;
try { [h, s] = call(e, 'srvMark', input, T.mark); } catch (x) {
if (!isTimeout(x)) throw x;
recover(e, () => rebuildAfterRead(e));
throw Object.assign(new Error(`marking the network took longer than ${T.mark} ms`), { mark: true, timeout: true });
}
if (h.srvErr) {
if (e.polluted) recover(e, () => rebuildAfterRead(e));
throw Object.assign(new Error('marking the network failed: ' + LINE(h.srvErr)), { mark: true });
}
const m = { s, uidN: h.uidN, rt: h.rt || null, day: h.day, clock: h.clock, live: true };
if (input.day) e.dayMark = m;
e.mark = m;
return m;
}
// After a throw: back to the mark in place; if even that fails, a fresh realm from the mark.
// After a throw: back to the mark in place; if even that fails (or the realm is polluted), a fresh realm from the mark.
function restore(e, input) {
if (!e.polluted) {
try { const [h] = call(e, 'srvRestore', input, T.small); if (!h.srvErr) return; log('warn', `[${e.nid}] restore failed: ${h.srvErr}`); }
catch (x) { log('warn', `[${e.nid}] restore timed out`); }
catch (x) { log('warn', `[${e.nid}] restore failed: ${LINE(x)}`); }
}
rebuild(e, { ...e.mark, rt: input.day ? e.mark.rt : markRt(e) });
}
// A read-only call that timed out: the realm's state is whole (nothing applied was interrupted), so the fresh realm
// starts from its save when it still answers, else from the last mark.
// A call that changed nothing applied and timed out (or left the realm polluted): the fresh realm starts from the
// realm's own save. When even that cannot be read, this throws: never an older mark.
function rebuildAfterRead(e) {
let from = null;
try { const [h, txt] = call(e, 'srvSave', undefined, T.save); if (!h.srvErr) from = { s: txt, uidN: h.uidN, rt: h.rt, clock: h.clock }; } catch (x) { /* gone */ }
if (from) rebuild(e, from, false); else rebuild(e, { ...e.mark, rt: markRt(e) });
try { const [h, txt] = peek(e, 'srvSave', undefined, T.save); if (!h.srvErr && typeof txt === 'string') from = { s: txt, uidN: h.uidN, rt: h.rt, clock: h.clock }; } catch (x) { /* gone */ }
if (!from) { e.realm = null; throw new Error('rebuilding the realm failed: its save could not be read'); }
rebuild(e, from, false);
}
/* ---- the handlers: each returns the reply (or throws, which the engine turns into a rejection) ---- */
@ -105,66 +159,65 @@ function createCore(opts = {}) {
if (n.begin) out.saved = saved(e);
return out;
} catch (x) {
realms.delete(key(c, n.nid));
if (realms.get(key(c, n.nid)) === e) realms.delete(key(c, n.nid));
log('warn', `[${n.nid}] did not load: ${MSG(x)}`);
return { t: 'loaded', nid: n.nid, err: isTimeout(x) ? 'the network took too long to load' : String((x && x.message) || x).split('\n')[0].slice(0, 300) };
return { t: 'loaded', nid: n.nid, err: isTimeout(x) ? 'the network took too long to load' : LINE(x) };
}
}
function saved(e) {
const [h, txt] = call(e, 'srvSave', undefined, T.save);
if (h.srvErr) throw new Error(h.srvErr);
if (h.srvErr) { if (e.polluted) recover(e, () => rebuildAfterRead(e)); throw new Error(h.srvErr); }
return { t: 'saved', nid: e.nid, txt, uidN: h.uidN, rt: h.rt, day: h.day, lost: h.lost };
}
// One network's day, with its mark, one retry, and broken after a second failure.
function dayOne(e, m) {
const t0 = now(), d0 = e.day;
const input = { speed: m.speed, last: m.last, alone: (m.alone || []).includes(e.nid), mute: !!m.mute };
let retried = false, err = null;
for (let i = 0; i < 2; i++) {
const input = { speed: m.speed, last: m.last, alone: m.alone.includes(e.nid), mute: !!m.mute };
let err = null;
for (let i = 0; i < 2 && e.realm; i++) {
try {
mark(e, { day: true });
const [h] = call(e, 'srvDay', input, T.day);
if (h.srvErr) throw Object.assign(new Error(h.srvErr), { inRealm: true });
if (h.srvErr) throw new Error(h.srvErr);
e.day = h.day; e.lost = h.lost;
return { day: h.day, lost: h.lost, ...(h.pause ? { pause: true } : {}), ...(retried ? { retried: true } : {}), ms: +(now() - t0).toFixed(2) };
return { day: h.day, lost: h.lost, ...(h.pause ? { pause: true } : {}), ...(i ? { retried: true } : {}), ms: msOf(t0) };
} catch (x) {
err = x; retried = true;
log('warn', `[${e.nid}] day ${d0 + 1} failed (${isTimeout(x) ? 'timeout' : 'throw'}${i ? ', again' : ''}): ${MSG(x)}`);
try { if (isTimeout(x) || !e.mark) rebuild(e, e.dayMark || e.mark); else restore(e, { day: true }); }
catch (y) { log('error', `[${e.nid}] could not go back before the day: ${MSG(y)}`); break; }
err = x;
log('warn', `[${e.nid}] day ${d0 + 1} failed (${x.mark ? 'mark' : isTimeout(x) ? 'timeout' : e.polluted ? 'polluted' : 'throw'}${i ? ', again' : ''}): ${MSG(x)}`);
// A failed mark changed nothing (the realm is as it was, built again from its own save, or dropped). Else back
// to this attempt's mark: in place after a throw, a fresh realm after a timeout or a pollution.
if (!x.mark && !recover(e, () => { if (isTimeout(x) || e.polluted) rebuild(e, e.dayMark); else restore(e, { day: true }); })) break;
}
}
e.broken = true;
return { day: e.day, lost: !!e.lost, err: (isTimeout(err) ? 'timeout: ' : '') + String((err && err.message) || err).split('\n')[0].slice(0, 300), retried: true, ms: +(now() - t0).toFixed(2) };
return { day: e.day, lost: !!e.lost, err: (isTimeout(err) ? 'timeout: ' : '') + LINE(err) + gone(e), retried: true, ms: msOf(t0) };
}
// An action or a what-if: its mark, the call, and the way back when it fails.
function marked(m, e, name, input, ms, what) {
try { mark(e, input); } catch (x) { if (!x.mark) throw x; return [errReply(m, x.timeout ? 'timeout' : 'throw', x.message + gone(e))]; }
let r;
try { r = call(e, name, m.msg, ms); } catch (x) {
if (!isTimeout(x)) throw x;
recover(e, () => rebuild(e, { ...e.mark, rt: markRt(e) }));
return [errReply(m, 'timeout', `the ${what} took longer than ${ms} ms` + gone(e))];
}
if (r[0].srvErr) { recover(e, () => (e.polluted ? rebuild(e, { ...e.mark, rt: markRt(e) }) : restore(e, {}))); return [errReply(m, 'throw', r[0].srvErr + gone(e))]; }
return r;
}
const H = {
act(m, e) {
if (e.broken || e.lost) return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: 'stopped', v: e.v, upd: null };
try {
mark(e, { keys: true });
const [h, upd] = call(e, 'srvAct', m.msg, T.act);
if (h.srvErr) { restore(e, {}); return errReply(m, 'throw', h.srvErr); }
const t0 = now(), [h, upd] = marked(m, e, 'srvAct', { keys: true }, T.act, 'action');
if (h.t === 'err') return h;
e.v = h.v;
if (h.outcome === 'stopped') e.lost = true;
return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: h.outcome, ...(h.why ? { why: h.why } : {}), v: h.v, upd: upd || null };
} catch (x) {
if (!isTimeout(x)) throw x;
rebuild(e, { ...e.mark, rt: markRt(e) });
return errReply(m, 'timeout', `the action took longer than ${T.act} ms`);
}
return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: h.outcome, ...(h.why ? { why: h.why } : {}), v: h.v, upd: upd || null, ms: msOf(t0) };
},
ask(m, e) {
if (e.broken || e.lost) return { t: 'askDone', nid: m.nid, rid: m.msg.rid, err: 'stopped' };
try {
mark(e, {});
const [h] = call(e, 'srvAsk', m.msg, T.ask);
if (h.srvErr) { restore(e, {}); return errReply(m, 'throw', h.srvErr); }
return { t: 'askDone', nid: m.nid, rid: m.msg.rid, ...h };
} catch (x) {
if (!isTimeout(x)) throw x;
rebuild(e, { ...e.mark, rt: markRt(e) });
return errReply(m, 'timeout', `the what-if took longer than ${T.ask} ms`);
}
const t0 = now(), [h] = marked(m, e, 'srvAsk', {}, T.ask, 'what-if');
if (h.t === 'err') return h;
return { t: 'askDone', nid: m.nid, rid: m.msg.rid, ...h, ms: msOf(t0) };
},
pull(m, e) { return pulled(m, e, 'srvPull', { snap: !!m.snap, views: m.views }); },
greet(m, e) { return pulled(m, e, 'srvGreet', {}); },
@ -173,28 +226,36 @@ function createCore(opts = {}) {
},
save(m, e) { return guarded(m, e, () => saved(e)); },
card(m, e) { return guarded(m, e, () => { const [h] = call(e, 'srvCard', undefined, T.small); if (h.srvErr) return errReply(m, 'throw', h.srvErr); return { t: 'card', nid: m.nid, card: h.card || null }; }); },
prefs(m, e) { if (m.prefs) e.prefs = { ...e.prefs, ...m.prefs }; return guarded(m, e, () => { call(e, 'srvPrefs', { prefs: m.prefs }, T.small); return null; }); },
prefs(m, e) { if (m.prefs) e.prefs = { ...e.prefs, ...m.prefs }; return guarded(m, e, () => { const [h] = call(e, 'srvPrefs', { prefs: m.prefs }, T.small); return h.srvErr ? errReply(m, 'throw', h.srvErr) : null; }); },
// Tests only: a piece of code in the realm, its value back.
eval(m, e) {
if (!test) throw new Error('eval is for tests');
try { return { value: e.realm.eval(m.src, m.ms || 5000) }; }
catch (x) { if (isTimeout(x)) { rebuildAfterRead(e); return { timeout: true, epoch: e.epoch }; } return { error: MSG(x) }; }
catch (x) { if (isTimeout(x)) { recover(e, () => rebuildAfterRead(e)); return { timeout: true, epoch: e.epoch }; } return { error: MSG(x) }; }
},
};
function pulled(m, e, name, input) {
return guarded(m, e, () => {
const [h, ...p] = call(e, name, input, T.pull);
const t0 = now(), [h, ...p] = call(e, name, input, T.pull);
if (h.srvErr) return errReply(m, 'throw', h.srvErr);
e.v = h.v;
const o = { t: 'pulled', nid: m.nid, epoch: e.epoch, v: h.v };
(h.parts || []).forEach((k, i) => { o[k] = p[i]; });
if (h.subs) o.subs = h.subs;
o.ms = msOf(t0);
return o;
});
}
// A call that changes nothing applied: after a timeout the realm is built again from its own save.
// A call that changes nothing applied: after a timeout (or a pollution) the realm is built again from its own save.
function guarded(m, e, f) {
try { return f(); } catch (x) { if (!isTimeout(x)) throw x; rebuildAfterRead(e); return errReply(m, 'timeout', `${m.t} took too long`); }
let r;
try { r = f(); } catch (x) {
if (!isTimeout(x)) { if (e.polluted && e.realm) recover(e, () => rebuildAfterRead(e)); throw x; }
recover(e, () => rebuildAfterRead(e));
return errReply(m, 'timeout', `${m.t} took too long` + gone(e));
}
if (e.polluted && e.realm) recover(e, () => rebuildAfterRead(e));
return r;
}
/* ---- the queue ---- */
@ -224,6 +285,7 @@ function createCore(opts = {}) {
}
return false;
}
const strings = (a) => [...new Set(a.filter((n) => typeof n === 'string'))];
function start(j) {
if (j.t === 'mem') { const h = v8.getHeapStatistics(), mu = process.memoryUsage(); return reply(j, { heapUsed: h.used_heap_size, heapTotal: h.total_heap_size, external: h.external_memory, rss: mu.rss, realms: realms.size }); }
if (j.t === 'load') {
@ -237,13 +299,16 @@ function createCore(opts = {}) {
seen.add(n.nid);
}
const s = session(j.code);
for (const n of nets) realms.set(key(j.code, n.nid), { code: j.code, nid: n.nid, lang: n.lang || 'en', prefs: n.prefs || {}, loading: true, realm: null, epoch: '', v: 0, day: 0, lost: false, broken: false, mark: null, dayMark: null });
for (const n of nets) realms.set(key(j.code, n.nid), { code: j.code, nid: n.nid, lang: n.lang || 'en', prefs: n.prefs || {}, loading: true, realm: null, epoch: '', v: 0, day: 0, lost: false, broken: false, polluted: false, mark: null, dayMark: null });
s.load = { j, i: 0, out: [] };
return;
}
if (j.t === 'day') {
// The lists as lists (of network ids), or the day is refused whole; speed and last the realm checks itself.
for (const k of ['nets', 'alone']) if (j[k] !== undefined && !Array.isArray(j[k])) throw new Error(`day: ${k} must be a list`);
j.alone = strings(j.alone || []);
const s = session(j.code);
const order = [...new Set(j.nets || [])].sort().filter((n) => { const e = realms.get(key(j.code, n)); return e && !e.loading && !e.broken && !e.lost; });
const order = strings(j.nets || []).sort().filter((n) => { const e = realms.get(key(j.code, n)); return e && !e.loading && !e.broken && !e.lost; });
s.day = { j, order, i: 0, out: {} };
return;
}
@ -254,25 +319,49 @@ function createCore(opts = {}) {
}
const e = realms.get(key(j.code, j.nid));
if (e && e.loading) { realms.delete(key(j.code, j.nid)); log('error', `[${j.nid}] marked loading with no load under way: dropped`); }
if (!e || e.loading) throw Object.assign(new Error(`no realm ${key(j.code, j.nid)}`), { code: 'NO_REALM' });
if (!e || e.loading || !e.realm) throw Object.assign(new Error(`no realm ${key(j.code, j.nid)}`), { code: 'NO_REALM' });
const h = H[j.t];
if (!h) throw new Error(`unknown message ${j.t}`);
running(j.code);
return reply(j, h(j, e));
}
// One step of a session's load (one network) or day (one network).
// One step of a session's load (one network) or day (one network). A throw answers the whole call, never the worker.
function runStep() {
const ss = [...sessions.values()].filter((s) => s.load || s.day);
if (!ss.length) return false;
const s = ss[turn++ % ss.length];
if (s.load) {
const L = s.load, n = L.j.nets[L.i++];
if (n) L.out.push(loadOne(L.j.code, n));
const L = s.load;
try {
const n = L.j.nets[L.i++];
if (n) { running(s.code); L.out.push(loadOne(L.j.code, n)); }
if (L.i >= L.j.nets.length) { s.load = null; reply(L.j, L.out); }
} catch (x) {
s.load = null;
for (const n of L.j.nets.slice(L.i)) { const e = n && realms.get(key(L.j.code, n.nid)); if (e && e.loading) realms.delete(key(L.j.code, n.nid)); }
log('error', `mp-sim worker: a load of ${s.code} failed: ${MSG(x)}`);
fail(L.j, x);
}
return true;
}
const D = s.day, nid = D.order[D.i++];
if (nid) { const e = realms.get(key(D.j.code, nid)); if (e && !e.broken && !e.lost) D.out[nid] = dayOne(e, D.j); }
const D = s.day;
try {
const nid = D.order[D.i++];
const e = nid && realms.get(key(D.j.code, nid));
if (e && !e.broken && !e.lost && e.realm) {
running(s.code);
try { D.out[nid] = dayOne(e, D.j); } catch (x) {
e.broken = true;
log('error', `[${nid}] the day could not run: ${MSG(x)}`);
D.out[nid] = { day: e.day, lost: !!e.lost, err: 'the day could not run: ' + LINE(x), retried: false, ms: 0 };
}
}
if (D.i >= D.order.length) { s.day = null; reply(D.j, { t: 'dayDone', code: D.j.code, d: D.j.d, nets: D.out }); }
} catch (x) {
s.day = null;
log('error', `mp-sim worker: a day of ${s.code} failed: ${MSG(x)}`);
fail(D.j, x);
}
return true;
}
/* Turns: a message and a step of a session's load or day, in alternation. The worker goes on only while something ran:
@ -283,11 +372,13 @@ function createCore(opts = {}) {
function pump() {
pumping = false;
flip = !flip;
try {
if (flip ? runJob() || runStep() : runStep() || runJob()) return kick();
if (!jobs.length) return;
const j = jobs.shift();
log('error', `mp-sim worker: ${j.t} for ${key(j.code, j.nid)} waited for nothing that could come; answered`);
fail(j, new Error(`${j.t} could not run`));
} catch (x) { log('error', `mp-sim worker: ${MSG(x)}`); }
kick();
}
function kick() { if (!pumping) { pumping = true; setImmediate(pump); } }
@ -304,7 +395,11 @@ if (!isMainThread && workerData && workerData.mpSim) {
const log = (level, text) => post({ log: [level, text] });
process.on('unhandledRejection', (e) => log('warn', 'unhandled rejection in a realm: ' + MSG(e)));
let core;
try { core = createCore({ ...W, log, post }); } catch (e) { post({ fatal: MSG(e) }); process.exit(1); }
try {
// Tests only: a worker that cannot start (the engine backs off, then stops trying).
if (W.test && W.test.startFail) throw new Error('injected: the game does not start');
core = createCore({ ...W, log, post });
} catch (e) { post({ fatal: MSG(e) }); process.exit(1); }
parentPort.on('message', (m) => core.handle(m));
post({ ready: true, simId: core.simId });
}

View file

@ -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,
};

View file

@ -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 };

View file

@ -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) },

View file

@ -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);

View file

@ -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) => {

View file

@ -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' };

View file

@ -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 {