@boardgamecommons/sandbox 0.0.0 → 0.2.0-next.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ export type SandboxErrorCode = 'cpu' | 'memory' | 'stack' | 'crash' | 'error';
2
+ export declare class SandboxError extends Error {
3
+ code: SandboxErrorCode;
4
+ constructor(code: SandboxErrorCode, message: string);
5
+ }
6
+ export type SandboxPool = {
7
+ run(bundle: string, op: string, argsJson: string, opts?: {
8
+ cpuMs?: number;
9
+ }): Promise<string>;
10
+ close(): Promise<void>;
11
+ };
12
+ export declare function createSandboxPool(opts?: {
13
+ size?: number;
14
+ cpuMs?: number;
15
+ memoryBytes?: number;
16
+ stackBytes?: number;
17
+ }): SandboxPool;
package/dist/index.js ADDED
@@ -0,0 +1,89 @@
1
+ // packages/sandbox/src/index.ts
2
+ import { Worker } from "node:worker_threads";
3
+ var SandboxError = class extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "SandboxError";
8
+ this.code = code;
9
+ }
10
+ };
11
+ var MiB = 1024 * 1024;
12
+ var WATCHDOG_GRACE_MS = 50;
13
+ function createSandboxPool(opts = {}) {
14
+ const { size = 4, cpuMs = 25, memoryBytes = 32 * MiB, stackBytes = 256 * 1024 } = opts;
15
+ const queue = [];
16
+ let nextId = 1;
17
+ let closed = false;
18
+ const limitMessage = (code, ms) => code === "cpu" ? `The game's rules ran past their ${ms} ms time limit and were stopped.` : code === "memory" ? `The game's rules used more than their ${Math.round(memoryBytes / MiB)} MiB memory limit and were stopped.` : code === "stack" ? `The game's rules nested calls past their ${Math.round(stackBytes / 1024)} KiB stack limit and were stopped.` : `The game's rules crashed their sandbox and were stopped.`;
19
+ function finish(slot, outcome) {
20
+ const job = slot.job;
21
+ if (slot.timer) clearTimeout(slot.timer);
22
+ slot.job = null;
23
+ slot.timer = null;
24
+ if (job) "value" in outcome ? job.resolve(outcome.value) : job.reject(outcome.error);
25
+ }
26
+ function spawn() {
27
+ const worker = new Worker(
28
+ new URL(import.meta.url.endsWith(".ts") ? "./worker.ts" : "./worker.js", import.meta.url),
29
+ // .js once compiled for npm
30
+ {
31
+ workerData: { memoryBytes, stackBytes },
32
+ resourceLimits: { maxOldGenerationSizeMb: 64, maxYoungGenerationSizeMb: 16 }
33
+ }
34
+ );
35
+ const slot = { worker, ready: false, job: null, timer: null };
36
+ worker.on("message", (m) => {
37
+ if (m === "ready") slot.ready = true;
38
+ else if (slot.job?.call.id === m.id) {
39
+ finish(slot, m.ok ? { value: m.value } : { error: new SandboxError(m.code, m.code === "error" ? m.message : limitMessage(m.code, slot.job.call.cpuMs)) });
40
+ }
41
+ pump();
42
+ });
43
+ worker.on("error", (e) => {
44
+ const code = e.code === "ERR_WORKER_OUT_OF_MEMORY" ? "memory" : "crash";
45
+ finish(slot, { error: new SandboxError(code, limitMessage(code, slot.job?.call.cpuMs ?? cpuMs)) });
46
+ });
47
+ worker.on("exit", () => {
48
+ finish(slot, { error: new SandboxError("crash", limitMessage("crash", cpuMs)) });
49
+ if (closed) return;
50
+ slots[slots.indexOf(slot)] = spawn();
51
+ pump();
52
+ });
53
+ return slot;
54
+ }
55
+ function pump() {
56
+ for (const slot of slots) {
57
+ if (!queue.length) return;
58
+ if (!slot.ready || slot.job) continue;
59
+ const job = queue.shift();
60
+ slot.job = job;
61
+ slot.timer = setTimeout(() => {
62
+ slot.ready = false;
63
+ finish(slot, { error: new SandboxError("cpu", limitMessage("cpu", job.call.cpuMs)) });
64
+ void slot.worker.terminate();
65
+ }, job.call.cpuMs + WATCHDOG_GRACE_MS);
66
+ slot.worker.postMessage(job.call);
67
+ }
68
+ }
69
+ const slots = [];
70
+ for (let i = 0; i < size; i++) slots.push(spawn());
71
+ return {
72
+ run(bundle, op, argsJson, runOpts = {}) {
73
+ if (closed) return Promise.reject(new SandboxError("crash", "The rules sandbox has shut down."));
74
+ return new Promise((resolve, reject) => {
75
+ queue.push({ call: { id: nextId++, bundle, op, argsJson, cpuMs: runOpts.cpuMs ?? cpuMs }, resolve, reject });
76
+ pump();
77
+ });
78
+ },
79
+ async close() {
80
+ closed = true;
81
+ for (const job of queue.splice(0)) job.reject(new SandboxError("crash", "The rules sandbox has shut down."));
82
+ await Promise.all(slots.map((s) => s.worker.terminate()));
83
+ }
84
+ };
85
+ }
86
+ export {
87
+ SandboxError,
88
+ createSandboxPool
89
+ };
@@ -0,0 +1,17 @@
1
+ export type Call = {
2
+ id: number;
3
+ bundle: string;
4
+ op: string;
5
+ argsJson: string;
6
+ cpuMs: number;
7
+ };
8
+ export type Reply = {
9
+ id: number;
10
+ ok: true;
11
+ value: string;
12
+ } | {
13
+ id: number;
14
+ ok: false;
15
+ code: 'cpu' | 'memory' | 'stack' | 'error';
16
+ message: string;
17
+ };
package/dist/worker.js ADDED
@@ -0,0 +1,64 @@
1
+ // packages/sandbox/src/worker.ts
2
+ import { parentPort, workerData } from "node:worker_threads";
3
+ import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
4
+ import variant from "@jitl/quickjs-wasmfile-release-sync";
5
+ var { memoryBytes, stackBytes } = workerData;
6
+ var QuickJS = await newQuickJSWASMModuleFromVariant(
7
+ // The package's types resolve to its CJS shape under nodenext; at runtime the default export is the variant.
8
+ variant
9
+ );
10
+ var PRELUDE = `delete globalThis.Date;
11
+ Math.random = function random() { throw new Error('Math.random is not available to game rules; use the seeded rng from @boardgamecommons/core.'); };`;
12
+ function run({ id, bundle, op, argsJson, cpuMs }) {
13
+ const rt = QuickJS.newRuntime();
14
+ rt.setMemoryLimit(memoryBytes);
15
+ rt.setMaxStackSize(stackBytes);
16
+ const start = process.threadCpuUsage();
17
+ const budgetMicros = cpuMs * 1e3;
18
+ let interrupted = false;
19
+ rt.setInterruptHandler(() => {
20
+ const used = process.threadCpuUsage(start);
21
+ return interrupted = used.user + used.system > budgetMicros;
22
+ });
23
+ let reply;
24
+ const ctx = rt.newContext();
25
+ try {
26
+ const r = ctx.evalCode(`${PRELUDE}
27
+ ${bundle}
28
+ ;globalThis.__bgc(${JSON.stringify(op)}, ${JSON.stringify(argsJson)})`, "rules.js");
29
+ if (r.error) {
30
+ let err;
31
+ try {
32
+ err = ctx.dump(r.error);
33
+ } catch {
34
+ err = null;
35
+ }
36
+ r.error.dispose();
37
+ const text = err && typeof err === "object" ? `${err.name ?? ""}: ${err.message ?? ""}` : String(err);
38
+ if (interrupted) reply = { id, ok: false, code: "cpu", message: text };
39
+ else if (err === null || /out of memory|string too long|invalid array length/i.test(text)) reply = { id, ok: false, code: "memory", message: text };
40
+ else if (/stack overflow|call stack/i.test(text)) reply = { id, ok: false, code: "stack", message: text };
41
+ else reply = { id, ok: false, code: "error", message: err && typeof err === "object" && err.message ? String(err.message) : String(err) };
42
+ } else {
43
+ const t = ctx.typeof(r.value);
44
+ reply = t === "string" ? { id, ok: true, value: ctx.getString(r.value) } : { id, ok: false, code: "error", message: `The game's rules returned ${t} instead of text.` };
45
+ r.value.dispose();
46
+ }
47
+ } catch (e) {
48
+ reply = { id, ok: false, code: interrupted ? "cpu" : "memory", message: String(e) };
49
+ }
50
+ try {
51
+ ctx.dispose();
52
+ rt.dispose();
53
+ return { reply, healthy: true };
54
+ } catch {
55
+ return { reply, healthy: false };
56
+ }
57
+ }
58
+ parentPort.on("message", (call) => {
59
+ const { reply, healthy } = run(call);
60
+ parentPort.postMessage(reply);
61
+ if (!healthy) process.exit(1);
62
+ });
63
+ run({ id: 0, bundle: 'globalThis.__bgc = () => "warm";', op: "warm", argsJson: "{}", cpuMs: 1e3 });
64
+ parentPort.postMessage("ready");
package/package.json CHANGED
@@ -1 +1,23 @@
1
- {"name":"@boardgamecommons/sandbox","version":"0.0.0","license":"Apache-2.0","description":"Placeholder. See https://github.com/boardgamecommons/kit"}
1
+ {
2
+ "name": "@boardgamecommons/sandbox",
3
+ "version": "0.2.0-next.2",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=26"
7
+ },
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/boardgamecommons/kit.git",
11
+ "directory": "packages/sandbox"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "quickjs-emscripten-core": "^0.32.0",
21
+ "@jitl/quickjs-wasmfile-release-sync": "^0.32.0"
22
+ }
23
+ }