Compare commits

..

7 commits

Author SHA1 Message Date
jvanvik
3e30621684 Test timings of the server-run engine's tests and the built-ins test
Some checks failed
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Has been cancelled
Container image / test (push) Has been cancelled
Container image / publish (push) Has been cancelled
Seconds per file from a full npm test --timings run on this machine
(every file at once), for the shard split.
2026-11-09 22:22:40 +01:00
jvanvik
77f4035853 Six actions look up their city among the network's own POPs only
launchBB, addSite, addRouter, upRouter, addGen and myIxUp read S.pops[city]
(S.myIx[city]) without checking the key, so a city named '__proto__' found
Object.prototype and wrote to it (launchBB left Object.prototype.bb behind,
and every for…in after it saw that), and 'constructor' spent cash on
statics of Object. Only an MCP agent or a request to a server-run network
can send such a city; the page's own buttons never do. Each now takes the
POP only when it is an own key (own(), as sanitize() does).

tests/act-args-builtins.test.js sends every action an agent may send with
'__proto__', 'constructor' and 'prototype' in each usual arg and checks
that the page's built-ins stay as they were; without this change it finds
exactly these six. No state, strings or saves change.

Performance on the big network against 61e31c5 (npm run perf, headless,
median of 15 runs, ms):

| What | Base | This | Change | p |
|---|--:|--:|--:|--:|
| Routing: compute() | 25.4 | 28.1 | +11% | 0.90 |
| One game day: dayTick() | 27.8 | 28.7 | +3% | 0.77 |
| An action: after() | 1.82 | 1.77 | -3% | 0.77 |
| Side panel and left list | 58.8 | 57.1 | -3% | 0.013 |
| NOC dashboard tabs | 95.9 | 95.9 | +0% | 1.00 |
| Map at three zoom levels | 3.49 | 3.30 | -6% | 0.53 |
| The NOC intern's shift: opsDay() | 3.45 | 3.52 | +2% | 0.80 |

Routing results are identical to the base; no slowdowns beyond noise.
2026-11-09 22:18:56 +01:00
jvanvik
9597d89079 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.
2026-11-09 22:16:52 +01:00
jvanvik
3b8c331556 Auto-TE and the chaos monkey's leaving are written as a reload makes them
Two places left a key in a shape that sanitize() repairs on the next load, so
the live game was not its own save (the server-run engine refuses such an
action at its gate, and its strict day check would refuse such a day):

- buyTE wrote S.te as {on, day}; a reload adds script:''. It now writes the
  script slot itself (src/game/90-actions/30-route-script-and-tools.js).
- mkLeave turned the monkey off but kept start, until, snip, n, hurt and c;
  sanitize() keeps only next and on for a monkey that is away. It now leaves
  S.monkey as {next, on:0}, after the toasts that still read the visit's count
  (src/game/85-incidents/40-chaos-monkey.js). This covers the visit running
  out, the banana and the rules sending it home.

No new state field, nothing for old saves: both keys load as before. Nothing a
player sees changes, so no CHANGELOG bullet.

Tests: tests/backbone-core.test.js (S.te after buyTE equals what a reload makes
of it) and tests/chaos-monkey.test.js (S.monkey after each way home: outlasted,
hurt, sent home by calmer rules, bribed). Both fail without this change. The
server-run tests take their workarounds out: buyTE and the banana pass the gate
and leave the network the page leaves (tests/mp-sim-acts.test.js, the former
todo), the 60-day realm-vs-page plan clicks buyTE on day 21 instead of setting
S.te, and the gate audit no longer excuses either act.

The Pie in the Sky line the review also named (60-pie.js:66, S.monkey.n++ on a
monkey that is away) is not reachable: its only caller fires a laser incident
behind mkOn(), so it is left as it is.

Performance (npm run perf -- --base-ref 61e31c5, headless, big network, median
of 15 runs, ms):

| What | Base | This | Change | p |
|---|--:|--:|--:|--:|
| Routing: compute() | 27.3 | 26.1 | -4% | 0.51 |
| One game day: dayTick() | 29.7 | 30.1 | +1% | 0.71 |
| An action: after() | 1.96 | 1.86 | -5% | 0.48 |
| Side panel and left list | 62.0 | 59.2 | -5% | 0.023 |
| NOC dashboard tabs | 110 | 110 | +0% | 0.93 |
| Map at three zoom levels | 3.69 | 3.90 | +6% | 0.43 |
| The NOC intern's shift: opsDay() | 4.06 | 3.95 | -3% | 0.11 |

Routing results identical to the base; no change beyond noise.
2026-11-09 20:47:42 +01:00
jvanvik
72f31e809b Server-run engine: every call answers, and a crashing load gets its own worker
A load whose networks did not all check out could hang its session for good, a
worker could spin on a job it could never run, a session whose load crashed its
worker never got a worker of its own, and an unload followed at once by a load
(a language change) lost the session's place or never answered. Fixed:

- Worker: a load call is checked whole before it touches anything. One that
  names no network, or one twice, is refused (ERR) and every realm stays as it
  was. A network without a save now answers err (broken) like one whose save
  does not load, and the others load. A network marked loading with no load
  under way answers NO_REALM instead of waiting for ever.
- Worker: it goes on only while something ran. If a job were ever still
  waiting when nothing could run, it is answered (ERR, logged) rather than left
  pending, and the worker no longer busy-loops on it.
- Engine: a session is on its worker from the moment its load is sent. A worker
  exit counts against the sessions whose load was under way (else against every
  session it held), so a save that crashes its worker gets a worker of its own
  after two exits and is given up (GAVE_UP) after a third, while the sessions
  that only shared the worker lose their realms but not their place in the pool.
  Loads under way count for placement.
- Engine: an unload no longer drops the placement of a session whose next load
  is under way, so an unload and a load sent back to back stay on one worker; a
  worker of its own is retired only when no call is pending on it (a pending
  call there used to never settle).
- Engine: a message that cannot be sent rejects (ERR) and leaves nothing pending.
- Realm: a what-if puts UI.hotMap back too (teSlop's trial left its own).
- Realm: a network in a language this server has no dictionary for plays in
  English, as the page does, instead of loading broken.

Tests (tests/mp-sim-engine.test.js): a malformed load changes nothing and every
call of the session answers within 3 s, with the workers idle after; an unload
and a load back to back keep the session on its worker; a session whose load
takes its worker down twice gets a worker of its own, then GAVE_UP, while the
bystander is never blamed; an ask leaves UI.hotMap as it was; a network in an
unknown language loads in English. Each fails on the engine before this change
(the worker's alone: the hang; the engine's alone: the placement and the exits;
the realm's alone: teSlop's hotMap and the language).

The two drafts no test played are played now (tests/mp-sim-acts.test.js): a
premium border crossing into Hong Kong (buildLink with cnPrem) and the AI's own
script deployed as it wrote it while it drops most of the traffic (teDeploy with
slop, on a small network with one capped transit port), each compared byte for
byte with the page's clicks, and both read in the DRAFTS check (nothing is left
unplayed).

Runs, each file alone under an 8G cap: mp-sim-engine 16/16 (11.6 s),
mp-sim-contract 8/8, mp-sim-acts 5 + 1 todo (10.9 s), mp-sim-determinism 6/6
(53.4 s).
2026-11-09 20:47:31 +01:00
jvanvik
c5c7ea9508 Server-run engine: a restored network plays on exactly as before
A network loaded from its checkpoint drifted from the one that never stopped:
after a checkpoint on day 1, 2 or 5 its R differed at once (bizDem at Ashburn
6426 against 26, then cityDem, citySrv, tNet), and from the next day S too
(cash, eyeball growth). Three causes, each shown by a probe:

- R after a day is the R of the day's last routing, made before the day's end
  changed S (customers who left or signed, moods, bills, transit history) and
  routed from the memory of the R before it. srvLoad routed the saved S again
  from R's own memory: another R, which the next day reads (sfOf for eyeball
  growth, the peering share). Every compute() in the realm now keeps, for the
  R it makes, S as it routed it (one JSON per top-level key, 0.8 ms big) and
  the memory it started from. rt carries that routing point (pt: the memory,
  the keys that changed since, the keys S did not have then), and srvLoad
  routes that S again from it: the same R, byte for byte. The old restore test
  checkpointed after day 10, where a failure or event routed again at the end
  of the day and nothing changed after it: it passed by luck.
- The sales desk's tried offers (UI.slTried, an offer that did not fit waits a
  week) live outside S. A fresh realm forgot them and the desk tried other
  offers. rt carries them (sl); a day mark keeps them and the in-place restore
  after a throw puts them back (before, a parsed S dropped them).
- A save and a reload give some keys back in another key order (a customer's
  defaults go last, the intern's week tally in its own order), and the week's
  report lists the tally in that order. At a checkpoint rt carries the live
  text of each such key (ord, srvGate's round trip, about 8 ms), taken on load
  only where it holds what sanitize() made of the save. A fresh realm after a
  timeout takes the mark's own text the same way (live).

The plain game drifts across a save and a reload too (jsdom: from the first
day after it; the page routes a reloaded S with an empty R and keeps no desk
memory): a game property, so the engine carries what is missing.

The envelope keeps its shape {s, uidN, rt, last, day}; rt keeps R's own route
memory, so an older checkpoint loads as before (close, not exact). Big network:
the checkpoint grows from about 42-49 KB gzip to 54-79 KB (rt 7-29 KB; the
whole R would be 375 KB), srvSave from 2-2.5 ms to 7-8 ms, a load by one
routing. A day with its mark costs the same (big 39.8 -> 37.8 ms, busy
90.0 -> 88.8 ms, within noise: the day mark joins per-key JSON now, which pays
for the routing point).

Tests: the restore test checkpoints after days 1, 2, 5 and 10 of the scenic big
network and of the same network busy (intern on every order, the desk signing
on its own, failures, events, an attack), those after days 2 and 10 right after
an action and a what-if (sent to the copies too), each compared byte for byte
at once and 10 days later (SIM_LONG: after every day to 30, 60 checkpoints). It
fails on the old engine, and without any one of the three parts. The retry test
plays busy networks (fails without the desk memory in srvRestore). The market
checkpoint compares bytes too; canon() is gone.
2026-11-09 20:16:38 +01:00
jvanvik
065c922287 Server-run play, part 2: the engine
The engine that runs every network of a server session (server-sim design,
section 4): each network in its own vm realm, realms in a small pool of
worker threads, a promise API for the session host. Nothing uses it yet;
the plain build and the game are unchanged (no file under src/).

- scripts/lib/mp-sim-realm.js: one network in a DONT_CONTEXTIFY realm
  running the plain page's game (never the MP page's client folder), with
  recording DOM stand-ins, no-op timers that count, and the srv... calls:
  load from a checkpoint (route memory seeded, then routed), begin a new
  network, marks and restores, the day as a page runs it, the action
  pipeline with drafts, arming, the sanitize gate and rollback, what-ifs
  that put S, R, the dice and uidN back, pulls with top-level key diffs,
  slim R and flow records on demand, fx captured and bounded, saves, cards.
- scripts/lib/mp-sim-worker.js: realms per session in one worker, days one
  network at a time with other messages between them, loads and unloads
  waiting for a session's day, time limits; a throw goes back to the mark
  in place, a timeout gets a fresh realm (new epoch) carrying the old R, a
  day is retried once and the network broken after a second failure.
- scripts/lib/mp-sim-engine.js: createEngine() with the fake engine's API,
  placement by realm count, every pending call rejected when its worker
  exits, a worker of its own after two exits in an hour; snapWith() joins
  the host's clock, roster and since to a realm's snapshot.
- Contract: a pulled snapshot is the realm's half (the host adds clock,
  roster, since); haptic fx carry milliseconds; the fake engine follows,
  with close() and snapWith(). The button crawl moved to tests/lib.
- Tests: realm vs jsdom byte for byte over 60 scenic big-network days with
  actions; restore; retry after a throw or a timeout; realm order; a timer
  audit and the gate over a sweep of sent buttons (SIM_LONG=1: a year and
  every button); captures, rollbacks, asks, selection reports, ordering,
  bounds, pollution, worker exits; the act tables against the game.

The gate found two keys the game writes in a shape a reload repairs (buyTE's
S.te, mkLeave's S.monkey): game fixes for the integrator, kept visible as a
todo test and a list in the audit.

Rebased onto the 3.3.0 merge (61e31c5): the engine itself needed no change. A
realm still routes in the game's own code (no route worker, no saves), the
route cache that now keeps list orders from day to day leaves a checkpoint and a
retry the same, and the capacity market and moved customers play in a realm as
on a page, under the strict gate. The tests needed three things: an old save's
first days earn the new traffic badges, which the unwatched network's snapshot
keeps; the restore test compares JSON text with sorted keys instead of a
deep-equal of two networks (a diff of gigabytes when they differ); and the crawl
opens the windows that move a customer, with a new test playing the market's and
the path moves' acts, 40 days of sales and a checkpoint against the page.
2026-11-09 19:30:38 +01:00
23 changed files with 2915 additions and 64 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

@ -0,0 +1,268 @@
// The server-run engine (the server-sim design, sections 4.2-4.3): a small pool of worker threads (mp-sim-worker.js),
// each holding the vm realms (mp-sim-realm.js) of the sessions placed on it, behind a promise API. The session host
// (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, 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
// here: route memory, R's routing point, key order, the sales desk's memory); begin: {name, home,
// preset, asn, mp, tut} builds a new network, checkpointed at once (saved). A network that comes
// without a save, whose save does not load, or that cannot begin answers err: broken (4.7), and
// the others load. A load of a network that is loaded replaces its realm (a failed one leaves none).
// 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, 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 (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), 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.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;
/* The stream event of a snapshot: the realm's half (S, r, keep, epoch, v, now) with the host's (clock, roster,
since), joined as text: the realm's 270 KB are never parsed again. */
function snapWith(snap, { clock, roster, since }) {
if (typeof snap !== 'string' || !snap.endsWith('}')) throw new Error('snapWith: not a snapshot');
return snap.slice(0, -1) + ',"clock":' + JSON.stringify(clock) + ',"roster":' + JSON.stringify(roster) + ',"since":' + JSON.stringify(since) + '}';
}
function createEngine(opts = {}) {
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 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;
// 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).
const size = (w) => [...w.sessions.values()].reduce((a, b) => a + b.size, 0);
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, 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) { 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);
// An idle worker does not keep the process alive; one with calls pending does.
if (!w.pending.size) w.worker.unref();
if (m.ok) p.ok(m.reply);
else p.no(Object.assign(new Error(m.error.message), { code: m.error.code }));
});
w.worker.on('error', (e) => log('error', 'mp-sim worker failed: ' + (e && e.message)));
w.worker.on('exit', (c) => died(w, c));
w.worker.unref();
return w;
}
function died(w, c) {
if (w.dead) return;
w.dead = true;
// 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();
for (const [k, x] of own) if (x === w) own.delete(k);
if (closed) return;
const i = pool.indexOf(w);
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());
// The worker of a session: where it is, else the pool's least loaded one (or one of its own, after two exits).
function workerOf(code, create) {
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 {
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(CLOSED());
if (!w || w.dead) return Promise.reject(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
const id = ++seq;
return new Promise((ok, no) => {
if (!w.pending.size) w.worker.ref();
w.pending.set(id, { ok, no });
// A message that cannot be sent (not cloneable) is a malformed call, and nothing waits for its answer.
try { w.worker.postMessage({ id, ...m }); } catch (e) { w.pending.delete(id); if (!w.pending.size) w.worker.unref(); no(Object.assign(new Error(String((e && e.message) || e)), { code: 'ERR' })); }
});
}
const noRealm = (code, nid) => Promise.reject(Object.assign(new Error(`no realm ${code}/${nid}`), { code: 'NO_REALM' }));
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,
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); }
// Under way: the session is on this worker from now (an exit meanwhile counts against it, and its placement holds).
const n = nets.length, done = () => { const k = (w.loading.get(code) || 0) - n; if (k > 0) w.loading.set(code, k); else w.loading.delete(code); };
w.loading.set(code, (w.loading.get(code) || 0) + n);
return send(w, { t: 'load', code, nets }).then((r) => {
done();
const s = mine(w, code);
for (const l of r) if (!l.err) s.add(l.nid); else s.delete(l.nid);
return r;
}, (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 });
},
act(code, nid, msg) { return to(code, nid, { t: 'act', msg }); },
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((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) => {
const s = w.sessions.get(code);
if (s) { if (nid === undefined) s.clear(); else s.delete(nid); }
// Gone from here, unless a load of it sent after this unload is under way.
if ((!s || !s.size) && !w.loading.has(code)) { w.sessions.delete(code); if (placed.get(code) === w) placed.delete(code); }
// A worker of its own with nothing on it and nothing pending is done (with a call pending it would never answer).
if (w.dedicated && !w.dead && !w.sessions.size && !w.loading.size && !w.pending.size) { if (own.get(code) === w) own.delete(code); w.dead = true; w.worker.terminate(); }
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) };
},
close() {
closed = true;
const ws = [...pool, ...own.values()];
return Promise.all(ws.map((w) => (w.dead ? null : w.worker.terminate()))).then(() => undefined);
},
snapWith,
};
if (test) {
engine.eval = (code, nid, src, ms) => to(code, nid, { t: 'eval', src: String(src), ...(ms ? { ms } : {}) });
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);
}
return engine;
}
module.exports = { createEngine, snapWith };

562
scripts/lib/mp-sim-realm.js Normal file
View file

@ -0,0 +1,562 @@
// One network of a server session, run by the game's own code in a vm realm (the server-sim design, section 4.1).
// The realm is a vm context made with DONT_CONTEXTIFY, so it has its own intrinsics (a prototype polluted in one realm
// stays there) and runs at full speed. Into it go, in order: the prelude below (DOM stand-ins that record what the
// game writes and reads back, no-op timers that count, the network's language), the network's dictionary
// (site/i18n/<lang>.js, not English), the game script, and the epilogue (the srv… functions: what the server asks of a
// network, and the rebinds that turn toasts, sounds, windows and the like into effects, "fx", for the page).
//
// The worker (mp-sim-worker.js) calls into a realm only through call()/raw(): the input goes in as one JSON string
// (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 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, 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';
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { assemble, simId, ROOT } = require('./page');
const ACTS = require('./mp-sim-acts');
/* The page whose game a realm runs: the plain one (design 4.1), never a multiplayer build's page. That one also holds
the server-play client (src/game/98-server-play/), whose rebinds of after, toast and save are for a page that shows
a server's network; inside the server's own realm they would have to be switched off one by one. The build id
(SIM_ID) still names the multiplayer page, which holds this game and its client both. */
const REALM_PAGE = Object.freeze({ dev: false, mp: false });
function gameSource({ root = ROOT, page = REALM_PAGE } = {}) {
const html = assemble({ src: path.join(root, 'src'), dev: !!page.dev, mp: !!page.mp }).html;
let best = '';
html.replace(/<script>([\s\S]*?)<\/script>/g, (m, s) => { if (s.length > best.length) best = s; return m; });
if (!best.includes('function dayTick')) throw new Error('mp-sim-realm: no game script in the assembled page');
return best;
}
const LANG_RE = /^[a-z]{2}$/;
function dictSource(lang, root = ROOT) {
if (!lang || lang === 'en') return null;
if (!LANG_RE.test(lang)) throw new Error(`mp-sim-realm: bad language ${JSON.stringify(String(lang).slice(0, 20))}`);
const f = path.join(root, 'site', 'i18n', lang + '.js');
if (!fs.existsSync(f)) throw new Error(`mp-sim-realm: no dictionary for ${lang}`);
return fs.readFileSync(f, 'utf8');
}
/* The realm's stand-ins (start: probe/srv-engine/common.js prelude({mode:'record'}), which kept S byte-identical to
jsdom over 30 big-network days). opts.seed: a test's seeded Math.random under the game's own seeded wrapper (the
harness's generator, so a realm and a test page draw the same numbers); opts.now: a test's pinned Date.now, moved on
by opts.step at every day. Without them the realm has its own Math.random and the real clock. */
function prelude({ lang = 'en', seed = null, now = null, step = 2500, test = false } = {}) {
const L = JSON.stringify(LANG_RE.test(lang) ? lang : 'en');
return `'use strict';
globalThis.self=globalThis;self.window=self;self.__TUBES_WORKER__=1;self.__TUBES_TEST__=true;
{const hn=__hostNow;self.performance={now:()=>hn(),mark(){},measure(){},timeOrigin:0};}
{const hl=__hostLog,f=l=>(...a)=>{try{hl(l,a.map(x=>x&&x.stack?x.stack:String(x)).join(' '));}catch(e){}};self.console={log:f('log'),info:f('info'),warn:f('warn'),error:f('error'),debug:f('debug'),trace:f('debug')};}
// No timers in a realm: nothing may run outside the worker's handling of a message. Calls are counted (the timer audit).
self.__SRV_T={n:0,at:${test ? '[]' : 'null'}};
{const t=k=>function(){__SRV_T.n++;if(__SRV_T.at&&__SRV_T.at.length<50)__SRV_T.at.push(k+': '+String(new Error().stack).split('\\n').slice(2,7).join(' < '));return 0;};
for(const k of ['setTimeout','setInterval','requestAnimationFrame','queueMicrotask','setImmediate','requestIdleCallback'])self[k]=t(k);
for(const k of ['clearTimeout','clearInterval','cancelAnimationFrame','clearImmediate','cancelIdleCallback'])self[k]=()=>{};}
${seed == null ? '' : `{let r=${(+seed | 0) || 12345};Math.random=()=>{r=(r*16807)%2147483647;return r/2147483647;};}`}
${now == null ? '' : `{let t=${+now};Date.now=()=>t;self.__srvClock=v=>{if(typeof v==='number')t=v;return t;};self.__srvStep=${+step || 0};}`}
const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true});
const _store=()=>{const m=new Map();return {getItem:k=>m.has(String(k))?m.get(String(k)):null,setItem(k,v){m.set(String(k),String(v));},removeItem(k){m.delete(String(k));},clear(){m.clear();},key:i=>[...m.keys()][i]??null,get length(){return m.size;}};};
const _ent={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\\u00a0',middot:'\\u00b7',times:'\\u00d7',rarr:'\\u2192',larr:'\\u2190',hellip:'\\u2026',mdash:'\\u2014',ndash:'\\u2013',bull:'\\u2022',deg:'\\u00b0',euro:'\\u20ac',thinsp:'\\u2009'};
const _txt=h=>String(h).replace(/<[^>]*>/g,'').replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi,(m,e)=>e[0]==='#'?String.fromCodePoint(e[1]==='x'||e[1]==='X'?parseInt(e.slice(2),16):+e.slice(1)):(e in _ent?_ent[e]:m));
// Elements keep innerHTML, hidden and value, and answer textContent and firstElementChild from what was written; they
// have no children (morphKids would loop for ever on the inert proxy's endless nextSibling).
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;
for(const [k,v] of Object.entries({document:_doc,localStorage:_store(),sessionStorage:_store(),innerWidth:1024,innerHeight:768,devicePixelRatio:1,
matchMedia:q=>({matches:/pointer:\\s*coarse/.test(String(q))?!!self.__srvCoarse:false,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}),
Image:_n,Audio:_n,AudioContext:undefined,webkitAudioContext:undefined,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},
SOT_LANG:${L},SOT_LANGS:{en:'English',it:'Italiano',pt:'Português',fr:'Français',es:'Español',de:'Deutsch'},I18N:{},
location:{href:'https://server.invalid/',protocol:'https:',hostname:'server.invalid',host:'server.invalid',origin:'https://server.invalid',search:'',hash:'',pathname:'/',reload(){},replace(){},assign(){}},
addEventListener(){},removeEventListener(){},dispatchEvent(){return true;},
// Nothing reaches out of a realm: no channels, sockets or requests (fetch never settles), no workers.
BroadcastChannel:undefined,WebSocket:undefined,EventSource:undefined,Worker:undefined,fetch:()=>new Promise(()=>{}),
navigator:{language:${L},languages:[${L}],userAgent:'tubes-server',onLine:true,maxTouchPoints:0,hardwareConcurrency:1,vibrate:()=>false}}))
Object.defineProperty(self,k,{value:v,writable:true,configurable:true,enumerable:true});
`;
}
/* 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, 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=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,
mark:null,markK:null,markRt:null,strict:false};
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);
if(q.length>200){const i=q.findIndex(x=>!SIM_KEEP.has(x[0]));q.splice(i>=0?i:0,1);}
if(SIM_KEEP.has(f[0])){let n=0;for(const x of q)if(SIM_KEEP.has(x[0]))n++;if(n>32)q.splice(q.findIndex(x=>SIM_KEEP.has(x[0])),1);}}
// At most 60 in one update: floaters go first, then sounds and the like, then the oldest toasts; windows, badges,
// pauses and the chaos monkey's last word stay.
function srvCap(fx){if(fx.length<=60)return fx;let out=fx;
for(const k of ['floater','sfx','haptic','track','mk','told','toast']){let over=out.length-60;if(over<=0)break;
out=out.filter(f=>{if(over>0&&f[0]===k&&!(k==='mk'&&f[1]&&f[1].e==='end')){over--;return false;}return true;});}
return out.length>60?out.slice(-60):out;}
/* ---- capture: what the page shows, as fx (design 4.1's table) ---- */
toast=function(h,k='',a=[],o=null){if(S)logNote(h,k,a,o);if(k==='bad')SIMR.bad=true;srvFx(['toast',{h:String(h),k:String(k),a:Array.isArray(a)?a:[],o:o||null,tick:!!UI.tick}]);};
sfx=function(n){srvFx(['sfx',String(n)]);};
haptic=function(n){srvFx(['haptic',+n||12]);};
floater=function(x,y,t,c){if(SIMR.floats>=40)return;SIMR.floats++;srvFx(['floater',[+x||0,+y||0,String(t),String(c)]]);};
track=function(n,once){srvFx(['track',[String(n),!!once]]);};
// Alone, an auto-pause pauses the world (the host stops the clock after the day) and its toast's Resume votes for the
// speed it ran at; with others it does not pause, and the page offers a vote instead.
// Alone it stops this realm's clock too, as the page's does: a second auto-pause that day finds it paused (srvDay sets
// the speed again before the next day).
autoPause=function(){if(!S||!UI.speed)return false;SIMR.pause=true;srvFx(['pause',1]);if(!SIMR.alone)return false;UI.resumeSpeed=UI.lastSpeed=SIMR.last;UI.speed=0;return true;};
openModal=function(h,c=''){SIMR.modal={h:String(h),c:String(c||'')};const m=$('modal');m.className=String(c||'');m.hidden=false;$('modalCard').innerHTML=String(h);};
{const c0=closeModal;closeModal=function(){c0();SIMR.closed=true;};}
showWin=function(){srvFx(['modal','win']);};
showLose=function(){srvFx(['modal','lose']);};
showBaronWin=function(){srvFx(['modal','baron']);};
{const s0=mkStart,r0=mkRun,e0=mkEnd;
mkStart=function(c){s0(c);srvFx(['mk',{e:'start',c:String(c)}]);};
mkRun=function(l,dur,bad){r0(l,dur,bad);srvFx(['mk',{e:'run',link:l&&l.id!==undefined?String(l.id):null,felt:!!bad}]);};
mkEnd=function(ok,bye){e0(ok,bye);srvFx(['mk',{e:'end',ok:!!ok,bye:!!bye}]);};}
{const b0=checkBadges;checkBadges=function(){const a0=S&&S.ach?{...S.ach}:{},p0=S&&S.achP?{...S.achP}:{};b0();
if(S&&S.achP)for(const id of Object.keys(S.achP))if(a0[id]===undefined||p0[id]!==S.achP[id])srvFx(['badge',{id,v:String(S.achP[id])}]);};}
// Never shown here, and linkPanel would drop a selection it cannot find; the page keeps its own.
renderPanel=function(){};renderLeft=function(){};
// Checkpoints are the engine's (UI.slot is null anyway).
save=function(){};
// This realm is the server: a server network is never shown here.
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=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.
const srvR6=(k,v)=>typeof v==='number'&&!Number.isInteger(v)&&Number.isFinite(v)?+v.toPrecision(6):v;
function srvSlimR(){const c=SIM_RTXT.get(R);if(c)return c;const o={};
for(const k in R){if(SIM_RNEVER.has(k))continue;o[k]=k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k];}
const tn={};for(const id in o.tNet)tn[id]=Object.fromEntries(Object.entries(o.tNet[id]).sort((a,b)=>b[1]-a[1]).slice(0,4));o.tNet=tn;
o.tTop8=transitTop(S.transit.map(t=>t.id),8);
const t=JSON.stringify(o,srvR6);SIM_RTXT.set(R,t);return t;}
const SIM_RTXT=new WeakMap();
/* ---- rt (4.1, 4.6): what a fresh realm needs besides the save to go on exactly as this one ---- */
// The route memory: what compute() reads of the R before it (R.load, R.l2route, R.efg cut to the scenic circuits' keys).
function srvRtOut(r){const efg={},E=r&&r.efg;
if(E)for(const id in E){const t=E[id]&&E[id].t;if(!t||!t.g)continue;const g=[],v=[];for(const [k,s] of t.g)if(String(k).startsWith('l2:')){g.push([k,v.length]);v.push(+t.v[s]);}if(g.length)efg[id]={g,v};}
return {load:(r&&r.load)||{},l2route:(r&&r.l2route)||{},efg};}
function srvRtIn(rt){const r=emptyR();if(!rt||typeof rt!=='object')return r;
if(rt.load&&typeof rt.load==='object')r.load=rt.load;if(rt.l2route&&typeof rt.l2route==='object')r.l2route=rt.l2route;
if(rt.efg&&typeof rt.efg==='object'){const o={};for(const id of Object.keys(rt.efg)){const t=rt.efg[id];if(t&&Array.isArray(t.g)&&Array.isArray(t.v))o[id]={g:new Map(t.g),v:t.v};}
Object.defineProperty(r,'efg',{value:rwEfgIn(o)});}
return r;}
/* The routing point. R after a day is the R of the day's last routing, which ran before the day's end changed S (bills,
moods, customers who left or signed) and started from the memory of the R before it. compute() of the saved S, even
from R's own memory, gives another R, and the next day reads it (eyeball growth, the peering share): a network
restored that way drifts from its first day on. So every compute() keeps, for the R it makes, S as it routed it (one
JSON per top-level key, 0.8 ms big) and the memory it started from. rt carries that point (pt: the memory, at: the
keys that changed since, gone: the keys S did not have then), and a fresh realm routes that S again from that memory:
the same R (srvReroute). Trials route and put R back: their points go with their R. */
const SIM_RIN=new WeakMap();
{const c0=compute;compute=function(){const k=S?srvKeyJson():null,rt=JSON.stringify(srvRtOut(R)),v=c0.apply(this,arguments);if(k)SIM_RIN.set(R,{k,rt});return v;};}
// The sales desk's memory (39-sales-auto.js): the offers it tried, which wait a week before it tries them again. It is
// not in S; rt carries the entries of offers still on the table (no other can count again).
function srvSlOut(){const t=UI.slTried;if(!t||t.s!==S||!t.m)return [];const ids=new Set(S.offers.map(o=>o.id));return [...t.m].filter(e=>ids.has(e[0]));}
function srvSlIn(sl){const m=new Map();if(Array.isArray(sl))for(const e of sl.slice(0,1000))if(Array.isArray(e)&&typeof e[0]==='string'&&Number.isInteger(e[1]))m.set(e[0],e[1]);UI.slTried=m.size?{s:S,m}:null;}
/* Key order: a reload gives some keys back with their keys in another order (a customer's defaults go last, the intern's
week tally comes back in its own order, and the week's report lists it in that order). At a checkpoint rt carries the
live text of each such key (ord, srvGate's round trip: ≈ 8 ms big, once per checkpoint), and a fresh realm takes it
only where it holds what sanitize() made of the save (srvSame): only the order comes from it. */
function srvOrdOut(txt,K){const u0=uidN,r0=S.rng;let B;
try{B=migrate(JSON.parse(txt));}catch(e){srvLog('checkpoint: the save does not load: '+String(e&&e.message||e));return '{}';}finally{uidN=u0;S.rng=r0;}
const o=[];for(const k in K)if(srvOwn(B,k)&&JSON.stringify(B[k])!==K[k])o.push(JSON.stringify(k)+':'+K[k]);return '{'+o.join(',')+'}';}
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,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:'')+(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;}
// R as the routing point gives it: that S routed from that memory, then the loaded S again (R's attacks found in it).
function srvReroute(pt){const K=srvAtK(pt);if(!K)return false;const S1=S,u0=uidN;
try{S=JSON.parse(srvJoin(K));R=srvRtIn(pt);compute();}
catch(e){srvLog('routing the checkpoint again failed: '+String(e&&e.stack||e));return false;}
finally{S=S1;uidN=u0;}
srvAttacks();return true;}
// R with its point, when it came whole (rpack): a checkpoint before its next routing still carries the point.
function srvPointIn(r,pt){const K=srvAtK(pt);if(K)SIM_RIN.set(r,{k:K,rt:JSON.stringify({load:pt.load||{},l2route:pt.l2route||{},efg:pt.efg||{}})});}
// R's attacks are its only references into S (rwPack): looked up again in a new S.
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){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. */
const SIM_TA=new Set(['Float64Array','Float32Array','Int32Array','Uint32Array','Int16Array','Uint16Array','Int8Array','Uint8Array','Uint8ClampedArray']);
const srvEnc=(k,v)=>typeof v==='number'&&!Number.isFinite(v)?{__n:String(v)}:v instanceof Map?{__m:[...v]}:v instanceof Set?{__s:[...v]}:ArrayBuffer.isView(v)&&SIM_TA.has(v.constructor.name)?{__t:v.constructor.name,a:Array.from(v)}:v;
const srvDec=(k,v)=>!v||typeof v!=='object'||Array.isArray(v)?v:'__n' in v?Number(v.__n):'__m' in v?new Map(v.__m):'__s' in v?new Set(v.__s):'__t' in v&&SIM_TA.has(v.__t)?new self[v.__t](v.a):v;
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;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. 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);
// A test's pinned clock goes on where the realm this one replaces had it.
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)){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;
return JSON.stringify({day:S.day,lost:!!S.lost});}
const srvClockNow=()=>self.__srvClock?{clock:__srvClock()}:{};
// srvBegin: a new network of a server session (T1's beginState, then the server's own marks and the welcome).
function srvBegin(inp){const m=JSON.parse(inp),b=m.begin||{};SIMR.strict=!!m.strict;
if(typeof b.home!=='string'||!homeOk(b.home))throw new Error('srvBegin: '+String(b.home).slice(0,20)+' cannot be a home city');
if(!b.mp||typeof b.mp!=='object')throw new Error('srvBegin: no session');
srvSetPrefs(m.prefs);UI.pitched=true;
beginState(String(b.name||'').slice(0,24)||randomNetworkName(),b.home,{mode:'normal',preset:b.preset,mp:b.mp,asn:Number(b.asn)});
if(!S.mp)throw new Error('srvBegin: the session did not take');
S.mp.sim=1;S.tut=b.tut?0:null;compute();srvFresh(m.epoch);
// The welcome: in S.log, and an fx that waits for the first update after the first snapshot (srvPullParts).
beginHello();
return JSON.stringify({day:S.day,lost:!!S.lost});}
function srvPrefs(inp){const m=JSON.parse(inp);srvSetPrefs(m.prefs);return '{}';}
/* srvMark: the restore point of the next day (day) or action (keys: one JSON per top-level key, whose join is the same
string, kept for the action's own comparison). The worker keeps the string, uidN and a day's rt too, to build a fresh
realm if this one times out. */
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,rk:UI.rk,rkR:UI.rkR}};
// As text: nothing the day does reaches it.
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
S; the sales desk's memory is the marked one (a failed day may have added to it). (The design rebuilt R from route
memory after a failed day; that R is close, not the same: tests/mp-sim-determinism.) */
function srvRestore(inp){const k=SIMR.mark;if(!k)return '{"none":1}';
let parsed=false;if(JSON.stringify(S)!==k.s){S=JSON.parse(k.s);parsed=true;}
uidN=k.uidN;S.rng=k.rng;if(self.__srvClock&&typeof k.clock==='number')__srvClock(k.clock);
// R: the marked object. A day or an action routes into a new R (compute() never writes to the one it starts from),
// 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;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). */
function srvDay(inp){const m=inp?JSON.parse(inp):{};
if(!S||S.lost)return JSON.stringify({day:S?S.day:0,lost:true});
SIMR.alone=!!m.alone;SIMR.last=[0.5,1,2,4,8].includes(m.last)?m.last:1;SIMR.pause=false;
UI.speed=[0.5,1,2,4,8].includes(m.speed)?m.speed:1;UI.clockLocked=true;UI.started=true;
if(self.__srvClock&&self.__srvStep)__srvClock(__srvClock()+__srvStep);
const n0=SIMR.fx.length;
dayTick();UI.ticking=true;try{renderHUD();}finally{UI.ticking=false;}
tutAdvance();
if(m.mute)SIMR.fx=SIMR.fx.slice(0,n0).concat(SIMR.fx.slice(n0).filter(f=>SIM_KEEP.has(f[0])));
// Tests (SIM_STRICT): live S after a day is what a reload makes of it, every key (T1's canonical state).
if(SIMR.strict){const bad=srvGate(null).bad;if(bad.length)throw new Error('sanitize would repair day '+S.day+': '+bad.join(', '));}
// Done: the marked R (and its flow tables) need not stay alive until the next mark.
SIMR.mark=null;
return JSON.stringify({day:S.day,lost:!!S.lost,...(SIMR.pause?{pause:true}:{})});}
/* The sanitize gate (5.8 step 6): the keys an action changed must come through the save path as they are. Never adopts
the repaired copy (a new S without compute() would leave R's attacks pointing into the old one). keys null: all. */
const srvSortK=v=>Array.isArray(v)?v.map(srvSortK):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,k)=>(v[k]!==undefined&&(o[k]=srvSortK(v[k])),o),Object.create(null)):v;
const srvSame=(a,b)=>{const x=JSON.stringify(a),y=JSON.stringify(b);return x===y||JSON.stringify(srvSortK(a))===JSON.stringify(srvSortK(b));};
function srvGate(keys){const u0=uidN,r0=S.rng;
try{const txt=JSON.stringify(packSave(S)),a=JSON.parse(txt),b=JSON.parse(JSON.stringify(packSave(migrate(JSON.parse(txt)))));
const ks=keys||[...new Set([...Object.keys(a),...Object.keys(b)])];return {bad:ks.filter(k=>!srvSame(a[k],b[k])),len:txt.length};}
finally{uidN=u0;S.rng=r0;}}
/* ---- actions (5.8) ---- */
const srvSel=v=>v&&typeof v==='object'&&typeof v.id==='string'&&(v.type==='city'?isCity(v.id):v.type==='link'?S.links.some(l=>l.id===v.id):false)?{type:v.type,id:v.id}:null;
function srvView(c){c=c&&typeof c==='object'?c:{};
innerWidth=Number.isFinite(c.w)?c.w:1024;innerHeight=Number.isFinite(c.h)?c.h:768;self.__srvCoarse=!!c.coarse;}
function srvArm(act,args){const t=SIMT.CONFIRM[act];return t.replace(/\\{(\\w+)\\}/g,(m,k)=>String(args&&args[k]!==undefined?args[k]:''));}
// The drafts an act reads, from the request, each checked against the game's catalogs; anything else is wiped first, so
// nothing of an earlier request leaks into this one. A bad one: the reason; the act does not run.
function srvDrafts(act,ui,args){for(const k of SIM_DRAFT){if(k==='pending')UI.pending=null;else delete UI[k];}
const allowed=SIMT.DRAFTS[act]||[];
for(const k of Object.keys(ui||{})){if(!allowed.includes(k))return 'draft '+k+' is not '+act+'\\'s';const v=ui[k];
if(k==='pending'){if(!v||typeof v!=='object'||!isCity(v.a)||!isCity(v.b)||v.a===v.b)return 'pending names no two places';UI.pending={a:v.a,b:v.b};}
else if(k==='route'){if(typeof v!=='string'||!/^(|same|diverse|t:[A-Za-z0-9_.:|~-]{1,40})$/.test(v))return 'bad route';UI.route=v;}
else if(k==='via'){if(!(v===''||v==='land'||(typeof v==='string'&&CABLES.some(c=>c.id===v))))return 'bad via';UI.via=v;}
else if(k==='dfSrc'){if(!['lease','build','cable'].includes(v))return 'bad dfSrc';UI.dfSrc=v;}
else if(k==='dfSys'){if(typeof v!=='string'||!srvOwn(DF_SYS,v))return 'bad dfSys';UI.dfSys=v;}
else if(k==='seaDesign'){if(typeof v!=='string'||!srvOwn(SEA_DESIGNS,v))return 'bad seaDesign';UI.seaDesign=v;}
else if(k==='decom'){if(!Array.isArray(v))return 'bad decom';UI.decom=new Set(v.filter(isCity).slice(0,200));}
else if(k==='slop'){if(typeof v!=='boolean')return 'bad slop';if(v&&typeof args.script==='string')UI.slop=args.script.slice(0,4000);}
else{if(typeof v!=='boolean')return 'bad '+k;UI[k]=v;}}
return null;}
function srvAct(inp){const m=JSON.parse(inp),act=String(m.act),ent={rid:String(m.rid),dev:String(m.dev),ui:{}};
if(!S||S.lost)return srvOut({outcome:'stopped',v:SIMR.v});
const args=m.args&&typeof m.args==='object'&&!Array.isArray(m.args)?m.args:{};
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);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};
SIMR.modal=null;SIMR.closed=false;SIMR.bad=false;
let err=null;try{ACT[act](a2);tutAdvance();}catch(e){err=e;}
if(err){srvRestore('{}');srvLog('act '+act+' threw: '+String(err&&err.stack||err));done('error','the game threw: '+String(err&&err.message||err).slice(0,200));}
else{const K=srvKeyJson(),ch=[];for(const k in K)if(!K0||K0[k]!==K[k])ch.push(k);if(K0)for(const k in K0)if(!(k in K))ch.push(k);
if(!ch.length)done(SIMR.bad?'rejected':'no_effect');
else if(SIMR.bad&&ch.every(k=>k==='log'))done('rejected');
else{const g=srvGate(ch);let len=0,len0=0;for(const k in K)len+=K[k].length;if(K0)for(const k in K0)len0+=K0[k].length;
if(g.bad.length){srvRestore('{}');srvLog('sanitize would repair '+act+': '+g.bad.join(', '));done('error','sanitize would repair '+act+': '+g.bad.join(', '));}
else if(g.len>4194304||len-len0>262144){srvRestore('{}');srvLog('size guard: '+act);done('error','the network would grow too big');}
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;}}}}
srvWinOff();SIMR.mark=null;SIMR.markK=null;SIMR.acts.push(ent);
const p=srvPullParts({});
return srvOut({outcome,...(why?{why}:{}),v:SIMR.v},p.upd);}
/* ---- asks (5.9): what-ifs that open a window and put everything back ---- */
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;
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;srvWinOff();
return JSON.stringify(out);}
/* ---- pulls (5.3-5.6, 5.10): the only place the version moves ---- */
function srvSubs(views){const o={};if(!Array.isArray(views))return o;
for(const w of views.slice(0,16)){if(!w||typeof w!=='object')continue;
if(typeof w.link==='string'){const l=S.links.find(x=>x.id===w.link),ef={},egd={};
if(l){const k=edgeKey(l),rec=R.ef&&R.ef[k];if(rec){ef[k]=rec;for(const e in rec.eg||{})if(R.egDesc&&R.egDesc[e])egd[e]=R.egDesc[e];}}
o['link:'+w.link]={ef,egd};}
if(typeof w.peer==='string'&&isCity(w.peer))o['peer:'+w.peer]={pf:{[w.peer]:S.pops[w.peer]?pniFlows(w.peer):{}}};}
return o;}
function srvPullParts(m,K){K=K||srvKeyJson();const now=Date.now();
// The first snapshot of an epoch, before any update: nobody holds anything of this realm yet, so there is no update to
// 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||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;
let t='{"t":"upd","from":'+from+',"v":'+v+',"now":'+now+',"day":'+S.day+',"s":{'+s.map(k=>JSON.stringify(k)+':'+K[k]).join(',')+'}';
if(del.length)t+=',"del":'+JSON.stringify(del);
if(rNew)t+=',"r":'+srvSlimR();
const cf=srvCap(fx);if(cf.length)t+=',"fx":'+JSON.stringify(cf);
if(acts.length)t+=',"acts":'+JSON.stringify(acts);
upd=t+'}';SIMR.base=K;SIMR.rSent=new WeakRef(R);SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.seen=true;}
let snap='';
// A snapshot at the same version: what the host adds (clock, roster, since) it adds to this text itself.
if(m.snap){const keep=fx.filter(f=>SIM_KEEP.has(f[0])).slice(-32);
snap='{"t":"snap","epoch":'+JSON.stringify(SIMR.epoch)+',"v":'+SIMR.v+',"now":'+now+',"S":'+srvJoin(K)+',"r":'+srvSlimR()+',"keep":'+JSON.stringify(keep)+'}';
SIMR.base=K;SIMR.rSent=new WeakRef(R);}
return {upd,snap,subs:m.views?srvSubs(m.views):null};}
function srvPull(inp){const m=inp?JSON.parse(inp):{},p=srvPullParts(m),parts=[],h={v:SIMR.v,parts};
if(p.upd)parts.push('upd');if(p.snap)parts.push('snap');if(p.subs)h.subs=p.subs;
return srvOut(h,...(p.upd?[p.upd]:[]),...(p.snap?[p.snap]:[]));}
function srvSub(inp){const m=inp?JSON.parse(inp):{};return JSON.stringify({v:SIMR.v,subs:srvSubs(m.views)});}
// The one-shots a page says when a network opens (the courtesy route, Australia's prices): they change S, so the
// server says them, as fx of the next update.
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(),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}, 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. 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 game = typeof src === 'string' && src ? src : gameSource({ root, page });
return {
game: new vm.Script(game, { filename: 'game.js' }),
epilogue: new vm.Script(EPILOGUE, { filename: 'srv-epilogue.js' }),
simId: id || simId(assemble({ src: path.join(root, 'src'), mp: true }).html),
root,
};
}
const DICTS = new Map();
function dictScript(lang, root) {
const k = root + '|' + lang;
if (!DICTS.has(k)) { const s = dictSource(lang, root); DICTS.set(k, s ? new vm.Script(s, { filename: `i18n-${lang}.js` }) : null); }
return DICTS.get(k);
}
class Realm {
/* code: compileCode()'s; lang: the network's language; test: {seed, now, step} for tests; log(level, text). */
constructor({ code, lang = 'en', test = null, log = () => {}, loadMs = 30000 }) {
const t0 = performance.now();
const ctx = vm.createContext(vm.constants.DONT_CONTEXTIFY);
ctx.__hostNow = () => performance.now();
let n = 0, w0 = 0;
// The realm's console, rate-limited: 20 lines, then one a second.
ctx.__hostLog = (lvl, txt) => { const t = Date.now(); if (n > 20 && t - w0 < 1000) return; if (t - w0 >= 1000) { w0 = t; n = Math.min(n, 20); } n++; log(lvl, String(txt).slice(0, 2000)); };
// A language this server has no dictionary for plays in English (the page falls back the same way), not broken.
let d = null;
if (LANG_RE.test(lang) && lang !== 'en') { try { d = dictScript(lang, code.root); } catch (e) { log('warn', `no dictionary for ${lang}: English`); } }
this.lang = d ? lang : 'en';
new vm.Script(prelude({ lang: this.lang, test: !!test, ...(test || {}) }), { filename: 'srv-prelude.js' }).runInContext(ctx, { timeout: loadMs });
if (d) d.runInContext(ctx, { timeout: loadMs });
code.game.runInContext(ctx, { timeout: loadMs });
code.epilogue.runInContext(ctx, { timeout: loadMs });
// The no-op timers the page's own start called (two canvas resizes) are not a simulation's.
new vm.Script('__SRV_T.n=0;if(__SRV_T.at)__SRV_T.at.length=0;').runInContext(ctx);
this.ctx = ctx;
this.ms = performance.now() - t0;
}
// 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 = ''; }
}
// The header parsed, plus the parts that follow it.
call(name, input, ms) { return parts(this.raw(name, input, ms)); }
// Tests only.
eval(src, ms = 5000) {
this.ctx.__in = String(src);
try { const r = EVAL.runInContext(this.ctx, { timeout: ms }); return JSON.parse(r); } finally { this.ctx.__in = ''; }
}
}
// [header (parsed), ...parts (strings)] of a realm's answer.
function parts(text) {
const t = String(text);
const i = t.indexOf('\n');
if (i < 0) return [JSON.parse(t || '{}')];
const rest = t.slice(i + 1).split('\n');
return [JSON.parse(t.slice(0, i)), ...rest];
}
const isTimeout = (e) => !!e && e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT';
module.exports = { REALM_PAGE, gameSource, dictSource, prelude, EPILOGUE, API, compileCode, Realm, parts, isTimeout };

View file

@ -0,0 +1,407 @@
// A worker thread of the server-run engine (the server-sim design, section 4.2): it compiles the game once, holds the
// realms of the sessions placed on it (every network of a session in one worker), and answers the host's messages.
//
// Order. Messages run one at a time, in arrival order per network. A session's day is one task per network, in sorted
// 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), 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 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]}, 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, 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, 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, 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 || (() => {});
const post = opts.post || (() => {});
const realms = new Map(), sessions = new Map(), jobs = [];
let epochN = 0, pumping = false, turn = 0;
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. 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) {
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] = 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) {
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 (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 failed: ${LINE(x)}`); }
}
rebuild(e, { ...e.mark, rt: input.day ? e.mark.rt : markRt(e) });
}
// 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] = 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) ---- */
const errReply = (m, what, msg) => ({ t: 'err', code: m.code, nid: m.nid, ...(m.msg && m.msg.rid ? { rid: m.msg.rid } : {}), what, msg: String(msg).slice(0, 500) });
function loadOne(c, n) {
const e = realms.get(key(c, n.nid));
try {
if (!n.begin && !(n.env && typeof n.env === 'object' && typeof n.env.s === 'string')) throw new Error('no save to load');
e.realm = build(n.nid, n.lang);
e.lang = e.realm.lang;
const epoch = epochOf();
const [h] = n.begin
? call(e, 'srvBegin', { begin: n.begin, prefs: n.prefs, epoch, strict: !!opts.strict }, T.load)
: call(e, 'srvLoad', { save: n.env.s, uidN: n.env.uidN, rt: n.env.rt, prefs: n.prefs, rng: n.rng, epoch, strict: !!opts.strict }, T.load);
if (h.srvErr) throw new Error(h.srvErr);
Object.assign(e, { epoch, v: 0, day: h.day, lost: h.lost, loading: false });
const out = { t: 'loaded', nid: n.nid, epoch, day: h.day, lost: h.lost };
if (n.begin) out.saved = saved(e);
return out;
} catch (x) {
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' : LINE(x) };
}
}
function saved(e) {
const [h, txt] = call(e, 'srvSave', undefined, T.save);
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 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 new Error(h.srvErr);
e.day = h.day; e.lost = h.lost;
return { day: h.day, lost: h.lost, ...(h.pause ? { pause: true } : {}), ...(i ? { retried: true } : {}), ms: msOf(t0) };
} catch (x) {
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: ' : '') + 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 };
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, ms: msOf(t0) };
},
ask(m, e) {
if (e.broken || e.lost) return { t: 'askDone', nid: m.nid, rid: m.msg.rid, err: 'stopped' };
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', {}); },
sub(m, e) {
return guarded(m, e, () => { const [h] = call(e, 'srvSub', { views: m.views || [] }, T.pull); if (h.srvErr) return errReply(m, 'throw', h.srvErr); return { t: 'subbed', nid: m.nid, epoch: e.epoch, v: h.v, subs: h.subs }; });
},
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, () => { 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)) { 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 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 (or a pollution) the realm is built again from its own save.
function guarded(m, e, f) {
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 ---- */
const SESSION_OPS = new Set(['load', 'unload', 'day']);
function runnable(j, i) {
const s = sessions.get(j.code);
if (SESSION_OPS.has(j.t)) {
if (s && (s.day || s.load)) return false;
for (let k = 0; k < i; k++) if (jobs[k].code === j.code) return false;
return true;
}
for (let k = 0; k < i; k++) if (jobs[k].code === j.code && SESSION_OPS.has(jobs[k].t) && jobs[k].t !== 'day') return false;
// A network that is loading waits for its load; one marked loading with no load under way (none can be: a guard)
// waits for nothing, so start() answers NO_REALM.
const e = realms.get(key(j.code, j.nid));
return !e || !e.loading || !(s && s.load);
}
function reply(j, r) { post({ id: j.id, ok: true, reply: r === undefined ? null : r }); }
function fail(j, x) { post({ id: j.id, ok: false, error: { message: String((x && x.message) || x), code: (x && x.code) || 'ERR' } }); }
function runJob() {
for (let i = 0; i < jobs.length; i++) {
const j = jobs[i];
if (!runnable(j, i)) continue;
jobs.splice(i, 1);
try { start(j); } catch (x) { fail(j, x); }
return true;
}
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') {
// The whole call first, with no side effects: a malformed one is refused and leaves every realm as it was. A
// network without a save to load (or a begin) is only that network's problem: loadOne answers it broken.
const nets = Array.isArray(j.nets) ? j.nets : [], seen = new Set();
if (!nets.length) throw new Error('load: give the networks to load');
for (const n of nets) {
if (!n || typeof n !== 'object' || typeof n.nid !== 'string' || !n.nid) throw new Error('load: each network needs a nid');
if (seen.has(n.nid)) throw new Error(`load: ${n.nid.slice(0, 40)} is there twice`);
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, 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 = 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;
}
if (j.t === 'unload') {
for (const [k, e] of [...realms]) if (e.code === j.code && (j.nid === undefined || e.nid === j.nid)) realms.delete(k);
if (![...realms.values()].some((e) => e.code === j.code)) sessions.delete(j.code);
return reply(j, { t: 'unloaded', code: j.code, ...(j.nid !== undefined ? { nid: j.nid } : {}) });
}
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 || !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). 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;
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;
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:
what a job waits for (a load, a day, an earlier job of its session) is itself a job or a step that runs, so a pass
where nothing could run means nothing will until a message comes (handle() kicks). If a job were still waiting
then, nothing could ever free it: it is answered, not left pending, and the worker does not spin on it. */
let flip = false;
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); } }
return {
handle(m) { jobs.push(m); kick(); },
stats: () => ({ realms: realms.size, sessions: sessions.size, jobs: jobs.length }),
simId: code.simId,
};
}
if (!isMainThread && workerData && workerData.mpSim) {
const W = workerData.mpSim;
const post = (m) => parentPort.postMessage(m);
const log = (level, text) => post({ log: [level, text] });
process.on('unhandledRejection', (e) => log('warn', 'unhandled rejection in a realm: ' + MSG(e)));
let core;
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 });
}
module.exports = { createCore, TIMEOUTS };

View file

@ -51,6 +51,8 @@ function mkLeave(why){const M=S.monkey,d=S.day,ok=!why&&M.n>0&&M.hurt===0;M.on=0
if(why==='banana')toast(tr('chaos_monkey.bribed'),'good');
else if(ok){const b=mkBonus();S.cash+=b;S.stats.mkSurv=(S.stats.mkSurv||0)+1;toast(tr('chaos_monkey.survived',{n:M.n,cash:fmt$(b)}),'goal');sfx('coin');track('monkey_survived');}
else if(!why)toast(tr('chaos_monkey.went_home',{n:M.n,hurt:M.hurt}),'');
// Away, it is only its next visit: what a reload keeps of it (sanitize), so the live game is its own save.
S.monkey={next:M.next,on:0};
if(typeof mkEnd==='function')mkEnd(ok,true);}
// The NOC tab's card while it is here.
function mkCard(){if(!mkOn())return '';const M=S.monkey,c=mkBananaCost();

View file

@ -1,6 +1,6 @@
Object.assign(ACT,{
buildPop:({city})=>{if(S.pops[city]||!CITY[city])return;if(!cityOn(city)){toast(popOffWhy(city),'bad');sfx('err');return;}const flipNote=CITY[city]&&CITY[city].au;if(cnCity(city)&&!cnOk()){toast(tr('pops_transit_ix.you_need_a_license_first_foreign'),'bad');sfx('err');return;}if(!spend(popCost(city)))return;S.pops[city]={day:S.day,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};popStdApply(city);floater(CITY[city].x,CITY[city].y-30,tr('common.new_pop'),'#FF4F9A');if(flipNote)toast(pick([tr('pops_transit_ix.router_installed_in_city_upside_down',{city:CITY[city].name}),tr('pops_transit_ix.router_installed_in_city_the_vendor',{city:CITY[city].name})]),'good',[],{a:'city',v:city});UI.tab='cust';after();},
launchBB:({city})=>{const p=S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();},
launchBB:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||p.bb)return;const C=CITY[city];if(!spend(bbCost(city)))return;p.bb={d:bbStart(city)};floater(C.x,C.y-30,tr('common.eyeballs_online'),'#16A866');after();},
ad:({city})=>{const p=S.pops[city];if(!p||!p.bb)return;if(!spend(8000))return;p.boost=S.day+30;floater(CITY[city].x,CITY[city].y-30,tr('common.ad_campaign'),'#FF8A3D');after();},
// A new port has every field sanitize() gives one, so live S is what a reload makes of it.
buyTransit:({city,net,tier})=>{tier=+tier;if(scnRule('noTransit')){toast(tr('pops_transit_ix.no_transit_in_this_scenario_peering'),'bad');sfx('err');return;}if(!S.pops[city]||!NET[net]||!sellsAt(NET[net],city)||!PORT[tier])return;if(!portOk(city,tier)){toast(tr('actions.your_router_can_t_take_a',{port:PORT[tier].n}),'bad');sfx('err');return;}const ex=S.transit.find(t=>t.city===city&&t.net===net);if(ex&&tier<=ex.tier)return;if(!portGate(city,ex?(PORT_SLOT(tier)-PORT_SLOT(ex.tier))*(ex.n||1):PORT_SLOT(tier)))return;if(!spend(PORT[tier].setup*(ex&&ex.n||1)))return;if(ex)ex.tier=tier;else{const pr=premOnlyAt(NET[net],city);S.transit.push({id:uid(),city,net,tier,down:0,...(pr?{premium:true}:{}),lacp:null,site:'a',n:1,clean:false,...(pr?{}:{premium:false})});}toast(tr('pops_transit_ix.net_transit_is_live_in_city',{net:esc(NET[net].name),city:CITY[city].name}),'good');after();},

View file

@ -15,7 +15,7 @@ Object.assign(ACT,{
if(drop>0.1&&UI.slop===src){if(drop>0.3)S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_the',{p:pct(drop)}),'bad');sfx('alert');}
else if(drop>0.3){S.stats.fat=1;toast(tr('route_script_and_tools.commit_complete_traffic_down_p_you',{p:pct(drop)}),'bad');sfx('alert');}
else{if(saved>0.1&&drop<0.01)S.stats.kiddie=1;toast(`<b>${tr('common.commit_complete')}</b><br>${saved>0.01?trn('route_script_and_tools.n_rule_live_transit_bill_down',p.n,{p:pct(saved)}):trn('route_script_and_tools.n_rule_live',p.n)}`,'good');sfx('build');}closeModal();UI.slop=undefined;checkGoals();},
buyTE:()=>{if(S.te)return;if(lvl()<3){toast(tr('route_script_and_tools.auto_te_unlocks_at_customer_level'),'bad');sfx('err');return;}if(!coreTE()){toast(tr('core.auto_te_needs_an_rsvp_te_or'),'bad');sfx('err');return;}if(!spend(TE_COST))return;S.te={on:true,day:S.day};toast(tr('route_script_and_tools.auto_te_is_live_the_controller'),'good');after();},
buyTE:()=>{if(S.te)return;if(lvl()<3){toast(tr('route_script_and_tools.auto_te_unlocks_at_customer_level'),'bad');sfx('err');return;}if(!coreTE()){toast(tr('core.auto_te_needs_an_rsvp_te_or'),'bad');sfx('err');return;}if(!spend(TE_COST))return;S.te={on:true,day:S.day,script:''};toast(tr('route_script_and_tools.auto_te_is_live_the_controller'),'good');after();},
teToggle:()=>{if(!S.te)return;S.te.on=!S.te.on;after();},
trace:({city})=>traceModal(city),
traceRun:()=>{const f=$('trFrom'),t=$('trTo');traceModal(f&&f.value,t&&t.value);},

View file

@ -1,5 +1,5 @@
Object.assign(ACT,{
addSite:({city})=>{const p=S.pops[city];if(!p||p.site2)return;if(!spend(SITE2_COST))return;p.site2=true;p.site2Day=S.day;toast(tr('sites_peering_caches.second_site_live_in_city_b',{city:CITY[city].name,b:esc(siteName(city,'b')),a:esc(siteName(city,'a'))}),'good');sfx('build');after();},
addSite:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||p.site2)return;if(!spend(SITE2_COST))return;p.site2=true;p.site2Day=S.day;toast(tr('sites_peering_caches.second_site_live_in_city_b',{city:CITY[city].name,b:esc(siteName(city,'b')),a:esc(siteName(city,'a'))}),'good');sfx('build');after();},
rmSite:({city})=>{const p=S.pops[city];if(!p||!p.site2)return;if(UI.confirm!=='site'+city){UI.confirm='site'+city;renderPanel();return;}UI.confirm=null;p.site2=0;p.sdown=null;p.ringcut=0;for(const t of S.transit)if(t.city===city)t.site='a';for(const x of S.pni)if(x.city===city)x.site='a';for(const x of S.caches)if(x.city===city)x.site='a';if(S.ixSite)for(const x of ixIdsIn(city))delete S.ixSite[x];after();},
siteSet:({k,id,s})=>{if(!['a','b','ab'].includes(s))return;
const o=k==='t'?S.transit.find(x=>x.id===id):k==='p'?S.pni.find(x=>x.id===id):null;if(k!=='ix'&&!o)return;if(k==='ix'&&(!isIx(id)||S.ixp[id]===undefined||!S.pops[ixCity(id)]))return;

View file

@ -11,7 +11,7 @@ Object.assign(ACT,{
// At sea, paying means a private charter: another ship sails, it does not appear (50-cable-ships.js).
if(shipSea(i)){if(shipRush(i)){const s=SHIP[i.ship];toast(tr('cable_ships.ship_chartered',{ship:esc(s.n),home:esc(CITY[s.home].name),n:Math.max(1,i.until-S.day)}),'good');sfx('coin');after();}return;}if(i.slow&&i.rushed)return;if(!spend(i.cost))return;
if(i.slow&&i.until>S.day+1){i.rushed=true;i.cost=0;i.until=S.day+1;const p=S.pops[i.ref];if(p)p.down=Math.min(p.down,S.day+1);toast(tr('links.power_cycled_the_router_in_city',{city:esc(CITY[i.ref].name),chip:esc(RG[(p&&p.rgen)||0].chip)}),'good');after();return;}clearInc(i);toast(tr('links.fixed_what_resolved_early',{what:incTitle(i.type)}),'good');after();},
myIxUp:({city})=>{const m=S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
myIxUp:({city})=>{const m=own(S.myIx,city)&&S.myIx[city];if(!m)return;const f=(m.fab|0)+1,N=MYIX_FAB[f];if(!N)return;if(N.lvl>lvl()){toast(tr('links.a_fab_fabric_unlocks_at_customer',{fab:N.n,lv:N.lvl}),'bad');sfx('err');return;}if(!spend(N.cost))return;m.fab=f;toast(tr('links.ix_now_runs_a_fab_fabric',{ix:esc(m.name),fab:N.n,max:N.max}),'good');m.next=Math.min(m.next,S.day+3);after();},
foundIx:({city})=>{if(!isCity(city))return;const why=foundIxWhy(city);if(why){toast(why,'bad');sfx('err');return;}if(!spend(MYIX_COST))return;const nm=(S.name.split(' ')[0]||'My').replace(/[^A-Za-z0-9]/g,'').slice(0,10)+'-IX '+CITY[city].name;
S.myIx[city]={name:nm,members:[],next:S.day+4,fab:0};S.ixp[city]=2;toast(tr('links.you_founded_ix_networks_will_join',{ix:esc(nm)}),'goal');after();},
buildLink:({tier})=>{tier=+tier;const p=UI.pending;if(!p||noTalk(p.a,p.b))return;const {a,b}=p;const km=kmBetween(a,b),sub=isSub(a,b),sib=pairLinks(a,b).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(a,b):null,same=!!jn,border=cnCity(a)!==cnCity(b),mult=(sib.length&&!(jn&&jn.k===(landTrenches(a,b)[0]||{}).k)?DIVERSE:1)*(border?3*(UI.cnPrem&&(a==='hkg'||b==='hkg')?1.6:1):1);

View file

@ -16,10 +16,10 @@ Object.assign(ACT,{
popStdSet:({city})=>{const p=S.pops[city];if(!p||pzOn())return;S.popStd=bstdPut({...bstd(),g:p.rgen||0,rt:p.routers||1,site2:!!p.site2,gen:!!p.gen});
toast(tr('pop_std.new_pops_now_start_with_list',{list:esc(bstdPopParts(bstd()).join(', '))}),'good');sfx('click');after();if(bstdShown())bstdModal();},
popStdClear:()=>{S.popStd=null;sfx('click');after();if(bstdShown())bstdModal();},
addRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();},
addRouter:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||(p.routers||1)>=RMAX)return;if(!spend(routerCost(p.rgen||0,p.routers||1)))return;p.routers=(p.routers||1)+1;floater(CITY[city].x,CITY[city].y-30,tr('common.router_added'),'#FF4F9A');after();},
models:()=>{UI.models=!UI.models;renderPanel();},
rmRouter:({city})=>{const p=S.pops[city];if(!p||(p.routers||1)<=1)return;if(portsUsed(city)>portsMax(city,undefined,p.routers-1)){toast(tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(city)),max:portsMax(city,undefined,p.routers-1)}),'bad');sfx('err');return;}p.routers--;{const back=tradeIn(p.rgen||0,1);if(back>0){S.cash+=back;toast(tr('routing_and_routers.sold_a_model_on_ebuy_price',{model:esc(RG[p.rgen||0].n),price:fmt$(back)}),'good');}}after();},
upRouter:({city,g})=>{const p=S.pops[city];if(!p)return;g=g===undefined?mainRG(RG[p.rgen||0].cls+1):+g;if(!RG[g]||g===(p.rgen||0))return;{const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}}if(!techOk('rg',g,RG[g].lvl)){toast(tr('routing_and_routers.model_unlocks_at_customer_level_lv',{model:esc(RG[g].n),lv:RG[g].lvl}),'bad');sfx('err');return;}
upRouter:({city,g})=>{const p=own(S.pops,city)&&S.pops[city];if(!p)return;g=g===undefined?mainRG(RG[p.rgen||0].cls+1):+g;if(!RG[g]||g===(p.rgen||0))return;{const why=modelFits(city,g);if(why){toast(tr('routing_and_routers.the_model_won_t_fit_why',{model:esc(RG[g].n),why:esc(why)}),'bad');sfx('err');return;}}if(!techOk('rg',g,RG[g].lvl)){toast(tr('routing_and_routers.model_unlocks_at_customer_level_lv',{model:esc(RG[g].n),lv:RG[g].lvl}),'bad');sfx('err');return;}
const rt=p.routers||1,old=p.rgen||0;if(p.rupDay===S.day){toast(tr('routing_and_routers.the_new_routers_in_city_are',{city:CITY[city].name}),'bad');sfx('err');return;}const back=tradeIn(old,rt);if(!spend(swapCost(city,g)))return;p.rgen=g;p.rupDay=S.day;if(back>0)toast(tr('routing_and_routers.sold_the_old_model_on_ebuy',{model:esc(RG[old].n),price:fmt$(back)}),'good');
if(rt===1&&popIdle(city))toast(tr('routing_and_routers.new_router_in_city_swapped_before',{city:CITY[city].name}),'good');
else if(rt===1){const sl=slowBoot(city),dd=sl?3:1;p.down=Math.max(p.down||0,S.day+dd);addInc({type:'maint',ref:city,until:S.day+dd,msg:sl?tr('routing_and_routers.swapping_the_only_router_in_city',{city:CITY[city].name,model:RG[g].n,how:pick(SLOW_BOOT),n:dd}):tr('routing_and_routers.swapping_the_only_router_in_city_d5b5',{city:CITY[city].name,model:RG[g].n}),cost:0});toast(`<b>${tr('routing_and_routers.maintenance_window_in_city',{city:CITY[city].name})}</b><br>${sl?tr('routing_and_routers.one_router_and_this_one_takes',{n:dd}):tr('routing_and_routers.one_router_means_downtime_during_the')}`,'bad');}

View file

@ -38,5 +38,5 @@ Object.assign(ACT,{
layShip:({id})=>{const l=S.links.find(x=>x.id===id);const q=l&&layQuote(l);if(!q||!spend(q.cost))return;l.ship2=1;setCableReady(l,l.ready-q.save);
toast(trn('cable_ships.second_lay_ship_booked',q.save,{ship:esc(layName(l,1)),n:q.save}),'good');sfx('coin');after();},
crews:({id,all})=>{const l=S.links.find(x=>x.id===id);if(!l||l.kind!=='df'||!l.own||l.sub||!crewSteps(l))return;const n=all?crewSteps(l):1,c=n*crewCost(l);if(!spend(c))return;const ready=Math.max(crewFloor(l),l.ready-30*n),saved=l.ready-ready;setCableReady(l,ready);toast(trn('fiber_and_hardware.more_crews_on_site_construction_is',saved,{n:saved}),'good');after();},
addGen:({city})=>{const p=S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('common.generator'),'#FF8A3D');after();},
addGen:({city})=>{const p=own(S.pops,city)&&S.pops[city];if(!p||p.gen)return;if(!spend(GEN_COST))return;p.gen=true;floater(CITY[city].x,CITY[city].y-30,tr('common.generator'),'#FF8A3D');after();},
});

View file

@ -0,0 +1,37 @@
// A click's args name things the game looks up by key: S.pops[city], S.myIx[city]. A city that is '__proto__' or
// 'constructor' (an MCP agent's, or a request to a server-run network) must find nothing there, never a prototype or a
// built-in's statics: every action that takes one, with each such name in each usual arg, leaves the page's built-ins
// as they were and spends nothing on them.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const BAD = ['__proto__', 'constructor', 'prototype'];
const ARGS = ['city', 'id', 'net', 'k', 'c', 'v', 'a', 'b', 'to', 'from', 'link', 's'];
test('no action reaches a built-in through an arg that names one', (t) => {
// The development page: API_CMD is every action an agent may send (the MCP facade), the sent ones of a server's page.
const { ev, errors, dom } = load({ agent: true });
t.after(() => dom.window.close());
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;");
for (const c of ['fra', 'ams', 'lon', 'par']) ev(`ACT.buildPop({city:'${c}'})`);
ev("ACT.launchBB({city:'fra'});closeModal();UI.confirm=null;compute();");
// What the built-ins hold now: anything an action adds to them is found by name.
ev(`window.__fp=()=>{const o={};for(const [n,x] of [['Object',Object],['Object.prototype',Object.prototype],['Array',Array],['Array.prototype',Array.prototype],['Function.prototype',Function.prototype],['String.prototype',String.prototype]])o[n]=Object.getOwnPropertyNames(x).sort().join(',');
const e=[];for(const k in {})e.push(k);for(const k in [])e.push('[]'+k);o.enum=e.join(',');return o;};window.__fp0=__fp();
window.__clean=()=>{for(const [n,x] of [['Object',Object],['Object.prototype',Object.prototype],['Array',Array],['Array.prototype',Array.prototype],['Function.prototype',Function.prototype],['String.prototype',String.prototype]]){const had=new Set(__fp0[n].split(','));for(const k of Object.getOwnPropertyNames(x))if(!had.has(k))delete x[k];}};`);
const acts = JSON.parse(ev('JSON.stringify(Object.keys(API_CMD).filter(k=>typeof ACT[k]==="function"&&!/^pz[A-Z]/.test(k)))'));
const hits = [];
for (const act of acts) {
for (const name of ARGS) {
for (const v of BAD) {
const r = JSON.parse(ev(`(()=>{const c0=S.cash;let err=null;try{ACT[${JSON.stringify(act)}]({[${JSON.stringify(name)}]:${JSON.stringify(v)}});}catch(e){err=String(e&&e.message||e);}
try{closeModal();}catch(e){}UI.confirm=null;const f=__fp(),d=Object.keys(f).filter(k=>f[k]!==__fp0[k]);if(d.length)__clean();return JSON.stringify({d,spent:c0-S.cash,err});})()`));
if (r.d.length) hits.push(`${act}({${name}:'${v}'}) changed ${r.d.join(', ')}${r.spent > 0 ? ` and spent ${r.spent}` : ''}`);
}
}
}
t.diagnostic(`${acts.length} actions × ${ARGS.length} args × ${BAD.length} names`);
assert.deepEqual(hits, []);
assert.deepEqual(errors, []);
});

View file

@ -52,6 +52,7 @@ test('a new network runs plain IGP: no Auto-TE until the backbone is upgraded, o
assert.equal(ev('S.core.run'), 2);
ev('ACT.buyTE()');
assert.equal(ev('!!S.te'), true, 'RSVP-TE unlocks Auto-TE');
assert.equal(ev('JSON.stringify(S.te)'), ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(packSave(S)))).te)'), 'Auto-TE as a reload makes it');
// Customer levels gate each step.
ev('S.lvl=3;ACT.coreUp()');
assert.equal(ev('S.core.lv'), 2, 'SR-MPLS needs customer level 5');

View file

@ -14,6 +14,9 @@ function net(preset) {
return { ev, errors, dom };
}
const link = (ev, a, b) => `S.links.find(l=>(l.a==='${a}'&&l.b==='${b}')||(l.a==='${b}'&&l.b==='${a}'))`;
// The monkey as the game holds it, and as a reload makes it: once it has gone home they are the same (only its next
// visit), so a server that checks every action and day against the save path finds nothing to repair.
const asSaved = (ev) => [ev('JSON.stringify(S.monkey)'), ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(packSave(S)))).monkey)')];
test('the chaos monkey visits On-call and BGP at 3 a.m., never Change Freeze or Sandbox', () => {
for (const [preset, ok] of [['oncall', true], ['bgp', true], ['freeze', false]]) {
@ -62,10 +65,16 @@ test('outlasting it unnoticed pays a bonus and earns the badge; going home hurt
ev('dayTick();checkBadges()');
assert.equal(ev('S.monkey.on'), 0);
assert.equal(ev('S.stats.mkSurv'), 1);
{ const [live, saved] = asSaved(ev); assert.equal(live, saved, 'gone home: what a reload keeps'); }
assert.ok(ev('S.cash') >= cash + bonus - 1e6, 'bonus paid');
assert.ok(ev("S.ach.monkey!==undefined"));
ev('S.monkey.next=S.day;dayTick();S.monkey.n=4;S.monkey.hurt=2;S.monkey.until=S.day+1;dayTick()');
assert.equal(ev('S.stats.mkSurv'), 1, 'no bonus when customers felt it');
{ const [live, saved] = asSaved(ev); assert.equal(live, saved); }
// Sent home by the rules (chaos turned down mid-visit): the same.
ev("S.monkey.next=S.day;dayTick();S.rules.chaos='calm';dayTick()");
assert.equal(ev('S.monkey.on'), 0);
{ const [live, saved] = asSaved(ev); assert.equal(live, saved, 'sent home quietly'); }
assert.deepEqual(errors, []);
});
@ -77,6 +86,7 @@ test('a banana sends it home early, for a price', () => {
ev('ACT.mkBanana({})');
assert.equal(ev('S.monkey.on'), 0);
assert.equal(ev('S.cash'), cash - cost);
{ const [live, saved] = asSaved(ev); assert.equal(live, saved, 'bribed: what a reload keeps'); }
assert.equal(ev('S.stats.mkSurv||0'), 0);
ev('S.cash=0;S.monkey.next=S.day;dayTick();ACT.mkBanana({})');
assert.equal(ev('S.monkey.on'), 1, 'no banana without the cash');

View file

@ -1,4 +1,5 @@
{
"tests/act-args-builtins.test.js": 4.9,
"tests/any-home-city.test.js": 12.0,
"tests/architect.test.js": 20.1,
"tests/automation.test.js": 13.8,
@ -32,7 +33,10 @@
"tests/modes.test.js": 41.1,
"tests/more-cables.test.js": 14.3,
"tests/moscow-premium.test.js": 12.0,
"tests/mp-sim-contract.test.js": 7.0,
"tests/mp-sim-acts.test.js": 41.3,
"tests/mp-sim-contract.test.js": 9.1,
"tests/mp-sim-determinism.test.js": 96.7,
"tests/mp-sim-engine.test.js": 39.7,
"tests/networks-list.test.js": 6.4,
"tests/new-game-speed.test.js": 10.1,
"tests/optic-counts.test.js": 9.7,

28
tests/lib/mp-sim-crawl.js Normal file
View file

@ -0,0 +1,28 @@
// Every button and drop-down a rich game shows, as the page would send it: [act, args]. Runs in a jsdom page of the
// game (tests/harness.js load()) on whatever network it holds: city panels and their tabs, link panels, the left
// lists, every dashboard tab, the bank, the sheets the big buttons open, the link window, the windows that move a
// customer to another path, and armed two-click buttons.
// Used by the envelope check (tests/mp-sim-contract.test.js) and the engine's timer audit and gate
// (tests/mp-sim-determinism.test.js), which send them to a server realm.
'use strict';
function crawl(ev) {
ev(`window.__btns=[];window.__grab=()=>{for(const el of document.querySelectorAll('[data-act],[data-chg]')){const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){a={bad:el.dataset.args};}
if(el.dataset.chg){a={...a,v:el.value}}__btns.push([act,a]);}};`);
const views = [
"for(const c of ['fra','ams','nyc','sin','syd']){for(const tab of ['cust','up','peer','infra','links']){UI.sel={type:'city',id:c};UI.tab=tab;renderPanel();__grab();}}",
"for(const l of S.links.slice(0,40)){UI.sel={type:'link',id:l.id};renderPanel();__grab();}",
"UI.leftOpen=true;for(const k of ['goals','deals','noc','nets']){UI.left=k;renderLeft();__grab();}",
"$('dash').hidden=false;for(const k of DTABS){UI.dtab=k;renderDash();__grab();}$('dash').hidden=true;",
'ACT.bank();__grab();ACT.bankClose();',
"for(const [a,x] of [['opsOpen',{}],['utilities',{city:'fra'}],['bstdOpen',{}],['pniAllOpen',{net:null}],['pniAllOpen',{net:'cog'}],['salesOpen',{}],['routingOpen',{}],['ip4Open',{}],['models',{}],['decomOpen',{}],['teEdit',{}]]){try{ACT[a](x);}catch(e){}__grab();closeModal();}",
"openLinkModal('fra','nyc');__grab();closeModal();openLinkModal('fra','ams');__grab();closeModal();",
// Moving a customer to another path (3.3.0): its buttons are only in that window.
'for(const b of S.biz.filter(b=>pathKind(b)).slice(0,6)){ACT.pathOpen({id:b.id});__grab();closeModal();}',
"UI.confirm=null;for(const t of S.transit.slice(0,3)){UI.sel={type:'city',id:t.city};UI.tab='up';UI.confirm=t.id;renderPanel();__grab();}UI.confirm=null;",
];
for (const v of views) ev(v);
return JSON.parse(ev('JSON.stringify(__btns)'));
}
module.exports = { crawl };

View file

@ -3,25 +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}])
// 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.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;
@ -31,19 +42,28 @@
// (retried:true, no err).
'use strict';
const { fixture } = require('./mp-sim-shape');
const { snapWith } = require('../../scripts/lib/mp-sim-engine');
const coded = (msg, code) => Object.assign(new Error(msg), { code });
const CODES = { exit: ['worker exited', 'EXIT'], gaveUp: ['session kept failing its worker', 'GAVE_UP'], down: ['server-run play is down', 'SIM_DOWN'] };
let SIM = null;
function createFakeEngine(opts = {}) {
const F = { snap: fixture('snap'), day: fixture('upd-day'), act: fixture('upd-act'), sub: fixture('sub'), roster: fixture('roster') };
const realms = new Map(), held = new Map(), fails = new Map(), pending = new Set(), breaks = new Set(), flaky = new Set();
const key = (code, nid) => code + '/' + nid;
let epochN = 0;
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 = () => {
@ -51,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}` });
@ -69,9 +89,10 @@ function createFakeEngine(opts = {}) {
const s = { ...base.s, day: r.day };
return JSON.stringify({ ...base, from, v, now: Date.now(), day: r.day, s, ...extra });
};
// The realm's half of a snapshot: the host adds clock, roster and since with snapWith().
const snapOf = (code, nid, r) => {
const S = { ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } };
return JSON.stringify({ ...F.snap, epoch: r.epoch, v: r.v, now: Date.now(), S, keep: r.keep.splice(0) });
return JSON.stringify({ t: 'snap', epoch: r.epoch, v: r.v, now: Date.now(), S, r: F.snap.r, keep: r.keep.splice(0) });
};
const subsOf = (views = []) => {
const o = {};
@ -83,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) } : {}) };
};
@ -101,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;
@ -131,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 }]);
@ -146,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);
},
@ -156,15 +194,26 @@ 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(); closed = true; return Promise.resolve(); },
snapWith,
// Test controls.
lose(code, nid) { realm(code, nid).loseNext = true; },
pause(code, nid) { realm(code, nid).pause = true; },
@ -175,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,
};

91
tests/lib/mp-sim-play.js Normal file
View file

@ -0,0 +1,91 @@
// What the engine's tests share (tests/mp-sim-engine.test.js, mp-sim-determinism.test.js, mp-sim-acts.test.js): the
// networks they play, the requests a page sends, and the page's side of a comparison, run in jsdom by the click path.
//
// page({save}) a jsdom page holding a network as the server's realm holds it (pinned clock, seeded): {ev, …}
// 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, 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
// differs(a, b) the first differing top-level keys of two JSON texts (compare texts, never a deep-equal)
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
const { load } = require('../harness');
const { lit } = require('../../scripts/lib/js-literal');
const { simId } = require('../../scripts/lib/page');
const A = require('../../scripts/lib/mp-sim-acts');
const { checkWorker, checkEvent } = require('./mp-sim-shape');
const CODE = 'K7Q2XD', PID = 'abcd1234', DEV = '9f8e7d6c', T0 = 1.7e12, STEP = 2500;
const MP = { code: CODE, pid: PID, asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
const TEST = { seed: 4242, now: T0, step: STEP };
// Time limits for engines whose tests inject no timeout: a busy machine (every test file at once) must not time out a
// big network's day or action that takes 40 ms when it is quiet. The tests of timeouts use the engine's own limits.
const ROOMY = { day: 20000, act: 20000, ask: 20000, pull: 20000, save: 20000, mark: 20000, small: 20000 };
let SIM;
const sim = () => SIM || (SIM = simId());
const BIG = path.join(__dirname, '..', 'fixtures', 'big-network.json');
// A jsdom page whose clock and dice are the realm's (TEST): a day there is __t+=STEP; dayTick(); and the day's end render.
function page({ save, uidN = 1000 } = {}) {
const h = load({ seed: TEST.seed });
h.ev(`window.__t=${T0};Date.now=()=>__t;UI.started=true;UI.pitched=true;UI.speed=0;closeModal();`);
if (save) h.ev(`S=migrate(JSON.parse(${lit(save)}));uidN=${uidN};R=emptyR();compute();`);
h.day = () => h.ev('__t+=' + STEP + ';dayTick();UI.ticking=true;renderHUD();UI.ticking=false;');
h.close = () => h.dom.window.close();
return h;
}
let BIGS = null;
function bigScenic() {
if (BIGS) return BIGS;
const h = load({ seed: TEST.seed });
h.ev(`S=migrate(JSON.parse(${lit(fs.readFileSync(BIG, 'utf8'))}));S.rng=${MP.seed};S.mp={...${JSON.stringify(MP)},seq:0,sim:1};
for(const b of S.biz)if(BIZ_T[b.type].l2)b.route='scenic';`);
BIGS = h.ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))))');
h.dom.window.close();
return BIGS;
}
let n = 0;
function msg(act, args = {}, more = {}) {
const body = JSON.parse(JSON.stringify({ rid: 'r' + (++n).toString(36).padStart(8, '0'), dev: DEV, sim: sim(), act, args, ...more }));
const r = A.checkEnvelope(A.ASK.includes(act) ? 'ask' : 'act', body, { sim: sim() });
assert.ok(r.ok, `${act}: the page would not send this (${r.error})`);
return body;
}
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);})()";
function checked(r) {
const p = checkWorker(r);
assert.deepEqual(p, [], `${r && r.t}: ${p.join('; ')}`);
if (r && typeof r.upd === 'string') assert.deepEqual(checkEvent(JSON.parse(r.upd)), [], 'the update');
return r;
}
// The first top-level keys whose JSON differs, with a glimpse of each side: for a failing comparison's message.
function differs(a, b) {
const A2 = JSON.parse(a), B2 = JSON.parse(b);
return Object.keys({ ...A2, ...B2 }).filter((k) => JSON.stringify(A2[k]) !== JSON.stringify(B2[k]))
.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, winOf, begin, RSIG, checked, differs };

View file

@ -83,7 +83,9 @@ function checkFx(f, w = 'fx', out = []) {
const bad = () => out.push(`${w}: bad ${k} payload ${JSON.stringify(p).slice(0, 80)}`);
switch (k) {
case 'toast': fields(p, { h: str, k: [str, 'opt'], a: [listOf((x) => obj(x) && str(x.l) && str(x.act)), 'opt'], o: [(v) => v === null || obj(v), 'opt'], tick: [bool, 'opt'] }, `${w}.toast`, out); break;
case 'sfx': case 'haptic': if (!str(p)) bad(); break;
case 'sfx': if (!str(p)) bad(); break;
// The game's haptic(ms) takes how long to buzz.
case 'haptic': if (!(num(p) && p >= 0)) bad(); break;
case 'floater': if (!Array.isArray(p) || p.length !== 4 || !num(p[0]) || !num(p[1]) || !str(p[2]) || !str(p[3])) bad(); break;
case 'track': if (!Array.isArray(p) || p.length !== 2 || !str(p[0]) || !(p[1] === undefined || p[1] === null || bool(p[1]))) bad(); break;
case 'pause': if (p !== 1) bad(); break;
@ -111,14 +113,18 @@ const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str
feed: listOf((f, w, out) => { fields(f, { k: str, pid: str, name: str, at: nat, text: [str, 'opt'] }, w, out); return true; }),
on: listOf((v) => PID.test(v)) };
/* A snapshot is made in two halves: the realm's (the network: S, r, keep, at its epoch and version) and the host's
(clock, roster, since: the session and this stream). A worker's pulled.snap is the realm's half as text; the engine's
snapWith() joins the host's to it (scripts/lib/mp-sim-engine.js). */
const SNAP_REALM = { t: str, epoch: (v) => EPOCH.test(v), v: nat, now: nat, S: liveS, r: slimR,
keep: (v, ww, o) => { if (!Array.isArray(v) || v.length > 32) return false; v.forEach((f, i) => { checkFx(f, `${ww}[${i}]`, o); if (f[0] !== 'badge' && f[0] !== 'modal') o.push(`${ww}[${i}]: keep holds only badge and modal`); }); return true; } };
const SNAP_HOST = { clock: (v, ww, o) => { fields(v, CLOCK, ww, o); return true; }, roster: (v, ww, o) => { fields(v, ROSTER, ww, o); return true; },
since: (v, ww, o) => { fields(v, { days: nat, again: nat }, ww, o); return true; } };
function checkEvent(e) {
const out = [];
if (!obj(e) || !str(e.t)) return ['an event is an object with t'];
const w = e.t;
if (e.t === 'snap') fields(e, { t: str, epoch: (v) => EPOCH.test(v), v: nat, now: nat, S: liveS, r: slimR,
clock: (v, ww, o) => { fields(v, CLOCK, ww, o); return true; }, roster: (v, ww, o) => { fields(v, ROSTER, ww, o); return true; },
since: (v, ww, o) => { fields(v, { days: nat, again: nat }, ww, o); return true; },
keep: (v, ww, o) => { if (!Array.isArray(v) || v.length > 32) return false; v.forEach((f, i) => { checkFx(f, `${ww}[${i}]`, o); if (f[0] !== 'badge' && f[0] !== 'modal') o.push(`${ww}[${i}]: keep holds only badge and modal`); }); return true; } }, w, out);
if (e.t === 'snap') fields(e, { ...SNAP_REALM, ...SNAP_HOST }, w, out);
else if (e.t === 'upd') {
fields(e, { t: str, from: nat, v: nat, now: nat, day: nat, s: obj, del: [listOf(str), 'opt'], r: [slimR, 'opt'], fx: [fxList, 'opt'], acts: [listOf(actEntry), 'opt'] }, w, out);
if (nat(e.v) && nat(e.from) && e.v !== e.from + 1) out.push('upd: v is from + 1 (only a pull makes a version)');
@ -135,16 +141,21 @@ function checkEvent(e) {
// Worker → host replies (4.2). Big payloads (an update, a snapshot) are JSON text, ready to write to every stream.
const json = (t) => (v, w, out) => { if (!str(v)) return false; let e; try { e = JSON.parse(v); } catch (x) { return false; } for (const p of checkEvent(e)) out.push(`${w}: ${p}`); if (e.t !== t) out.push(`${w}: not a ${t}`); return true; };
// The realm's half of a snapshot (above): the host's three fields come later, so here they are unknown.
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: [json('snap'), '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) },
@ -157,7 +168,7 @@ function checkWorker(m) {
fields(m, WORKER[m.t], m.t, out);
if (m.t === 'loaded' && m.err === undefined) for (const k of ['epoch', 'day', 'lost']) if (m[k] === undefined) out.push(`loaded.${k}: missing`);
if (m.t === 'loaded' && m.err !== undefined && m.saved !== undefined) out.push('loaded: a network that did not load has nothing saved');
if (m.t === 'pulled' && m.snap !== undefined && str(m.snap)) { try { const e = JSON.parse(m.snap); if (e.epoch !== m.epoch) out.push('pulled: the snapshot\'s epoch is not the realm\'s'); } catch (x) { /* reported above */ } }
if (m.t === 'pulled' && m.snap !== undefined && str(m.snap)) { try { const e = JSON.parse(m.snap); if (e.epoch !== m.epoch) out.push('pulled: the snapshot\'s epoch is not the realm\'s'); if (e.v !== m.v) out.push('pulled: the snapshot is not at the version pulled'); } catch (x) { /* reported above */ } }
return out;
}

312
tests/mp-sim-acts.test.js Normal file
View file

@ -0,0 +1,312 @@
// The act tables of server-run play (scripts/lib/mp-sim-acts.js) against the game itself (the server-sim design, 5.8):
// SEND is the agent's game commands, adjusted; the CONFIRM table is how each two-click button arms (SRV_ARM is the key
// its first click writes); DRAFTS are the page-held UI values each act reads, all of them; and for every draft and text
// act, and every two-click one, the server's pipeline (drafts and arming from the request, then one run) leaves the same
// network as the page's clicks in jsdom.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
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 { 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());
test('SEND is the agent\'s game commands without the puzzles, teCheck, traceRun and closeModal, with connCancel, pieRename and tutSkip', (t) => {
const { ev, errors, dom } = load({ agent: true });
t.after(() => dom.window.close());
const cmd = JSON.parse(ev('JSON.stringify(Object.keys(API_CMD))'));
const want = cmd.filter((k) => !/^pz[A-Z]/.test(k) && !['teCheck', 'traceRun', 'closeModal'].includes(k)).concat(['connCancel', 'pieRename', 'tutSkip']).sort();
assert.deepEqual(A.SEND, want);
for (const a of [...A.SEND, ...A.ASK]) assert.equal(ev(`typeof ACT[${JSON.stringify(a)}]`), 'function', a);
assert.deepEqual(errors, []);
});
/* A rich network with something behind every two-click button: the big fixture, an intern, a sales head, a scrubbing
center, a teleport, an own exchange. Its S also goes to the realm, so both sides start the same. */
function rich() {
const P = page({ save: bigScenic() });
P.ev(`S.lvl=Math.max(S.lvl,6);ACT.opsHire({id:'kevin'});closeModal();ACT.salesHire({id:'eng'});closeModal();
ACT.buildScrub({city:'fra'});closeModal();ACT.teleBuild({city:'sea'});closeModal();UI.confirm=null;UI.sel=null;
S.day=Math.max(S.day,IP4_HOLD+30);S=migrate(JSON.parse(JSON.stringify(S)));compute();`);
// (Address blocks are held two years before they may be sold: these were bought long ago.)
return P;
}
// Pie in the Sky: a network that won (a Tier 1 club in Frankfurt, as tests/pie-in-the-sky.test.js builds it) and
// founded a rocket company with a factory, a pad in Singapore and pies on the shelf.
function pieCo() {
const P = page();
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;" + 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
// (teDeploy's other path, when the AI's script is the one deployed).
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;" + 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) => { 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();
t.after(() => P.close());
const { ev } = P;
const code = 'C0NF1R', nid = 'conf0001';
await loadInto(code, nid, P);
// Each act's args as its button carries them, from a crawl; the rest made here (they arm before any check).
const found = {};
for (const [a, args] of crawl(ev)) if (A.CONFIRM[a] && !found[a]) found[a] = args;
ev('UI.confirm=null;UI.sel=null;closeModal();');
Object.assign(found, { rmScrub: { city: 'fra' }, teleRm: { city: 'sea' }, cancelVxc: found.cancelVxc || { id: 'nolink' }, dkOptOut: found.dkOptOut || { city: 'fra', n: 'Nobody' } }, found);
const missing = Object.keys(A.CONFIRM).filter((a) => !found[a] && a !== 'repayLoan');
assert.deepEqual(missing, [], 'a button for every two-click act');
const changed = {};
for (const [a, args] of Object.entries(found)) {
const kind = A.CONFIRM[a];
// The first click: the page's own (a view change), never sent. S stays; the button is armed.
ev('UI.confirm=null;');
const s0 = ev('JSON.stringify(S)');
ev(`ACT[${JSON.stringify(a)}](${JSON.stringify(args)})`);
assert.equal(ev('JSON.stringify(S)'), s0, `${a}: the first click changes nothing`);
const armed = JSON.parse(ev('JSON.stringify(UI.confirm)'));
if (kind === 'arg') assert.notEqual(armed, null, `${a}: armed`);
else assert.equal(armed, A.armKey(a, args), `${a}: SRV_ARM's key is what the first click writes`);
// The second click on the page, and the same click on the server, sent with confirmed:true.
const ctx = ctxOf(ev);
if (kind === 'arg') ev(`UI.confirm=null;ACT[${JSON.stringify(a)}](${JSON.stringify({ ...args, ok: 1 })})`);
else ev(`ACT[${JSON.stringify(a)}](${JSON.stringify(args)})`);
closeAll(ev);
const r = checked(await E.act(code, nid, msg(a, args, { confirmed: true, ctx })));
changed[a] = ev('JSON.stringify(S)') !== s0;
const want = ev('JSON.stringify(S)'), got = (await E.eval(code, nid, 'return JSON.stringify(S)')).value;
assert.ok(want === got, `${a} ${JSON.stringify(args)} (${r.outcome}${r.why ? ': ' + r.why : ''}):\n${want === got ? '' : differs(want, got)}`);
if (changed[a]) assert.equal(r.outcome, 'applied', a);
}
// The ones with a real target were really done.
for (const a of ['cancelTransit', 'cancelIx', 'cancelPni', 'rmLink', 'rmSite', 'dropBiz', 'salesFire', 'opsFire', 'rmScrub', 'teleRm', 'connCancel']) if (found[a]) assert.equal(changed[a], true, `${a} did its thing`);
assert.deepEqual(P.errors, []);
});
const closeAll = (ev) => ev('closeModal();');
test('repayLoan: armed by its id, repaid by the second click (a network small enough to borrow)', async (t) => {
const P = page();
t.after(() => P.close());
P.ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:{code:'K7Q2XD',pid:'loan0001',asn:201234,seed:5,preset:'oncall',color:'#3a86ff',title:'x'}});S.mp.sim=1;S.tut=null;compute();
ACT.launchBB({city:'fra'});spawnLoanOffer(false);ACT.takeLoan({id:S.loanOffers[0].id});closeModal();S.cash+=5e6;uidN=1000;`);
const id = P.ev('S.loans[0].id');
const code = 'L0ANS0', nid = 'loan0001';
await loadInto(code, nid, P);
P.ev('UI.confirm=null');
const s0 = P.ev('JSON.stringify(S)');
P.ev(`ACT.repayLoan({id:'${id}'})`);
assert.equal(P.ev('JSON.stringify(S)'), s0);
assert.equal(P.ev('UI.confirm'), A.armKey('repayLoan', { id }));
P.ev(`ACT.repayLoan({id:'${id}'})`);
assert.equal(P.ev('S.loans.length'), 0, 'repaid');
const r = checked(await E.act(code, nid, msg('repayLoan', { id }, { confirmed: true })));
assert.equal(r.outcome, 'applied');
assert.equal((await E.eval(code, nid, 'return JSON.stringify(S)')).value, P.ev('JSON.stringify(S)'));
});
/* 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, 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());
const SPY = `window.__reads=new Set();window.__spy=()=>{for(const k of new Set(${JSON.stringify(PAGE_HELD)}.concat(Object.keys(UI)))){let v=UI[k];Object.defineProperty(UI,k,{get(){__reads.add(k);return v;},set(x){v=x;},configurable:true,enumerable:true});}};
window.__unspy=()=>{const r=[...__reads];for(const k of Object.keys(UI)){const d=Object.getOwnPropertyDescriptor(UI,k);const v=d.get?d.get():d.value;Object.defineProperty(UI,k,{value:v,writable:true,configurable:true,enumerable:true});}return r;};`;
const { ev } = P;
ev(SPY);
const near = ev("Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((a,b)=>kmBetween('ams',a)-kmBetween('ams',b))[0]");
const sib = ev("(()=>{const l=S.links.find(l=>l.kind==='wave'&&landTrenches(l.a,l.b).length);return l.a+'|'+l.b;})()").split('|');
const runs = [
['buildLink', `openLinkModal('fra','${near}')`, { tier: 1 }],
['buildLink', `openLinkModal('${sib[0]}','${sib[1]}');UI.route='same';`, { tier: 1 }],
['buildLink', `openLinkModal('lon','nyc');UI.via='land';`, { tier: 1 }],
['buildLink', CROSS + "openLinkModal('hkg','sha');ACT.cnPrem({v:1});", { tier: 1 }],
['orderDf', "UI.pending={a:'fra',b:'muc'};UI.dfSrc='lease';UI.dfSys='lite';", {}],
['orderDf', "UI.pending={a:'fra',b:'muc'};UI.dfSrc='build';UI.dfSys='lite';", {}],
['orderCable', "UI.pending={a:'lon',b:'nyc'};UI.seaDesign='express';UI.seaterminal=true;UI.seaengineering=false;", {}],
['decomGo', "UI.decom=new Set(['bet']);", {}],
['teDeploy', "S.te={on:true,day:S.day,script:''};UI.slop=undefined;", { script: 'prefer cog at fra' }],
(() => { const Q = oneUp(); return ['teDeploy', `UI.slop=${JSON.stringify(Q.cap)};`, { script: Q.cap }, Q]; })(),
['pieLaunch', 'UI.pieIns=true;UI.pieLas=false;', { rk: 'falcon', cr: 'short' }, pieCo()],
];
const reads = {};
for (const [act, setup, args, other] of runs) {
const ev = other ? other.ev : P.ev;
if (other) { t.after(() => other.close()); ev(SPY); }
ev(setup);
ev(`window.__keep=[after,openModal,renderAll,renderPanel,renderLeft,renderHUD,renderHint,renderDash,renderBank];
after=openModal=renderAll=renderPanel=renderLeft=renderHUD=renderHint=renderDash=renderBank=()=>{};__spy();__reads.clear();`);
try { ev(`ACT.${act}(${JSON.stringify(args)})`); } finally {
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) && !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)) {
assert.ok(reads[act], `${act} was played`);
for (const k of A.DRAFTS[act]) assert.ok(reads[act].has(k), `${act} reads ${k}`);
}
assert.deepEqual(P.errors, []);
});
test('drafts and texts: the server\'s run of each draft and text act leaves the network the page\'s clicks leave', async (t) => {
const P = rich();
t.after(() => P.close());
const { ev } = P;
ev("S.te={on:true,day:S.day,script:''};closeModal();UI.sel=null;compute();" + CROSS);
const code = 'DRAFT5', nid = 'drft0001';
await loadInto(code, nid, P);
const near = ev("Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((a,b)=>kmBetween('ams',a)-kmBetween('ams',b))[0]");
const script = ev('TE_EXAMPLE'), metric = ev("S.links.find(l=>l.kind==='wave'&&l.a!=='bet'&&l.b!=='bet').id");
// [act, args, what the page did before the click (its drafts), the drafts sent]
const plays = [
['buildLink', { tier: 1 }, `openLinkModal('fra','${near}')`, () => pick(ev, ['pending', 'route', 'via', 'cnPrem'])],
['buildLink', { tier: 1 }, "openLinkModal('hkg','sha');ACT.cnPrem({v:1});", () => pick(ev, ['pending', 'route', 'via', 'cnPrem'])],
['orderDf', {}, "UI.pending={a:'fra',b:'muc'};UI.dfSrc='lease';UI.dfSys='lite';", () => pick(ev, ['pending', 'dfSrc', 'dfSys'])],
['orderCable', {}, "UI.pending={a:'lon',b:'nyc'};UI.seaDesign='express';UI.seaterminal=true;UI.seaengineering=false;", () => pick(ev, ['pending', 'seaDesign', 'seaterminal', 'seaengineering'])],
['decomGo', {}, "UI.decom=new Set(['bet']);", () => ({ decom: JSON.parse(ev('JSON.stringify([...UI.decom])')) })],
['teDeploy', { script }, 'UI.slop=undefined;', () => ({ slop: false })],
['setMetric', { id: metric, v: 'custom' }, '', null],
['metricSet', { id: metric, v: '42' }, '', null],
['renameGo', { name: 'Tubular Bells' }, '', null],
];
await play(code, nid, ev, plays);
assert.equal(ev("S.links.filter(l=>l.premium).length"), 1, 'the crossing into Hong Kong went premium');
// A what-if with its text: the window, and the network as it was.
const K = checked(await E.ask(code, nid, msg('teCheck', { script })));
assert.match(K.modal.h, /term/);
assert.equal((await E.eval(code, nid, 'return JSON.stringify(S)')).value, ev('JSON.stringify(S)'));
assert.deepEqual(P.errors, []);
// The rocket company's acts, on a network that won and founded one.
const Q = pieCo();
t.after(() => Q.close());
await loadInto('P1EC0S', 'piec0001', Q);
await play('P1EC0S', 'piec0001', Q.ev, [
['pieRename', { name: 'Pie Hard' }, '', null],
['pieLaunch', { rk: 'falcon', cr: 'short' }, 'UI.pieIns=true;UI.pieLas=false;', () => pick(Q.ev, ['pieIns', 'pieLas'])],
]);
assert.deepEqual(Q.errors, []);
// The AI's script, deployed as it wrote it, drops most of the traffic: its own apology, not the fat-finger one.
const T = oneUp();
t.after(() => T.close());
await loadInto('SL0PPY', 'slop0001', T);
await play('SL0PPY', 'slop0001', T.ev, [['teDeploy', { script: T.cap }, `UI.slop=${JSON.stringify(T.cap)};`, () => ({ slop: true })]]);
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);
const ctx = ctxOf(ev), drafts = ui ? ui() : null;
const s0 = ev('JSON.stringify(S)');
ev(`ACT.${act}(${JSON.stringify(args)});closeModal();`);
const r = checked(await E.act(code, nid, msg(act, args, { ...(drafts ? { ui: drafts } : {}), ctx })));
const want = ev('JSON.stringify(S)'), got = (await E.eval(code, nid, 'return JSON.stringify(S)')).value;
assert.notEqual(want, s0, `${act} did something on the page`);
assert.equal(r.outcome, 'applied', `${act}: ${r.why || ''}`);
assert.ok(want === got, `${act}:\n${want === got ? '' : differs(want, got)}`);
}
}
const pick = (ev, keys) => JSON.parse(ev(`JSON.stringify(Object.fromEntries(${JSON.stringify(keys)}.filter(k=>UI[k]!==undefined&&UI[k]!==null).map(k=>[k,UI[k]])))`));
// The gate (5.8 step 6) passes buyTE and the monkey's banana: the game writes S.te and S.monkey as a reload makes them,
// so the server runs both and leaves the network the page's clicks leave.
test('buyTE and the banana pass the gate, and leave the network the page leaves', async (t) => {
const P = page({ save: bigScenic() });
t.after(() => P.close());
const code = 'B0YTE0', nid = 'buyt0001';
P.ev("S.rules=makeRules('oncall');S.cash=Math.max(S.cash,1e9);S.monkey.next=S.day;mkTick(S.day);closeModal();compute();");
assert.equal(P.ev('mkOn()'), true, 'the monkey is here');
await loadInto(code, nid, P);
for (const [act, run] of [['coreUp', 'ACT.coreUp()'], ['coreUp', 'ACT.coreUp()'], ['buyTE', 'ACT.buyTE()'], ['mkBanana', 'ACT.mkBanana({})']]) {
P.ev(run + ';closeModal();');
const r = checked(await E.act(code, nid, msg(act, {})));
assert.equal(r.outcome, 'applied', `${act}: ${r.why || ''}`);
const want = P.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)}`);
}
assert.deepEqual(JSON.parse(P.ev('JSON.stringify([!!S.te,S.monkey.on])')), [true, 0]);
assert.deepEqual(P.errors, []);
});

View file

@ -10,11 +10,14 @@ const { lit } = require('../scripts/lib/js-literal');
const A = require('../scripts/lib/mp-sim-acts');
const { checkEvent, checkFx, checkWorker, parseSse, fixture, FIXTURES } = require('./lib/mp-sim-shape');
const { createFakeEngine } = require('./lib/mp-sim-fake-engine');
const { crawl } = require('./lib/mp-sim-crawl');
const fs = require('node:fs');
const path = require('node:path');
const SIM = simId();
const env = (act, args = {}, more = {}) => ({ rid: 'a1b2c3d4e5', dev: '9f8e7d6c', sim: SIM, act, args, ...more });
// A checkpoint as the host hands it to load(): the save text (the canned network on that day).
const sv = (day) => JSON.stringify({ ...fixture('snap').S, day });
test('every ACT is classified once: SEND, ASK, VOTE, LOCAL or PUZZLE; SEND is the agent\'s game commands, adjusted', (t) => {
// The development page of a multiplayer build: every ACT there is, the server-play client's (98-server-play) too.
@ -44,24 +47,6 @@ test('every ACT is classified once: SEND, ASK, VOTE, LOCAL or PUZZLE; SEND is th
assert.deepEqual(errors, []);
});
// Every button and drop-down a rich game shows, as the page would send it: [act, args].
function crawl(ev) {
ev(`window.__btns=[];window.__grab=()=>{for(const el of document.querySelectorAll('[data-act],[data-chg]')){const act=el.dataset.act||el.dataset.chg;let a={};try{a=el.dataset.args?JSON.parse(el.dataset.args):{};}catch(e){a={bad:el.dataset.args};}
if(el.dataset.chg){a={...a,v:el.value}}__btns.push([act,a]);}};`);
const views = [
"for(const c of ['fra','ams','nyc','sin','syd']){for(const tab of ['cust','up','peer','infra','links']){UI.sel={type:'city',id:c};UI.tab=tab;renderPanel();__grab();}}",
"for(const l of S.links.slice(0,40)){UI.sel={type:'link',id:l.id};renderPanel();__grab();}",
"UI.leftOpen=true;for(const k of ['goals','deals','noc','nets']){UI.left=k;renderLeft();__grab();}",
"$('dash').hidden=false;for(const k of DTABS){UI.dtab=k;renderDash();__grab();}$('dash').hidden=true;",
'ACT.bank();__grab();ACT.bankClose();',
"for(const [a,x] of [['opsOpen',{}],['utilities',{city:'fra'}],['bstdOpen',{}],['pniAllOpen',{net:null}],['pniAllOpen',{net:'cog'}],['salesOpen',{}],['routingOpen',{}],['ip4Open',{}],['models',{}],['decomOpen',{}],['teEdit',{}]]){try{ACT[a](x);}catch(e){}__grab();closeModal();}",
"openLinkModal('fra','nyc');__grab();closeModal();openLinkModal('fra','ams');__grab();closeModal();",
"UI.confirm=null;for(const t of S.transit.slice(0,3)){UI.sel={type:'city',id:t.city};UI.tab='up';UI.confirm=t.id;renderPanel();__grab();}UI.confirm=null;",
];
for (const v of views) ev(v);
return JSON.parse(ev('JSON.stringify(__btns)'));
}
test('the envelope check passes every button a rich game shows for a sent act, as the page sends it', (t) => {
const fsx = require('node:fs');
const BIG = fsx.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
@ -74,7 +59,7 @@ test('the envelope check passes every button a rich game shows for a sent act, a
assert.ok(sent.length > 200, `a real sweep: ${sent.length} sent buttons of ${btns.length}`);
const acts = new Set(sent.map(([a]) => a));
assert.ok(acts.size > 40, `${acts.size} different acts`);
for (const q of ['pniAll', 'bstdApply', 'utilityKit']) assert.ok(acts.has(q), `the sweep found ${q}`);
for (const q of ['pniAll', 'bstdApply', 'utilityKit', 'mktCfg', 'pathPin']) assert.ok(acts.has(q), `the sweep found ${q}`);
for (const [act, args] of sent) {
// The page adds the drafts the act reads, as they are, and confirms a two-click act's second click.
const ui = A.DRAFTS[act] ? JSON.parse(ev(`JSON.stringify({pending:UI.pending||{a:'fra',b:'ams'},route:UI.route||'',via:UI.via||'',cnPrem:!!UI.cnPrem,dfSrc:'lease',dfSys:'lite',seaDesign:'standard',
@ -111,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 } });
@ -180,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);
@ -207,6 +210,11 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
// The worker built that realm again: a new epoch, versions from 0, so every page of it takes a snapshot.
const P3 = await e.pull(code, a, { snap: true });
assert.notEqual(P3.epoch, L[0].epoch); assert.equal(P3.v, 0); assert.equal(JSON.parse(P3.snap).epoch, P3.epoch);
// A pulled snapshot is the realm's half; with the host's clock, roster and since it is the stream event.
const host = { clock: fixture('clock'), roster: fixture('roster'), since: { days: 0, again: 0 } };
assert.match(checkEvent(JSON.parse(P3.snap)).join(), /clock: missing/, 'the realm\'s half alone is no stream event');
assert.deepEqual(checkEvent(JSON.parse(e.snapWith(P3.snap, host))), []);
assert.deepEqual(JSON.parse(e.snapWith(P3.snap, host)).clock, host.clock);
all.push(D2, D3, tmo, P3);
for (const m of all) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
// Held answers wait; a worker that dies rejects everything pending.
@ -227,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);
@ -266,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

@ -0,0 +1,382 @@
// The server's realm plays a network exactly as the page does (the server-sim design, sections 4.1-4.3, 4.7, 11).
// - Realm vs jsdom: the big network with its L2 customers on scenic routes, 60 days with actions in between, the
// page's arm clicking as a player does (each click ending in after()) and rendering the HUD after every day: S and R
// byte for byte the same.
// - Restore: a checkpoint after any day, loaded into a fresh realm, plays on byte for byte as the network that kept
// going, the scenic big network and the same one busy (intern, sales desk, failures, events, an attack).
// - 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
// sent button a rich crawl finds: no timer is ever scheduled on these paths, nothing changes after them, and no
// action is rolled back by the sanitize gate (which also runs after every day here, SIM_STRICT).
// SIM_LONG=1 plays the audit for a year, as section 11 asks, and checkpoints after every day to 30 (a few minutes); by
// default the audit plays 60 days.
const test = require('node:test');
const assert = require('node:assert/strict');
const { createEngine } = require('../scripts/lib/mp-sim-engine');
const { crawl } = require('./lib/mp-sim-crawl');
const A = require('../scripts/lib/mp-sim-acts');
const { load } = require('./harness');
const { CODE, MP, TEST, ROOMY, page, bigScenic, msg, ctxOf, begin, RSIG, checked, differs } = require('./lib/mp-sim-play');
const LONG = process.env.SIM_LONG === '1';
const E = createEngine({ workers: 2, test: TEST, timeouts: ROOMY });
test.after(() => E.close());
// The big network with everything that keeps state between days on: the intern on every order, the sales desk (rep)
// signing on its own, a failure and an event due.
const busy = (rep) => `S.lvl=Math.max(S.lvl,6);S.rules=makeRules('bgp');ACT.opsHire({id:'kevin'});for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;closeModal();
ACT.salesHire({id:'${rep}'});ACT.salesAuto();closeModal();S.nextFail=S.day+2;S.nextEvent=S.day+3;compute();`;
const on = (X) => ({
day: (code, d, nets, o = {}) => X.day(code, { d, speed: 1, last: 1, alone: [], nets, ...o }).then(checked),
realmS: async (code, nid) => (await X.eval(code, nid, 'return JSON.stringify(S)')).value,
realmR: async (code, nid) => (await X.eval(code, nid, `return ${RSIG}`)).value,
});
const { day, realmS, realmR } = on(E);
const loadBig = async (code, nid) => checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
test('realm vs jsdom: 60 days of the scenic big network with actions in between, S and R byte for byte', async (t) => {
const P = page({ save: bigScenic() });
t.after(() => P.close());
const code = 'D3T3RM', nid = 'detr0001';
await loadBig(code, nid);
const ev = P.ev;
const near = ev("Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((a,b)=>kmBetween('fra',a)-kmBetween('fra',b))[0]");
const net = ev(`NETS.filter(n=>sellsAt(n,${JSON.stringify(near)}))[0].id`);
const script = ev('TE_EXAMPLE');
const gone = ev("S.links.find(l=>l.kind==='wave'&&l.a==='fra').id");
// On a day: what the player clicks, the page's way, and the request the same click sends the server.
const PLAN = {
5: () => ({ act: 'buildPop', args: { city: near }, page: () => ev(`ACT.buildPop({city:${JSON.stringify(near)}})`) }),
6: () => { ev(`openLinkModal('fra',${JSON.stringify(near)})`);
const ui = JSON.parse(ev("JSON.stringify(Object.fromEntries(['pending','route','via','cnPrem'].filter(k=>UI[k]!==undefined&&UI[k]!==null||k==='pending').map(k=>[k,UI[k]])))"));
return { act: 'buildLink', args: { tier: 1 }, ui, page: () => ev('ACT.buildLink({tier:1})') }; },
8: () => ({ act: 'buyTransit', args: { city: near, net, tier: 1 }, page: () => ev(`ACT.buyTransit({city:${JSON.stringify(near)},net:'${net}',tier:1})`) }),
12: () => { ev(`UI.sel={type:'link',id:'${gone}'};`); return { act: 'rmLink', args: { id: gone }, confirmed: true, page: () => ev(`ACT.rmLink({id:'${gone}'});ACT.rmLink({id:'${gone}'})`) }; },
15: () => ({ act: 'renameGo', args: { name: 'Tubular Bells' }, page: () => ev("ACT.renameGo({name:'Tubular Bells'})") }),
18: () => ({ act: 'coreUp', args: {}, page: () => ev('ACT.coreUp()') }),
19: () => ({ act: 'coreUp', args: {}, page: () => ev('ACT.coreUp()') }),
21: () => ({ act: 'buyTE', args: {}, page: () => ev('ACT.buyTE()') }),
22: () => ({ act: 'teDeploy', args: { script }, ui: { slop: false }, page: () => ev(`ACT.teDeploy({script:${JSON.stringify(script)}})`) }),
};
const outcomes = {};
for (let d = 1; d <= 60; d++) {
if (PLAN[d] && PLAN[d]().setup) { const x = PLAN[d]().setup; ev(x); await E.eval(code, nid, x + 'return 1;'); }
else if (PLAN[d]) {
const p = PLAN[d]();
const ctx = ctxOf(ev);
p.page();
const r = checked(await E.act(code, nid, msg(p.act, p.args, { ...(p.ui ? { ui: p.ui } : {}), ...(p.confirmed ? { confirmed: true } : {}), ctx })));
outcomes[p.act + '@' + d] = r.outcome + (r.why ? ': ' + r.why : '');
const a = ev('JSON.stringify(S)'), b = await realmS(code, nid);
assert.ok(a === b, `after ${p.act} on day ${d}:\n${a === b ? '' : differs(a, b)}`);
}
P.day();
const D = await day(code, d, [nid]);
assert.equal(D.nets[nid].err, undefined, `day ${d}`);
if (d % 20 === 0) {
const a = ev('JSON.stringify(S)'), b = await realmS(code, nid);
assert.ok(a === b, `S on day ${d}:\n${a === b ? '' : differs(a, b)}`);
assert.ok(ev(RSIG) === await realmR(code, nid), `R on day ${d}`);
}
}
// The plan really played: the network grew, a link went, the script is live.
for (const k of ['buildPop@5', 'buildLink@6', 'buyTransit@8', 'rmLink@12', 'renameGo@15', 'buyTE@21', 'teDeploy@22']) assert.equal(outcomes[k], 'applied', k);
assert.equal(ev('S.name'), 'Tubular Bells');
assert.equal(ev('!!(S.te&&S.te.on&&S.te.script)'), true, 'RouteScript is deployed');
assert.equal(ev('S.biz.filter(b=>b.route===\'scenic\').length') > 0, true, 'scenic circuits played');
assert.deepEqual(P.errors, []);
});
/* A restart or an idle unload is invisible (4.6, 4.7, 11): a network checkpointed after any day and loaded into a fresh
realm is at once, and stays, the network that kept going, S and R byte for byte. Two of them: the scenic big network,
and the same busy (busy(), and an attack on). They need everything rt carries besides the save: R's routing point (R
after a day is the R of the day's last routing, made before the day's end changed S, so the saved S routes to another
R, which the next day reads; a checkpoint after day 10 passed by luck: a failure or event routed at that day's end), the
sales desk's tried offers, and the live order of keys a reload reorders (the intern's weekly report lists its tally
in it). Checkpoints after days 1, 2, 5 and 10 of each (2 and 10 right after an action), each played 10 days on;
SIM_LONG: after every day up to 30. Compared as text: a deep-equal of two big networks that differ builds a diff of
gigabytes. */
test('restore: a checkpoint after any day, in a fresh realm, plays on byte for byte as the network that kept going', { timeout: LONG ? 1800e3 : 300e3 }, async (t) => {
const X = createEngine({ workers: 1, test: TEST, timeouts: ROOMY, heapMb: LONG ? 4096 : 1536 });
t.after(() => X.close());
const { day, realmS, realmR } = on(X);
const code = 'R3ST0R', H = 10, KS = LONG ? Array.from({ length: 30 }, (_, i) => i + 1) : [1, 2, 5, 10], N = Math.max(...KS) + H;
const bases = ['busy0000', 'scen0000'];
for (const nid of bases) checked((await X.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
assert.equal((await X.eval(code, bases[0], busy('eng') + 'const a=ddosAttack(true);a.until=S.day+6;return slP();')).value, 'eng');
const same = async (what, a, b) => {
const sa = await realmS(code, a), sb = await realmS(code, b);
assert.ok(sa === sb, `${what}: S\n${sa === sb ? '' : differs(sa, sb)}`);
const ra = await realmR(code, a), rb = await realmR(code, b);
assert.ok(ra === rb, `${what}: R\n${ra === rb ? '' : differs(ra, rb)}`);
};
let copies = [];
const carried = { point: 0, desk: 0, order: 0 };
for (let d = 1; d <= N; d++) {
await day(code, d, [...bases, ...copies.map((c) => c.nid)]);
for (const c of copies.filter((x) => x.k + H === d)) { await same(`${c.nid}, ${H} days after its checkpoint`, c.base, c.nid); await X.unload(code, c.nid); }
copies = copies.filter((x) => x.k + H > d);
if (!KS.includes(d)) continue;
// Every other one right after an action and a what-if (a server also checkpoints a network after an action), sent
// to the network and to its copies alike.
if (d % 2 === 0) for (const b of bases) {
const city = (await X.eval(code, b, "return Object.keys(CITY).filter(c=>!S.pops[c]&&homeOk(c)).sort((x,y)=>kmBetween('fra',x)-kmBetween('fra',y))[0]")).value;
const lid = (await X.eval(code, b, 'return S.links[0].id')).value;
for (const nid of [b, ...copies.filter((c) => c.base === b).map((c) => c.nid)]) {
assert.equal(checked(await X.act(code, nid, msg('buildPop', { city }))).outcome, 'applied', `${nid}: a POP in ${city}`);
assert.ok(checked(await X.ask(code, nid, msg('linkCheck', { id: lid }))).modal, `${nid}: the what-if`);
}
}
for (const b of bases) {
// The envelope a server writes (4.6), through text, into a fresh realm; the network's clock goes on.
const sv = checked(await X.save(code, b)), nid = b.slice(0, 4) + String(d).padStart(4, '0');
const env = JSON.parse(JSON.stringify({ s: sv.txt, uidN: sv.uidN, rt: sv.rt, last: d, day: sv.day }));
checked((await X.load(code, [{ nid, env, lang: 'en', prefs: {} }]))[0]);
await X.eval(code, nid, `__srvClock(${(await X.eval(code, b, 'return __srvClock()')).value});return 1;`);
await same(`${nid}, loaded from its checkpoint after day ${d}`, b, nid);
copies.push({ nid, base: b, k: d });
const rt = env.rt;
if (rt.pt && rt.pt.at.biz) carried.point++;
if (rt.sl.length) carried.desk++;
if (rt.ord && rt.ord.ops) carried.order++;
}
}
// What it played: scenic circuits, and checkpoints that needed each part of rt.
assert.ok(JSON.parse(await realmS(code, bases[1])).biz.some((x) => x.route === 'scenic'), 'with scenic circuits');
assert.ok(carried.point && carried.desk && carried.order, `rt carried each part: ${JSON.stringify(carried)}`);
await X.unload(code);
});
test('retry: a day that throws, or times out, once after the DDoS step with an attack on, leaves the same network', async (t) => {
// An engine with the server's own time limits: the injected endless loop is stopped by them.
const E = createEngine({ workers: 1, test: TEST });
t.after(() => E.close());
const { day, realmS, realmR } = on(E);
const code = 'R3TRYX', clean = 'rtya0001', thrown = 'rtyb0002', slow = 'rtyc0003', nets = [clean, thrown, slow];
const L = await E.load(code, nets.map((nid) => ({ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} })));
L.forEach(checked);
// Busy: what keeps state between days goes back to the mark too (the sales desk's tried offers live outside S).
for (const nid of nets) await E.eval(code, nid, busy('eng') + 'return 1;');
for (let d = 1; d <= 3; d++) await day(code, d, nets);
// An attack that is still on during day 4 (the same one in each).
for (const nid of nets) assert.ok((await E.eval(code, nid, 'const a=ddosAttack(true);a.until=S.day+3;return ddosAll().length')).value > 0, 'an attack is on');
const epoch = async (nid) => checked(await E.pull(code, nid, {})).epoch;
const e0 = { thrown: await epoch(thrown), slow: await epoch(slow) };
// Day 4 fails once in two of them, right after the DDoS step, while the attack is on.
const fault = (what) => `{const f=ddosTick;let once=true;ddosTick=function(){f();if(once&&ddosAll().length){once=false;${what}}};}return 1;`;
await E.eval(code, thrown, fault("throw new Error('injected failure')"));
await E.eval(code, slow, fault('for(;;){}'));
const D = await day(code, 4, nets);
assert.deepEqual([D.nets[clean].retried, D.nets[thrown].retried, D.nets[slow].retried], [undefined, true, true]);
for (const nid of nets) assert.equal(D.nets[nid].err, undefined, `${nid} played day 4`);
assert.equal(await epoch(thrown), e0.thrown, 'a throw is put back in place: the same realm');
assert.notEqual(await epoch(slow), e0.slow, 'a timeout gets a fresh realm: a new epoch');
for (let d = 5; d <= 8; d++) await day(code, d, nets);
const s0 = await realmS(code, clean), r0 = await realmR(code, clean);
for (const nid of [thrown, slow]) {
const s = await realmS(code, nid);
assert.ok(s === s0, `${nid}:\n${s === s0 ? '' : differs(s0, s)}`);
assert.ok(await realmR(code, nid) === r0, `${nid}: R`);
}
// A day that fails twice: broken at its state before the day; it gets no more days, its actions stop.
await E.eval(code, thrown, "{const f=ddosTick;ddosTick=function(){f();throw new Error('broken for good');};}return 1;");
const before = JSON.parse(await realmS(code, thrown)).day;
const D2 = await day(code, 9, nets);
assert.equal(D2.nets[thrown].retried, true);
assert.match(D2.nets[thrown].err, /broken for good/);
assert.equal(D2.nets[thrown].day, before, 'at its state before the day');
assert.equal(JSON.parse(await realmS(code, thrown)).day, before);
const D3 = await day(code, 10, nets);
assert.equal(D3.nets[thrown], undefined, 'no more days');
assert.equal(checked(await E.act(code, thrown, msg('buildPop', { city: 'dus' }))).outcome, 'stopped');
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' };
const one = { aaaa0001: X, mmmm0002: Y, zzzz0003: Z }, two = { zzzz0001: X, mmmm0002: Y, aaaa0003: Z };
const play = async (code, ids) => {
const nids = Object.keys(ids);
(await E.load(code, nids.map((nid, i) => ({ ...begin(nid, ids[nid]), begin: { ...begin(nid, ids[nid]).begin, mp: { code: 'S4M3C0', pid: 'same000' + i, asn: 201234, seed: 777, preset: ids[nid].preset || 'oncall', color: '#3a86ff', title: 'Order' } } })))).forEach(checked);
for (const nid of nids) {
const c = ids[nid].home;
for (const [act, args] of [['launchBB', { city: c }], ['buyTransit', { city: c, net: (await E.eval(code, nid, `return NETS.filter(n=>sellsAt(n,'${c}'))[0].id`)).value, tier: 1 }]]) checked(await E.act(code, nid, msg(act, args)));
}
for (let d = 1; d <= 40; d++) await day(code, d, nids.slice().reverse());
const out = {};
for (const nid of nids) out[ids[nid].home] = await realmS(code, nid);
await E.unload(code);
return out;
};
const a = await play('0RDER1', one), b = await play('0RDER2', two);
for (const k of Object.keys(a)) assert.ok(a[k] === b[k], `${k}:\n${a[k] === b[k] ? '' : differs(a[k], b[k])}`);
assert.notEqual(a.fra, a.nyc);
});
// The capacity market and moving customers came after the engine (3.2.0, 3.3.0): their acts and the market's days, on a
// network with fiber to sell (the big fixture has none), against the page, under the strict gate, then from a checkpoint.
test('market and moved customers: realm and page the same, the strict gate passes, a checkpoint plays on the same', async (t) => {
// New York to Ashburn three times (two fibers in one trench), the way round through Boston, Chicago; a wave, a managed
// wave and a circuit to move.
const fib = (id, a, z, km, tr, n = 8) => `S.links.push({id:'${id}',a:'${a}',b:'${z}',kind:'df',own:true,sys:'roadm',pairs:2,ch:Array(${n}).fill('zr4'),km:${km},sub:false,cable:null,mo:1,trench:'${tr}',cut:0,day:0,ready:0,spares:false});`;
const cust = (id, type, more) => `S.biz.push({id:'${id}',type:'${type}',name:'Customer ${id}',city:'nyc',city2:'ash',bw:1,rate:9000,reqs:[],mood:80,since:0,day:0,route:'normal'${more}});`;
const h = load({ seed: TEST.seed });
h.ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;S.lvl=13;UI.speed=0;" +
"for(const c of ['nyc','ash','bos','chi'])if(!S.pops[c])S.pops[c]={day:0,bb:null,boost:0,down:0,routers:4,gen:false,rgen:RG.length-3};" +
fib('a', 'nyc', 'ash', 350, 'ta') + fib('b', 'nyc', 'ash', 350, 'ta') + fib('c', 'ash', 'nyc', 420, 'tc') + fib('d', 'nyc', 'bos', 130, 'td') +
fib('e', 'bos', 'ash', 220, 'te') + fib('f', 'chi', 'nyc', 1200, 'tf', 16) +
cust('w', 'wwave', ",link:'a',slots:2,what:'x'") + cust('m', 'mwave', ",link:'b',slots:1,g:100,what:'x'") + cust('k', 'l2vpn', '') +
`S.rng=${MP.seed};S.mp={...${JSON.stringify(MP)},seq:0,sim:1};compute();`);
const save = h.ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(S))))');
h.dom.window.close();
const P = page({ save }), ev = P.ev;
t.after(() => P.close());
const S2 = createEngine({ workers: 1, test: TEST, strict: true, timeouts: ROOMY });
t.after(() => S2.close());
const code = 'MKTPTH', nid = 'mktp0001', nid2 = 'mktp0002';
checked((await S2.load(code, [{ nid, env: { s: save, uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const realm = async (n, src) => (await S2.eval(code, n, src)).value;
const same = async (what) => {
const x = ev('JSON.stringify(S)'), y = await realm(nid, 'return JSON.stringify(S)');
assert.ok(x === y, `${what}:\n${x === y ? '' : differs(x, y)}`);
};
const outcomes = [];
const act = async (a, args) => {
const ctx = ctxOf(ev);
ev(`ACT.${a}(${JSON.stringify(args)})`);
outcomes.push(a + ' ' + checked(await S2.act(code, nid, msg(a, args, { ctx }))).outcome);
await same(`after ${a}`);
};
let d = 0;
const days = async (n, nets, pg = true) => {
for (let i = 0; i < n; i++) {
if (pg) P.day();
const D = checked(await S2.day(code, { d: ++d, speed: 1, last: 1, alone: [], nets }));
for (const x of nets) assert.equal(D.nets[x].err, undefined, `${x} day ${d}: ${D.nets[x].err}`);
}
};
await act('mktHold', { v: 0 });
for (const p of ev('CM_P.join()').split(',')) { await act('mktCfg', { p, k: 'on', v: true }); await act('mktCfg', { p, k: 'floor', v: 60 }); }
await act('mktCfg', { p: 'w100', k: 'min', v: 1 });
await act('mktRoute', { k: 'ash|nyc' });
await act('mktRoute', { k: 'ash|nyc' });
const to = (id) => ev(`fiberTargets(S.biz.find(b=>b.id==='${id}')).filter(x=>!x.no).map(x=>x.l.id)[0]`);
await act('pathMove', { id: 'w', link: to('w') });
await act('pathMove', { id: 'm', link: to('m') });
const via = ev("circuitTargets(S.biz.find(b=>b.id==='k')).alts[0].p.join()");
await act('pathPin', { id: 'k', via });
await days(1, [nid]);
await act('pathAuto', { id: 'k' });
await act('pathPin', { id: 'k', via });
assert.deepEqual(outcomes.filter((o) => !o.endsWith(' applied')), [], 'every one applied');
for (let k = 0; k < 2; k++) {
await days(20, [nid]);
await same(`S on day ${d}`);
assert.ok(ev(RSIG) === await realm(nid, `return ${RSIG}`), `R on day ${d}`);
}
// What the days said (sales, news) reaches a page as fx of the next update, in the contract's shapes.
const U = JSON.parse(checked(await S2.pull(code, nid, {})).upd);
assert.ok(U.fx.some(([k, p]) => k === 'toast' && p.k === 'good'), 'the sales were told');
const sold = ev('S.stats.cmSold');
assert.ok(sold > 20 && ev("S.biz.find(b=>b.id==='k').pin.join()") === via, `the market sold (${sold}) and the circuit stayed pinned`);
// A checkpoint into a fresh realm (its rt, no route cache) plays on byte for byte as the realm that kept going.
const sv = checked(await S2.save(code, nid));
checked((await S2.load(code, [{ nid: nid2, env: { s: sv.txt, uidN: sv.uidN, rt: sv.rt }, lang: 'en', prefs: {} }]))[0]);
await realm(nid2, `__srvClock(${await realm(nid, 'return __srvClock()')});return 1;`);
await days(15, [nid, nid2], false);
const s1 = await realm(nid, 'return JSON.stringify(S)'), s2 = await realm(nid2, 'return JSON.stringify(S)');
assert.ok(s1 === s2, `S after the checkpoint:\n${s1 === s2 ? '' : differs(s1, s2)}`);
assert.ok(await realm(nid, `return ${RSIG}`) === await realm(nid2, `return ${RSIG}`), 'R after the checkpoint');
assert.ok(JSON.parse(s1).stats.cmSold > sold, 'it went on selling');
assert.deepEqual(await realm(nid, 'return [__SRV_T.n,__SRV_T.at]'), [0, []], 'no timer');
assert.deepEqual(P.errors, []);
});
test(`timer audit and gate: ${LONG ? 365 : 60} days with everything on, then every sent button a crawl finds`, { timeout: LONG ? 1800e3 : 300e3 }, async (t) => {
const S2 = createEngine({ workers: 1, test: TEST, strict: true, timeouts: ROOMY });
t.after(() => S2.close());
const code = 'AVD1T5', nid = 'audt0001';
const SETUP = busy('shark');
checked((await S2.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
await S2.eval(code, nid, SETUP + 'return 1;');
const timers = async () => (await S2.eval(code, nid, 'return [__SRV_T.n,__SRV_T.at]')).value;
const N = LONG ? 365 : 60;
let fails = 0;
for (let d = 1; d <= N; d++) {
const D = checked(await S2.day(code, { d, speed: 8, last: 8, alone: [], nets: [nid] }));
assert.equal(D.nets[nid].err, undefined, `day ${d}: ${D.nets[nid].err}`);
if (D.nets[nid].lost) break;
if (d % 30 === 0) checked(await S2.pull(code, nid, { snap: d === 30 }));
}
const after = (await S2.eval(code, nid, 'return [S.inc.length+S.stats.incidents,S.ops.log.length,S.biz.length,S.day]')).value;
assert.ok(after[0] > 0 && after[1] > 0, `failures happened and the intern worked: ${after}`);
let [n, at] = await timers();
assert.equal(n, 0, `no timer on a day: ${(at || []).join('\n')}`);
// Every sent button of the same network, found by a page.
const P = page({ save: (await S2.eval(code, nid, 'return JSON.stringify(S)')).value });
t.after(() => P.close());
const btns = crawl(P.ev).filter(([act]) => A.SEND.includes(act));
assert.ok(btns.length > 150, `a real sweep: ${btns.length} buttons`);
for (const q of ['mktCfg', 'mktHold', 'pathPin']) assert.ok(btns.some(([a]) => a === q), `the crawl found ${q}`);
// By default the first three different buttons of each act (about 250); SIM_LONG every one (about 3,000).
const seen = new Set(), per = {}, outs = {};
for (const [act, args] of btns) {
const k = act + JSON.stringify(args);
if (seen.has(k) || (!LONG && (per[act] || 0) >= 3)) continue;
seen.add(k); per[act] = (per[act] || 0) + 1;
let body;
try { body = msg(act, args, { ...(A.CONFIRM[act] ? { confirmed: true } : {}), ctx: { sel: { type: 'city', id: 'fra' }, tab: 'cust', left: 'noc', modal: false, w: 1024, h: 768 } }); } catch (e) { continue; }
const r = checked(await S2.act(code, nid, body));
if (r.t === 'err') { fails++; continue; }
outs[r.outcome] = (outs[r.outcome] || 0) + 1;
assert.ok(!/^sanitize would repair/.test(r.why || ''), `the gate rolled back ${act} ${JSON.stringify(args)}: ${r.why}`);
if (r.outcome === 'error') assert.fail(`${act} ${JSON.stringify(args)}: ${r.why}`);
}
assert.equal(fails, 0, 'no action timed out or broke its pipeline');
assert.ok(outs.applied > 20, `actions applied: ${JSON.stringify(outs)}`);
[n, at] = await timers();
assert.equal(n, 0, `no timer in an action: ${(at || []).join('\n')}`);
// Nothing waits to run later: S stays as it is after the worker's next turns.
const s1 = (await S2.eval(code, nid, 'return JSON.stringify(S)')).value;
await new Promise((r) => setTimeout(r, 50));
assert.ok((await S2.eval(code, nid, 'return JSON.stringify(S)')).value === s1, 'S changed after the call was over');
// A day after all of it still passes the strict gate.
const D = checked(await S2.day(code, { d: N + 1, speed: 1, last: 1, alone: [], nets: [nid] }));
assert.equal(D.nets[nid].err, undefined);
});

626
tests/mp-sim-engine.test.js Normal file
View file

@ -0,0 +1,626 @@
// The server-run engine (scripts/lib/mp-sim-engine.js, -worker.js, -realm.js; the server-sim design, sections 4.1-4.3,
// 5.3-5.10, 9): networks load, play days, take actions and what-ifs, and answer pulls and saves, every reply in the
// contract's shapes (tests/lib/mp-sim-shape.js); the capture table turns each kind of effect into an fx; failures go back
// to the mark (a throw in place, a timeout into a fresh realm, an exiting worker rejects everything pending); asks put
// 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');
const E = createEngine({ workers: 2, test: TEST, timeouts: ROOMY });
test.after(() => E.close());
const on = (X) => ({
day: (code, d, nets, o = {}) => X.day(code, { d, speed: 1, last: 1, alone: [], nets, ...o }).then(checked),
ev: async (code, nid, src) => { const r = await X.eval(code, nid, src); assert.equal(r.error, undefined, r.error); return r.value; },
});
const { day, ev } = on(E);
const updOf = (r) => JSON.parse(r.upd);
const wait = (ms) => new Promise((ok) => setTimeout(ok, ms));
// A call's answer within ms, or a failure that says it never came (a hung call would hang the test instead).
const within = (p, ms = 3000) => { let t; return Promise.race([p, new Promise((ok, no) => { t = setTimeout(() => no(new Error(`no answer within ${ms} ms`)), ms); })]).finally(() => clearTimeout(t)); };
const HOST = { clock: fixture('clock'), roster: fixture('roster'), since: { days: 0, again: 0 } };
test('a new network: begin, a snapshot, its welcome, actions, days, a what-if, views, prefs, a save and a card', async () => {
const code = 'NEWN3T', nid = 'neww0001';
const [L] = await E.load(code, [begin(nid, { tut: true })]);
checked(L);
assert.equal(L.day, 0);
assert.equal(L.saved.nid, nid, 'a new network is checkpointed at once');
assert.equal(JSON.parse(L.saved.txt).mp.sim, 1);
assert.equal(JSON.parse(L.saved.txt).tut, 0, 'the tutorial starts on the server');
// A page's first snapshot: v 0, the realm's half, a stream event once the host adds its own.
const P0 = checked(await E.pull(code, nid, { snap: true }));
assert.deepEqual([P0.v, P0.upd], [0, undefined]);
assert.deepEqual(checkEvent(JSON.parse(snapWith(P0.snap, HOST))), []);
assert.equal(JSON.parse(P0.snap).S.log[0].k, 'goal', 'the welcome is in the log');
// The welcome comes to that page with the first update: here the one-shots a page says on opening (greet).
const G = checked(await E.greet(code, nid));
assert.equal(G.v, 1);
assert.ok(updOf(G).fx.some(([k, p]) => k === 'toast' && p.k === 'goal' && /AS201234/.test(p.h)), 'the welcome toast');
// 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))]);
assert.equal(u1.s.tut, 1, 'the first coach step is done');
assert.ok('cash' in u1.s && 'pops' in u1.s, 'the keys it changed');
assert.ok(!('links' in u1.s), 'and only those');
const net = await ev(code, nid, "return NETS.filter(n=>sellsAt(n,'fra'))[0].id");
assert.equal(checked(await E.act(code, nid, msg('buyTransit', { city: 'fra', net, tier: 1 }))).outcome, 'applied');
assert.equal(checked(await E.act(code, nid, msg('buyTransit', { city: 'nowhere', net, tier: 1 }))).outcome, 'no_effect');
// Refused by the game with a toast (and its log line): rejected, and the page hears why.
const cash = await ev(code, nid, 'const c=S.cash;S.cash=10;return c;');
const poor = checked(await E.act(code, nid, msg('buildPop', { city: 'syd' })));
assert.equal(poor.outcome, 'rejected');
assert.ok(updOf(poor).fx.some(([k, p]) => k === 'toast' && p.k === 'bad'), 'the refusal toast');
await ev(code, nid, `S.cash=${cash};return 1;`);
assert.equal(checked(await E.act(code, nid, msg('buildPop', { city: 'ams' }))).outcome, 'applied');
const link = checked(await E.act(code, nid, msg('buildLink', { tier: 0 }, { ui: { pending: { a: 'fra', b: 'ams' }, route: '', via: '', cnPrem: false } })));
assert.equal(link.outcome, 'applied');
assert.equal(updOf(link).acts[0].ui.closed, 1, 'the link window closes on the page');
// A draft that names no place is refused before the act runs.
const bad = checked(await E.act(code, nid, msg('buildLink', { tier: 0 }, { ui: { pending: { a: 'fra', b: 'atlantis' } } })));
assert.deepEqual([bad.outcome, /pending/.test(bad.why)], ['rejected', true]);
for (let d = 1; d <= 6; d++) { const D = await day(code, d, [nid]); assert.equal(D.nets[nid].day, d); }
const P1 = checked(await E.pull(code, nid, {}));
const u = updOf(P1);
assert.deepEqual([u.from, u.day, u.s.day], [bad.v, 6, 6], 'the days come after the last action\'s update');
assert.ok(u.r && u.r.tTop8, 'a new R after days, slim');
assert.equal(checked(await E.pull(code, nid, {})).upd, undefined, 'nothing new, no version');
// A what-if: the window it opened, the network as it was.
const lid = await ev(code, nid, 'return S.links[0].id');
const s0 = await ev(code, nid, 'return JSON.stringify(S)');
const K = checked(await E.ask(code, nid, msg('linkCheck', { id: lid }, { ctx: { w: 390, h: 844, coarse: true } })));
assert.match(K.modal.h, /redundancy|backhoe/i);
assert.equal(K.modal.c, 'link-check');
assert.equal(await ev(code, nid, 'return JSON.stringify(S)'), s0);
// Views: the selected link's flows and a city's PNI flows, per view.
const V = checked(await E.pull(code, nid, { views: [{ link: lid }, { peer: 'fra' }] }));
assert.deepEqual(Object.keys(V.subs).sort(), ['link:' + lid, 'peer:fra']);
assert.ok(Object.keys(V.subs['link:' + lid].ef).length <= 1, 'at most the link\'s own flow record');
const SB = checked(await E.sub(code, nid, { views: [{ link: lid }] }));
assert.deepEqual(Object.keys(SB.subs), ['link:' + lid]);
assert.equal(await E.prefs(code, nid, { prefs: { warnUnhappy: false } }), undefined);
assert.equal(await ev(code, nid, 'return pref("warnUnhappy")'), false);
const SV = checked(await E.save(code, nid));
assert.deepEqual([SV.day, SV.lost, typeof SV.rt.load], [6, false, 'object']);
const C = checked(await E.card(code, nid));
assert.deepEqual([C.card.day, C.card.asn, C.card.pops.sort()], [6, MP.asn, ['ams', 'fra']]);
assert.deepEqual(E.stats().realms >= 1, true);
checked(await E.unload(code, nid));
await assert.rejects(E.act(code, nid, msg('launchBB', { city: 'ams' })), (e) => e.code === 'NO_REALM');
});
test('the capture table: every kind of effect comes out as an fx in its shape, at most 60 an update', async () => {
const code = 'CAPTVR', nid = 'capt0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.pull(code, nid, { snap: true }));
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
await ev(code, nid, `UI.speed=1;toast('<b>Hello</b> world','good',[{l:'Open',act:'leftTab',args:{t:'noc'}}]);sfx('coin');haptic(8);floater(1,2,'+$5','#16A866');
track('probe',true);autoPause();showWin();showLose();showBaronWin();mkStart('fra');mkEnd(true,true);
S.stats.loans=1;checkBadges();return 1;`);
const u = updOf(checked(await E.pull(code, nid, {})));
const kinds = new Set(u.fx.map((f) => f[0]));
for (const k of ['toast', 'sfx', 'haptic', 'floater', 'track', 'pause', 'modal', 'mk', 'badge']) assert.ok(kinds.has(k), `fx ${k}`);
for (const f of u.fx) assert.deepEqual(checkFx(f), [], JSON.stringify(f));
assert.deepEqual(u.fx.filter((f) => f[0] === 'modal').map((f) => f[1]), ['win', 'lose', 'baron'], 'windows are fx, not opened');
assert.equal(await ev(code, nid, "return $('modal').hidden"), true);
const t = u.fx.find((f) => f[0] === 'toast' && f[1].h.startsWith('<b>Hello'));
assert.deepEqual([t[1].k, t[1].a[0].act, t[1].tick], ['good', 'leftTab', false]);
assert.equal(await ev(code, nid, "return S.log.some(x=>x.h==='Hello')"), true, 'a toast is still a log line');
// Over 60: floaters go first; windows and badges stay.
await ev(code, nid, "for(let i=0;i<30;i++)floater(i,i,'x','#fff');for(let i=0;i<50;i++)sfx('click');showWin();return 1;");
const u2 = updOf(checked(await E.pull(code, nid, {})));
assert.equal(u2.fx.length, 60);
assert.deepEqual([u2.fx.filter((f) => f[0] === 'floater').length, u2.fx.filter((f) => f[0] === 'sfx').length], [9, 50], 'the 21 too many were the oldest floaters');
assert.deepEqual(u2.fx.filter((f) => f[0] === 'modal').map((f) => f[1]), ['win']);
await E.unload(code);
});
test('a timeout inside opsQuiet: the fresh realm has its toast and after, and the day is played', async (t) => {
// An engine with the server's own time limits: the injected endless loop is stopped by them.
const E = createEngine({ workers: 1, test: TEST });
t.after(() => E.close());
const { day, ev } = on(E);
const code = 'QV13T0', nid = 'quie0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
const ep0 = checked(await E.pull(code, nid, {})).epoch;
// The intern's way of working (opsQuiet mutes toast, after, sfx and floater), stuck for ever in the middle of a day.
await ev(code, nid, '{const f=ddosTick;ddosTick=function(){f();opsQuiet(()=>{for(;;){}});};}return 1;');
const D = await day(code, 1, [nid]);
assert.deepEqual([D.nets[nid].day, D.nets[nid].retried, D.nets[nid].err], [1, true, undefined]);
const P = checked(await E.pull(code, nid, {}));
assert.notEqual(P.epoch, ep0, 'a fresh realm');
assert.deepEqual(await ev(code, nid, "return [/srvFx/.test(String(toast)),/routeIfChanged/.test(String(after)),/srvFx/.test(String(sfx)),/srvFx/.test(String(floater))]"), [true, true, true, true]);
const a = checked(await E.act(code, nid, msg('buildPop', { city: 'ams' })));
assert.equal(a.outcome, 'applied');
assert.ok(updOf(a).fx.some((f) => f[0] === 'toast' || f[0] === 'sfx'), 'its toasts reach the page again');
// And a throw inside opsQuiet (its finally ran) leaves the same realm working, put back in place.
await ev(code, nid, "{const f=ddosTick;let once=true;ddosTick=function(){f();if(once){once=false;opsQuiet(()=>{throw new Error('inside')});}};}return 1;");
const D2 = await day(code, 2, [nid]);
assert.deepEqual([D2.nets[nid].day, D2.nets[nid].retried], [2, true]);
assert.equal(checked(await E.pull(code, nid, {})).epoch, P.epoch);
assert.equal(await ev(code, nid, 'return /srvFx/.test(String(toast))'), true);
await E.unload(code);
});
test('a throw in an action puts the network back in place; with an attack on, R\'s attacks point into the restored S', async () => {
const code = 'THR0WN', nid = 'thrw0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const ep = checked(await E.pull(code, nid, { snap: true })).epoch;
assert.ok(await ev(code, nid, 'const a=ddosAttack(true);a.until=S.day+5;return R.ddos.filter(m=>m.attack).length'), 'R holds the attack');
const s0 = await ev(code, nid, 'return JSON.stringify(S)');
await ev(code, nid, "{const f=ACT.buildPop;ACT.buildPop=a=>{f(a);throw new Error('after the change');};}return 1;");
const r = checked(await E.act(code, nid, msg('buildPop', { city: 'dus' })));
assert.deepEqual([r.outcome, /after the change/.test(r.why), r.epoch], ['error', true, ep]);
assert.equal(await ev(code, nid, 'return JSON.stringify(S)'), s0, 'S as it was');
assert.deepEqual(updOf(r).acts[0].ui, {}, 'the page is told, nothing else');
assert.equal(await ev(code, nid, 'return R.ddos.every(m=>!m.attack||m.attack===ddosFind(m.attack.id))&&R.ddos.some(m=>m.attack)'), true);
await E.unload(code);
});
test('an ask leaves S (the same object), R, the dice and uidN as they were, also during an attack', async () => {
const code = 'ASK3D0', nid = 'askd0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
await ev(code, nid, "const a=ddosAttack(true);a.until=S.day+5;S.te={on:true,day:S.day,script:''};compute();return 1;");
checked(await E.pull(code, nid, { snap: true })); checked(await E.pull(code, nid, {}));
const before = "window.__S0=S;window.__R0=R;window.__rng=S.rng;window.__u=uidN;window.__j=JSON.stringify(S);window.__hot=UI.hotMap;return 1;";
const same = 'return [S===__S0,R===__R0,S.rng===__rng,uidN===__u,JSON.stringify(S)===__j,R.ddos.some(m=>m.attack)&&R.ddos.every(m=>!m.attack||m.attack===ddosFind(m.attack.id)),UI.hotMap===__hot]';
const lid = await ev(code, nid, 'return S.links.find(l=>!linkDown(l)).id');
const script = await ev(code, nid, 'return TE_EXAMPLE');
for (const [act, args] of [['teSlop', {}], ['teCheck', { script }], ['linkCheck', { id: lid }], ['teSlop', {}]]) {
await ev(code, nid, before);
const r = checked(await E.ask(code, nid, msg(act, args)));
assert.ok(r.modal && r.modal.h.length > 20, `${act} answers with its window`);
if (act !== 'linkCheck') assert.equal(typeof r.ui.teDraft, 'string', `${act}: the draft`);
if (act === 'teSlop') assert.equal(r.ui.slop, r.ui.teDraft, 'the AI\'s script is the draft');
assert.deepEqual(await ev(code, nid, same), [true, true, true, true, true, true, true], act);
}
assert.equal(checked(await E.pull(code, nid, {})).upd, undefined, 'and nothing to send');
await E.unload(code);
});
test('ui.sel is reported only when the act changed it', async () => {
const code = 'SE1ECT', nid = 'selc0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const lid = await ev(code, nid, "return S.links.find(l=>l.kind==='wave').id");
const rm = checked(await E.act(code, nid, msg('rmLink', { id: lid }, { confirmed: true, ctx: { sel: { type: 'link', id: lid }, tab: 'cust', left: 'goals', modal: false } })));
assert.equal(rm.outcome, 'applied');
assert.equal(updOf(rm).acts[0].ui.sel, null, 'the selected link is gone: the selection with it');
const net = await ev(code, nid, "return NETS.filter(n=>sellsAt(n,'fra')&&!S.transit.some(t=>t.city==='fra'&&t.net===n.id))[0].id");
const bt = checked(await E.act(code, nid, msg('buyTransit', { city: 'fra', net, tier: 1 }, { ctx: { sel: { type: 'city', id: 'fra' }, tab: 'up', left: 'goals', modal: false } })));
assert.equal(bt.outcome, 'applied');
assert.equal('sel' in updOf(bt).acts[0].ui, false, 'a city still selected: nothing to say');
// A selection that names nothing is no selection.
const x = checked(await E.act(code, nid, msg('buildPop', { city: 'dus' }, { ctx: { sel: { type: 'link', id: 'nope' }, tab: 'cust', left: 'goals', modal: false } })));
assert.equal(x.outcome, 'applied');
// A busy link's view: its flow record, and the descriptions of the ways in it names.
const busy = await ev(code, nid, 'return S.links.find(l=>(R.load[l.id]||0)>1&&R.ef[edgeKey(l)]&&Object.keys(R.ef[edgeKey(l)].eg||{}).length).id');
const V = checked(await E.sub(code, nid, { views: [{ link: busy }, { peer: 'fra' }] }));
const rec = V.subs['link:' + busy];
assert.equal(Object.keys(rec.ef).length, 1);
assert.ok(Object.keys(rec.egd).length > 0, 'with its ways in');
assert.ok(Object.keys(V.subs['peer:fra'].pf.fra).length > 0, 'and Frankfurt\'s PNI flows');
await E.unload(code);
});
test('a begin sent during a session\'s day waits for its dayDone; actions of another session do not', async () => {
const code = 'M1DDAY', a = 'midd0001', b = 'midd0002', other = '0TH3R5', o = 'othr0001';
checked((await E.load(code, [{ nid: a, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
checked((await E.load(other, [begin(o)]))[0]);
const order = [];
const d = E.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [a] }).then((r) => { order.push('day'); return checked(r); });
const l = E.load(code, [begin(b)]).then((r) => { order.push('load'); return r; });
const D = await d, L = await l;
assert.deepEqual(order, ['day', 'load']);
assert.deepEqual(Object.keys(D.nets), [a], 'the day\'s networks were fixed when it started');
checked(L[0]);
assert.equal(L[0].day, 0);
await E.unload(code); await E.unload(other);
});
test('an unwatched network stays bounded: at most 200 fx, badges and windows kept (at most 32), a snapshot keeps them', async () => {
const code = 'VNWTCH', nid = 'unwt0001';
checked((await E.load(code, [begin(nid)]))[0]);
checked(await E.pull(code, nid, { snap: true }));
checked(await E.act(code, nid, msg('launchBB', { city: 'fra' })));
for (let d = 1; d <= 60; d++) await day(code, d, [nid]);
await ev(code, nid, "for(let i=0;i<500;i++)toast('note '+i);for(let i=0;i<40;i++)srvFx(['badge',{id:'b'+i,v:'oncall'}]);showLose();for(let i=0;i<300;i++)sfx('click');return 1;");
const [n, keep, last] = await ev(code, nid, "return [SIMR.fx.length,SIMR.fx.filter(f=>f[0]==='badge'||f[0]==='modal').length,SIMR.fx.filter(f=>f[0]==='modal').length]");
assert.ok(n <= 200, `${n} fx held`);
assert.equal(keep, 32);
assert.equal(last, 1, 'the newest window is kept');
const P = checked(await E.pull(code, nid, { snap: true }));
const snap = JSON.parse(P.snap);
assert.equal(snap.keep.length, 32);
assert.deepEqual(snap.keep.at(-1), ['modal', 'lose']);
assert.ok(JSON.parse(P.upd).fx.length <= 60);
assert.deepEqual(checkEvent(JSON.parse(snapWith(P.snap, HOST))), []);
await E.unload(code);
});
test('a loaded network that played unwatched: its first snapshot keeps the badges and windows, and no stale fx follow', async (t) => {
const code = 'VNSEEN', nid = 'unsn0001';
checked((await E.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
for (let d = 1; d <= 8; d++) await day(code, d, [nid]);
// The badges it earned on those days stay too (the big fixture predates the traffic badges: it earns some at once).
const won = await ev(code, nid, "return SIMR.fx.filter(f=>f[0]==='badge').map(f=>f[1].id)");
t.diagnostic(`badges earned unwatched: ${won.join(', ') || 'none'}`);
await ev(code, nid, "for(let i=0;i<300;i++)toast('old news '+i);srvFx(['badge',{id:'debt',v:'oncall'}]);showWin();return 1;");
const P = checked(await E.pull(code, nid, { snap: true }));
assert.deepEqual(JSON.parse(P.snap).keep.map((f) => (f[0] === 'badge' ? f[1].id : f[0] + ':' + f[1])), [...won, 'debt', 'modal:win']);
assert.equal(JSON.parse(P.snap).v, P.v, 'the snapshot is at the version after the update to the streams there were');
assert.equal(checked(await E.pull(code, nid, {})).upd, undefined, 'nothing stale comes after the snapshot');
await E.unload(code);
});
test('alone, an auto-pause stops the realm\'s clock as the page\'s does: a second one that day finds it paused', async () => {
const code = 'PAVSE2', nid = 'paus0001';
checked((await E.load(code, [begin(nid)]))[0]);
assert.deepEqual(await ev(code, nid, 'SIMR.alone=true;SIMR.last=4;UI.speed=4;const a=autoPause(),b=autoPause();return [a,b,UI.speed,UI.resumeSpeed]'), [true, false, 0, 4]);
assert.deepEqual(await ev(code, nid, 'SIMR.alone=false;UI.speed=4;return [autoPause(),autoPause(),UI.speed]'), [false, false, 4], 'with others the world goes on');
const D = await day(code, 1, [nid], { alone: [nid], speed: 2, last: 2 });
assert.equal(D.nets[nid].day, 1);
assert.equal(await ev(code, nid, 'return UI.speed'), 2, 'the next day runs at the session\'s speed');
await E.unload(code);
});
test('a network whose save does not load is broken; the others of the session load', async () => {
const code = 'BR0K3N', ok = 'okok0001', bad = 'badd0002', zz = 'zzzz0003';
const L = await E.load(code, [{ nid: ok, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'de', prefs: {} }, { nid: bad, env: { s: '{"v":1,"pops":', uidN: 1 }, lang: 'en', prefs: {} }, { ...begin(zz), lang: 'zz' }]);
L.forEach(checked);
assert.deepEqual([L[0].err, typeof L[1].err, L[2].err], [undefined, 'string', undefined]);
assert.deepEqual(Object.keys(L[1]).sort(), ['err', 'nid', 't']);
assert.equal(await ev(code, zz, 'return LANG'), 'en', 'a language without a dictionary here plays in English');
// The network's language is the realm's: the log speaks German.
checked(await E.act(code, ok, msg('buildPop', { city: 'dus' })));
assert.match(await ev(code, ok, 'return LANG+":"+S.log[0].t'), /^de:/);
await assert.rejects(E.act(code, bad, msg('buildPop', { city: 'dus' })), (e) => e.code === 'NO_REALM');
await E.unload(code);
});
test('a load call with a malformed network changes nothing, one without a save is broken, and every call still answers', async () => {
const code = 'MA1F0R', a = 'mala0001', b = 'malb0002';
const [A] = await E.load(code, [begin(a)]);
checked(A);
const env = { s: A.saved.txt, uidN: A.saved.uidN, rt: A.saved.rt };
// A network without a nid, or one twice: the call is refused whole, and a keeps the realm it had.
await assert.rejects(within(E.load(code, [{ nid: a, env, lang: 'en', prefs: {} }, { env, lang: 'en', prefs: {} }])), (e) => e.code === 'ERR');
assert.equal(checked(await within(E.pull(code, a, {}))).epoch, A.epoch, 'a as it was');
await assert.rejects(within(E.load(code, [begin(b), begin(b)])), (e) => e.code === 'ERR' && /twice/.test(e.message));
assert.equal(checked(await within(E.act(code, a, msg('launchBB', { city: 'ams' })))).epoch, A.epoch);
// a again with b, whose checkpoint the host could not read: b is broken, a loads (a new epoch).
const L = await within(E.load(code, [{ nid: a, env, lang: 'en', prefs: {} }, { nid: b, env: null, lang: 'en', prefs: {} }]));
L.forEach(checked);
assert.deepEqual([L[0].err, L[1].err], [undefined, 'no save to load']);
assert.notEqual(L[0].epoch, A.epoch);
// Every call of the session answers at once: a plays, b has no realm, unloads and loads go through.
assert.equal(checked(await within(E.act(code, a, msg('launchBB', { city: 'fra' })))).outcome, 'applied');
assert.equal(checked(await within(E.day(code, { d: 1, nets: [a, b] }))).nets[a].day, 1);
await assert.rejects(within(E.pull(code, b, {})), (e) => e.code === 'NO_REALM');
checked(await within(E.unload(code, a)));
checked((await within(E.load(code, [begin(a)])))[0]);
checked(await within(E.unload(code)));
// Nothing is left waiting, so the workers are idle (a job that can never run once kept one at 100% of a core).
await wait(100);
const c0 = process.cpuUsage();
await wait(1000);
const c = process.cpuUsage(c0), ms = (c.user + c.system) / 1000;
assert.ok(ms < 400, `${ms.toFixed(0)} ms of CPU over 1 s of quiet`);
});
test('an unload and a load sent back to back (a language change) keep the session on its worker', async () => {
const code = 'GERM4N', nid = 'lang0001';
checked((await E.load(code, [begin(nid)]))[0]);
const w = E.workerOf(code);
const u = E.unload(code), l = E.load(code, [{ ...begin(nid), lang: 'de' }]);
checked(await within(u));
checked((await within(l))[0]);
assert.equal(E.workerOf(code), w);
assert.equal(checked(await within(E.pull(code, nid, {}))).nid, nid, 'the network answers where it is');
checked((await E.load(code, [begin('lang0002')]))[0]);
assert.equal(E.workerOf(code), w, 'and the session\'s next network goes there too');
checked(await within(E.pull(code, nid, {})));
await E.unload(code);
});
test('a session whose load takes its worker down: twice, a worker of its own; once more, given up; the others keep their places', async () => {
const W = createEngine({ workers: 2, test: TEST, timeouts: ROOMY });
try {
const code = 'P01S0N', nid = 'pois0001', by = { BYST01: 'byst0001', BYST02: 'byst0002' };
for (const [c, n] of Object.entries(by)) checked((await W.load(c, [begin(n)]))[0]);
assert.deepEqual([W.workerOf('BYST01'), W.workerOf('BYST02')], [0, 1]);
// Its load crashes the worker (as a save that overflows the heap would): the worker it shares with BYST01.
const lost = [];
for (let i = 0; i < 2; i++) {
const p = W.load(code, [begin(nid)]);
assert.deepEqual([W.workerOf(code), W.dedicated(code)], [0, false], `attempt ${i + 1}: in the pool`);
W.killOf(code);
await assert.rejects(p, (e) => e.code === 'EXIT');
for (const [c, n] of Object.entries(by)) {
if (!(await W.pull(c, n, {}).then(() => false, (e) => e.code === 'NO_REALM'))) continue;
lost.push(c);
checked((await W.load(c, [begin(n)]))[0]);
assert.equal(W.dedicated(c), false, `${c} is not blamed: it goes back to the pool`);
}
}
assert.deepEqual(lost, ['BYST01', 'BYST01'], 'the bystander on that worker lost its realm each time, the other never');
// Twice within the hour: a worker of its own. An unload and a load back to back stay there, and answer.
checked((await W.load(code, [begin(nid)]))[0]);
assert.deepEqual([W.dedicated(code), W.stats().workers], [true, 3]);
const u = W.unload(code), l = W.load(code, [begin(nid)]);
checked(await within(u));
checked((await within(l))[0]);
checked(await within(W.pull(code, nid, {})));
assert.equal(W.dedicated(code), true);
// Once more, on its own worker: given up until a restart; its worker is not replaced, and the others play on.
const p = W.load(code, [begin('pois0002')]);
W.killOf(code);
await assert.rejects(p, (e) => e.code === 'EXIT');
await assert.rejects(W.load(code, [begin(nid)]), (e) => e.code === 'GAVE_UP');
for (const [c, n] of Object.entries(by)) checked(await within(W.pull(c, n, {})));
assert.deepEqual([W.stats().workers, W.dedicated('BYST01')], [2, false]);
} finally { await W.close(); }
});
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[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 {
const code = 'EX1T3D', nid = 'exit0001';
checked((await W.load(code, [{ nid, env: { s: bigScenic(), uidN: 1000, rt: null }, lang: 'en', prefs: {} }]))[0]);
const calls = [W.day(code, { d: 1, nets: [nid] }), W.act(code, nid, msg('buildPop', { city: 'dus' })), W.pull(code, nid, { snap: true }), W.save(code, nid)];
W.kill(0);
for (const p of calls) await assert.rejects(p, (e) => e.code === 'EXIT' && /worker exited/.test(e.message));
assert.deepEqual(W.stats(), { workers: 1, realms: 0, sessions: 0 }, 'its sessions are gone; a new worker took its place');
await assert.rejects(W.act(code, nid, msg('buildPop', { city: 'dus' })), (e) => e.code === 'NO_REALM');
// The host loads the session again (4.7).
checked((await W.load(code, [begin(nid)]))[0]);
assert.equal(W.stats().realms, 1);
} finally { await W.close(); }
});