Skip to content
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

postMessage support #1

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open

postMessage support #1

wants to merge 5 commits into from

Conversation

Twey
Copy link
Collaborator

@Twey Twey commented Oct 9, 2024

In order to pass JavaScript objects like shared array buffers or WebAssembly modules into the thread, we need to be able to clone them across with the structuredClone algorithm, i.e. by using postMessage.

In a slightly hacky way, this PR:

  • removes the (optionality of) es_modules feature — for complicated bundler reasons it was a pain to get this working with modules, it would have required a different approach for non-modules, and module worker support is now widespread
  • allows us to use async code in the spawned thread — this has to happen here because we close() the worker as soon as the function arrives, so the worker entrypoint has to be async-aware to not close the thread too soon
  • returns the created Worker object when we spawn as part of the JoinHandle so we can post_message to it later

Module workers are now widely available, and assuming modules allows
us to use `import.meta.url` to get the shim script URL directly
rather than dynamically generating the script with a value injected.

This results in a significantly more bundler-friendly experience, as
well as letting us make use of `wasm_thread` in environments where
dynamic code execution is not available, such as WebExtensions.
This allows us to run async code on the worker thread.

A two-stage approach is used: first, a `Send` function is passed to
the thread, which is executed to obtain a non-`Send` future.  This
supports the ‘work-dealing’ pattern in which the task is first moved
to another thread, and then kept there whilst running.
Remove the spawn request functionality, since nested Web workers are
now widely supported in browsers.  This allows us to return a `Worker`
directly that we can post messages to.
@Twey Twey requested review from ma2bd and jvff October 29, 2024 19:39
scope_data: Option<Arc<ScopeData>>,
) -> std::io::Result<JoinInner<'scope, T>>
) -> std::io::Result<(Thread, JoinInner<'scope, Fut::Output>)>
Copy link

Choose a reason for hiding this comment

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

Nit: would it make sense to return the JoinHandle directly here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants