146 lines
5.4 KiB
JavaScript
146 lines
5.4 KiB
JavaScript
// ext-cryo in the browser: the page side of Cryo\Sandbox\Sandbox (Module.cryoHost, see ext-cryo/cryo_host.h).
|
|
// Each sandbox is a Web Worker running its OWN PHP engine (jumphp-cryo-worker.js): separate memory, a crash or
|
|
// a trap there never touches the game. Nothing blocks: PHP sends frames (send), and reads, at each frame, what
|
|
// already arrived (recv: -1 when nothing yet, -2 when the sandbox is gone). The worker runs one request per
|
|
// message (cryo_sandbox_step) and posts each answer frame back.
|
|
// timeout (Sandbox option): the worker tells when a request starts (arm); if it is still running after the
|
|
// delay, this host terminates the worker and hands PHP the prebuilt "timeout" answer (exit code 124).
|
|
// crash: worker error, trap (RuntimeError), failed boot -> the instance ends (exit code 134 / 1), PHP fails
|
|
// the pending futures with a SandboxCrashedException (getStderr(): what the worker reported).
|
|
// exit(), fatal error, memory limit: the worker answers first (FATAL frame), then ends with its exit code.
|
|
const HDR = 12;
|
|
const u32 = (b, o) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0;
|
|
|
|
// bytes in, whole frames out (a frame = 12-byte header + payload; PHP writes the header and the payload separately)
|
|
export function framer(onFrame) {
|
|
let buf = new Uint8Array(0);
|
|
return (bytes) => {
|
|
const all = new Uint8Array(buf.length + bytes.length);
|
|
all.set(buf);
|
|
all.set(bytes, buf.length);
|
|
let off = 0;
|
|
while (all.length - off >= HDR) {
|
|
const len = u32(all, off);
|
|
if (all.length - off < HDR + len) break;
|
|
onFrame(all.slice(off, off + HDR + len));
|
|
off += HDR + len;
|
|
}
|
|
buf = all.slice(off);
|
|
};
|
|
}
|
|
|
|
// a queue of whole frames read as a byte stream: read(cap) -> Uint8Array (<= cap bytes) or null
|
|
export function byteQueue() {
|
|
const chunks = [];
|
|
let off = 0;
|
|
return {
|
|
push(c) { chunks.push(c); },
|
|
get size() { return chunks.length; },
|
|
read(cap) {
|
|
if (!chunks.length) return null;
|
|
const out = new Uint8Array(cap);
|
|
let n = 0;
|
|
while (n < cap && chunks.length) {
|
|
const c = chunks[0];
|
|
const take = Math.min(cap - n, c.length - off);
|
|
out.set(c.subarray(off, off + take), n);
|
|
n += take;
|
|
off += take;
|
|
if (off >= c.length) { chunks.shift(); off = 0; }
|
|
}
|
|
return n === cap ? out : out.slice(0, n);
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* The Module.cryoHost functions for sandboxes. boot() gives the message that starts a worker's PHP
|
|
* ({moduleUrl, dataUrl, wasmBinary, remote}, as for the task workers).
|
|
*/
|
|
export function sandboxHost({ workerUrl, boot, log = console }) {
|
|
const instances = new Map();
|
|
let next = 1;
|
|
const decoder = new TextDecoder();
|
|
|
|
const end = (inst, code, error) => {
|
|
if (inst.dead) return;
|
|
inst.dead = true;
|
|
inst.exit = code;
|
|
if (error) inst.error = String(error).slice(0, 2000);
|
|
clearTimeout(inst.timer);
|
|
try { inst.worker.terminate(); } catch (e) { /* already gone */ }
|
|
if (code !== 0 && code !== 137) log.warn(`[cryo] sandbox ${inst.id} ended (exit code ${code})${inst.error ? ': ' + inst.error : ''}`);
|
|
};
|
|
|
|
return {
|
|
instances,
|
|
spawn(bytes) {
|
|
if (typeof Worker === 'undefined') return -1;
|
|
let opts = {};
|
|
try { opts = JSON.parse(decoder.decode(bytes)) || {}; } catch (e) { /* defaults */ }
|
|
const id = next++;
|
|
let worker;
|
|
try { worker = new Worker(workerUrl(), { type: 'module' }); } catch (e) { log.error('[cryo]', e); return -1; }
|
|
const inst = { id, worker, opts, ready: false, out: [], inbox: byteQueue(), dead: false, exit: -1, error: '', timer: 0 };
|
|
inst.write = framer((frame) => {
|
|
if (inst.ready) inst.worker.postMessage({ type: 'frame', bytes: frame }, [frame.buffer]);
|
|
else inst.out.push(frame);
|
|
});
|
|
worker.onmessage = ({ data }) => {
|
|
if (inst.dead) return;
|
|
switch (data.type) {
|
|
case 'ready':
|
|
inst.ready = true;
|
|
for (const f of inst.out.splice(0)) worker.postMessage({ type: 'frame', bytes: f }, [f.buffer]);
|
|
break;
|
|
case 'frame': inst.inbox.push(new Uint8Array(data.bytes)); break;
|
|
case 'arm':
|
|
clearTimeout(inst.timer);
|
|
if (data.ms > 0 && data.frame) {
|
|
const frame = new Uint8Array(data.frame);
|
|
inst.timer = setTimeout(() => {
|
|
if (inst.dead) return;
|
|
inst.inbox.push(frame); // the answer the child prebuilt for this request
|
|
end(inst, 124, `timeout: the request ran for more than ${data.ms} ms`);
|
|
}, data.ms);
|
|
}
|
|
break;
|
|
case 'exit': end(inst, data.code | 0, data.error); break;
|
|
case 'crash': end(inst, 134, data.error); break;
|
|
case 'failed': end(inst, 1, 'the sandbox engine did not start: ' + data.error); break;
|
|
}
|
|
};
|
|
worker.onerror = (e) => { e.preventDefault?.(); end(inst, 134, e.message || 'worker error'); };
|
|
worker.onmessageerror = () => end(inst, 134, 'unreadable message from the sandbox');
|
|
instances.set(id, inst);
|
|
worker.postMessage({ type: 'boot', ...boot() });
|
|
return id;
|
|
},
|
|
send(id, bytes) {
|
|
const inst = instances.get(id);
|
|
if (!inst || inst.dead) return -1;
|
|
inst.write(bytes);
|
|
return bytes.length;
|
|
},
|
|
recv(id, cap) {
|
|
const inst = instances.get(id);
|
|
if (!inst) return -2;
|
|
const m = inst.inbox.read(cap);
|
|
if (m) return m;
|
|
return inst.dead ? -2 : null;
|
|
},
|
|
kill(id) {
|
|
const inst = instances.get(id);
|
|
if (!inst) return;
|
|
end(inst, 137, '');
|
|
instances.delete(id);
|
|
},
|
|
status(id) {
|
|
const inst = instances.get(id);
|
|
return !inst ? -1 : inst.dead ? inst.exit : -1;
|
|
},
|
|
error(id) {
|
|
return instances.get(id)?.error || '';
|
|
},
|
|
};
|
|
}
|