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