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.
This commit is contained in:
parent
61e31c53d3
commit
065c922287
12 changed files with 1906 additions and 29 deletions
182
scripts/lib/mp-sim-engine.js
Normal file
182
scripts/lib/mp-sim-engine.js
Normal file
|
|
@ -0,0 +1,182 @@
|
|||
// 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});
|
||||
// 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); begin: {name, home, preset, asn, mp, tut} builds a new network, checkpointed
|
||||
// at once (saved). A network whose save does not load (or that cannot begin) answers err: broken (4.7).
|
||||
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]: {day, lost,
|
||||
// pause?, err?, retried?, ms}}}. Each network in sorted order; one that failed twice answers err and
|
||||
// its day as it was, and is broken from then on (no more days; actions answer 'stopped').
|
||||
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd} (upd: the update with the result,
|
||||
// version v; null when stopped) | {t:'err', code, nid, rid, what:'timeout'|'throw', msg}
|
||||
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal?, ui?, err?} | {t:'err', …}
|
||||
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?}. snap is the realm's half
|
||||
// of a snapshot: snapWith(snap, {clock, roster, since}) makes the stream event.
|
||||
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}; engine.greet(code, nid) → a pulled
|
||||
// engine.prefs(code, nid, {prefs}) → undefined; engine.save(code, nid) → {t:'saved', nid, txt, uidN, rt, day, lost}
|
||||
// engine.card(code, nid) → {t:'card', nid, card}; engine.unload(code, nid?) → {t:'unloaded', code, nid?}
|
||||
// engine.stats() → {workers, realms, sessions} (not a promise); engine.close() → stops the workers
|
||||
// engine.simId the build id this engine's game belongs to (SIM_ID of the multiplayer page from the same src/)
|
||||
//
|
||||
// Rejections: a call for a network that is not loaded (code 'NO_REALM'), a malformed call, and every call pending on
|
||||
// a worker that exits (out of memory, a crash): Error('worker exited'), code 'EXIT'; that worker's sessions are gone and
|
||||
// the host loads them again (4.7). A session whose worker exited twice within an hour gets a worker of its own; when that
|
||||
// one exits too, its loads reject with code 'GAVE_UP' until the engine is made again (the server restarts).
|
||||
// Epochs: every realm load mints one (a load, a begin, the fresh realm after a timeout); loaded, pulled, actDone and
|
||||
// subbed carry the realm's current one. Versions are the realm's: only a pull (or an action's own pull) makes one.
|
||||
//
|
||||
// Tests only, with createEngine({test: {seed, now, step} | true}): engine.eval(code, nid, src) runs code in a realm
|
||||
// ({value} | {error} | {timeout, epoch}); engine.mem() reports each worker's heap; engine.kill(i) ends worker i.
|
||||
'use strict';
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { Worker } = require('node:worker_threads');
|
||||
|
||||
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 log = typeof opts.log === 'function' ? opts.log : () => {};
|
||||
const test = opts.test || null;
|
||||
const W = { root: opts.root, page: opts.page, test, strict: opts.strict !== undefined ? !!opts.strict : process.env.SIM_STRICT === '1', timeouts: opts.timeouts };
|
||||
let seq = 0, closed = false;
|
||||
const pool = [], own = new Map(), placed = new Map(), exits = new Map(), gaveUp = new Set();
|
||||
// A session's realms, counted where they live (placement by realm count).
|
||||
const count = (w) => [...w.sessions.values()].reduce((a, b) => a + b.size, 0);
|
||||
|
||||
function spawn(dedicated = false) {
|
||||
const w = { worker: null, pending: new Map(), sessions: new Map(), dedicated, dead: false };
|
||||
w.worker = new Worker(FILE, { workerData: { mpSim: W }, resourceLimits: { maxOldGenerationSizeMb: heapMb } });
|
||||
w.worker.on('message', (m) => {
|
||||
if (m.log) { log(m.log[0], m.log[1]); return; }
|
||||
if (m.fatal) { log('error', 'mp-sim worker could not start: ' + m.fatal); return; }
|
||||
if (m.ready) return;
|
||||
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;
|
||||
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 w.sessions.keys()) {
|
||||
placed.delete(code);
|
||||
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();
|
||||
if (!closed) {
|
||||
if (!closed) log('warn', `mp-sim: a worker exited (code ${c}); its sessions load again from their checkpoints`);
|
||||
const i = pool.indexOf(w);
|
||||
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 (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) {
|
||||
w = spawn(true); own.set(code, w);
|
||||
} else w = pool.reduce((a, b) => (count(b) < count(a) ? b : a));
|
||||
placed.set(code, w);
|
||||
return w;
|
||||
}
|
||||
function send(w, m) {
|
||||
if (closed) return Promise.reject(Object.assign(new Error('engine closed'), { code: 'CLOSED' }));
|
||||
if (!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 }); w.worker.postMessage({ id, ...m }); });
|
||||
}
|
||||
const noRealm = (code, nid) => Promise.reject(Object.assign(new Error(`no realm ${code}/${nid}`), { code: 'NO_REALM' }));
|
||||
const to = (code, nid, m) => { const w = workerOf(code, false); return w ? send(w, { code, nid, ...m }) : noRealm(code, nid); };
|
||||
const mine = (w, code) => { let s = w.sessions.get(code); if (!s) w.sessions.set(code, s = new Set()); return s; };
|
||||
|
||||
const engine = {
|
||||
simId: null,
|
||||
load(code, nets) {
|
||||
if (!Array.isArray(nets) || !nets.length) return Promise.reject(new Error('load: give the networks to load'));
|
||||
let w;
|
||||
try { w = workerOf(code, true); } catch (e) { return Promise.reject(e); }
|
||||
return send(w, { t: 'load', code, nets }).then((r) => {
|
||||
const s = mine(w, code);
|
||||
for (const l of r) if (!l.err) s.add(l.nid); else s.delete(l.nid);
|
||||
return r;
|
||||
});
|
||||
},
|
||||
day(code, { d, speed = 1, last = 1, alone = [], nets = [], mute = false } = {}) {
|
||||
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(() => 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) {
|
||||
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); if (!s.size) { w.sessions.delete(code); placed.delete(code); } }
|
||||
if (w.dedicated && !w.sessions.size) { own.delete(code); w.dead = true; w.worker.terminate(); }
|
||||
return r;
|
||||
});
|
||||
},
|
||||
stats() {
|
||||
const ws = [...pool, ...own.values()].filter((w) => !w.dead);
|
||||
return { workers: ws.length, realms: ws.reduce((a, w) => a + count(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.mem = () => Promise.all(pool.filter((w) => !w.dead).map((w) => send(w, { t: 'mem' })));
|
||||
engine.kill = (i = 0) => { const w = pool[i]; if (w && !w.dead) w.worker.terminate(); };
|
||||
engine.workerOf = (code) => pool.indexOf(placed.get(code));
|
||||
}
|
||||
{ const page = require('./page'); engine.simId = page.simId(page.assemble({ src: path.join(opts.root || page.ROOT, 'src'), mp: true }).html); }
|
||||
return engine;
|
||||
}
|
||||
|
||||
module.exports = { createEngine, snapWith };
|
||||
444
scripts/lib/mp-sim-realm.js
Normal file
444
scripts/lib/mp-sim-realm.js
Normal file
|
|
@ -0,0 +1,444 @@
|
|||
// 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 that runs over its time limit throws
|
||||
// ERR_SCRIPT_EXECUTION_TIMEOUT here, and the realm must not be used for play again (a timeout skips finally blocks).
|
||||
//
|
||||
// gameSource({root, page}) the game script (the largest inline <script> of the assembled page)
|
||||
// dictSource(lang, root) the source dictionary of a language, or null for English
|
||||
// prelude(opts), EPILOGUE the realm's own code around the game, as plain strings
|
||||
// compileCode({root, page}) {game, epilogue, simId} as vm.Scripts, once per process (a worker)
|
||||
// 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 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=>({'&':'&','<':'<','>':'>'})[c]);else o[k]=v;return true;}});};
|
||||
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, PREFS: ACTS.PREFS });
|
||||
const EPILOGUE = `'use strict';
|
||||
const SIMT=${TABLES},SIM_SEND=new Set(SIMT.SEND),SIM_ASK=new Set(SIMT.ASK),SIM_KEEP=new Set(['badge','modal']);
|
||||
const SIM_RNEVER=new Set(['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked']);
|
||||
const SIM_DRAFT=['pending','route','via','cnPrem','dfSrc','dfSys','seaDesign','seaterminal','seaengineering','decom','slop','pieIns','pieLas'];
|
||||
// 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));}
|
||||
|
||||
/* 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={};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();
|
||||
|
||||
/* ---- route memory (4.1): what compute() reads of yesterday's 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;}
|
||||
function srvRt(inp){const m=inp?JSON.parse(inp):{};return JSON.stringify(m.mark?(SIMR.markRt||srvRtOut(SIMR.mark?SIMR.mark.R:R)):srvRtOut(R));}
|
||||
/* R itself, whole, for the fresh realm that replaces this one after a timeout: route memory and compute() give a close R
|
||||
but not the same one (scenic paths settle over days, and S moved on since R's last routing), so the marked R travels
|
||||
the way the route worker sends it (rwPack/rwUnpack), as text: Maps, Sets, typed arrays and non-finite numbers tagged. */
|
||||
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];}
|
||||
function srvFresh(epoch){SIMR.epoch=String(epoch||'');SIMR.v=0;SIMR.seen=false;SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.rSent=new WeakRef(R);SIMR.base=srvKeyJson();SIMR.mark=null;SIMR.markK=null;SIMR.markRt=null;
|
||||
UI.sel=null;UI.confirm=null;UI.pending=null;UI.started=true;UI.pitched=true;UI.clockLocked=true;$('modal').hidden=true;}
|
||||
|
||||
/* srvLoad: a network from its save (a checkpoint, or the mark of a realm that timed out). The route memory goes in
|
||||
before compute(), the way the route worker seeds its R: 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). */
|
||||
function srvLoad(inp){const m=JSON.parse(inp);SIMR.strict=!!m.strict;
|
||||
S=migrate(JSON.parse(m.save));
|
||||
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);
|
||||
if(typeof m.rpack==='string'&&m.rpack){const x=JSON.parse(m.rpack,srvDec);R=rwUnpack(x.o,x.p);UI.hotMap=hotByCity();}
|
||||
else{R=srvRtIn(m.rt);compute();}
|
||||
srvFresh(m.epoch);
|
||||
// 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 the route memory too, to build a
|
||||
fresh realm if this one times out. */
|
||||
function srvMark(inp){const m=inp?JSON.parse(inp):{};let s;
|
||||
if(m.keys){SIMR.markK=srvKeyJson();s=srvJoin(SIMR.markK);}else{SIMR.markK=null;s=JSON.stringify(S);}
|
||||
SIMR.mark={s,uidN,rng:S.rng,R,...srvClockNow(),fx:SIMR.fx.slice(),floats:SIMR.floats,ui:{sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm,pending:UI.pending}};
|
||||
// A copy: R.load and R.l2route are R's own objects, and a day that fails half-way may already have written to them.
|
||||
const rtJ=m.day?JSON.stringify(srvRtOut(R)):'';SIMR.markRt=rtJ?JSON.parse(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 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&&R&&Array.isArray(R.ddos)){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;}
|
||||
UI.hotMap=hotByCity();
|
||||
Object.assign(UI,k.ui);SIMR.fx=k.fx.slice();SIMR.floats=k.floats;SIMR.modal=null;SIMR.closed=false;$('modal').hidden=true;
|
||||
return JSON.stringify({parsed});}
|
||||
|
||||
/* 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{const w=srvDrafts(act,m.ui,args);
|
||||
if(w)done('rejected',w);
|
||||
else{const c=m.ctx&&typeof m.ctx==='object'?m.ctx:{};
|
||||
UI.sel=srvSel(c.sel);if(typeof c.tab==='string')UI.tab=c.tab;if(typeof c.left==='string')UI.left=c.left;srvView(c);$('modal').hidden=!c.modal;
|
||||
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;}}}}
|
||||
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;
|
||||
srvView(m.ctx);$('modal').hidden=!(m.ctx&&m.ctx.modal);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;uidN=k.uidN;S.rng=k.rng;
|
||||
if(JSON.stringify(S)!==k.s){srvLog('ask '+act+' changed the game: put back');srvRestore('{}');}
|
||||
else Object.assign(UI,k.ui);
|
||||
SIMR.mark=null;UI.teDraft=td;UI.slop=sl;SIMR.fx=fx0;SIMR.floats=fl;SIMR.modal=null;$('modal').hidden=true;
|
||||
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||{},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);}
|
||||
function srvSave(){const txt=JSON.stringify(packSave(S));return srvOut({uidN,rt:srvRtOut(R),day:S.day,lost:!!S.lost,...srvClockNow()},txt);}
|
||||
function srvCard(){return JSON.stringify({card:mpCard()});}
|
||||
`;
|
||||
|
||||
// The realm API: one precompiled trampoline per name. Input in __in, a string out; a throw comes back as {srvErr}.
|
||||
const API = ['srvLoad', 'srvBegin', 'srvPrefs', 'srvMark', 'srvRestore', 'srvRt', 'srvRPack', 'srvDay', 'srvAct', 'srvAsk', 'srvPull', 'srvSub', 'srvGreet', 'srvSave', 'srvCard'];
|
||||
let TRAMP = null;
|
||||
const tramps = () => TRAMP || (TRAMP = Object.fromEntries(API.map((n) => [n, new vm.Script(
|
||||
`(()=>{try{return ${n}(globalThis.__in);}catch(e){return JSON.stringify({srvErr:String(e&&e.stack||e).slice(0,4000)});}})()`, { filename: `srv-${n}.js` })])));
|
||||
// Tests only (createEngine({test})): run a piece of code in a realm, answer its value as JSON.
|
||||
const EVAL = new vm.Script('(()=>{const f=new Function(globalThis.__in);const v=f();return v===undefined?"null":JSON.stringify(v);})()', { filename: 'srv-test-eval.js' });
|
||||
|
||||
/* The game, the epilogue and the build id, compiled once per process. */
|
||||
function compileCode({ root = ROOT, page = REALM_PAGE } = {}) {
|
||||
if (!vm.constants || vm.constants.DONT_CONTEXTIFY === undefined) {
|
||||
throw new Error(`server-run play needs Node 22.8 or newer (vm.constants.DONT_CONTEXTIFY); this is ${process.version}`);
|
||||
}
|
||||
const src = gameSource({ root, page });
|
||||
return {
|
||||
game: new vm.Script(src, { filename: 'game.js' }),
|
||||
epilogue: new vm.Script(EPILOGUE, { filename: 'srv-epilogue.js' }),
|
||||
simId: 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)); };
|
||||
this.lang = LANG_RE.test(lang) && lang !== 'en' && dictScript(lang, code.root) ? lang : 'en';
|
||||
new vm.Script(prelude({ lang: this.lang, test: !!test, ...(test || {}) }), { filename: 'srv-prelude.js' }).runInContext(ctx, { timeout: loadMs });
|
||||
const d = this.lang === 'en' ? null : dictScript(this.lang, code.root);
|
||||
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.
|
||||
raw(name, input, ms = 1000) {
|
||||
const s = tramps()[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 };
|
||||
290
scripts/lib/mp-sim-worker.js
Normal file
290
scripts/lib/mp-sim-worker.js
Normal file
|
|
@ -0,0 +1,290 @@
|
|||
// 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.
|
||||
//
|
||||
// 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 yesterday's route memory), and the
|
||||
// worker keeps the mark. A call that throws has run its finally blocks: the realm goes back to the mark in place. A call
|
||||
// that times out has not (vm skips them), so that realm is never used again: a fresh one is built from the mark, with a
|
||||
// new epoch. A failed day runs once more; failing again, the network is broken at its state before the day.
|
||||
//
|
||||
// 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]}.
|
||||
'use strict';
|
||||
const { isMainThread, parentPort, workerData } = require('node:worker_threads');
|
||||
const crypto = require('node:crypto');
|
||||
const v8 = require('node:v8');
|
||||
const { compileCode, Realm, isTimeout } = require('./mp-sim-realm');
|
||||
|
||||
const 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);
|
||||
|
||||
/* opts: {root, page, test: {seed, now, step} | true | null, strict, timeouts, log(level, text), post(message)}. */
|
||||
function createCore(opts = {}) {
|
||||
const code = compileCode({ root: opts.root, page: opts.page });
|
||||
const 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; };
|
||||
|
||||
/* ---- realms ---- */
|
||||
function build(nid, lang) {
|
||||
return new Realm({ code, lang, test: test && { seed: test.seed, now: test.now, step: test.step }, loadMs: T.load,
|
||||
log: (lvl, txt) => log(lvl === 'log' || lvl === 'info' || lvl === 'debug' ? 'info' : 'warn', `[${nid}] ${txt}`) });
|
||||
}
|
||||
// A realm call: [header, ...parts]; a throw inside the realm comes back as {srvErr}, a timeout throws.
|
||||
const call = (e, name, input, ms) => e.realm.call(name, input, ms);
|
||||
/* A fresh realm in place of one that timed out, from {s, uidN, rt}: same network, new epoch, versions from 0. R comes
|
||||
from the old realm, which still answers after a timeout: the marked R (mark) or its current one, packed whole. Only
|
||||
when it cannot is R routed again from the route memory, which gives a close R, not always the same. */
|
||||
function rebuild(e, from, mark = true) {
|
||||
let rpack = null;
|
||||
try { const s = e.realm && e.realm.raw('srvRPack', { mark }, T.load); if (typeof s === 'string' && s.startsWith('{"o"')) rpack = s; } catch (x) { /* gone */ }
|
||||
const r = build(e.nid, e.lang), epoch = epochOf();
|
||||
const [h] = r.call('srvLoad', { save: from.s, uidN: from.uidN, rt: from.rt, rpack, prefs: e.prefs, epoch, strict: !!opts.strict, clock: from.clock }, T.load);
|
||||
if (h.srvErr) throw new Error('rebuilding the realm failed: ' + h.srvErr);
|
||||
e.realm = r; e.epoch = epoch; e.v = 0; e.day = h.day; e.lost = h.lost;
|
||||
log('warn', `[${e.nid}] realm rebuilt after a timeout (epoch ${epoch}${rpack ? '' : ', R routed again'})`);
|
||||
}
|
||||
// The route memory of the old realm's mark, if it still answers; else the last day's.
|
||||
function markRt(e) {
|
||||
try { const [h] = call(e, 'srvRt', { mark: true }, 200); if (h && !h.srvErr && h.load) return h; } catch (x) { /* gone */ }
|
||||
return e.dayMark ? e.dayMark.rt : null;
|
||||
}
|
||||
function mark(e, input) {
|
||||
const [h, s] = call(e, 'srvMark', input, T.mark);
|
||||
if (h.srvErr) throw new Error('mark failed: ' + h.srvErr);
|
||||
const m = { s, uidN: h.uidN, rt: h.rt || null, day: h.day, clock: h.clock };
|
||||
if (input.day) e.dayMark = m;
|
||||
e.mark = m;
|
||||
return m;
|
||||
}
|
||||
// After a throw: back to the mark in place; if even that fails, a fresh realm from the mark.
|
||||
function restore(e, input) {
|
||||
try { const [h] = call(e, 'srvRestore', input, T.small); if (!h.srvErr) return; log('warn', `[${e.nid}] restore failed: ${h.srvErr}`); }
|
||||
catch (x) { log('warn', `[${e.nid}] restore timed out`); }
|
||||
rebuild(e, { ...e.mark, rt: input.day ? e.mark.rt : markRt(e) });
|
||||
}
|
||||
// A read-only call that timed out: the realm's state is whole (nothing applied was interrupted), so the fresh realm
|
||||
// starts from its save when it still answers, else from the last mark.
|
||||
function rebuildAfterRead(e) {
|
||||
let from = null;
|
||||
try { const [h, txt] = call(e, 'srvSave', undefined, T.save); if (!h.srvErr) from = { s: txt, uidN: h.uidN, rt: h.rt, clock: h.clock }; } catch (x) { /* gone */ }
|
||||
if (from) rebuild(e, from, false); else rebuild(e, { ...e.mark, rt: markRt(e) });
|
||||
}
|
||||
|
||||
/* ---- 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 {
|
||||
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) {
|
||||
realms.delete(key(c, n.nid));
|
||||
log('warn', `[${n.nid}] did not load: ${MSG(x)}`);
|
||||
return { t: 'loaded', nid: n.nid, err: isTimeout(x) ? 'the network took too long to load' : String((x && x.message) || x).split('\n')[0].slice(0, 300) };
|
||||
}
|
||||
}
|
||||
function saved(e) {
|
||||
const [h, txt] = call(e, 'srvSave', undefined, T.save);
|
||||
if (h.srvErr) throw new Error(h.srvErr);
|
||||
return { t: 'saved', nid: e.nid, txt, uidN: h.uidN, rt: h.rt, day: h.day, lost: h.lost };
|
||||
}
|
||||
// One network's day, with its mark, one retry, and broken after a second failure.
|
||||
function dayOne(e, m) {
|
||||
const t0 = now(), d0 = e.day;
|
||||
const input = { speed: m.speed, last: m.last, alone: (m.alone || []).includes(e.nid), mute: !!m.mute };
|
||||
let retried = false, err = null;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
try {
|
||||
mark(e, { day: true });
|
||||
const [h] = call(e, 'srvDay', input, T.day);
|
||||
if (h.srvErr) throw Object.assign(new Error(h.srvErr), { inRealm: true });
|
||||
e.day = h.day; e.lost = h.lost;
|
||||
return { day: h.day, lost: h.lost, ...(h.pause ? { pause: true } : {}), ...(retried ? { retried: true } : {}), ms: +(now() - t0).toFixed(2) };
|
||||
} catch (x) {
|
||||
err = x; retried = true;
|
||||
log('warn', `[${e.nid}] day ${d0 + 1} failed (${isTimeout(x) ? 'timeout' : 'throw'}${i ? ', again' : ''}): ${MSG(x)}`);
|
||||
try { if (isTimeout(x) || !e.mark) rebuild(e, e.dayMark || e.mark); else restore(e, { day: true }); }
|
||||
catch (y) { log('error', `[${e.nid}] could not go back before the day: ${MSG(y)}`); break; }
|
||||
}
|
||||
}
|
||||
e.broken = true;
|
||||
return { day: e.day, lost: !!e.lost, err: (isTimeout(err) ? 'timeout: ' : '') + String((err && err.message) || err).split('\n')[0].slice(0, 300), retried: true, ms: +(now() - t0).toFixed(2) };
|
||||
}
|
||||
const H = {
|
||||
act(m, e) {
|
||||
if (e.broken || e.lost) return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: 'stopped', v: e.v, upd: null };
|
||||
try {
|
||||
mark(e, { keys: true });
|
||||
const [h, upd] = call(e, 'srvAct', m.msg, T.act);
|
||||
if (h.srvErr) { restore(e, {}); return errReply(m, 'throw', h.srvErr); }
|
||||
e.v = h.v;
|
||||
if (h.outcome === 'stopped') e.lost = true;
|
||||
return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: h.outcome, ...(h.why ? { why: h.why } : {}), v: h.v, upd: upd || null };
|
||||
} catch (x) {
|
||||
if (!isTimeout(x)) throw x;
|
||||
rebuild(e, { ...e.mark, rt: markRt(e) });
|
||||
return errReply(m, 'timeout', `the action took longer than ${T.act} ms`);
|
||||
}
|
||||
},
|
||||
ask(m, e) {
|
||||
if (e.broken || e.lost) return { t: 'askDone', nid: m.nid, rid: m.msg.rid, err: 'stopped' };
|
||||
try {
|
||||
mark(e, {});
|
||||
const [h] = call(e, 'srvAsk', m.msg, T.ask);
|
||||
if (h.srvErr) { restore(e, {}); return errReply(m, 'throw', h.srvErr); }
|
||||
return { t: 'askDone', nid: m.nid, rid: m.msg.rid, ...h };
|
||||
} catch (x) {
|
||||
if (!isTimeout(x)) throw x;
|
||||
rebuild(e, { ...e.mark, rt: markRt(e) });
|
||||
return errReply(m, 'timeout', `the what-if took longer than ${T.ask} ms`);
|
||||
}
|
||||
},
|
||||
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, () => { call(e, 'srvPrefs', { prefs: m.prefs }, T.small); return null; }); },
|
||||
// Tests only: a piece of code in the realm, its value back.
|
||||
eval(m, e) {
|
||||
if (!test) throw new Error('eval is for tests');
|
||||
try { return { value: e.realm.eval(m.src, m.ms || 5000) }; }
|
||||
catch (x) { if (isTimeout(x)) { rebuildAfterRead(e); return { timeout: true, epoch: e.epoch }; } return { error: MSG(x) }; }
|
||||
},
|
||||
};
|
||||
function pulled(m, e, name, input) {
|
||||
return guarded(m, e, () => {
|
||||
const [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;
|
||||
return o;
|
||||
});
|
||||
}
|
||||
// A call that changes nothing applied: after a timeout the realm is built again from its own save.
|
||||
function guarded(m, e, f) {
|
||||
try { return f(); } catch (x) { if (!isTimeout(x)) throw x; rebuildAfterRead(e); return errReply(m, 'timeout', `${m.t} took too long`); }
|
||||
}
|
||||
|
||||
/* ---- 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;
|
||||
const e = realms.get(key(j.code, j.nid));
|
||||
return !e || !e.loading;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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') {
|
||||
const s = session(j.code);
|
||||
for (const n of j.nets) {
|
||||
if (!n || typeof n.nid !== 'string' || (!n.begin && !(n.env && typeof n.env.s === 'string'))) throw new Error('load: each network needs a nid and an env with its save text, or begin');
|
||||
realms.set(key(j.code, n.nid), { code: j.code, nid: n.nid, lang: n.lang || 'en', prefs: n.prefs || {}, loading: true, realm: null, epoch: '', v: 0, day: 0, lost: false, broken: false, mark: null, dayMark: null });
|
||||
}
|
||||
s.load = { j, i: 0, out: [] };
|
||||
return;
|
||||
}
|
||||
if (j.t === 'day') {
|
||||
const s = session(j.code);
|
||||
const order = [...new Set(j.nets || [])].sort().filter((n) => { const e = realms.get(key(j.code, n)); return e && !e.loading && !e.broken && !e.lost; });
|
||||
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) 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}`);
|
||||
return reply(j, h(j, e));
|
||||
}
|
||||
// One step of a session's load (one network) or day (one network).
|
||||
function runStep() {
|
||||
const ss = [...sessions.values()].filter((s) => s.load || s.day);
|
||||
if (!ss.length) return false;
|
||||
const s = ss[turn++ % ss.length];
|
||||
if (s.load) {
|
||||
const L = s.load, n = L.j.nets[L.i++];
|
||||
if (n) L.out.push(loadOne(L.j.code, n));
|
||||
if (L.i >= L.j.nets.length) { s.load = null; reply(L.j, L.out); }
|
||||
return true;
|
||||
}
|
||||
const D = s.day, nid = D.order[D.i++];
|
||||
if (nid) { const e = realms.get(key(D.j.code, nid)); if (e && !e.broken && !e.lost) D.out[nid] = dayOne(e, D.j); }
|
||||
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 }); }
|
||||
return true;
|
||||
}
|
||||
let flip = false;
|
||||
function pump() {
|
||||
pumping = false;
|
||||
flip = !flip;
|
||||
if (flip) { if (!runJob()) runStep(); } else if (!runStep()) runJob();
|
||||
if (jobs.length || [...sessions.values()].some((s) => s.load || s.day)) 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 { 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 };
|
||||
Loading…
Add table
Add a link
Reference in a new issue