winzik/engine/web/jumphp-cryo-worker.js

104 lines
4.6 KiB
JavaScript

// A Cryo\Sandbox\Sandbox in the browser (jumphp-cryo.js starts it): a Web Worker running its own PHP engine
// (the same php-web.wasm and game files as the page), so the sandbox has its own memory. It never blocks either:
// each frame from the page goes into this engine's Module.cryoHost queue, then cryo_sandbox_step() (ext-cryo)
// reads it and runs ONE request; the answer frames go back as they are written. The first frame is INIT
// (memory_limit, ini, disable_functions, bootstrap: applied by ext-cryo here, answered with HELLO).
// exit(), a fatal error or a failed bootstrap end PHP with _exit() (emscripten throws ExitStatus): reported as
// 'exit' with its code; any other exception out of the engine (a trap: stack overflow, out of bounds) as 'crash'.
import { framer, byteQueue } from './jumphp-cryo.js';
// the engine touches `document` / `window` when it loads (SDL's event targets): minimal stand-ins, never used
self.window = self;
const inert = () => ({ style: {}, getContext: () => null, addEventListener() {}, removeEventListener() {} });
self.document = {
addEventListener() {}, removeEventListener() {}, createElement: inert, getElementById: () => null,
querySelector: () => null, body: inert(), documentElement: inert(), title: '',
};
let module = null;
let finished = false;
const errors = [];
const inbox = byteQueue();
const early = []; // frames that arrived while PHP was booting
const toPage = framer((frame) => self.postMessage({ type: 'frame', bytes: frame }, [frame.buffer]));
async function boot({ moduleUrl, dataUrl, wasmBinary, remote }) {
const { default: createPhpModule } = await import(moduleUrl);
module = await createPhpModule({
wasmBinary,
locateFile: (path, prefix) => (path === 'php-web.data' ? dataUrl : prefix + path),
print: (text) => console.log('[sandbox]', text),
printErr(text) {
if (!text || /munmap\(\) failed/.test(text)) return;
errors.push(String(text));
if (errors.length > 8) errors.shift();
console.warn('[sandbox]', text); // the game gets it through the futures (failed): not a page error
},
});
if (remote) {
const { installRemote } = await import(new URL('jumphp-files.js' + (remote.version['jumphp-files.js'] ? `?v=${remote.version['jumphp-files.js']}` : ''), remote.engine).href);
await installRemote({ FS: module.FS, ...remote });
}
module.cryoHost = {
recv: (id, cap) => inbox.read(cap),
send: (id, bytes) => { toPage(bytes); return bytes.length; },
arm: (ms, frame) => self.postMessage({ type: 'arm', ms, frame }, frame ? [frame.buffer] : []),
emit() {},
};
if (typeof module._cryo_sandbox_step !== 'function') throw new Error('this engine has no sandbox support (cryo_sandbox_step)');
const { ccall } = module;
// PHP's own allocator here (not the page's USE_ZEND_ALLOC=0): it is the one that counts memory_limit, and the
// memory of a sandbox goes away with its worker anyway
ccall('php_embed_init', 'number', ['number', 'number'], [0, 0]);
// the game's classes are there (an autoloader), nothing of the engine runs: the sandbox is a blank PHP. Its errors
// reach the game through the futures; the console shows them as [sandbox] warnings
ccall('zend_eval_string', 'number', ['string', 'number', 'string'], [
`define('JUMPHP_WASM', true); define('JUMPHP_SANDBOX', true); if (is_dir('/game')) { chdir('/game'); } if (is_file('/game/vendor/autoload.php')) { require_once '/game/vendor/autoload.php'; }`,
0, 'jumphp sandbox']);
}
function finish(type, extra) {
if (finished) return;
finished = true;
self.postMessage({ type, ...extra, error: [extra.error, ...errors].filter(Boolean).join(' | ') });
self.close();
}
let scheduled = false;
function run() {
scheduled = false;
if (finished || !module) return;
let r;
try {
r = module._cryo_sandbox_step();
} catch (e) {
if (e && (e.name === 'ExitStatus' || typeof e.status === 'number')) finish('exit', { code: e.status | 0 });
else finish('crash', { error: e && e.stack ? String(e.stack).split('\n').slice(0, 3).join(' ') : String(e) });
return;
}
// one request ran: let the next messages in (a cancellation), then run the next one
if (r > 0) schedule();
}
function schedule() {
if (!scheduled) { scheduled = true; setTimeout(run, 0); }
}
self.onmessage = async ({ data }) => {
if (data.type === 'boot') {
try {
await boot(data);
for (const f of early.splice(0)) inbox.push(f);
self.postMessage({ type: 'ready' });
schedule();
} catch (e) {
finish('failed', { error: String(e && e.message ? e.message : e) });
}
return;
}
if (data.type === 'frame') {
const f = new Uint8Array(data.bytes);
if (!module) { early.push(f); return; }
inbox.push(f);
schedule();
}
};