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

fix(ext/node): worker_threads.receiveMessageOnPort doesn't panic #23406

Merged
merged 3 commits into from
Apr 16, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
21 changes: 21 additions & 0 deletions a.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import workerThreads from "node:worker_threads";
import { assertEquals } from "jsr:@std/assert";

const { port1, port2 } = new workerThreads.MessageChannel();

const message1 = { hello: "world" };
const message2 = { foo: "bar" };

assertEquals(workerThreads.receiveMessageOnPort(port2), undefined);
port2.start();

port1.postMessage(message1);
port1.postMessage(message2);
assertEquals(workerThreads.receiveMessageOnPort(port2), {
message: message1,
});
assertEquals(workerThreads.receiveMessageOnPort(port2), {
message: message2,
});
port1.close();
port2.close();
16 changes: 10 additions & 6 deletions ext/web/message_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use deno_core::OpState;
use deno_core::RcRef;
use deno_core::Resource;
use deno_core::ResourceId;
use futures::future::poll_fn;
use serde::Deserialize;
use serde::Serialize;
use tokio::sync::mpsc::error::TryRecvError;
Expand Down Expand Up @@ -52,16 +53,19 @@ impl MessagePort {
Ok(())
}

#[allow(clippy::await_holding_refcell_ref)] // TODO(ry) remove!
pub async fn recv(
&self,
state: Rc<RefCell<OpState>>,
) -> Result<Option<JsMessageData>, AnyError> {
let mut rx = self
.rx
.try_borrow_mut()
.map_err(|_| type_error("Port receiver is already borrowed"))?;
if let Some((data, transferables)) = rx.recv().await {
let rx = &self.rx;

let maybe_data = poll_fn(|cx| {
let mut rx = rx.borrow_mut();
rx.poll_recv(cx)
})
.await;

if let Some((data, transferables)) = maybe_data {
let js_transferables =
serialize_transferables(&mut state.borrow_mut(), transferables);
return Ok(Some(JsMessageData {
Expand Down
9 changes: 9 additions & 0 deletions foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Tinypool from "npm:tinypool";

const pool = new Tinypool({
filename: new URL("./worker.mjs", import.meta.url).href,
});
const result = await pool.run({ a: 4, b: 6 });
console.log(result); // Prints 10

await pool.destroy();
1 change: 1 addition & 0 deletions worker.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default ({ a, b }) => a + b;
Loading