Skip to main content

wasi_virt_layer_cli/test_run/
thread.rs

1use std::{collections::HashMap, io::Write as _};
2
3use compact_str::CompactString;
4
5/// Generates the HTML, TypeScript, and configuration files needed to run a thread-enabled WASM module in a browser/worker.
6pub fn gen_threads_run(
7    wasm_name: impl AsRef<str>,
8    mem_size: HashMap<CompactString, (u64, u64)>,
9    out_dir: impl AsRef<str>,
10) {
11    let wasm_name = wasm_name.as_ref();
12
13    [
14        ("common.ts", common_ts()),
15        ("inst.ts", &custom_instantiate_ts(wasm_name)),
16        ("test_run.ts", test_run_ts()),
17        ("thread_spawn.ts", thread_spawn_ts()),
18        ("tsconfig.json", tsconfig_json()),
19        ("package.json", package_json()),
20        ("worker_background_worker.ts", worker_background_worker_ts()),
21        ("worker.ts", &worker_ts(wasm_name, &mem_size)),
22        ("vite.config.ts", vite_config_ts()),
23        ("index.html", index_html()),
24    ]
25    .iter()
26    .for_each(|(name, content)| {
27        let out_dir = out_dir.as_ref();
28        std::fs::OpenOptions::new()
29            .write(true)
30            .create(true)
31            .open(format!("{out_dir}/{name}"))
32            .expect("Failed to create file")
33            .write_all(content.as_bytes())
34            .expect("Failed to write file");
35    });
36}
37
38fn common_ts() -> &'static str {
39    r#"
40// biome-ignore lint/suspicious/noExplicitAny: <explanation>
41let _worker: any = null;
42const set_fake_worker = async () => {
43	if (
44		(typeof process !== "undefined" &&
45			process.versions &&
46			process.versions.node &&
47            typeof Deno === "undefined")
48	) {
49		_worker = _worker || (await import("node:worker_threads"));
50		const { Worker, isMainThread, parentPort } = _worker;
51
52        class FakeWorker {
53            worker;
54            onmessage;
55
56            constructor(url) {
57                let absolute_url;
58                if (url instanceof URL) {
59                    absolute_url = url;
60                } else {
61                    absolute_url = new URL(url, import.meta.url);
62                }
63                this.worker = new Worker(absolute_url, {
64                    type: "module",
65                });
66
67                this.worker.on("message", (message) => {
68                    if (this.onmessage) {
69                        this.onmessage({ data: message });
70                    }
71                });
72            }
73            postMessage(message) {
74                this.worker.postMessage(message);
75            }
76        }
77
78		// biome-ignore lint/suspicious/noExplicitAny: <explanation>
79		(globalThis as any).Worker = FakeWorker;
80	}
81};
82
83export { set_fake_worker };
84"#
85    .trim()
86}
87
88fn custom_instantiate_ts(wasm_name: &str) -> String {
89    let pre = format!(
90        r#"
91import type {{ WASIFarmAnimal }} from "@oligami/browser_wasi_shim-threads";
92import {{ type ImportObject, instantiate }} from "./{wasm_name}.js";
93"#
94    );
95
96    let post = r#"
97function snakeToCamel(snakeCaseString) {
98	return snakeCaseString
99		.toLowerCase()
100		.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
101}
102
103export const custom_instantiate = async (
104	wasm_module: WebAssembly.Module,
105	wasiImport: {
106		[key: string]: (...args: unknown[]) => unknown;
107	},
108	wasiThreadImport: {
109		"thread-spawn": (start_arg: number) => number;
110	},
111	memory: {
112		[key: string]: WebAssembly.Memory;
113	},
114    /// By specifying a farm number, you can synchronously call the `unknown_fn` function of that farm.
115    /// This is used when you want to use custom imports with WIT.
116    call_unknown_fn: (idx: number, unknown: unknown) => unknown = (idx, unknown) => {
117        console.warn("call_unknown_fn is not set", idx, unknown);
118    },
119): Promise<WebAssembly.Instance> => {
120	const imports = {};
121	for (const key in wasiImport) {
122		const inner_key = `${snakeToCamel(key)}Import`;
123		imports[inner_key] = wasiImport[key];
124	}
125
126	const threadSpawnImports = {
127		threadSpawnImport: (start_arg) => {
128			const tid = wasiThreadImport["thread-spawn"](start_arg);
129			return tid;
130		},
131	};
132
133	let inst: WebAssembly.Instance | undefined = undefined;
134
135	const root = await instantiate(
136		(_path) => {
137			return wasm_module;
138		}, // instantiate has default function if undefined
139		{
140			"wasip1-vfs:host/virtual-file-system-wasip1-core": {
141				Wasip1: imports,
142			},
143			"wasip1-vfs:host/virtual-file-system-wasip1-threads-import": {
144				Wasip1Threads: threadSpawnImports,
145			},
146		} as ImportObject,
147		async (module, imports) => {
148			imports.env = {
149				...memory,
150			};
151
152			inst = await WebAssembly.instantiate(module, imports);
153			return inst;
154		},
155	);
156
157	if (inst === undefined) {
158		throw new Error("inst is not an instance");
159	}
160	inst = inst as WebAssembly.Instance;
161
162	const fake = {
163		exports: {
164			memory: inst.exports.memory as WebAssembly.Memory,
165			_start: () => {
166				if (root._start) {
167					root._start();
168				} else if (inst.exports._start) {
169					(inst.exports._start as Function)();
170				} else if (root.init) {
171					root.init();
172				}
173				if (root.main) {
174					root.main();
175				} else if (root.start) {
176					root.start();
177				} else if (inst.exports.main && !root.main) {
178					(inst.exports.main as Function)();
179				}
180				console.log("[WASI main] done.");
181			},
182			wasi_thread_start: (tid, arg) => {
183				console.log("[WASI wasi_thread_start] tid", tid, "arg", arg);
184				root.virtualFileSystemWasip1ThreadsExport.wasiThreadStart(tid, arg);
185			},
186		},
187	};
188
189    for (const key in root) {
190        if (typeof root[key] !== "function") {
191            continue;
192        }
193        fake[key] = root[key].bind(root);
194    }
195
196	return fake;
197};
198"#;
199
200    format!("{}\n{}", pre.trim(), post.trim())
201}
202
203fn test_run_ts() -> &'static str {
204    r#"
205// npx ts-node test_run.ts
206
207import { ConsoleStdout, Fd, File, OpenFile } from "@bjorn3/browser_wasi_shim";
208import { WASIFarm, wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
209
210import { set_fake_worker } from "./common.ts";
211
212await set_fake_worker();
213
214const isNode =
215	(typeof process !== "undefined" && !!process.versions?.node) ||
216	(typeof Deno !== "undefined");
217
218let farm: WASIFarm;
219if (!isNode) {
220    await import("@xterm/xterm/css/xterm.css");
221    const { FitAddon } = await import("xterm-addon-fit");
222    const { Terminal } = await import("@xterm/xterm");
223
224    wait_async_polyfill();
225
226	const term = new Terminal({
227		convertEol: true,
228	});
229	const terminalElement = document.getElementById("terminal");
230
231	if (!terminalElement) {
232		throw new Error("No terminal element found");
233	}
234
235	term.open(terminalElement);
236
237	const fitAddon = new FitAddon();
238	term.loadAddon(fitAddon);
239	fitAddon.fit();
240
241	class XtermStdio extends Fd {
242		term: Terminal;
243
244		constructor(term: Terminal) {
245			super();
246			this.term = term;
247		}
248		fd_write(data: Uint8Array) /*: {ret: number, nwritten: number}*/ {
249			const str = new TextDecoder().decode(data);
250			this.term.write(str);
251			console.log(str);
252			return { ret: 0, nwritten: data.byteLength };
253		}
254	}
255
256	farm = new WASIFarm(
257		new XtermStdio(term),
258		new XtermStdio(term),
259		new XtermStdio(term),
260		[],
261	);
262
263	const worker = new Worker("./worker.ts", { type: "module" });
264
265	worker.postMessage({
266		wasi_ref: farm.get_ref(),
267	});
268
269	worker.onmessage = (e) => {
270		if (e.data.type === 'exit') {
271			if (globalThis.process?.exit) {
272				globalThis.process.exit(e.data.code);
273			} else if (globalThis.Deno?.exit) {
274				globalThis.Deno.exit(e.data.code);
275			}
276		}
277	};
278} else {
279	farm = new WASIFarm(
280		new OpenFile(new File([])), // stdin
281		ConsoleStdout.lineBuffered((msg) => console.log(`[WASI stdout] ${msg}`)),
282		ConsoleStdout.lineBuffered((msg) => console.warn(`[WASI stderr] ${msg}`)),
283		[],
284	);
285
286	const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
287
288	worker.postMessage({
289        wasi_ref: farm.get_ref(),
290	});
291
292	if (typeof worker.on === "function") {
293		worker.on("error", (err: any) => {
294			console.error("Worker error:", err);
295			if (globalThis.process?.exit) {
296				globalThis.process.exit(1);
297			} else if (globalThis.Deno?.exit) {
298				globalThis.Deno.exit(1);
299			}
300		});
301		worker.on("message", (e: any) => {
302			if (e && e.type === 'exit') {
303				if (globalThis.process?.exit) {
304					globalThis.process.exit(e.code);
305				} else if (globalThis.Deno?.exit) {
306					globalThis.Deno.exit(e.code);
307				}
308			}
309		});
310	} else {
311		worker.onerror = (err: any) => {
312			console.error("Worker error:", err);
313			if (globalThis.process?.exit) {
314				globalThis.process.exit(1);
315			} else if (globalThis.Deno?.exit) {
316				globalThis.Deno.exit(1);
317			}
318		};
319		worker.onmessage = (e: any) => {
320			if (e.data && e.data.type === 'exit') {
321				if (globalThis.process?.exit) {
322					globalThis.process.exit(e.data.code);
323				} else if (globalThis.Deno?.exit) {
324					globalThis.Deno.exit(e.data.code);
325				}
326			}
327		};
328	}
329}
330"#
331    .trim()
332}
333
334fn thread_spawn_ts() -> &'static str {
335    r#"
336import { thread_spawn_on_worker, type WASIFarmAnimal } from "@oligami/browser_wasi_shim-threads";
337import { set_fake_worker } from "./common.ts";
338import { custom_instantiate } from "./inst.ts";
339
340await set_fake_worker();
341
342let animal: WASIFarmAnimal | undefined = undefined;
343
344globalThis.onmessage = async (event) => {
345	try {
346		await thread_spawn_on_worker(
347			event.data,
348			async (
349				thread_spawn_wasm: WebAssembly.Module,
350				imports: {
351					env: {
352						[key: string]: WebAssembly.Memory;
353					};
354					wasi: { "thread-spawn": (start_arg: number) => number };
355					// biome-ignore lint/suspicious/noExplicitAny: <explanation>
356					wasi_snapshot_preview1: { [key: string]: (...args: any[]) => unknown };
357				},
358			) => {
359				return custom_instantiate(
360					thread_spawn_wasm,
361					imports.wasi_snapshot_preview1,
362					imports.wasi,
363					imports.env,
364					(idx, unknown) => {
365						if (!animal) {
366							console.warn("Animal is not set yet", idx, unknown);
367							return;
368						}
369						return animal.call_unknown_fn(idx, unknown);
370					},
371				);
372			},
373			(new_animal) => {
374				animal = new_animal;
375			}
376		);
377		globalThis.postMessage({ type: 'exit', code: 0 });
378	} catch (e) {
379		console.error("Worker caught error:", e);
380		globalThis.postMessage({ type: 'exit', code: 1 });
381	}
382};
383"#
384    .trim()
385}
386
387fn tsconfig_json() -> &'static str {
388    r#"
389{
390	"compilerOptions": {
391		"target": "ESNext",
392		"module": "NodeNext",
393		"moduleResolution": "nodenext",
394		"esModuleInterop": true,
395		"skipLibCheck": true,
396		"forceConsistentCasingInFileNames": true,
397		"noEmit": true,
398		"allowImportingTsExtensions": true
399	},
400	"include": ["**/*.ts"],
401	"exclude": ["node_modules"]
402}
403"#
404    .trim()
405}
406
407fn package_json() -> &'static str {
408    r#"
409{
410	"scripts": {
411		"run": "ts-node test_run.ts",
412		"dev": "vite"
413	},
414	"type": "module",
415	"dependencies": {
416		"@bjorn3/browser_wasi_shim": "^0.4",
417		"@oligami/browser_wasi_shim-threads": "^0.5",
418		"@xterm/xterm": "^5.5",
419		"xterm-addon-fit": "^0.8.0"
420	},
421	"devDependencies": {
422		"ts-node": "^10.9.2",
423		"vite": "^8.0"
424	}
425}
426"#
427    .trim()
428}
429
430fn worker_background_worker_ts() -> &'static str {
431    r#"
432import { wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
433// @ts-ignore
434import run from "@oligami/browser_wasi_shim-threads/worker_background_worker";
435
436import { set_fake_worker } from "./common.ts";
437
438await set_fake_worker();
439
440wait_async_polyfill();
441
442run();
443"#
444    .trim()
445}
446
447fn worker_ts(wasm_name: &str, mem_size: &HashMap<CompactString, (u64, u64)>) -> String {
448    let mut memories = String::new();
449    for (name, (init, max)) in mem_size {
450        memories.push_str(&{
451            let str = format!(
452                r#"
453                {name}: new WebAssembly.Memory({{
454                    initial:{init},
455                    maximum:{max},
456                    shared:true,
457                }}),"#
458            );
459            format!("                {}", str.trim())
460        });
461    }
462
463    format!(
464        r#"
465import {{ WASIFarmAnimal }} from "@oligami/browser_wasi_shim-threads";
466import {{ set_fake_worker }} from "./common.ts";
467import {{ custom_instantiate }} from "./inst.ts";
468
469await set_fake_worker();
470
471const isNode =
472	(typeof process !== "undefined" && !!process.versions?.node) ||
473	(typeof Deno !== "undefined");
474// biome-ignore lint/suspicious/noExplicitAny: <explanation>
475let _fs: any = null;
476async function fetchCompile(url) {{
477    if (isNode) {{
478        _fs = _fs || (await import("node:fs/promises"));
479        return WebAssembly.compile(await _fs.readFile(new URL(url, import.meta.url)));
480    }}
481    return fetch(url).then(WebAssembly.compileStreaming);
482}}
483
484globalThis.onmessage = async (message) => {{
485    try {{
486        const {{ wasi_ref }} = message.data;
487
488        const wasm_path = "./{wasm_name}.core.wasm";
489        const wasm = await fetchCompile(wasm_path);
490
491        const args = ["bin", "arg1", "arg2"];
492        const env = ["FOO=bar"];
493
494        const wasi = new WASIFarmAnimal(
495            wasi_ref,
496            args, // args
497            env, // env
498            {{
499                can_thread_spawn: true,
500                thread_spawn_worker_url: "./thread_spawn.ts",
501                thread_spawn_wasm: wasm,
502                worker_background_worker_url: "./worker_background_worker.ts",
503                share_memory: {{
504    {memories}
505                }},
506            }},
507        );
508
509        await wasi.wait_worker_background_worker();
510
511        const root = await custom_instantiate(
512            wasm,
513            wasi.wasiImport,
514            wasi.wasiThreadImport,
515            wasi.get_share_memory(),
516        );
517
518        // biome-ignore lint/suspicious/noExplicitAny: <explanation>
519        wasi.start(root as any);
520
521        globalThis.postMessage({{ type: 'exit', code: 0 }});
522    }} catch (e) {{
523        console.error("Worker caught error:", e);
524        globalThis.postMessage({{ type: 'exit', code: 1 }});
525    }}
526}};
527"#
528    )
529    .trim()
530    .to_string()
531}
532
533fn vite_config_ts() -> &'static str {
534    r#"
535import { defineConfig } from "vite";
536
537export default defineConfig({
538	server: {
539		headers: {
540			"Cross-Origin-Embedder-Policy": "require-corp",
541			"Cross-Origin-Opener-Policy": "same-origin",
542		},
543	},
544});
545    "#
546    .trim()
547}
548
549fn index_html() -> &'static str {
550    r#"
551<!DOCTYPE html>
552<html>
553<head>
554<meta charset="utf-8">
555
556<div id="terminal"></div>
557
558<script type="module" src="./test_run.ts"></script>
559</body>
560</html>
561    "#
562    .trim()
563}