wasi_virt_layer_cli/test_run/
thread.rs1use std::{collections::HashMap, io::Write as _};
2
3use compact_str::CompactString;
4
5pub 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 ImportObject, instantiate }} from "./{wasm_name}.js";
92"#
93 );
94
95 let post = r#"
96function snakeToCamel(snakeCaseString) {
97 return snakeCaseString
98 .toLowerCase()
99 .replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
100}
101
102export const custom_instantiate = async (
103 wasm_module: WebAssembly.Module,
104 wasiImport: {
105 [key: string]: (...args: unknown[]) => unknown;
106 },
107 wasiThreadImport: {
108 "thread-spawn": (start_arg: number) => number;
109 },
110 memory: {
111 [key: string]: WebAssembly.Memory;
112 },
113): Promise<WebAssembly.Instance> => {
114 const imports = {};
115 for (const key in wasiImport) {
116 const inner_key = `${snakeToCamel(key)}Import`;
117 imports[inner_key] = wasiImport[key];
118 }
119
120 const threadSpawnImports = {
121 threadSpawnImport: (start_arg) => {
122 const tid = wasiThreadImport["thread-spawn"](start_arg);
123 return tid;
124 },
125 };
126
127 let inst: WebAssembly.Instance | undefined = undefined;
128
129 const root = await instantiate(
130 (_path) => {
131 return wasm_module;
132 }, // instantiate has default function if undefined
133 {
134 "wasip1-vfs:host/virtual-file-system-wasip1-core": {
135 Wasip1: imports,
136 },
137 "wasip1-vfs:host/virtual-file-system-wasip1-threads-import": {
138 Wasip1Threads: threadSpawnImports,
139 },
140 } as ImportObject,
141 async (module, imports) => {
142 imports.env = {
143 ...memory,
144 };
145
146 inst = await WebAssembly.instantiate(module, imports);
147 return inst;
148 },
149 );
150
151 if (inst === undefined) {
152 throw new Error("inst is not an instance");
153 }
154 inst = inst as WebAssembly.Instance;
155
156 const fake = {
157 exports: {
158 memory: inst.exports.memory as WebAssembly.Memory,
159 _start: () => {
160 // init only
161 if (root.main) {
162 root.main();
163 } else if (root._start) {
164 root._start();
165 } else if (inst.exports._start) {
166 (inst.exports._start as Function)();
167 } else if (inst.exports.main) {
168 (inst.exports.main as Function)();
169 }
170 console.log("[WASI main] done.");
171 },
172 wasi_thread_start: (tid, arg) => {
173 console.log("[WASI wasi_thread_start] tid", tid, "arg", arg);
174 root.virtualFileSystemWasip1ThreadsExport.wasiThreadStart(tid, arg);
175 },
176 },
177 };
178
179 return fake;
180};
181"#;
182
183 format!("{}{}", pre.trim(), post.trim())
184}
185
186fn test_run_ts() -> &'static str {
187 r#"
188// npx ts-node test_run.ts
189
190import { ConsoleStdout, Fd, File, OpenFile } from "@bjorn3/browser_wasi_shim";
191import { WASIFarm, wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
192
193import { set_fake_worker } from "./common.ts";
194
195await set_fake_worker();
196
197const isNode =
198 (typeof process !== "undefined" && !!process.versions?.node) ||
199 (typeof Deno !== "undefined");
200
201let farm: WASIFarm;
202if (!isNode) {
203 await import("@xterm/xterm/css/xterm.css");
204 const { FitAddon } = await import("xterm-addon-fit");
205 const { Terminal } = await import("@xterm/xterm");
206
207 wait_async_polyfill();
208
209 const term = new Terminal({
210 convertEol: true,
211 });
212 const terminalElement = document.getElementById("terminal");
213
214 if (!terminalElement) {
215 throw new Error("No terminal element found");
216 }
217
218 term.open(terminalElement);
219
220 const fitAddon = new FitAddon();
221 term.loadAddon(fitAddon);
222 fitAddon.fit();
223
224 class XtermStdio extends Fd {
225 term: Terminal;
226
227 constructor(term: Terminal) {
228 super();
229 this.term = term;
230 }
231 fd_write(data: Uint8Array) /*: {ret: number, nwritten: number}*/ {
232 const str = new TextDecoder().decode(data);
233 this.term.write(str);
234 console.log(str);
235 return { ret: 0, nwritten: data.byteLength };
236 }
237 }
238
239 farm = new WASIFarm(
240 new XtermStdio(term),
241 new XtermStdio(term),
242 new XtermStdio(term),
243 [],
244 );
245
246 const worker = new Worker("./worker.ts", { type: "module" });
247
248 worker.postMessage({
249 wasi_ref: farm.get_ref(),
250 });
251} else {
252 farm = new WASIFarm(
253 new OpenFile(new File([])), // stdin
254 ConsoleStdout.lineBuffered((msg) => console.log(`[WASI stdout] ${msg}`)),
255 ConsoleStdout.lineBuffered((msg) => console.warn(`[WASI stderr] ${msg}`)),
256 [],
257 );
258
259 const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
260
261 worker.postMessage({
262 wasi_ref: farm.get_ref(),
263 });
264}
265"#
266 .trim()
267}
268
269fn thread_spawn_ts() -> &'static str {
270 r#"
271import { thread_spawn_on_worker } from "@oligami/browser_wasi_shim-threads";
272import { set_fake_worker } from "./common.ts";
273import { custom_instantiate } from "./inst.ts";
274
275await set_fake_worker();
276
277globalThis.onmessage = (event) => {
278 thread_spawn_on_worker(
279 event.data,
280 async (
281 thread_spawn_wasm: WebAssembly.Module,
282 imports: {
283 env: {
284 [key: string]: WebAssembly.Memory;
285 };
286 wasi: { "thread-spawn": (start_arg: number) => number };
287 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
288 wasi_snapshot_preview1: { [key: string]: (...args: any[]) => unknown };
289 },
290 ) => {
291 return custom_instantiate(
292 thread_spawn_wasm,
293 imports.wasi_snapshot_preview1,
294 imports.wasi,
295 imports.env,
296 );
297 },
298 );
299};
300"#
301 .trim()
302}
303
304fn tsconfig_json() -> &'static str {
305 r#"
306{
307 "compilerOptions": {
308 "target": "ESNext",
309 "module": "NodeNext",
310 "moduleResolution": "nodenext",
311 "esModuleInterop": true,
312 "skipLibCheck": true,
313 "forceConsistentCasingInFileNames": true,
314 "noEmit": true,
315 "allowImportingTsExtensions": true
316 },
317 "include": ["**/*.ts"],
318 "exclude": ["node_modules"]
319}
320"#
321 .trim()
322}
323
324fn package_json() -> &'static str {
325 r#"
326{
327 "scripts": {
328 "run": "ts-node test_run.ts",
329 "dev": "vite"
330 },
331 "type": "module",
332 "dependencies": {
333 "@bjorn3/browser_wasi_shim": "^0.4.2",
334 "@oligami/browser_wasi_shim-threads": "^0.2.2",
335 "@xterm/xterm": "^5.5",
336 "xterm-addon-fit": "^0.8.0"
337 },
338 "devDependencies": {
339 "ts-node": "^10.9.2",
340 "vite": "^7.1.7"
341 }
342}
343"#
344 .trim()
345}
346
347fn worker_background_worker_ts() -> &'static str {
348 r#"
349import { wait_async_polyfill } from "@oligami/browser_wasi_shim-threads";
350// @ts-ignore
351import run from "./node_modules/@oligami/browser_wasi_shim-threads/dist/worker_background_worker.min.js";
352
353import { set_fake_worker } from "./common.ts";
354
355await set_fake_worker();
356
357wait_async_polyfill();
358
359run();
360"#
361 .trim()
362}
363
364fn worker_ts(wasm_name: &str, mem_size: &HashMap<CompactString, (u64, u64)>) -> String {
365 let mut memories = String::new();
366 for (name, (init, max)) in mem_size {
367 memories.push_str(&{
368 let str = format!(
369 r#"
370 {name}: new WebAssembly.Memory({{
371 initial:{init},
372 maximum:{max},
373 shared:true,
374 }}),"#
375 );
376 format!(" {}", str.trim())
377 });
378 }
379
380 format!(
381 r#"
382import {{ WASIFarmAnimal }} from "@oligami/browser_wasi_shim-threads";
383import {{ set_fake_worker }} from "./common.ts";
384import {{ custom_instantiate }} from "./inst.ts";
385
386await set_fake_worker();
387
388const isNode =
389 (typeof process !== "undefined" && !!process.versions?.node) ||
390 (typeof Deno !== "undefined");
391// biome-ignore lint/suspicious/noExplicitAny: <explanation>
392let _fs: any = null;
393async function fetchCompile(url) {{
394 if (isNode) {{
395 _fs = _fs || (await import("node:fs/promises"));
396 return WebAssembly.compile(await _fs.readFile(new URL(url, import.meta.url)));
397 }}
398 return fetch(url).then(WebAssembly.compileStreaming);
399}}
400
401globalThis.onmessage = async (message) => {{
402 const {{ wasi_ref }} = message.data;
403
404 const wasm_path = "./{wasm_name}.core.wasm";
405 const wasm = await fetchCompile(wasm_path);
406
407 const args = ["bin", "arg1", "arg2"];
408 const env = ["FOO=bar"];
409
410 const wasi = new WASIFarmAnimal(
411 wasi_ref,
412 args, // args
413 env, // env
414 {{
415 can_thread_spawn: true,
416 thread_spawn_worker_url: "./thread_spawn.ts",
417 thread_spawn_wasm: wasm,
418 worker_background_worker_url: "./worker_background_worker.ts",
419 share_memory: {{
420{memories}
421 }},
422 }},
423 );
424
425 await wasi.wait_worker_background_worker();
426
427 const root = await custom_instantiate(
428 wasm,
429 wasi.wasiImport,
430 wasi.wasiThreadImport,
431 wasi.get_share_memory(),
432 );
433
434 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
435 wasi.start(root as any);
436
437 globalThis.process?.exit(0);
438 globalThis.Deno?.exit(0);
439}};
440"#
441 )
442 .trim()
443 .to_string()
444}
445
446fn vite_config_ts() -> &'static str {
447 r#"
448import { defineConfig } from "vite";
449
450export default defineConfig({
451 server: {
452 headers: {
453 "Cross-Origin-Embedder-Policy": "require-corp",
454 "Cross-Origin-Opener-Policy": "same-origin",
455 },
456 },
457});
458 "#
459 .trim()
460}
461
462fn index_html() -> &'static str {
463 r#"
464<!DOCTYPE html>
465<html>
466<head>
467<meta charset="utf-8">
468
469<div id="terminal"></div>
470
471<script type="module" src="./test_run.ts"></script>
472</body>
473</html>
474 "#
475 .trim()
476}