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