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