Skip to content

JSPI and Asyncify #551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions crates/js-component-bindgen-component/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,20 @@ impl From<BindingsMode> for js_component_bindgen::BindingsMode {
}
}

impl From<AsyncMode> for js_component_bindgen::AsyncMode {
fn from(value: AsyncMode) -> Self {
match value {
AsyncMode::Sync => js_component_bindgen::AsyncMode::Sync,
AsyncMode::Jspi(AsyncImportsExports { imports, exports }) => {
js_component_bindgen::AsyncMode::JavaScriptPromiseIntegration { imports, exports }
}
AsyncMode::Asyncify(AsyncImportsExports { imports, exports }) => {
js_component_bindgen::AsyncMode::Asyncify { imports, exports }
}
}
}
}

struct JsComponentBindgenComponent;

export!(JsComponentBindgenComponent);
Expand All @@ -76,6 +90,7 @@ impl Guest for JsComponentBindgenComponent {
multi_memory: options.multi_memory.unwrap_or(false),
import_bindings: options.import_bindings.map(Into::into),
guest: options.guest.unwrap_or(false),
async_mode: options.async_mode.map(Into::into),
};

let js_component_bindgen::Transpiled {
Expand Down Expand Up @@ -162,6 +177,7 @@ impl Guest for JsComponentBindgenComponent {
multi_memory: false,
import_bindings: None,
guest: opts.guest.unwrap_or(false),
async_mode: opts.async_mode.map(Into::into),
};

let files = generate_types(name, resolve, world, opts).map_err(|e| e.to_string())?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,31 @@ world js-component-bindgen {
/// Whether to generate namespaced exports like `foo as "local:package/foo"`.
/// These exports can break typescript builds.
no-namespaced-exports: option<bool>,

/// Whether to generate module declarations like `declare module "local:package/foo" {...`.
guest: option<bool>,

/// Whether to output core Wasm utilizing multi-memory or to polyfill
/// this handling.
multi-memory: option<bool>,

/// Configure whether to use `async` imports or exports with
/// JavaScript Promise Integration (JSPI) or Asyncify.
async-mode: option<async-mode>,
}

record async-imports-exports {
imports: list<string>,
exports: list<string>,
}

variant async-mode {
/// default to sync mode
sync,
/// use JavaScript Promise Integration (JSPI)
jspi(async-imports-exports),
/// use Asyncify
asyncify(async-imports-exports),
}

variant wit {
Expand Down Expand Up @@ -96,6 +114,9 @@ world js-component-bindgen {
features: option<enabled-feature-set>,
/// Whether to generate module declarations like `declare module "local:package/foo" {...`.
guest: option<bool>,
/// Configure whether to use `async` imports or exports with
/// JavaScript Promise Integration (JSPI) or Asyncify.
async-mode: option<async-mode>,
}

enum export-type {
Expand Down
18 changes: 15 additions & 3 deletions crates/js-component-bindgen/src/function_bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub struct FunctionBindgen<'a> {
pub callee: &'a str,
pub callee_resource_dynamic: bool,
pub resolve: &'a Resolve,
pub is_async: bool,
}

impl FunctionBindgen<'_> {
Expand Down Expand Up @@ -1048,7 +1049,13 @@ impl Bindgen for FunctionBindgen<'_> {
Instruction::CallWasm { sig, .. } => {
let sig_results_length = sig.results.len();
self.bind_results(sig_results_length, results);
uwriteln!(self.src, "{}({});", self.callee, operands.join(", "));
let maybe_async_await = if self.is_async { "await " } else { "" };
uwriteln!(
self.src,
"{maybe_async_await}{}({});",
self.callee,
operands.join(", ")
);

if let Some(prefix) = self.tracing_prefix {
let to_result_string = self.intrinsic(Intrinsic::ToResultString);
Expand All @@ -1066,15 +1073,20 @@ impl Bindgen for FunctionBindgen<'_> {

Instruction::CallInterface { func } => {
let results_length = func.results.len();
let maybe_async_await = if self.is_async { "await " } else { "" };
let call = if self.callee_resource_dynamic {
format!(
"{}.{}({})",
"{maybe_async_await}{}.{}({})",
operands[0],
self.callee,
operands[1..].join(", ")
)
} else {
format!("{}({})", self.callee, operands.join(", "))
format!(
"{maybe_async_await}{}({})",
self.callee,
operands.join(", ")
)
};
if self.err == ErrHandling::ResultCatchHandler {
// result<_, string> allows JS error coercion only, while
Expand Down
132 changes: 132 additions & 0 deletions crates/js-component-bindgen/src/intrinsics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ use std::fmt::Write;

#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum Intrinsic {
AsyncifyAsyncInstantiate,
AsyncifySyncInstantiate,
AsyncifyWrapExport,
AsyncifyWrapImport,
Base64Compile,
ClampGuest,
ComponentError,
Expand All @@ -23,6 +27,7 @@ pub enum Intrinsic {
HasOwnProperty,
I32ToF32,
I64ToF64,
Imports,
InstantiateCore,
IsLE,
ResourceTableFlag,
Expand Down Expand Up @@ -114,6 +119,117 @@ pub fn render_intrinsics(

for i in intrinsics.iter() {
match i {
Intrinsic::AsyncifyAsyncInstantiate => output.push_str("
const asyncifyModules = [];
let asyncifyPromise;
let asyncifyResolved;
async function asyncifyInstantiate(module, imports) {
const instance = await instantiateCore(module, imports);
const memory = instance.exports.memory || (imports && imports.env && imports.env.memory);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should be a bit smarter about this memory detection, and instead make the memoryExportName an argument into the asyncifyInstantiate function - we should be able to have the context at the Rust side to know this information?

Also flipping between the imports or the exports for the memory seems a bit too loose - can you explain the cases further? Could we make it a boolean argument from the Rust side whether the import or export memory should be used?

const realloc = instance.exports.cabi_realloc || instance.exports.cabi_export_realloc;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as for the memory, this should be an argument.

if (instance.exports.asyncify_get_state && memory) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if we don't have a memory here or asyncify_get_state? Does the fallthrough work, or should we throw an error?

let address;
if (realloc) {
address = realloc(0, 0, 4, 1024);
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
} else {
address = 16;
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
}
asyncifyModules.push({ instance, memory, address });
}
return instance;
}
function asyncifyState() {
return asyncifyModules[0]?.instance.exports.asyncify_get_state();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this function take an asyncify module index?

}
function asyncifyAssertNoneState() {
let state = asyncifyState();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this assert across all asyncify module indices?

if (state !== 0) {
throw new Error(`reentrancy not supported, expected asyncify state '0' but found '${state}'`);
}
}
"),

Intrinsic::AsyncifySyncInstantiate => output.push_str("
const asyncifyModules = [];
let asyncifyPromise;
let asyncifyResolved;
function asyncifyInstantiate(module, imports) {
const instance = instantiateCore(module, imports);
const memory = instance.exports.memory || (imports && imports.env && imports.env.memory);
const realloc = instance.exports.cabi_realloc || instance.exports.cabi_export_realloc;
if (instance.exports.asyncify_get_state && memory) {
let address;
if (realloc) {
address = realloc(0, 0, 4, 1024);
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
} else {
address = 16;
new Int32Array(memory.buffer, address).set([address + 8, address + 1024]);
}
asyncifyModules.push({ instance, memory, address });
}
return instance;
}
function asyncifyState() {
return asyncifyModules[0]?.instance.exports.asyncify_get_state();
}
function asyncifyAssertNoneState() {
let state = asyncifyState();
if (state !== 0) {
throw new Error(`reentrancy not supported, expected asyncify state '0' but found '${state}'`);
}
}
"),

Intrinsic::AsyncifyWrapExport => output.push_str("
function asyncifyWrapExport(fn) {
return async (...args) => {
if (asyncifyModules.length === 0) {
throw new Error(`none of the Wasm modules were processed with wasm-opt asyncify`);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we didn't have the fall-through path on the asyncify instantiate, would we be able to turn this into a static instead of a runtime error?

}
asyncifyAssertNoneState();
let result = fn(...args);
while (asyncifyState() === 1) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It sounds like the logic here is that the first module to be instantiated is the top of the call graph.

What happens if the first module we instantiate is not the top of the asyncify call graph?

asyncifyModules.forEach(({ instance }) => {
instance.exports.asyncify_stop_unwind();
});
asyncifyResolved = await asyncifyPromise;
asyncifyPromise = undefined;
asyncifyAssertNoneState();
asyncifyModules.forEach(({ instance, address }) => {
instance.exports.asyncify_start_rewind(address);
});
result = fn(...args);
}
asyncifyAssertNoneState();
return result;
};
}
"),

Intrinsic::AsyncifyWrapImport => output.push_str("
function asyncifyWrapImport(fn) {
return (...args) => {
if (asyncifyState() === 2) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this be something like asyncifyState(instantiateIdx) where instantiateIdx is the index of the imported function being executed when sorted by the instantiation order?

asyncifyModules.forEach(({ instance }) => {
instance.exports.asyncify_stop_rewind();
});
const ret = asyncifyResolved;
asyncifyResolved = undefined;
return ret;
}
asyncifyAssertNoneState();
let value = fn(...args);
asyncifyModules.forEach(({ instance, address }) => {
instance.exports.asyncify_start_unwind(address);
});
asyncifyPromise = value;
};
}
"),

Intrinsic::Base64Compile => if !no_nodejs_compat {
output.push_str("
const base64Compile = str => WebAssembly.compile(typeof Buffer !== 'undefined' ? Buffer.from(str, 'base64') : Uint8Array.from(atob(str), b => b.charCodeAt(0)));
Expand Down Expand Up @@ -285,6 +401,8 @@ pub fn render_intrinsics(
const i64ToF64 = i => (i64ToF64I[0] = i, i64ToF64F[0]);
"),

Intrinsic::Imports => {},

Intrinsic::InstantiateCore => if !instantiation {
output.push_str("
const instantiateCore = WebAssembly.instantiate;
Expand Down Expand Up @@ -654,6 +772,14 @@ impl Intrinsic {
pub fn get_global_names() -> &'static [&'static str] {
&[
// Intrinsic list exactly as below
"asyncifyAssertNoneState",
"asyncifyInstantiate",
"asyncifyModules",
"asyncifyPromise",
"asyncifyResolved",
"asyncifyState",
"asyncifyWrapExport",
"asyncifyWrapImport",
"base64Compile",
"clampGuest",
"ComponentError",
Expand All @@ -671,6 +797,7 @@ impl Intrinsic {
"hasOwnProperty",
"i32ToF32",
"i64ToF64",
"imports",
"instantiateCore",
"isLE",
"resourceCallBorrows",
Expand Down Expand Up @@ -733,6 +860,10 @@ impl Intrinsic {

pub fn name(&self) -> &'static str {
match self {
Intrinsic::AsyncifyAsyncInstantiate => "asyncifyInstantiate",
Intrinsic::AsyncifySyncInstantiate => "asyncifyInstantiate",
Intrinsic::AsyncifyWrapExport => "asyncifyWrapExport",
Intrinsic::AsyncifyWrapImport => "asyncifyWrapImport",
Intrinsic::Base64Compile => "base64Compile",
Intrinsic::ClampGuest => "clampGuest",
Intrinsic::ComponentError => "ComponentError",
Expand All @@ -751,6 +882,7 @@ impl Intrinsic {
Intrinsic::HasOwnProperty => "hasOwnProperty",
Intrinsic::I32ToF32 => "i32ToF32",
Intrinsic::I64ToF64 => "i64ToF64",
Intrinsic::Imports => "imports",
Intrinsic::InstantiateCore => "instantiateCore",
Intrinsic::IsLE => "isLE",
Intrinsic::ResourceCallBorrows => "resourceCallBorrows",
Expand Down
2 changes: 1 addition & 1 deletion crates/js-component-bindgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub mod function_bindgen;
pub mod intrinsics;
pub mod names;
pub mod source;
pub use transpile_bindgen::{BindingsMode, InstantiationMode, TranspileOpts};
pub use transpile_bindgen::{AsyncMode, BindingsMode, InstantiationMode, TranspileOpts};

use anyhow::Result;
use transpile_bindgen::transpile_bindgen;
Expand Down
Loading
Loading