/ proof-of-concept / plate-dynamics-lab-2
Sign in
proof-of-concept / plate-dynamics-lab-2
plate-dynamics-lab-2 / packages / core / src / runner / worker.ts
33 lines · 1.2 KBBlameHistoryRaw
1/// <reference lib="webworker" />
2/**
3 * Web Worker that owns a numbl instance. One run at a time; the host cancels
4 * a run by terminating the worker, which is why nothing here needs to be
5 * interruptible. The modes of stage 1 travel back to the host and return as
6 * an input of stage 2, so a cancelled or crashed worker loses nothing kept.
7 */
8import { executeBundle, numblVersion } from "./execute";
9import { collectBuffers } from "./plain";
10import type { FromWorker, ToWorker } from "./protocol";
11import type { BackendInfo } from "./types";
13const backend: BackendInfo = {
14 engine: "numbl",
15 version: numblVersion(),
16 optimization: "1",
17 host: "web-worker",
18};
20const post = (msg: FromWorker, transfer: ArrayBuffer[] = []) => self.postMessage(msg, transfer);
22self.onmessage = (e: MessageEvent<ToWorker>) => {
23 const msg = e.data;
24 if (msg.type === "info") {
25 post({ type: "info", id: msg.id, backend });
26 return;
27 }
28 const result = executeBundle({ bundle: msg.bundle, inputs: msg.inputs }, backend, (text) =>
29 post({ type: "output", id: msg.id, text }),
30 );
31 const transfer = result.ok ? collectBuffers(result.value) : [];
32 post({ type: "done", id: msg.id, result }, transfer);
33};
↑↓ move↵openescclose