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				// init only
167				if (root.main) {
168					root.main();
169				} else if (root._start) {
170					root._start();
171				} else if (inst.exports._start) {
172					(inst.exports._start as Function)();
173				} else if (inst.exports.main) {
174					(inst.exports.main as Function)();
175				}
176				console.log("[WASI main] done.");
177			},
178			wasi_thread_start: (tid, arg) => {
179				console.log("[WASI wasi_thread_start] tid", tid, "arg", arg);
180				root.virtualFileSystemWasip1ThreadsExport.wasiThreadStart(tid, arg);
181			},
182		},
183	};
184
185    for (const key in root) {
186        if (typeof root[key] !== "function") {
187            continue;
188        }
189        fake[key] = root[key].bind(root);
190    }
191
192	return fake;
193};
194"#;
195
196    format!("{}\n{}", pre.trim(), post.trim())
197}
198
199fn test_run_ts() -> &'static str {
200    r#"
201// npx ts-node test_run.ts
202
203import { ConsoleStdout, Fd, File, OpenFile } from "@bjorn3/browser_wasi_shim";
204import { WASIFarm, wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
205
206import { set_fake_worker } from "./common.ts";
207
208await set_fake_worker();
209
210const isNode =
211	(typeof process !== "undefined" && !!process.versions?.node) ||
212	(typeof Deno !== "undefined");
213
214let farm: WASIFarm;
215if (!isNode) {
216    await import("@xterm/xterm/css/xterm.css");
217    const { FitAddon } = await import("xterm-addon-fit");
218    const { Terminal } = await import("@xterm/xterm");
219
220    wait_async_polyfill();
221
222	const term = new Terminal({
223		convertEol: true,
224	});
225	const terminalElement = document.getElementById("terminal");
226
227	if (!terminalElement) {
228		throw new Error("No terminal element found");
229	}
230
231	term.open(terminalElement);
232
233	const fitAddon = new FitAddon();
234	term.loadAddon(fitAddon);
235	fitAddon.fit();
236
237	class XtermStdio extends Fd {
238		term: Terminal;
239
240		constructor(term: Terminal) {
241			super();
242			this.term = term;
243		}
244		fd_write(data: Uint8Array) /*: {ret: number, nwritten: number}*/ {
245			const str = new TextDecoder().decode(data);
246			this.term.write(str);
247			console.log(str);
248			return { ret: 0, nwritten: data.byteLength };
249		}
250	}
251
252	farm = new WASIFarm(
253		new XtermStdio(term),
254		new XtermStdio(term),
255		new XtermStdio(term),
256		[],
257	);
258
259	const worker = new Worker("./worker.ts", { type: "module" });
260
261	worker.postMessage({
262		wasi_ref: farm.get_ref(),
263	});
264} else {
265	farm = new WASIFarm(
266		new OpenFile(new File([])), // stdin
267		ConsoleStdout.lineBuffered((msg) => console.log(`[WASI stdout] ${msg}`)),
268		ConsoleStdout.lineBuffered((msg) => console.warn(`[WASI stderr] ${msg}`)),
269		[],
270	);
271
272	const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
273
274	worker.postMessage({
275        wasi_ref: farm.get_ref(),
276	});
277}
278"#
279    .trim()
280}
281
282fn thread_spawn_ts() -> &'static str {
283    r#"
284import { thread_spawn_on_worker } from "@oligami/browser_wasi_shim-threads";
285import { set_fake_worker } from "./common.ts";
286import { custom_instantiate } from "./inst.ts";
287
288await set_fake_worker();
289
290let animal: WASIFarmAnimal | undefined = undefined;
291
292globalThis.onmessage = async (event) => {
293	thread_spawn_on_worker(
294		event.data,
295		async (
296			thread_spawn_wasm: WebAssembly.Module,
297			imports: {
298				env: {
299					[key: string]: WebAssembly.Memory;
300				};
301				wasi: { "thread-spawn": (start_arg: number) => number };
302				// biome-ignore lint/suspicious/noExplicitAny: <explanation>
303				wasi_snapshot_preview1: { [key: string]: (...args: any[]) => unknown };
304			},
305		) => {
306			return custom_instantiate(
307				thread_spawn_wasm,
308				imports.wasi_snapshot_preview1,
309				imports.wasi,
310				imports.env,
311                (idx, unknown) => {
312                    if (!animal) {
313                        console.warn("Animal is not set yet", idx, unknown);
314                        return;
315                    }
316                    animal.call_unknown_fn(idx, unknown);
317                },
318			);
319		},
320		(new_animal) => {
321			animal = new_animal;
322		}
323	);
324};
325"#
326    .trim()
327}
328
329fn tsconfig_json() -> &'static str {
330    r#"
331{
332	"compilerOptions": {
333		"target": "ESNext",
334		"module": "NodeNext",
335		"moduleResolution": "nodenext",
336		"esModuleInterop": true,
337		"skipLibCheck": true,
338		"forceConsistentCasingInFileNames": true,
339		"noEmit": true,
340		"allowImportingTsExtensions": true
341	},
342	"include": ["**/*.ts"],
343	"exclude": ["node_modules"]
344}
345"#
346    .trim()
347}
348
349fn package_json() -> &'static str {
350    r#"
351{
352	"scripts": {
353		"run": "ts-node test_run.ts",
354		"dev": "vite"
355	},
356	"type": "module",
357	"dependencies": {
358		"@bjorn3/browser_wasi_shim": "^0.4",
359		"@oligami/browser_wasi_shim-threads": "^0.3",
360		"@xterm/xterm": "^5.5",
361		"xterm-addon-fit": "^0.8.0"
362	},
363	"devDependencies": {
364		"ts-node": "^10.9.2",
365		"vite": "^8.0"
366	}
367}
368"#
369    .trim()
370}
371
372fn worker_background_worker_ts() -> &'static str {
373    r#"
374import { wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
375// @ts-ignore
376import run from "@oligami/browser_wasi_shim-threads/worker_background_worker";
377
378import { set_fake_worker } from "./common.ts";
379
380await set_fake_worker();
381
382wait_async_polyfill();
383
384run();
385"#
386    .trim()
387}
388
389fn worker_ts(wasm_name: &str, mem_size: &HashMap<CompactString, (u64, u64)>) -> String {
390    let mut memories = String::new();
391    for (name, (init, max)) in mem_size {
392        memories.push_str(&{
393            let str = format!(
394                r#"
395                {name}: new WebAssembly.Memory({{
396                    initial:{init},
397                    maximum:{max},
398                    shared:true,
399                }}),"#
400            );
401            format!("                {}", str.trim())
402        });
403    }
404
405    format!(
406        r#"
407import {{ WASIFarmAnimal }} from "@oligami/browser_wasi_shim-threads";
408import {{ set_fake_worker }} from "./common.ts";
409import {{ custom_instantiate }} from "./inst.ts";
410
411await set_fake_worker();
412
413const isNode =
414	(typeof process !== "undefined" && !!process.versions?.node) ||
415	(typeof Deno !== "undefined");
416// biome-ignore lint/suspicious/noExplicitAny: <explanation>
417let _fs: any = null;
418async function fetchCompile(url) {{
419    if (isNode) {{
420        _fs = _fs || (await import("node:fs/promises"));
421        return WebAssembly.compile(await _fs.readFile(new URL(url, import.meta.url)));
422    }}
423    return fetch(url).then(WebAssembly.compileStreaming);
424}}
425
426globalThis.onmessage = async (message) => {{
427	const {{ wasi_ref }} = message.data;
428
429	const wasm_path = "./{wasm_name}.core.wasm";
430	const wasm = await fetchCompile(wasm_path);
431
432	const args = ["bin", "arg1", "arg2"];
433	const env = ["FOO=bar"];
434
435	const wasi = new WASIFarmAnimal(
436		wasi_ref,
437		args, // args
438		env, // env
439		{{
440			can_thread_spawn: true,
441			thread_spawn_worker_url: "./thread_spawn.ts",
442			thread_spawn_wasm: wasm,
443			worker_background_worker_url: "./worker_background_worker.ts",
444            share_memory: {{
445{memories}
446            }},
447        }},
448	);
449
450	await wasi.wait_worker_background_worker();
451
452	const root = await custom_instantiate(
453		wasm,
454		wasi.wasiImport,
455		wasi.wasiThreadImport,
456		wasi.get_share_memory(),
457	);
458
459	// biome-ignore lint/suspicious/noExplicitAny: <explanation>
460	wasi.start(root as any);
461
462    globalThis.process?.exit(0);
463    globalThis.Deno?.exit(0);
464}};
465"#
466    )
467    .trim()
468    .to_string()
469}
470
471fn vite_config_ts() -> &'static str {
472    r#"
473import { defineConfig } from "vite";
474
475export default defineConfig({
476	server: {
477		headers: {
478			"Cross-Origin-Embedder-Policy": "require-corp",
479			"Cross-Origin-Opener-Policy": "same-origin",
480		},
481	},
482});
483    "#
484    .trim()
485}
486
487fn index_html() -> &'static str {
488    r#"
489<!DOCTYPE html>
490<html>
491<head>
492<meta charset="utf-8">
493
494<div id="terminal"></div>
495
496<script type="module" src="./test_run.ts"></script>
497</body>
498</html>
499    "#
500    .trim()
501}