Skip to content

Commit

Permalink
Improved node examples
Browse files Browse the repository at this point in the history
  • Loading branch information
syrusakbary committed Oct 15, 2024
1 parent d0bf6a9 commit e92f7ec
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 25 deletions.
10 changes: 5 additions & 5 deletions examples/node/example.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ process.stdin.on("data", data => stdin?.write(encoder.encode(data)));
// Replace __filename with "/Users/syrusakbary/Development/wasmer-js/node_modules/.deno/[email protected]/node_modules/web-worker/node.js"

async function run() {
// await init({log: "trace"});
await init();
await init({log: "trace"});
// await init();

let cowsay = await Wasmer.fromRegistry("python/python")
let cowsay = await Wasmer.fromRegistry("cowsay")

// let instance = await cowsay.entrypoint.run({args: ["hello world"]});
let instance = await cowsay.entrypoint.run({args: []});
let instance = await cowsay.entrypoint.run({args: ["hello world"]});
// let instance = await cowsay.entrypoint.run({args: []});

await connectStreams(instance);
// const output = await instance.wait();
Expand Down
5 changes: 5 additions & 0 deletions src-js/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import load, {
ThreadPoolWorker,
initializeLogger,
setWorkerUrl,
setSDKUrl,
} from "../pkg/wasmer_js";

export type WasmerRegistryConfig = {
Expand All @@ -18,6 +19,7 @@ export type WasmerInitInput = {
module?: InitInput | Promise<InitInput>;
memory?: WebAssembly.Memory;
workerUrl?: string | URL;
sdkUrl?: string | URL;
log?: string;
} & WasmerRegistryConfig;

Expand Down Expand Up @@ -62,6 +64,9 @@ export const init = async (
if (initValue.workerUrl) {
setWorkerUrl(initValue.workerUrl.toString());
}
if (initValue.sdkUrl) {
setSDKUrl(initValue.sdkUrl.toString());
}
return output;
};

Expand Down
8 changes: 8 additions & 0 deletions src-js/node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export * from "./";
// import { Worker } from "node:worker_threads";
import Worker from "web-worker";
import { fileURLToPath } from 'node:url';
import { init as load, InitOutput, WasmerInitInput, VolumeTree } from "./";
import fs from "node:fs/promises";
import path from "node:path";
Expand All @@ -22,6 +24,12 @@ export const init = async (
const path = new URL("wasmer_js_bg.wasm", import.meta.url).pathname;
initValue.module = await fs.readFile(path);
}
if (!initValue.workerUrl) {
initValue.workerUrl = fileURLToPath(new URL("worker.mjs", import.meta.url));
}
if (!initValue.sdkUrl) {
initValue.sdkUrl = fileURLToPath(new URL("node.mjs", import.meta.url));
}
return load(initValue);
};

Expand Down
4 changes: 2 additions & 2 deletions src-js/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ let handleMessage = async data => {

globalThis.onmessage = async ev => {
if (ev.data.type == "init") {
const { memory, module, id, import_url } = ev.data;
const imported = await import(import_url);
const { memory, module, id, sdkUrl } = ev.data;
const imported = await import(sdkUrl);

// HACK: How we load our imports will change depending on how the code
// is deployed. If we are being used in "wasm-pack test" then we can
Expand Down
37 changes: 19 additions & 18 deletions src/tasks/worker_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ impl WorkerHandle {
pub(crate) fn spawn(worker_id: u32, sender: Scheduler) -> Result<Self, Error> {
let name = format!("worker-{worker_id}");

// let worker_url = WORKER_URL;
let worker_url = "/Users/syrusakbary/Development/wasmer-js/dist/worker.mjs";
let worker_url = worker_url();
let worker = web_sys::Worker::new_with_options(
&worker_url,
web_sys::WorkerOptions::new().name(&name).type_(web_sys::WorkerType::Module),
Expand Down Expand Up @@ -136,8 +135,8 @@ fn init_message(id: u32) -> Result<JsValue, JsValue> {
js_sys::Reflect::set(&msg, &JsString::from("id"), &JsValue::from(id))?;
js_sys::Reflect::set(
&msg,
&JsString::from("import_url"),
&JsValue::from(import_meta_url()),
&JsString::from("sdkUrl"),
&JsValue::from(sdk_url()),
)?;
js_sys::Reflect::set(
&msg,
Expand All @@ -148,24 +147,26 @@ fn init_message(id: u32) -> Result<JsValue, JsValue> {
Ok(msg.into())
}

/// The URL used by the bootstrapping script to import the `wasm-bindgen` glue
/// code.
fn import_meta_url() -> String {
#[wasm_bindgen]
#[allow(non_snake_case)]
extern "C" {
#[wasm_bindgen(js_namespace = ["import", "meta"], js_name = url)]
static IMPORT_META_URL: String;
}
/// The URL used by the bootstrapping script to import the Wasmer SDK.
fn sdk_url() -> String {
let sdk_url = crate::CUSTOM_SDK_URL.lock().unwrap();
let sdk_url = sdk_url.as_deref().unwrap_or(DEFAULT_WORKER_URL.as_str());

sdk_url.to_string()
}

let import_url = crate::CUSTOM_WORKER_URL.lock().unwrap();
let import_url = import_url.as_deref().unwrap_or(IMPORT_META_URL.as_str());

import_url.to_string()
/// The URL user for the worker.
fn worker_url() -> String {
let worker_url = crate::CUSTOM_WORKER_URL.lock().unwrap();
let worker_url = worker_url.as_deref().unwrap_or(DEFAULT_WORKER_URL.as_str());

worker_url.to_string()
}


/// A data URL containing our worker's bootstrap script.
static WORKER_URL: Lazy<String> = Lazy::new(|| {
static DEFAULT_WORKER_URL: Lazy<String> = Lazy::new(|| {
let script = include_str!("../../src-js/worker.js");

let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(
Expand All @@ -174,5 +175,5 @@ static WORKER_URL: Lazy<String> = Lazy::new(|| {
)
.unwrap();

web_sys::Url::create_object_url_with_blob(&blob).unwrap()
web_sys::Url::create_object_url_with_blob(&blob).unwrap_or("worker.mjs".to_string())
});

0 comments on commit e92f7ec

Please sign in to comment.