Skip to content

Truly independent web browser

LibWeb: Implement MessagePort and MessageChannel in Rust

Shannon Booth0ba91085d13f
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
index ea9b00f0578..a665d54c55e 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
@@ -83,6 +83,16 @@ impl CppEventTarget {
Self(unsafe { CppCell::from_raw(web_bindings_create_event_target()) })
}
+ /// An EventTarget of LibWeb's C++ code, which this keeps alive.
+ ///
+ /// # Safety
+ ///
+ /// `event_target` must be a live EventTarget.
+ pub(crate) unsafe fn from_raw(event_target: *mut c_void) -> Self {
+ // SAFETY: The caller passes a live EventTarget.
+ Self(unsafe { CppCell::from_raw(event_target) })
+ }
+
pub(crate) fn set_owner<T: GetTheParent>(&self, owner: Ref<T>) {
unsafe extern "C" fn get_the_parent<T: GetTheParent>(owner: *mut c_void) -> *mut c_void {
// SAFETY: LibWeb passes the owner that set_owner() gave it, which is the live cell of an object of T.
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
index 64aaf003d2a..883a68b0176 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs
@@ -231,15 +231,19 @@ pub(crate) fn implementation_if<T: Interface>(wrapper: Gc<Object>) -> Option<Ref
unsafe { T::CELL_CLASS.downcast(host_data) }
}
+/// The object of the interface that the object is a wrapper of, if it is one.
+pub(crate) fn implementation_if_wrapper<T: Interface>(object: Gc<Object>) -> Option<Ref<T>> {
+ is_host_instance_of(&object, T::wrapper_class()).then(|| implementation_of(object))
+}
+
/// An object of the interface converted from a JS value, https://webidl.spec.whatwg.org/#js-interface
pub(crate) fn to_interface<T: Interface>(vm: &Vm, value: Value) -> ThrowCompletionOr<Ref<T>> {
// 1. If V implements I, then return the IDL interface type value that represents a reference to that platform
// object.
- if value.is_object() {
- let object = value.as_object();
- if is_host_instance_of(&object, T::wrapper_class()) {
- return Ok(implementation_of(object));
- }
+ if value.is_object()
+ && let Some(object) = implementation_if_wrapper(value.as_object())
+ {
+ return Ok(object);
}
// 2. Throw a TypeError.
vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&T::NAME])
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index 9f93634cc64..7564a96b146 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -4,19 +4,22 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The C ABI through which LibWeb's C++ creates and reads the ImageData and ImageBitmap objects that it handles,
-//! which Libraries/LibWeb/HTML/ImageData.cpp and Libraries/LibWeb/HTML/ImageBitmap.cpp declare. A cell is the cell of
-//! an object of the interface that the name of the function says.
+//! The C ABI through which LibWeb's C++ creates and reads the ImageData, ImageBitmap and MessagePort objects that it
+//! handles, which Libraries/LibWeb/HTML/ImageData.cpp, Libraries/LibWeb/HTML/ImageBitmap.cpp and
+//! Libraries/LibWeb/HTML/MessagePort.cpp declare. A cell is the cell of an object of the interface that the name of
+//! the function says.
use core::ffi::c_void;
use core::ptr::NonNull;
use libgfx_rust::image_frame::ImageFrameHandle;
-use libjs_rust::api::{RawNativeFunctionResult, Value, Vm};
+use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, Value, Vm};
use super::image_bitmap::ImageBitmap;
use super::image_data::ImageData;
+use super::message_port::MessagePort;
use crate::bindings::CallContext;
+use crate::bindings::event_target::CppEventTarget;
use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};
/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.
@@ -184,3 +187,151 @@ pub unsafe extern "C" fn web_image_bitmap_frame(image_bitmap: *mut c_void) -> *c
// SAFETY: The caller passes a live cell.
unsafe { object_from_abi::<ImageBitmap>(image_bitmap) }.raw_frame()
}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `realm` a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_create(vm: *mut c_void, realm: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ cell_into_abi(MessagePort::create(vm, realm))
+}
+
+/// Entangles the two ports, https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
+///
+/// # Safety
+///
+/// `vm` must be the live VM, and `port` and `remote_port` live cells of MessagePorts.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_entangle(vm: *mut c_void, port: *mut c_void, remote_port: *mut c_void) {
+ // SAFETY: The caller passes the live VM and live cells of MessagePorts.
+ let (vm, port, remote_port) = unsafe {
+ (
+ &*vm.cast::<Vm>(),
+ cell_from_abi::<MessagePort>(port),
+ cell_from_abi::<MessagePort>(remote_port),
+ )
+ };
+ MessagePort::entangle(vm, port, remote_port);
+}
+
+/// # Safety
+///
+/// `port` must be a live cell of a MessagePort.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_entangled_port(port: *mut c_void) -> *mut c_void {
+ // SAFETY: The caller passes a live cell of a MessagePort.
+ let port = unsafe { cell_from_abi::<MessagePort>(port) };
+ port.entangled_port().map_or(core::ptr::null_mut(), cell_into_abi)
+}
+
+/// Sets the port's message event target, https://html.spec.whatwg.org/multipage/web-messaging.html#message-event-target
+///
+/// # Safety
+///
+/// `port` must be a live cell of a MessagePort, and `event_target` a live EventTarget.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_set_message_event_target(port: *mut c_void, event_target: *mut c_void) {
+ // SAFETY: The caller passes a live cell of a MessagePort and a live EventTarget.
+ let (port, event_target) = unsafe {
+ (
+ cell_from_abi::<MessagePort>(port),
+ CppEventTarget::from_raw(event_target),
+ )
+ };
+ port.set_message_event_target(event_target);
+}
+
+/// postMessage(message, transfer) on the port, https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `realm` a live realm, and `port` a live cell of a MessagePort. The message must be live,
+/// and the transfer list `count` live objects.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_post_message(
+ vm: *mut c_void,
+ realm: *mut c_void,
+ port: *mut c_void,
+ message: u64,
+ transfer: *const *mut c_void,
+ count: usize,
+) -> RawNativeFunctionResult {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ let mut cx = CallContext::new(vm, realm);
+ // SAFETY: The caller passes a live cell of a MessagePort and a live value.
+ let (port, message) = unsafe { (cell_from_abi::<MessagePort>(port), Value::from_raw(message)) };
+ let transfer_list = MarkedVec::with_capacity(vm, count);
+ for index in 0..count {
+ // SAFETY: The caller passes `count` live objects.
+ transfer_list.push(unsafe {
+ Gc::from_non_null(NonNull::new((*transfer.add(index)).cast::<Object>()).expect("C++ passes objects"))
+ });
+ }
+ let result = MessagePort::post_message(&port, &mut cx, message, transfer_list);
+ RawNativeFunctionResult::from_completion(
+ result
+ .map(|()| Value::UNDEFINED)
+ .map_err(|exception| exception.throw(&cx)),
+ )
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `port` a live cell of a MessagePort.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_enable(vm: *mut c_void, port: *mut c_void) {
+ // SAFETY: The caller passes the live VM and a live cell of a MessagePort.
+ let (vm, port) = unsafe { (&*vm.cast::<Vm>(), cell_from_abi::<MessagePort>(port)) };
+ MessagePort::enable(port, vm);
+}
+
+/// The close() method steps of the port, https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-close
+///
+/// # Safety
+///
+/// `port` must be a live cell of a MessagePort.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_close(port: *mut c_void) {
+ // SAFETY: The caller passes a live cell of a MessagePort.
+ unsafe { cell_from_abi::<MessagePort>(port) }.close_steps();
+}
+
+/// # Safety
+///
+/// `port` must be a live cell of a MessagePort.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_discard_pending_messages(port: *mut c_void) {
+ // SAFETY: The caller passes a live cell of a MessagePort.
+ unsafe { cell_from_abi::<MessagePort>(port) }.discard_pending_messages();
+}
+
+/// # Safety
+///
+/// `port` must be a live cell of a MessagePort.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_pending_outgoing_message_count(port: *mut c_void) -> usize {
+ // SAFETY: The caller passes a live cell of a MessagePort.
+ unsafe { cell_from_abi::<MessagePort>(port) }.pending_outgoing_message_count()
+}
+
+/// # Safety
+///
+/// `port` must be a live cell of a MessagePort.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_fail_next_transfer_for_testing(port: *mut c_void) {
+ // SAFETY: The caller passes a live cell of a MessagePort.
+ unsafe { cell_from_abi::<MessagePort>(port) }.fail_next_transfer_for_testing();
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `realm` a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_message_port_disentangle_ports_of_realm(vm: *mut c_void, realm: *mut c_void) {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ MessagePort::disentangle_ports_of_realm(vm, realm);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_channel.rs
new file mode 100644
index 00000000000..40f10be0ef9
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_channel.rs
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2021-2022, Andreas Kling <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! MessageChannel, https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels
+
+use libjs_rust::api::{Gc, Realm, Trace, Vm};
+
+use crate::bindings::interface::{Ref, Wrappable};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::html::message_port::MessagePort;
+
+// https://html.spec.whatwg.org/multipage/web-messaging.html#messagechannel
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MessageChannel {
+ realm: Gc<Realm>,
+ // Each MessageChannel object has an associated port 1 and an associated port 2, both MessagePort objects.
+ port1: Ref<MessagePort>,
+ port2: Ref<MessagePort>,
+}
+
+impl Wrappable for MessageChannel {
+ fn relevant_realm(&self, _: &Vm) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+}
+
+impl MessageChannel {
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messagechannel
+ pub(crate) fn construct(cx: &mut CallContext) -> WebIdlResult<Self> {
+ let vm = cx.vm();
+ let realm = cx.realm();
+
+ // 1. Set this's port 1 to a new MessagePort in this's relevant realm.
+ let port1 = MessagePort::create(vm, realm);
+
+ // 2. Set this's port 2 to a new MessagePort in this's relevant realm.
+ let port2 = MessagePort::create(vm, realm);
+
+ // 3. Entangle this's port 1 and this's port 2.
+ MessagePort::entangle(vm, port1, port2);
+
+ Ok(Self { realm, port1, port2 })
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messagechannel-port1
+ pub(crate) fn port1(&self, _: &mut CallContext) -> WebIdlResult<Ref<MessagePort>> {
+ // The port1 getter steps are to return this's port 1.
+ Ok(self.port1)
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messagechannel-port2
+ pub(crate) fn port2(&self, _: &mut CallContext) -> WebIdlResult<Ref<MessagePort>> {
+ // The port2 getter steps are to return this's port 2.
+ Ok(self.port2)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
new file mode 100644
index 00000000000..6adbcef71cc
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
@@ -0,0 +1,711 @@
+/*
+ * Copyright (c) 2021, Andreas Kling <[email protected]>
+ * Copyright (c) 2023, Andrew Kaster <[email protected]>
+ * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! MessagePort, https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports
+
+use core::cell::{Cell, RefCell};
+use core::ffi::c_void;
+use core::ptr::NonNull;
+use std::collections::VecDeque;
+
+use ak::Utf16String;
+use libjs_rust::api::{
+ CellRoot, EmbedderCell, Gc, GcRefCell, GcWeak, MarkedVec, Object, Realm, Trace, Value, Vm, is_host_instance_of,
+};
+
+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent, set_event_handler_attribute};
+use crate::bindings::interface::{
+ Interface, Ref, Wrappable, Wrapped, allocate, implementation_if_wrapper, with_temporary_execution_context,
+};
+use crate::bindings::promise::{TaskSource, queue_a_global_task};
+use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};
+use crate::bindings::transport::{MessagePortTransport, ShouldShutdown};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::html::structured_serialize::cpp::{OwnedSerializedTransferRecord, SerializedTransferRecord};
+use crate::html::structured_serialize::{structured_deserialize_with_transfer, structured_serialize_with_transfer};
+
+/// The dictionary StructuredSerializeOptions of HTML/MessagePort.idl, whose members the bindings convert.
+pub(crate) struct StructuredSerializeOptions<'vm> {
+ pub(crate) transfer: MarkedVec<'vm, Gc<Object>>,
+}
+
+// https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct MessagePort {
+ event_target: CppEventTarget,
+ realm: Gc<Realm>,
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-event-target
+ message_event_target: GcRefCell<CppEventTarget>,
+
+ // The port this port is entangled with, if that port is in this agent. A port entangled over a transport has none.
+ remote_port: Cell<Option<Ref<MessagePort>>>,
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#has-been-shipped
+ has_been_shipped: Cell<bool>,
+ has_ever_been_entangled: Cell<bool>,
+ fail_next_transfer_for_testing: Cell<bool>,
+
+ #[gc(untraced)]
+ transport: RefCell<Option<MessagePortTransport>>,
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#port-message-queue
+ // NB: Holds the messages whose tasks have not run yet. Each task takes the message at the front.
+ #[gc(untraced)]
+ port_message_queue: RefCell<VecDeque<OwnedSerializedTransferRecord>>,
+ #[gc(untraced)]
+ pending_outgoing_messages: RefCell<Vec<OwnedSerializedTransferRecord>>,
+ message_task_generation: Cell<u64>,
+ should_shutdown_on_enable: Cell<bool>,
+ enabled: Cell<bool>,
+ // The root that keeps the port alive while it has a transport and its port message queue is enabled, which
+ // update_keep_alive() creates and clears.
+ #[gc(untraced)]
+ #[cfg_attr(
+ ladybird_gc_lints,
+ expect(
+ root_in_traced_type,
+ reason = "the port roots itself only while it has a transport and its port message queue is enabled, and clears the root when either goes"
+ )
+ )]
+ keep_alive: RefCell<Option<CellRoot<EmbedderCell<Wrapped<MessagePort>>>>>,
+
+ // https://html.spec.whatwg.org/multipage/structured-data.html#detached
+ detached: Cell<bool>,
+}
+
+impl Wrappable for MessagePort {
+ fn relevant_realm(&self, _: &Vm) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+
+ const FINALIZES: bool = true;
+
+ fn finalize(port: Ref<Self>) {
+ port.disentangle();
+ }
+
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event_target.as_cpp_parent()
+ }
+}
+
+impl GetTheParent for MessagePort {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+/// The ports of the thread's agent, which disentangle_ports_of_realm() visits: references that do not keep them alive,
+/// which a collected port leaves empty. The empty ones are pruned once the list has grown to twice what was live after
+/// the last pruning.
+struct MessagePorts {
+ ports: Vec<GcWeak<EmbedderCell<Wrapped<MessagePort>>>>,
+ live_after_pruning: usize,
+}
+
+impl MessagePorts {
+ const PORTS_BEFORE_FIRST_PRUNING: usize = 128;
+
+ fn add(&mut self, vm: &Vm, port: Ref<MessagePort>) {
+ if self.ports.len() >= (2 * self.live_after_pruning).max(Self::PORTS_BEFORE_FIRST_PRUNING) {
+ self.ports.retain(|port| port.get().is_some());
+ self.live_after_pruning = self.ports.len();
+ }
+ self.ports.push(GcWeak::new(vm.heap(), port));
+ }
+}
+
+thread_local! {
+ static MESSAGE_PORTS: RefCell<MessagePorts> = const {
+ RefCell::new(MessagePorts {
+ ports: Vec::new(),
+ live_after_pruning: 0,
+ })
+ };
+}
+
+/// What the read hook of a port's transport runs with: the port, which the hook must not keep alive, and the VM.
+struct ReadHookState {
+ vm: NonNull<Vm>,
+ port: GcWeak<EmbedderCell<Wrapped<MessagePort>>>,
+}
+
+impl ReadHookState {
+ fn new(vm: &Vm, port: Ref<MessagePort>) -> Self {
+ Self {
+ vm: NonNull::from(vm),
+ port: GcWeak::new(vm.heap(), port),
+ }
+ }
+
+ /// The read hook, which runs on the owner thread when messages arrive.
+ fn read_from_transport(&self) {
+ let Some(port) = self.port.get() else {
+ return;
+ };
+ // SAFETY: The VM outlives the transport, which the port, a cell of the VM's heap, owns.
+ let vm = unsafe { self.vm.as_ref() };
+ MessagePort::read_from_transport(port, vm);
+ }
+}
+
+impl MessagePort {
+ fn new(realm: Gc<Realm>) -> Self {
+ let event_target = CppEventTarget::new();
+ Self {
+ // Unless otherwise specified, it defaults to the MessagePort object itself.
+ message_event_target: GcRefCell::new(event_target.clone()),
+ event_target,
+ realm,
+ remote_port: Cell::new(None),
+ has_been_shipped: Cell::new(false),
+ has_ever_been_entangled: Cell::new(false),
+ fail_next_transfer_for_testing: Cell::new(false),
+ transport: RefCell::new(None),
+ port_message_queue: RefCell::new(VecDeque::new()),
+ pending_outgoing_messages: RefCell::new(Vec::new()),
+ message_task_generation: Cell::new(0),
+ should_shutdown_on_enable: Cell::new(false),
+ enabled: Cell::new(false),
+ keep_alive: RefCell::new(None),
+ detached: Cell::new(false),
+ }
+ }
+
+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Self> {
+ let port = allocate(vm, |_| Self::new(realm));
+ port.event_target.set_owner(port);
+ MESSAGE_PORTS.with_borrow_mut(|message_ports| message_ports.add(vm, port));
+ port
+ }
+
+ pub(crate) fn event_target(&self) -> &CppEventTarget {
+ &self.event_target
+ }
+
+ pub(crate) fn entangled_port(&self) -> Option<Ref<Self>> {
+ self.remote_port.get()
+ }
+
+ pub(crate) fn pending_outgoing_message_count(&self) -> usize {
+ self.pending_outgoing_messages.borrow().len()
+ }
+
+ pub(crate) fn fail_next_transfer_for_testing(&self) {
+ self.fail_next_transfer_for_testing.set(true);
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-event-target
+ pub(crate) fn set_message_event_target(&self, target: CppEventTarget) {
+ self.message_event_target.replace(target);
+ }
+
+ /// Disentangles every port whose relevant realm is the realm, for a document that is destroyed.
+ pub(crate) fn disentangle_ports_of_realm(vm: &Vm, realm: Gc<Realm>) {
+ let ports = MarkedVec::new(vm);
+ MESSAGE_PORTS.with_borrow(|message_ports| {
+ for port in message_ports.ports.iter().filter_map(GcWeak::get) {
+ if port.realm == realm {
+ ports.push(port);
+ }
+ }
+ });
+ for port in ports.values().iter() {
+ port.disentangle();
+ }
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#ports-and-garbage-collection
+ // When a MessagePort object o is entangled, user agents must either act as if o's entangled MessagePort object has a
+ // strong reference to o, or as if o's relevant global object has a strong reference to o.
+ // NB: Same-agent entanglement does the former, through the remote_port edges ordinary GC traversal visits.
+ // AD-HOC: A port entangled over a transport has no edge to the port it's entangled with, so it isn't kept alive as if
+ // its relevant global object referenced it: It's kept alive only while its port message queue is enabled,
+ // since no message ever reaches script through a port whose queue isn't. So once script drops such a port,
+ // collecting it is unobservable, and disentangling it then closes its transport, which lets the port at the
+ // other end of the channel go too. Keeping every such port alive would keep the transport, and its IO thread,
+ // of every channel that script ever transferred and dropped without close() for the life of the process.
+ fn update_keep_alive(this: Ref<Self>) {
+ let mut keep_alive = this.keep_alive.borrow_mut();
+ if this.transport.borrow().is_some() && this.enabled.get() {
+ if keep_alive.is_none() {
+ *keep_alive = Some(CellRoot::new(this));
+ }
+ return;
+ }
+ *keep_alive = None;
+ }
+
+ fn is_entangled(&self) -> bool {
+ self.remote_port.get().is_some() || self.transport.borrow().is_some()
+ }
+
+ fn transfer_list_contains(transfer: &[Gc<Object>], port: Ref<Self>) -> bool {
+ transfer
+ .iter()
+ .any(|object| implementation_if_wrapper::<Self>(*object) == Some(port))
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage
+ pub(crate) fn post_message(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ message: Value,
+ transfer: MarkedVec<'_, Gc<Object>>,
+ ) -> WebIdlResult<()> {
+ // 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
+ let target_port = this.remote_port.get();
+
+ // 2. Let options be «[ "transfer" → transfer ]».
+ // 3. Run the message port post message steps providing this, targetPort, message and options.
+ Self::message_port_post_message_steps(*this, cx, target_port, message, &transfer.values())
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage-options
+ pub(crate) fn post_message_with_options(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ message: Value,
+ options: StructuredSerializeOptions<'_>,
+ ) -> WebIdlResult<()> {
+ // 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
+ let target_port = this.remote_port.get();
+
+ // 2. Run the message port post message steps providing this, targetPort, message and options.
+ Self::message_port_post_message_steps(*this, cx, target_port, message, &options.transfer.values())
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-port-post-message-steps
+ pub(crate) fn message_port_post_message_steps(
+ this: Ref<Self>,
+ cx: &CallContext,
+ target_port: Option<Ref<Self>>,
+ message: Value,
+ transfer: &[Gc<Object>],
+ ) -> WebIdlResult<()> {
+ let vm = cx.vm();
+
+ // 1. Let transfer be options["transfer"].
+
+ // 2. If transfer contains sourcePort, then throw a "DataCloneError" DOMException.
+ if Self::transfer_list_contains(transfer, this) {
+ return Err(Exception::Dom(
+ "DataCloneError",
+ Utf16String::from_ascii(b"Cannot transfer a MessagePort to itself"),
+ ));
+ }
+
+ // 3. Let doomed be false.
+ let mut doomed = false;
+
+ // 4. If targetPort is not null and transfer contains targetPort, then set doomed to true and optionally report to a developer console that the target port was posted to itself, causing the communication channel to be lost.
+ if let Some(target_port) = target_port
+ && Self::transfer_list_contains(transfer, target_port)
+ {
+ doomed = true;
+ // FIXME: Report to a developer console that the target port was posted to itself, causing the communication
+ // channel to be lost.
+ }
+
+ // 5. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
+ let serialize_with_transfer_result = structured_serialize_with_transfer(cx, message, transfer)?;
+
+ // 6. If targetPort is null, or if doomed is true, then return.
+ if doomed {
+ return Ok(());
+ }
+ let Some(target_port) = target_port else {
+ // AD-HOC: A port entangled over a transport has no targetPort in this agent, so it sends the message for the
+ // other end to add the task. A port that has never been entangled keeps the message until it is.
+ if this.transport.borrow().is_some() {
+ Self::post_port_message(this, serialize_with_transfer_result.record());
+ } else if !this.detached.get() && !this.has_been_shipped.get() && !this.has_ever_been_entangled.get() {
+ this.pending_outgoing_messages
+ .borrow_mut()
+ .push(serialize_with_transfer_result);
+ }
+ return Ok(());
+ };
+
+ // 7. Add a task that runs the following steps to the port message queue of targetPort:
+ Self::add_message_task(target_port, vm, serialize_with_transfer_result);
+
+ Ok(())
+ }
+
+ /// Adds the task that fires the message to the port message queue of the port. The event loop runs it only once the
+ /// queue is enabled.
+ fn add_message_task(this: Ref<Self>, vm: &Vm, serialize_with_transfer_result: OwnedSerializedTransferRecord) {
+ this.port_message_queue
+ .borrow_mut()
+ .push_back(serialize_with_transfer_result);
+ if this.enabled.get() {
+ Self::queue_message_task(this, vm);
+ }
+ }
+
+ /// Queues the task for the message at the front of the port message queue, which fires nothing if the queue was
+ /// emptied since.
+ fn queue_message_task(this: Ref<Self>, vm: &Vm) {
+ let message_task_generation = this.message_task_generation.get();
+ queue_a_global_task(
+ vm,
+ this.realm,
+ TaskSource::PostedMessage,
+ (this, message_task_generation),
+ |vm, (this, message_task_generation)| {
+ if message_task_generation != this.message_task_generation.get() {
+ return;
+ }
+ let Some(serialize_with_transfer_result) = this.port_message_queue.borrow_mut().pop_front() else {
+ return;
+ };
+ Self::post_message_task_steps(this, vm, serialize_with_transfer_result);
+ },
+ );
+ }
+
+ fn flush_pending_outgoing_messages(this: Ref<Self>, vm: &Vm) {
+ if let Some(remote_port) = this.remote_port.get() {
+ let pending_outgoing_messages = core::mem::take(&mut *this.pending_outgoing_messages.borrow_mut());
+ for pending_message in pending_outgoing_messages {
+ Self::add_message_task(remote_port, vm, pending_message);
+ }
+ return;
+ }
+
+ if !this
+ .transport
+ .borrow()
+ .as_ref()
+ .is_some_and(MessagePortTransport::is_open)
+ {
+ return;
+ }
+
+ let pending_outgoing_messages = core::mem::take(&mut *this.pending_outgoing_messages.borrow_mut());
+ for pending_message in &pending_outgoing_messages {
+ Self::post_port_message(this, pending_message.record());
+ }
+ }
+
+ /// Reads the messages that have arrived on the port's transport, and notes whether the other end went away.
+ fn drain_transport(&self) -> Vec<OwnedSerializedTransferRecord> {
+ let mut messages = Vec::new();
+ let transport = self.transport.borrow();
+ let Some(transport) = &*transport else {
+ return messages;
+ };
+
+ let should_shutdown = transport.read_as_many_messages_as_possible_without_blocking(&mut messages);
+
+ // The peer is gone, so nothing more arrives; the pending messages are delivered once the port is enabled.
+ if should_shutdown == ShouldShutdown::Yes {
+ self.should_shutdown_on_enable.set(true);
+ transport.close();
+ }
+ messages
+ }
+
+ fn post_port_message(this: Ref<Self>, serialize_with_transfer_result: SerializedTransferRecord) {
+ let sent = {
+ let transport = this.transport.borrow();
+ let Some(transport) = &*transport else {
+ return;
+ };
+ if !transport.is_open() {
+ return;
+ }
+ transport.send(serialize_with_transfer_result)
+ };
+ if !sent {
+ this.disentangle();
+ }
+ }
+
+ fn read_from_transport(this: Ref<Self>, vm: &Vm) {
+ for message in this.drain_transport() {
+ Self::add_message_task(this, vm, message);
+ }
+
+ if this.enabled.get() && this.should_shutdown_on_enable.replace(false) {
+ queue_a_global_task(vm, this.realm, TaskSource::PostedMessage, this, |_, this| {
+ this.close_steps();
+ });
+ }
+ }
+
+ fn post_message_task_steps(
+ this: Ref<Self>,
+ vm: &Vm,
+ serialize_with_transfer_result: OwnedSerializedTransferRecord,
+ ) {
+ // 1. Let finalTargetPort be the MessagePort in whose port message queue the task now finds itself.
+ // NOTE: This can be different from targetPort, if targetPort itself was transferred and thus all its tasks moved along with it.
+ let final_target_port = this;
+
+ // 2. Let messageEventTarget be finalTargetPort's message event target.
+ let message_event_target = final_target_port.message_event_target.borrow().clone();
+
+ // 3. Let targetRealm be finalTargetPort's relevant realm.
+ let target_realm = final_target_port.realm;
+ let cx = CallContext::new(vm, target_realm);
+
+ // 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
+ // NB: The execution context must not stay on the stack while the event is dispatched, so that a microtask
+ // checkpoint can be performed after each listener.
+ let deserialize_record = with_temporary_execution_context(target_realm, || {
+ structured_deserialize_with_transfer(&cx, serialize_with_transfer_result.record())
+ });
+ let Ok(deserialize_record) = deserialize_record else {
+ // If this throws an exception, catch it, fire an event named messageerror at messageEventTarget, using MessageEvent, and then return.
+ let event = CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[]);
+ event.set_is_trusted(true);
+ message_event_target.dispatch_event(&event);
+ return;
+ };
+
+ // 5. Let messageClone be deserializeRecord.[[Deserialized]].
+ let message_clone = deserialize_record.deserialized;
+
+ // 6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.
+ // FIXME: Use a FrozenArray
+ let new_ports = MarkedVec::new(vm);
+ for value in deserialize_record.transferred_values.values().iter() {
+ if is_host_instance_of(value, Self::wrapper_class()) {
+ new_ports.push(*value);
+ }
+ }
+
+ // 7. Fire an event named message at messageEventTarget, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.
+ let event = CppEvent::create_message_event(target_realm, "message", message_clone, &new_ports.values());
+ event.set_is_trusted(true);
+ message_event_target.dispatch_event(&event);
+ }
+
+ pub(crate) fn enable(this: Ref<Self>, vm: &Vm) {
+ if this.enabled.replace(true) {
+ return;
+ }
+ Self::update_keep_alive(this);
+
+ let queued_messages = this.port_message_queue.borrow().len();
+ for _ in 0..queued_messages {
+ Self::queue_message_task(this, vm);
+ }
+ Self::read_from_transport(this, vm);
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-start
+ pub(crate) fn start(this: &Ref<Self>, cx: &mut CallContext) -> WebIdlResult<()> {
+ // The start() method steps are to enable this's port message queue, if it is not already enabled.
+ Self::enable(*this, cx.vm());
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-close
+ pub(crate) fn close(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ self.close_steps();
+ Ok(())
+ }
+
+ /// The close() method steps, which a port whose peer went away runs once it is enabled as well.
+ pub(crate) fn close_steps(&self) {
+ // 1. Set this's [[Detached]] internal slot value to true.
+ self.detached.set(true);
+
+ // 2. If this is entangled, disentangle it.
+ if self.is_entangled() {
+ self.disentangle();
+ }
+
+ self.clear_message_queues();
+ }
+
+ /// Empties the port message queue, so that the message tasks already queued fire nothing.
+ pub(crate) fn discard_pending_messages(&self) {
+ self.port_message_queue.borrow_mut().clear();
+ self.message_task_generation.set(self.message_task_generation.get() + 1);
+ }
+
+ /// Drops every message the port holds, both ways, and forgets that its peer went away.
+ fn clear_message_queues(&self) {
+ self.discard_pending_messages();
+ self.pending_outgoing_messages.borrow_mut().clear();
+ self.should_shutdown_on_enable.set(false);
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#disentangle
+ pub(crate) fn disentangle(&self) {
+ // 1. Let otherPort be the MessagePort which initiatorPort was entangled with.
+ // 2. Assert: otherPort exists.
+ // NB: A port is also disentangled when it is collected, when its document is destroyed and when a send fails,
+ // whether it is entangled or not. A port entangled over a transport has no otherPort in this agent.
+
+ // 3. Disentangle initiatorPort and otherPort, so that they are no longer entangled or associated with each other.
+ if let Some(other_port) = self.remote_port.take() {
+ other_port.remote_port.set(None);
+ }
+ let transport = self.transport.borrow_mut().take();
+ if let Some(transport) = transport {
+ transport.close_after_sending_all_pending_messages();
+ }
+ self.keep_alive.replace(None);
+
+ self.clear_message_queues();
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
+ pub(crate) fn entangle(vm: &Vm, this: Ref<Self>, remote_port: Ref<Self>) {
+ // 1. If one of the ports is already entangled, then disentangle it and the port that it was entangled with.
+ if this.is_entangled() {
+ this.disentangle();
+ }
+ if remote_port.is_entangled() {
+ remote_port.disentangle();
+ }
+
+ // 2. Associate the two ports to be entangled, so that they form the two parts of a new channel.
+ // (There is no MessageChannel object that represents this channel.)
+ remote_port.remote_port.set(Some(this));
+ this.remote_port.set(Some(remote_port));
+ remote_port.has_ever_been_entangled.set(true);
+ this.has_ever_been_entangled.set(true);
+
+ Self::flush_pending_outgoing_messages(this, vm);
+ Self::flush_pending_outgoing_messages(remote_port, vm);
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#handler-messageeventtarget-onmessage
+ pub(crate) fn set_onmessage(this: &Ref<Self>, cx: &mut CallContext, value: Value) {
+ let port: &Self = this;
+ set_event_handler_attribute(port, "message", value);
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:handler-messageeventtarget-onmessage
+ // The first time a MessagePort object's onmessage IDL attribute is set, the port's port message queue must be enabled,
+ // as if the start() method had been called.
+ Self::enable(*this, cx.vm());
+ }
+}
+
+impl Transferable for MessagePort {
+ fn detached(&self) -> &Cell<bool> {
+ &self.detached
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-steps
+ fn transfer_steps(
+ this: &Ref<Self>,
+ cx: &mut CallContext,
+ data_holder: &mut TransferDataWriter,
+ ) -> WebIdlResult<()> {
+ let this = *this;
+ let vm = cx.vm();
+
+ // NB: The ports change only once every write to dataHolder has succeeded, so steps 1 and 3.1 run last.
+
+ // NB: A port entangled over a transport hands its transport over. Stop the transport's IO thread before draining
+ // it below, so that no message arrives between the drain and the handle going to the new owner.
+ let released_transport = this
+ .transport
+ .borrow()
+ .as_ref()
+ .map(MessagePortTransport::release_for_transfer);
+
+ // 2. Set dataHolder.[[PortMessageQueue]] to value's port message queue.
+ // NB: Drain the transport into the queue first, so that the messages it received and a pending shutdown move
+ // with the port instead of being left behind on the old transport.
+ let received_messages = this.drain_transport();
+ let mut port_message_queue = this.port_message_queue.borrow_mut();
+ port_message_queue.extend(received_messages);
+ data_holder.write_records(port_message_queue.make_contiguous())?;
+ drop(port_message_queue);
+ data_holder.write_records(&this.pending_outgoing_messages.borrow())?;
+ data_holder.write_bool(this.should_shutdown_on_enable.get())?;
+
+ // 3. If value is entangled with another port remotePort:
+ // NB: Ports in the same agent need no transport until one of them is shipped. Keep remotePort in this agent, and
+ // entangle it over a new transport with the port that the transfer-receiving steps create.
+ let (remote_port, remote_port_handle) = match this.remote_port.get() {
+ Some(remote_port) => {
+ let (transport, handle) = MessagePortTransport::create_paired();
+ (Some((remote_port, transport)), Some(handle))
+ }
+ None => (None, released_transport),
+ };
+
+ // 2. Set dataHolder.[[RemotePort]] to remotePort.
+ // 4. Otherwise, set dataHolder.[[RemotePort]] to null.
+ data_holder.write_bool(remote_port_handle.is_some())?;
+ if let Some(remote_port_handle) = remote_port_handle {
+ if this.fail_next_transfer_for_testing.replace(false) {
+ return Err(Exception::Dom(
+ "DataCloneError",
+ Utf16String::from_ascii(b"Forced MessagePort transfer failure"),
+ ));
+ }
+ data_holder.write_transport_handle(remote_port_handle)?;
+ }
+
+ // 1. Set value's has been shipped flag to true.
+ this.has_been_shipped.set(true);
+
+ if let Some((remote_port, mut transport)) = remote_port {
+ // 3.1. Set remotePort's has been shipped flag to true.
+ remote_port.has_been_shipped.set(true);
+
+ remote_port.remote_port.set(None);
+ this.remote_port.set(None);
+ transport.set_up_read_hook(ReadHookState::new(vm, remote_port), ReadHookState::read_from_transport);
+ *remote_port.transport.borrow_mut() = Some(transport);
+ Self::update_keep_alive(remote_port);
+ Self::flush_pending_outgoing_messages(remote_port, vm);
+ }
+
+ // NB: The port's transport and messages went with it.
+ *this.transport.borrow_mut() = None;
+ Self::update_keep_alive(this);
+ this.clear_message_queues();
+
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-receiving-steps
+ fn transfer_receiving_steps(cx: &mut CallContext, data_holder: &mut TransferDataReader) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+ let value = Self::create(vm, cx.realm());
+
+ // 1. Set value's has been shipped flag to true.
+ value.has_been_shipped.set(true);
+
+ // 2. Move all the tasks that are to fire message events in dataHolder.[[PortMessageQueue]] to the port message queue of value,
+ // if any, leaving value's port message queue in its initial disabled state, and, if value's relevant global object is a Window,
+ // associating the moved tasks with value's relevant global object's associated Document.
+ *value.port_message_queue.borrow_mut() = data_holder.read_records()?.into();
+ *value.pending_outgoing_messages.borrow_mut() = data_holder.read_records()?;
+ value.should_shutdown_on_enable.set(data_holder.read_bool()?);
+
+ // 3. If dataHolder.[[RemotePort]] is not null, then entangle dataHolder.[[RemotePort]] and value.
+ // (This will disentangle dataHolder.[[RemotePort]] from the original port that was transferred.)
+ if data_holder.read_bool()? {
+ let mut transport = data_holder.read_transport_handle()?.create_transport();
+ value.has_ever_been_entangled.set(true);
+
+ transport.set_up_read_hook(ReadHookState::new(vm, value), ReadHookState::read_from_transport);
+ *value.transport.borrow_mut() = Some(transport);
+ Self::update_keep_alive(value);
+
+ Self::flush_pending_outgoing_messages(value, vm);
+ }
+
+ Ok(value)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 43780106b42..161b8a7680b 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -6,7 +6,8 @@
//! The 2D canvas contexts, with the attributes and operations of each of their mixins in the module of its IDL file,
//! the objects that they draw with, the images that they and WebGL read and write the pixels of, and the operations of
-//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d.
+//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d. The message
+//! ports and channels of web messaging are here as well.
pub(crate) mod canvas_path;
pub(crate) mod color_stops;
@@ -58,6 +59,10 @@ pub(crate) mod image_bitmap;
#[cfg(not(test))]
pub(crate) mod image_data;
#[cfg(not(test))]
+pub(crate) mod message_channel;
+#[cfg(not(test))]
+pub(crate) mod message_port;
+#[cfg(not(test))]
pub(crate) mod offscreen_canvas_rendering_context2d;
#[cfg(not(test))]
pub(crate) mod path2d;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs
index f6c7d98411d..2dd1014486d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/algorithms.rs
@@ -15,8 +15,12 @@ use crate::bindings::conversions::to_unrestricted_double;
use crate::bindings::interface::{Ref, wrap};
use crate::bindings::promise::{WebIdlPromise, create_rejected_promise, create_resolved_promise};
use crate::bindings::{CallContext, WebIdlResult};
+use crate::html::message_port::MessagePort;
use crate::streams::cpp::{CppPromiseAlgorithm, CppPromiseAlgorithmWithArgument};
-use crate::streams::cross_realm_transform::{CrossRealmTransformPort, CrossRealmWritableState};
+use crate::streams::cross_realm_transform::{
+ CrossRealmWritableState, cross_realm_transform_abort_algorithm, cross_realm_transform_cancel_algorithm,
+ cross_realm_transform_close_algorithm, cross_realm_transform_pull_algorithm,
+};
use crate::streams::generic_transform_stream::RustTransformSteps;
use crate::streams::readable_stream::{
ReadableStream, readable_stream_from_iterable_cancel_algorithm, readable_stream_from_iterable_pull_algorithm,
@@ -95,7 +99,7 @@ pub(crate) enum PullAlgorithm {
/// The pullAlgorithm of InitializeTransformStream.
TransformStream(Ref<TransformStream>),
/// The pullAlgorithm of SetUpCrossRealmTransformReadable.
- CrossRealm(CrossRealmTransformPort),
+ CrossRealm(Ref<MessagePort>),
/// The pullAlgorithmWrapper of setting up a ReadableStream with byte reading support, given the pullAlgorithm that
/// C++ set the stream up with, if any.
WithByteReadingSupport(Option<CppPromiseAlgorithm>),
@@ -124,7 +128,7 @@ impl PullAlgorithm {
}
}
Self::TransformStream(stream) => transform_stream_default_source_pull_algorithm(cx, *stream),
- Self::CrossRealm(port) => port.pull_algorithm(cx),
+ Self::CrossRealm(port) => cross_realm_transform_pull_algorithm(cx, *port),
Self::WithByteReadingSupport(pull_algorithm) => {
// 1. Let result be the result of running pullAlgorithm, if pullAlgorithm was given, or null otherwise.
// If this throws an exception e, return a promise rejected with e.
@@ -168,7 +172,7 @@ pub(crate) enum CancelAlgorithm {
/// The cancelAlgorithm of InitializeTransformStream.
TransformStream(Ref<TransformStream>),
/// The cancelAlgorithm of SetUpCrossRealmTransformReadable.
- CrossRealm(CrossRealmTransformPort),
+ CrossRealm(Ref<MessagePort>),
/// The cancelAlgorithmWrapper of setting up a ReadableStream with byte reading support or a TransformStream, given
/// the cancelAlgorithm that C++ set the stream up with, if any.
Wrapper(Option<CppPromiseAlgorithmWithArgument>),
@@ -198,7 +202,7 @@ impl CancelAlgorithm {
}
}
Self::TransformStream(stream) => transform_stream_default_source_cancel_algorithm(cx, *stream, reason),
- Self::CrossRealm(port) => port.cancel_algorithm(cx, reason),
+ Self::CrossRealm(port) => cross_realm_transform_cancel_algorithm(cx, *port, reason),
Self::Wrapper(cancel_algorithm) => {
// 1. Let result be the result of running cancelAlgorithm given reason, if cancelAlgorithm was given,
// or null otherwise. If this throws an exception e, return a promise rejected with e.
@@ -289,7 +293,7 @@ pub(crate) enum CloseAlgorithm {
/// The closeAlgorithm of InitializeTransformStream.
TransformStream(Ref<TransformStream>),
/// The closeAlgorithm of SetUpCrossRealmTransformWritable.
- CrossRealm(CrossRealmTransformPort),
+ CrossRealm(Ref<MessagePort>),
}
impl CloseAlgorithm {
@@ -299,7 +303,7 @@ impl CloseAlgorithm {
Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),
Self::Callback { close, underlying_sink } => close.invoke(Some(*underlying_sink), &[]),
Self::TransformStream(stream) => transform_stream_default_sink_close_algorithm(cx, *stream),
- Self::CrossRealm(port) => port.close_algorithm(cx),
+ Self::CrossRealm(port) => cross_realm_transform_close_algorithm(cx, *port),
}
}
}
@@ -319,7 +323,7 @@ pub(crate) enum AbortAlgorithm {
/// The abortAlgorithm of InitializeTransformStream.
TransformStream(Ref<TransformStream>),
/// The abortAlgorithm of SetUpCrossRealmTransformWritable.
- CrossRealm(CrossRealmTransformPort),
+ CrossRealm(Ref<MessagePort>),
}
impl AbortAlgorithm {
@@ -329,7 +333,7 @@ impl AbortAlgorithm {
Self::ReturnsResolvedUndefined => resolved_with_undefined(cx),
Self::Callback { abort, underlying_sink } => abort.invoke(Some(*underlying_sink), &[reason]),
Self::TransformStream(stream) => transform_stream_default_sink_abort_algorithm(cx, *stream, reason),
- Self::CrossRealm(port) => port.abort_algorithm(cx, reason),
+ Self::CrossRealm(port) => cross_realm_transform_abort_algorithm(cx, *port, reason),
}
}
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs
index a9829cb9dd2..891b3253f2f 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/cross_realm_transform.rs
@@ -4,27 +4,24 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Transferable streams, https://streams.spec.whatwg.org/#transferrable-streams, which LibWeb's C++ MessagePort
-//! carries.
+//! Transferable streams, https://streams.spec.whatwg.org/#transferrable-streams, which MessagePorts carry.
use core::cell::Cell;
-use core::ffi::c_void;
-use core::ptr::NonNull;
use libjs_rust::api::{
- EmbedderCell, EmbedderClass, EmbedderValue, Gc, Must, NativeFunction, Object, PrimitiveString, PropertyKey,
- RawNativeFunctionResult, Realm, Trace, Value, Vm,
+ EmbedderCell, EmbedderClass, EmbedderValue, Gc, Must, NativeFunction, Object, PrimitiveString, PropertyKey, Realm,
+ Trace, Value, Vm,
};
-use crate::bindings::cpp_cell::CppCell;
use crate::bindings::event_target::message_event_data;
-use crate::bindings::interface::{Ref, allocate};
+use crate::bindings::interface::{Ref, allocate, implementation_of, wrap};
use crate::bindings::promise::{
NativeSteps, WebIdlPromise, create_promise, create_rejected_promise_from_exception, create_resolved_promise,
exception_value, reject_promise_with_exception, resolve_promise, upon_fulfillment,
};
use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter};
use crate::bindings::{CallContext, Exception, MustNotThrow, WebIdlResult};
+use crate::html::message_port::MessagePort;
use crate::streams::algorithms::{
AbortAlgorithm, CancelAlgorithm, CloseAlgorithm, PullAlgorithm, SizeAlgorithm, StartAlgorithm, WriteAlgorithm,
};
@@ -40,229 +37,173 @@ use crate::streams::writable_stream_default_controller::{
writable_stream_default_controller_error_if_needed,
};
-unsafe extern "C" {
- /// Two new MessagePorts in the realm, entangled with each other.
- fn web_streams_create_entangled_ports(realm: *mut c_void, port1: &mut *mut c_void, port2: &mut *mut c_void);
-
- /// Adds handlers for the port's message and messageerror events that call the functions, native functions of the
- /// realm, with the event.
- fn web_streams_message_port_add_handlers(
- realm: *mut c_void,
- port: *mut c_void,
- on_message: *mut c_void,
- on_message_error: *mut c_void,
- );
-
- /// Runs the message port post message steps providing the port with which the port is entangled, if any, the
- /// message and «[ "transfer" → « » ]».
- fn web_streams_message_port_post_message(
- realm: *mut c_void,
- port: *mut c_void,
- message: u64,
- ) -> RawNativeFunctionResult;
-
- /// Disentangles the port.
- fn web_streams_message_port_disentangle(port: *mut c_void);
-
- /// Enables the port's port message queue.
- fn web_streams_message_port_enable(port: *mut c_void);
-
- /// The MessagePort that a wrapper wraps.
- fn web_streams_message_port_from_object(object: *mut c_void) -> *mut c_void;
-
- /// The wrapper of the MessagePort in the realm.
- fn web_streams_message_port_wrapper(realm: *mut c_void, port: *mut c_void) -> *mut c_void;
-}
-
/// The steps of a port's message event handler, given the state of the transform and the data of the message.
type MessageSteps<C> = fn(&CallContext, C, Value);
/// The steps of a port's messageerror event handler, given the state of the transform.
type MessageErrorSteps<C> = fn(&CallContext, C);
-/// A MessagePort that a cross-realm transform posts its messages to.
-#[derive(Clone, Trace)]
-#[gc(crate = libjs_rust)]
-pub(crate) struct CrossRealmTransformPort(CppCell);
-
-impl CrossRealmTransformPort {
- fn as_ptr(&self) -> *mut c_void {
- self.0.as_ptr()
- }
-
- // https://html.spec.whatwg.org/multipage/web-messaging.html#disentangle
- fn disentangle(&self) {
- // SAFETY: The port is live.
- unsafe { web_streams_message_port_disentangle(self.as_ptr()) };
- }
+/// Adds the handlers for the port's message and messageerror events, which are given the state.
+fn add_handlers<C: Trace + Copy + 'static>(
+ cx: &CallContext,
+ port: Ref<MessagePort>,
+ state: C,
+ on_message: MessageSteps<C>,
+ on_message_error: MessageErrorSteps<C>,
+) {
+ let realm = cx.realm();
+ let on_message = NativeFunction::create(
+ cx.vm(),
+ NativeSteps {
+ captures: (state, realm),
+ steps: on_message,
+ },
+ |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageSteps<C>>| {
+ let (state, realm) = function.captures;
+ // NB: The port's message event handler is called with a MessageEvent.
+ let data = message_event_data(vm.argument(0));
+ (function.steps)(&CallContext::new(vm, realm), state, data);
+ Ok(Value::UNDEFINED)
+ },
+ 1,
+ &PropertyKey::from_utf8(""),
+ Some(realm),
+ None,
+ None,
+ );
+ let on_message_error = NativeFunction::create(
+ cx.vm(),
+ NativeSteps {
+ captures: (state, realm),
+ steps: on_message_error,
+ },
+ |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageErrorSteps<C>>| {
+ let (state, realm) = function.captures;
+ (function.steps)(&CallContext::new(vm, realm), state);
+ Ok(Value::UNDEFINED)
+ },
+ 1,
+ &PropertyKey::from_utf8(""),
+ Some(realm),
+ None,
+ None,
+ );
+ port.event_target()
+ .add_event_listener(cx, "message", on_message.as_function_object_gc());
+ port.event_target()
+ .add_event_listener(cx, "messageerror", on_message_error.as_function_object_gc());
+}
- // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-start
- fn enable(&self) {
- // SAFETY: The port is live.
- unsafe { web_streams_message_port_enable(self.as_ptr()) };
- }
+// https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessage
+fn pack_and_post_message(cx: &CallContext, port: Ref<MessagePort>, r#type: &str, value: Value) -> WebIdlResult<()> {
+ let vm = cx.vm();
- /// Adds the handlers for the port's message and messageerror events, which are given the state.
- fn add_handlers<C: Trace + Copy + 'static>(
- &self,
- cx: &CallContext,
- state: C,
- on_message: MessageSteps<C>,
- on_message_error: MessageErrorSteps<C>,
- ) {
- let realm = cx.realm();
- let on_message = NativeFunction::create(
- cx.vm(),
- NativeSteps {
- captures: (state, realm),
- steps: on_message,
- },
- |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageSteps<C>>| {
- let (state, realm) = function.captures;
- // NB: The port's message event handler is called with a MessageEvent.
- let data = message_event_data(vm.argument(0));
- (function.steps)(&CallContext::new(vm, realm), state, data);
- Ok(Value::UNDEFINED)
- },
- 1,
- &PropertyKey::from_utf8(""),
- Some(realm),
- None,
- None,
- );
- let on_message_error = NativeFunction::create(
- cx.vm(),
- NativeSteps {
- captures: (state, realm),
- steps: on_message_error,
- },
- |vm: &Vm, function: &NativeSteps<(C, Gc<Realm>), MessageErrorSteps<C>>| {
- let (state, realm) = function.captures;
- (function.steps)(&CallContext::new(vm, realm), state);
- Ok(Value::UNDEFINED)
- },
- 1,
- &PropertyKey::from_utf8(""),
- Some(realm),
- None,
- None,
- );
- // SAFETY: The realm, the port and the functions are live.
- unsafe {
- web_streams_message_port_add_handlers(
- realm.as_ptr().cast(),
- self.as_ptr(),
- on_message.as_ptr().cast(),
- on_message_error.as_ptr().cast(),
- );
- }
- }
+ // 1. Let message be OrdinaryObjectCreate(null).
+ let message = Object::create(vm, cx.realm(), None);
- // https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessage
- fn pack_and_post_message(&self, cx: &CallContext, r#type: &str, value: Value) -> WebIdlResult<()> {
- let vm = cx.vm();
-
- // 1. Let message be OrdinaryObjectCreate(null).
- let message = Object::create(vm, cx.realm(), None);
-
- // 2. Perform ! CreateDataProperty(message, "type", type).
- let r#type = Value::from_string(PrimitiveString::create_from_ascii(vm, r#type.as_bytes()));
- message
- .create_data_property(vm, &vm.names.type_, r#type, None, None)
- .must();
-
- // 3. Perform ! CreateDataProperty(message, "value", value).
- message
- .create_data_property(vm, &vm.names.value, value, None, None)
- .must();
-
- // 4. Let targetPort be the port with which port is entangled, if any; otherwise let it be null.
- // 5. Let options be «[ "transfer" → « » ]».
- // 6. Run the message port post message steps providing targetPort, message, and options.
- // SAFETY: The realm, the port and the message are live.
- unsafe {
- web_streams_message_port_post_message(
- cx.realm().as_ptr().cast(),
- self.as_ptr(),
- Value::from_object(message).to_raw(),
- )
- }
- .into_completion()?;
- Ok(())
- }
+ // 2. Perform ! CreateDataProperty(message, "type", type).
+ let r#type = Value::from_string(PrimitiveString::create_from_ascii(vm, r#type.as_bytes()));
+ message
+ .create_data_property(vm, &vm.names.type_, r#type, None, None)
+ .must();
- // https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessagehandlingerror
- fn pack_and_post_message_handling_error(&self, cx: &CallContext, r#type: &str, value: Value) -> WebIdlResult<()> {
- // 1. Let result be PackAndPostMessage(port, type, value).
- let result = self.pack_and_post_message(cx, r#type, value);
+ // 3. Perform ! CreateDataProperty(message, "value", value).
+ message
+ .create_data_property(vm, &vm.names.value, value, None, None)
+ .must();
- // 2. If result is an abrupt completion,
- let Err(exception) = result else {
- // 3. Return result as a completion record.
- return Ok(());
- };
- let error = exception_value(cx.vm(), cx.realm(), exception);
+ // 4. Let targetPort be the port with which port is entangled, if any; otherwise let it be null.
+ let target_port = port.entangled_port();
- // 1. Perform ! CrossRealmTransformSendError(port, result.[[Value]]).
- self.cross_realm_transform_send_error(cx, error);
+ // 5. Let options be «[ "transfer" → « » ]».
+ // 6. Run the message port post message steps providing targetPort, message, and options.
+ MessagePort::message_port_post_message_steps(port, cx, target_port, Value::from_object(message), &[])
+}
+// https://streams.spec.whatwg.org/#abstract-opdef-packandpostmessagehandlingerror
+fn pack_and_post_message_handling_error(
+ cx: &CallContext,
+ port: Ref<MessagePort>,
+ r#type: &str,
+ value: Value,
+) -> WebIdlResult<()> {
+ // 1. Let result be PackAndPostMessage(port, type, value).
+ let result = pack_and_post_message(cx, port, r#type, value);
+
+ // 2. If result is an abrupt completion,
+ let Err(exception) = result else {
// 3. Return result as a completion record.
- Err(Exception::Thrown(libjs_rust::api::Throw::new(error)))
- }
-
- // https://streams.spec.whatwg.org/#abstract-opdef-crossrealmtransformsenderror
- fn cross_realm_transform_send_error(&self, cx: &CallContext, error: Value) {
- // 1. Perform PackAndPostMessage(port, "error", error), discarding the result.
- let _ = self.pack_and_post_message(cx, "error", error);
- }
+ return Ok(());
+ };
+ let error = exception_value(cx.vm(), cx.realm(), exception);
- /// The pullAlgorithm of SetUpCrossRealmTransformReadable.
- pub(crate) fn pull_algorithm(&self, cx: &CallContext) -> WebIdlPromise {
- // 1. Perform ! PackAndPostMessage(port, "pull", undefined).
- self.pack_and_post_message(cx, "pull", Value::UNDEFINED).must();
+ // 1. Perform ! CrossRealmTransformSendError(port, result.[[Value]]).
+ cross_realm_transform_send_error(cx, port, error);
- // 2. Return a promise resolved with undefined.
- create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)
- }
+ // 3. Return result as a completion record.
+ Err(Exception::Thrown(libjs_rust::api::Throw::new(error)))
+}
- /// The cancelAlgorithm of SetUpCrossRealmTransformReadable, and the abortAlgorithm of
- /// SetUpCrossRealmTransformWritable.
- pub(crate) fn cancel_algorithm(&self, cx: &CallContext, reason: Value) -> WebIdlPromise {
- // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).
- let result = self.pack_and_post_message_handling_error(cx, "error", reason);
+// https://streams.spec.whatwg.org/#abstract-opdef-crossrealmtransformsenderror
+fn cross_realm_transform_send_error(cx: &CallContext, port: Ref<MessagePort>, error: Value) {
+ // 1. Perform PackAndPostMessage(port, "error", error), discarding the result.
+ let _ = pack_and_post_message(cx, port, "error", error);
+}
- // 2. Disentangle port.
- self.disentangle();
+/// The pullAlgorithm of SetUpCrossRealmTransformReadable.
+pub(crate) fn cross_realm_transform_pull_algorithm(cx: &CallContext, port: Ref<MessagePort>) -> WebIdlPromise {
+ // 1. Perform ! PackAndPostMessage(port, "pull", undefined).
+ pack_and_post_message(cx, port, "pull", Value::UNDEFINED).must();
- // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].
- if let Err(exception) = result {
- return create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception);
- }
+ // 2. Return a promise resolved with undefined.
+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)
+}
- // 4. Otherwise, return a promise resolved with undefined.
- create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)
+/// The cancelAlgorithm of SetUpCrossRealmTransformReadable, and the abortAlgorithm of
+/// SetUpCrossRealmTransformWritable.
+pub(crate) fn cross_realm_transform_cancel_algorithm(
+ cx: &CallContext,
+ port: Ref<MessagePort>,
+ reason: Value,
+) -> WebIdlPromise {
+ // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).
+ let result = pack_and_post_message_handling_error(cx, port, "error", reason);
+
+ // 2. Disentangle port.
+ port.disentangle();
+
+ // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].
+ if let Err(exception) = result {
+ return create_rejected_promise_from_exception(cx.vm(), cx.realm(), exception);
}
- /// The closeAlgorithm of SetUpCrossRealmTransformWritable.
- pub(crate) fn close_algorithm(&self, cx: &CallContext) -> WebIdlPromise {
- // 1. Perform ! PackAndPostMessage(port, "close", undefined).
- self.pack_and_post_message(cx, "close", Value::UNDEFINED).must();
+ // 4. Otherwise, return a promise resolved with undefined.
+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)
+}
- // 2. Disentangle port.
- self.disentangle();
+/// The closeAlgorithm of SetUpCrossRealmTransformWritable.
+pub(crate) fn cross_realm_transform_close_algorithm(cx: &CallContext, port: Ref<MessagePort>) -> WebIdlPromise {
+ // 1. Perform ! PackAndPostMessage(port, "close", undefined).
+ pack_and_post_message(cx, port, "close", Value::UNDEFINED).must();
- // 3. Return a promise resolved with undefined.
- create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)
- }
+ // 2. Disentangle port.
+ port.disentangle();
- /// The abortAlgorithm of SetUpCrossRealmTransformWritable.
- pub(crate) fn abort_algorithm(&self, cx: &CallContext, reason: Value) -> WebIdlPromise {
- // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).
- // 2. Disentangle port.
- // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].
- // 4. Otherwise, return a promise resolved with undefined.
- self.cancel_algorithm(cx, reason)
- }
+ // 3. Return a promise resolved with undefined.
+ create_resolved_promise(cx.vm(), cx.realm(), Value::UNDEFINED)
+}
+
+/// The abortAlgorithm of SetUpCrossRealmTransformWritable.
+pub(crate) fn cross_realm_transform_abort_algorithm(
+ cx: &CallContext,
+ port: Ref<MessagePort>,
+ reason: Value,
+) -> WebIdlPromise {
+ // 1. Let result be PackAndPostMessageHandlingError(port, "error", reason).
+ // 2. Disentangle port.
+ // 3. If result is an abrupt completion, return a promise rejected with result.[[Value]].
+ // 4. Otherwise, return a promise resolved with undefined.
+ cross_realm_transform_cancel_algorithm(cx, port, reason)
}
/// The type and the value of a message that a cross-realm transform received, ! Get(data, "type") and
@@ -299,26 +240,15 @@ fn data_clone_error(cx: &CallContext) -> Value {
#[derive(Clone, Copy, Trace)]
#[gc(crate = libjs_rust)]
struct ReadableHandlerState {
- port: Gc<EmbedderCell<PortCell>>,
+ port: Ref<MessagePort>,
controller: Ref<ReadableStreamDefaultController>,
}
-/// A cell that holds a MessagePort, which the handlers of its events capture.
-#[derive(Trace)]
-#[gc(crate = libjs_rust)]
-struct PortCell(CrossRealmTransformPort);
-
-static PORT_CELL_CLASS: EmbedderClass<PortCell> = EmbedderClass::new("CrossRealmTransformPort");
-
-impl EmbedderValue for PortCell {
- const CLASS: &'static EmbedderClass<Self> = &PORT_CELL_CLASS;
-}
-
// https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable
pub(crate) fn set_up_cross_realm_transform_readable(
cx: &CallContext,
stream: Ref<ReadableStream>,
- port: CrossRealmTransformPort,
+ port: Ref<MessagePort>,
) {
stream.set_realm(cx.realm());
@@ -327,14 +257,11 @@ pub(crate) fn set_up_cross_realm_transform_readable(
// 2. Let controller be a new ReadableStreamDefaultController.
let controller = allocate(cx.vm(), ReadableStreamDefaultController::new);
- let state = ReadableHandlerState {
- port: PORT_CELL_CLASS.allocate(cx.vm(), |_| PortCell(port.clone())),
- controller,
- };
+ let state = ReadableHandlerState { port, controller };
// 3. Add a handler for port’s message event with the following steps:
fn on_message(cx: &CallContext, state: ReadableHandlerState, data: Value) {
- let port = &state.port.0;
+ let port = state.port;
let controller = state.controller;
// 1. Let data be the data of the message.
@@ -370,13 +297,13 @@ pub(crate) fn set_up_cross_realm_transform_readable(
// 4. Add a handler for port’s messageerror event with the following steps:
fn on_message_error(cx: &CallContext, state: ReadableHandlerState) {
- let port = &state.port.0;
+ let port = state.port;
// 1. Let error be a new "DataCloneError" DOMException.
let error = data_clone_error(cx);
// 2. Perform ! CrossRealmTransformSendError(port, error).
- port.cross_realm_transform_send_error(cx, error);
+ cross_realm_transform_send_error(cx, port, error);
// 3. Perform ! ReadableStreamDefaultControllerError(controller, error).
readable_stream_default_controller_error(cx, state.controller, error);
@@ -384,16 +311,16 @@ pub(crate) fn set_up_cross_realm_transform_readable(
// 4. Disentangle port.
port.disentangle();
}
- port.add_handlers(cx, state, on_message, on_message_error);
+ add_handlers(cx, port, state, on_message, on_message_error);
// 5. Enable port’s port message queue.
- port.enable();
+ MessagePort::enable(port, cx.vm());
// 6. Let startAlgorithm be an algorithm that returns undefined.
let start_algorithm = StartAlgorithm::ReturnsUndefined;
// 7. Let pullAlgorithm be the following steps:
- let pull_algorithm = PullAlgorithm::CrossRealm(port.clone());
+ let pull_algorithm = PullAlgorithm::CrossRealm(port);
// 8. Let cancelAlgorithm be the following steps, taking a reason argument:
let cancel_algorithm = CancelAlgorithm::CrossRealm(port);
@@ -420,7 +347,7 @@ pub(crate) fn set_up_cross_realm_transform_readable(
#[derive(Trace)]
#[gc(crate = libjs_rust)]
pub(crate) struct CrossRealmWritableState {
- port: CrossRealmTransformPort,
+ port: Ref<MessagePort>,
controller: Ref<WritableStreamDefaultController>,
// backpressurePromise
backpressure_promise: Cell<Option<WebIdlPromise>>,
@@ -461,7 +388,7 @@ impl CrossRealmWritableState {
this.backpressure_promise.set(Some(create_promise(cx.vm(), cx.realm())));
// 2. Let result be PackAndPostMessageHandlingError(port, "chunk", chunk).
- let result = this.port.pack_and_post_message_handling_error(cx, "chunk", chunk);
+ let result = pack_and_post_message_handling_error(cx, this.port, "chunk", chunk);
match result {
// 3. If result is an abrupt completion,
@@ -496,7 +423,7 @@ impl CrossRealmWritableState {
pub(crate) fn set_up_cross_realm_transform_writable(
cx: &CallContext,
stream: Ref<WritableStream>,
- port: CrossRealmTransformPort,
+ port: Ref<MessagePort>,
) {
// 1. Perform ! InitializeWritableStream(stream).
initialize_writable_stream(cx.vm(), stream);
@@ -506,7 +433,7 @@ pub(crate) fn set_up_cross_realm_transform_writable(
// 3. Let backpressurePromise be a new promise.
let state = CROSS_REALM_WRITABLE_STATE_CLASS.allocate(cx.vm(), |_| CrossRealmWritableState {
- port: port.clone(),
+ port,
controller,
backpressure_promise: Cell::new(Some(create_promise(cx.vm(), cx.realm()))),
});
@@ -542,7 +469,7 @@ pub(crate) fn set_up_cross_realm_transform_writable(
let error = data_clone_error(cx);
// 2. Perform ! CrossRealmTransformSendError(port, error).
- state.port.cross_realm_transform_send_error(cx, error);
+ cross_realm_transform_send_error(cx, state.port, error);
// 3. Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, error).
writable_stream_default_controller_error_if_needed(cx, state.controller, error);
@@ -550,10 +477,10 @@ pub(crate) fn set_up_cross_realm_transform_writable(
// 4. Disentangle port.
state.port.disentangle();
}
- port.add_handlers(cx, state, on_message, on_message_error);
+ add_handlers(cx, port, state, on_message, on_message_error);
// 6. Enable port’s port message queue.
- port.enable();
+ MessagePort::enable(port, cx.vm());
// 7. Let startAlgorithm be an algorithm that returns undefined.
let start_algorithm = StartAlgorithm::ReturnsUndefined;
@@ -562,7 +489,7 @@ pub(crate) fn set_up_cross_realm_transform_writable(
let write_algorithm = WriteAlgorithm::CrossRealm(state);
// 9. Let closeAlgorithm be the following steps:
- let close_algorithm = CloseAlgorithm::CrossRealm(port.clone());
+ let close_algorithm = CloseAlgorithm::CrossRealm(port);
// 10. Let abortAlgorithm be the following steps, taking a reason argument:
let abort_algorithm = AbortAlgorithm::CrossRealm(port);
@@ -587,45 +514,22 @@ pub(crate) fn set_up_cross_realm_transform_writable(
}
/// Two new MessagePorts in the current realm, entangled with each other.
-pub(crate) fn create_entangled_ports(cx: &CallContext) -> (CrossRealmTransformPort, CrossRealmTransformPort) {
- let mut port1 = core::ptr::null_mut();
- let mut port2 = core::ptr::null_mut();
- // SAFETY: The realm is live, and LibWeb returns two live ports.
- unsafe {
- web_streams_create_entangled_ports(cx.realm().as_ptr().cast(), &mut port1, &mut port2);
- (
- CrossRealmTransformPort(CppCell::from_raw(port1)),
- CrossRealmTransformPort(CppCell::from_raw(port2)),
- )
- }
+pub(crate) fn create_entangled_ports(cx: &CallContext) -> (Ref<MessagePort>, Ref<MessagePort>) {
+ let port1 = MessagePort::create(cx.vm(), cx.realm());
+ let port2 = MessagePort::create(cx.vm(), cx.realm());
+ MessagePort::entangle(cx.vm(), port1, port2);
+ (port1, port2)
}
/// Sets the data holder to ! StructuredSerializeWithTransfer(port, « port »).
-pub(crate) fn serialize_message_port(
- cx: &CallContext,
- data_holder: &mut TransferDataWriter,
- port: &CrossRealmTransformPort,
-) {
- // SAFETY: The realm and the port are live, and LibWeb returns the wrapper of the port.
- let wrapper = unsafe { web_streams_message_port_wrapper(cx.realm().as_ptr().cast(), port.as_ptr()) };
- let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns a wrapper");
- // SAFETY: LibWeb returns a live wrapper.
- let wrapper = unsafe { Gc::from_non_null(wrapper) };
+pub(crate) fn serialize_message_port(cx: &CallContext, data_holder: &mut TransferDataWriter, port: Ref<MessagePort>) {
data_holder
- .write_transferred_value(cx, Value::from_object(wrapper))
+ .write_transferred_value(cx, Value::from_object(wrap(cx, port)))
.must();
}
/// The MessagePort of ! StructuredDeserializeWithTransfer(dataHolder.[[port]], the current Realm).
-pub(crate) fn deserialize_message_port(
- cx: &CallContext,
- data_holder: &mut TransferDataReader,
-) -> CrossRealmTransformPort {
+pub(crate) fn deserialize_message_port(cx: &CallContext, data_holder: &mut TransferDataReader) -> Ref<MessagePort> {
let deserialized = data_holder.read_transferred_value(cx).must();
- assert!(deserialized.is_object());
- // SAFETY: The object is live, and LibWeb returns the MessagePort that it wraps.
- unsafe {
- let port = web_streams_message_port_from_object(deserialized.as_object().as_ptr().cast());
- CrossRealmTransformPort(CppCell::from_raw(port))
- }
+ implementation_of(deserialized.as_object())
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs
index 176c1e644b8..45c180a2759 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/readable_stream.rs
@@ -586,7 +586,7 @@ impl Transferable for ReadableStream {
mark_promise_as_handled(cx.vm(), promise);
// 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).
- serialize_message_port(cx, data_holder, &port2);
+ serialize_message_port(cx, data_holder, port2);
Ok(())
})
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs
index f6ee52f89f6..f4ebf2f5a09 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/streams/writable_stream.rs
@@ -285,7 +285,7 @@ impl Transferable for WritableStream {
mark_promise_as_handled(cx.vm(), promise);
// 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).
- serialize_message_port(cx, data_holder, &port2);
+ serialize_message_port(cx, data_holder, port2);
Ok(())
})
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
index 9da6d319399..8dee72a5301 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs
@@ -45,7 +45,7 @@ use std::sync::Arc;
use libjs_rust::api::{
EmbedderCell, EmbedderClass, EmbedderValue, ErrorKind, ErrorType, Gc, GcWeak, Realm, Throw, ThrowCompletionOr,
- Trace, Value, Visitor, Vm, is_host_instance_of,
+ Trace, Value, Visitor, Vm,
};
use libwasm_engine::Module as CoreModule;
use libwasm_engine::runtime::entity::{Entity, Handle};
@@ -54,7 +54,7 @@ use libwasm_engine::runtime::{InstantiationError, Store, TagAddress, Trap, Value
use libwasm_engine::types::FuncType;
use crate::bindings::conversions::BufferSource;
-use crate::bindings::interface::{Interface, Ref, Wrapped, implementation_of};
+use crate::bindings::interface::{Interface, Ref, Wrapped, implementation_if_wrapper};
use crate::web_assembly::errors::{WebAssemblyError, throw_webassembly_error};
use crate::web_assembly::exception::Exception;
use crate::web_assembly::memory::{Memory, refresh_the_memory_buffer};
@@ -319,10 +319,10 @@ pub(crate) fn set_host_object<T>(cell: *mut u8, object: Gc<T>) {
/// The object of the interface that the value is the wrapper of, if it is one.
pub(crate) fn implementation_of_value<T: Interface>(value: Value) -> Option<Ref<T>> {
- if !value.is_object() || !is_host_instance_of(&value.as_object(), T::wrapper_class()) {
+ if !value.is_object() {
return None;
}
- Some(implementation_of::<T>(value.as_object()))
+ implementation_if_wrapper(value.as_object())
}
/// A copy of the bytes held by a buffer, which the algorithms compile: their stableBytes.
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index b359171c75c..f3354694ac0 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -575,7 +575,6 @@ set(SOURCES
HTML/Location.cpp
HTML/MediaError.cpp
HTML/MediaTrackBase.cpp
- HTML/MessageChannel.cpp
HTML/MessageEvent.cpp
HTML/MessagePort.cpp
HTML/MimeType.cpp
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index bf9a83c62ba..ce6aae9ee27 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -6580,26 +6580,21 @@ void Document::destroy()
// 3. Set document's salvageable state to false.
m_salvageable = false;
- // 4. Let ports be the list of MessagePorts whose relevant global object's associated Document is document.
- // 5. For each port in ports, disentangle port.
- HTML::MessagePort::for_each_message_port([&](HTML::MessagePort& port) {
- auto& global = port.relevant_global_object();
- auto* window = HTML::window_from_global_object(global);
- if (!window)
- return;
-
- if (&window->associated_document() == this)
- port.disentangle();
- });
+ // AD-HOC: Disentangle the ports of the window's realm, which closes the transports of the channels that document
+ // took part in, so that the ports at their other ends learn that nothing arrives any more. A window that
+ // was reused for another document keeps its ports. The specification once did this here, as steps of
+ // destroying a document, and no longer does.
+ if (auto window = this->window(); window && &window->associated_document() == this)
+ HTML::MessagePort::disentangle_ports_of_realm(HTML::relevant_realm(*window));
- // 6. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
+ // 4. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
run_unloading_cleanup_steps();
// AD-HOC: Destruction does not go through did_stop_being_active_document_in_navigable().
// Tear the layout tree down now instead of holding it until finalization.
tear_down_layout_tree();
- // 7. Remove any tasks whose document is document from any task queue (without running those tasks).
+ // 5. Remove any tasks whose document is document from any task queue (without running those tasks).
HTML::main_thread_event_loop().task_queue().remove_tasks_matching([this](auto& task) {
return task.document() == this;
});
@@ -6614,7 +6609,7 @@ void Document::destroy()
}
m_resize_observers.clear();
- // 8. Set document's browsing context to null.
+ // 6. Set document's browsing context to null.
m_browsing_context = nullptr;
// Not in the spec:
@@ -6632,7 +6627,7 @@ void Document::destroy()
}
}
- // 9. Set document's node navigable's active session history entry's document state's document to null.
+ // 7. Set document's node navigable's active session history entry's document state's document to null.
if (auto navigable = this->navigable()) {
navigable->set_active_document(nullptr);
@@ -6641,10 +6636,10 @@ void Document::destroy()
page().navigable_document_destroyed({}, *navigable);
}
- // 10. Remove document from the owner set of each WorkerGlobalScope object whose set contains document.
+ // 8. Remove document from the owner set of each WorkerGlobalScope object whose set contains document.
HTML::relevant_settings_object(*this).release_owned_worker_agents();
- // FIXME: 11. For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.
+ // FIXME: 9. For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.
}
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#make-document-unsalvageable
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 45a72240673..5598eb2ac99 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -762,7 +762,6 @@ class LocalNavigable;
class LocalTraversableNavigable;
class Location;
class MediaError;
-class MessageChannel;
class MessageEvent;
class MessagePort;
class MimeType;
diff --git a/Libraries/LibWeb/HTML/BroadcastChannel.cpp b/Libraries/LibWeb/HTML/BroadcastChannel.cpp
index 2ef764f3b71..50a88310bd5 100644
--- a/Libraries/LibWeb/HTML/BroadcastChannel.cpp
+++ b/Libraries/LibWeb/HTML/BroadcastChannel.cpp
@@ -15,7 +15,6 @@
#include <LibWeb/HTML/BroadcastChannel.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/MessageEvent.h>
-#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/StructuredSerialize.h>
#include <LibWeb/HTML/Window.h>
diff --git a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp
index 376f2be2bca..c1b16ef053e 100644
--- a/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/DedicatedWorkerGlobalScope.cpp
@@ -180,7 +180,7 @@ WebIDL::ExceptionOr<void> DedicatedWorkerGlobalScope::post_message(JS::Realm& re
// The postMessage(message, transfer) and postMessage(message, options) methods on DedicatedWorkerGlobalScope objects act as if,
// when invoked, it immediately invoked the respective postMessage(message, transfer) and postMessage(message, options)
// on the port, with the same arguments, and returned the same return value.
- return m_internal_port->post_message(realm, message, options);
+ return m_internal_port->post_message(realm, message, options.transfer);
}
WebIDL::ExceptionOr<void> DedicatedWorkerGlobalScope::post_message(JS::Realm& realm, JS::Value message, Bindings::StructuredSerializeOptions const& options)
@@ -211,7 +211,7 @@ void DedicatedWorkerGlobalScope::set_onmessage(WebIDL::CallbackType* callback)
// https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:handler-messageeventtarget-onmessage
// The first time a MessagePort object's onmessage IDL attribute is set, the port's port message queue must be enabled,
// as if the start() method had been called.
- m_internal_port->start();
+ m_internal_port->enable();
}
void DedicatedWorkerGlobalScope::set_onmessageerror(WebIDL::CallbackType* callback)
diff --git a/Libraries/LibWeb/HTML/EventSource.cpp b/Libraries/LibWeb/HTML/EventSource.cpp
index 3cd80b12760..9c2bc0f1f7e 100644
--- a/Libraries/LibWeb/HTML/EventSource.cpp
+++ b/Libraries/LibWeb/HTML/EventSource.cpp
@@ -23,7 +23,6 @@
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/EventSource.h>
#include <LibWeb/HTML/MessageEvent.h>
-#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/PotentialCORSRequest.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
diff --git a/Libraries/LibWeb/HTML/MessageChannel.cpp b/Libraries/LibWeb/HTML/MessageChannel.cpp
deleted file mode 100644
index f1a2aec1dd6..00000000000
--- a/Libraries/LibWeb/HTML/MessageChannel.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2021-2022, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibGC/Heap.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/MessageChannel.h>
-#include <LibWeb/HTML/MessagePort.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-
-namespace Web::HTML {
-
-GC_DEFINE_ALLOCATOR(MessageChannel);
-
-GC::Ref<MessageChannel> MessageChannel::create(GC::Ref<DOM::EventTarget> relevant_global_object)
-{
- auto port1 = MessagePort::create(relevant_global_object);
- auto port2 = MessagePort::create(relevant_global_object);
- auto channel = GC::Heap::the().allocate<MessageChannel>(port1, port2);
-
- // 3. Entangle this's port 1 and this's port 2.
- channel->m_port1->entangle_with(*channel->m_port2);
-
- return channel;
-}
-
-GC::Ref<MessageChannel> MessageChannel::create_for_constructor(JS::Object& relevant_global_object)
-{
- auto* global_scope = window_or_worker_global_scope_from_global_object(relevant_global_object);
- VERIFY(global_scope);
- return create(global_scope->this_impl());
-}
-
-MessageChannel::MessageChannel(GC::Ref<MessagePort> port1, GC::Ref<MessagePort> port2)
- : m_port1(port1)
- , m_port2(port2)
-{
-}
-
-MessageChannel::~MessageChannel() = default;
-
-void MessageChannel::visit_edges(GC::Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_port1);
- visitor.visit(m_port2);
-}
-
-MessagePort* MessageChannel::port1()
-{
- return m_port1.ptr();
-}
-
-MessagePort* MessageChannel::port2()
-{
- return m_port2.ptr();
-}
-
-MessagePort const* MessageChannel::port1() const
-{
- return m_port1.ptr();
-}
-
-MessagePort const* MessageChannel::port2() const
-{
- return m_port2.ptr();
-}
-
-}
diff --git a/Libraries/LibWeb/HTML/MessageChannel.h b/Libraries/LibWeb/HTML/MessageChannel.h
deleted file mode 100644
index e9ed80adf91..00000000000
--- a/Libraries/LibWeb/HTML/MessageChannel.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2021-2022, Andreas Kling <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-
-namespace Web::HTML {
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#message-channels
-class MessageChannel final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(MessageChannel, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(MessageChannel);
-
-public:
- static GC::Ref<MessageChannel> create(GC::Ref<DOM::EventTarget> relevant_global_object);
- static GC::Ref<MessageChannel> create_for_constructor(JS::Object&);
- virtual ~MessageChannel() override;
-
- MessagePort* port1();
- MessagePort const* port1() const;
-
- MessagePort* port2();
- MessagePort const* port2() const;
-
-private:
- MessageChannel(GC::Ref<MessagePort>, GC::Ref<MessagePort>);
-
- virtual void visit_edges(GC::Cell::Visitor&) override;
-
- GC::Ptr<MessagePort> m_port1;
- GC::Ptr<MessagePort> m_port2;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/MessageChannel.idl b/Libraries/LibWeb/HTML/MessageChannel.idl
index 571bf5a143b..7bc3bdf0c33 100644
--- a/Libraries/LibWeb/HTML/MessageChannel.idl
+++ b/Libraries/LibWeb/HTML/MessageChannel.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/web-messaging.html#messagechannel
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface MessageChannel {
constructor();
diff --git a/Libraries/LibWeb/HTML/MessagePort.cpp b/Libraries/LibWeb/HTML/MessagePort.cpp
index 5ca8d27dfa3..de4781134d5 100644
--- a/Libraries/LibWeb/HTML/MessagePort.cpp
+++ b/Libraries/LibWeb/HTML/MessagePort.cpp
@@ -6,603 +6,132 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/ByteReader.h>
-#include <AK/MemoryStream.h>
-#include <AK/NeverDestroyed.h>
-#include <LibCore/System.h>
-#include <LibGC/Heap.h>
-#include <LibGC/WeakHashSet.h>
-#include <LibIPC/Decoder.h>
-#include <LibIPC/Encoder.h>
-#include <LibIPC/Transport.h>
-#include <LibIPC/TransportHandle.h>
-#include <LibWeb/Bindings/MessagePort.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/DOM/EventDispatcher.h>
-#include <LibWeb/HTML/EventNames.h>
-#include <LibWeb/HTML/MessageEvent.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/Realm.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/HTML/MessagePort.h>
-#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/StructuredSerialize.h>
-#include <LibWeb/HTML/WorkerGlobalScope.h>
-#include <LibWeb/HTML/WorkletGlobalScope.h>
namespace Web::HTML {
-constexpr u8 IPC_FILE_TAG = 0xA5;
+extern "C" {
-GC_DEFINE_ALLOCATOR(MessagePort);
+// Defined in Bindings/Rust/src/html/exports.rs.
+void* web_rust_message_port_create(JSVM*, void* realm);
+void web_rust_message_port_entangle(JSVM*, void* port, void* remote_port);
+void* web_rust_message_port_entangled_port(void* port);
+void web_rust_message_port_set_message_event_target(void* port, DOM::EventTarget*);
+JSCompletion web_rust_message_port_post_message(JSVM*, void* realm, void* port, JSValue message, JSObject* const* transfer, size_t count);
+void web_rust_message_port_enable(JSVM*, void* port);
+void web_rust_message_port_close(void* port);
+void web_rust_message_port_discard_pending_messages(void* port);
+size_t web_rust_message_port_pending_outgoing_message_count(void* port);
+void web_rust_message_port_fail_next_transfer_for_testing(void* port);
+void web_rust_message_port_disentangle_ports_of_realm(JSVM*, void* realm);
-static GC::WeakHashSet<MessagePort>& all_message_ports()
-{
- static NeverDestroyed<GC::WeakHashSet<MessagePort>> ports;
- return *ports;
-}
-
-GC::Ref<MessagePort> MessagePort::create(GC::Ref<DOM::EventTarget> relevant_global_event_target)
-{
- return GC::Heap::the().allocate<MessagePort>(relevant_global_event_target);
-}
-
-MessagePort::MessagePort(GC::Ref<DOM::EventTarget> relevant_global_event_target)
- : DOM::EventTarget()
- , m_global_event_target(relevant_global_event_target)
-{
- all_message_ports().set(*this);
+// The entry points of the generated bindings of the interface.
+bool web_rust_message_port_is_detached(void* port);
+JSCompletion web_rust_message_port_transfer_steps(JSVM*, void* realm, void* port, Bindings::RustTransferDataWriter*);
+JSCompletion web_rust_message_port_transfer_receiving_steps(JSVM*, void* realm, Bindings::RustTransferDataReader*);
}
-MessagePort::~MessagePort() = default;
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#ports-and-garbage-collection
-// When a MessagePort object o is entangled, user agents must either act as if o's entangled MessagePort object has a
-// strong reference to o, or as if o's relevant global object has a strong reference to o.
-// NB: Same-agent entanglement does the former, through the m_remote_port edges ordinary GC traversal visits.
-// AD-HOC: A port entangled over a transport has no edge to the port it's entangled with, so it isn't kept alive as if
-// its relevant global object referenced it: It's kept alive only while its port message queue is enabled,
-// since no message ever reaches script through a port whose queue isn't. So once script drops such a port,
-// collecting it is unobservable, and disentangling it then closes its transport, which lets the port at the
-// other end of the channel go too. Keeping every such port alive would keep the transport, and its IO thread,
-// of every channel that script ever transferred and dropped without close() for the life of the process.
-void MessagePort::update_keep_alive()
+static JSVM* vm_abi()
{
- if (m_transport && m_enabled) {
- if (!m_keep_alive)
- m_keep_alive = GC::make_root(*this);
- return;
- }
- m_keep_alive = nullptr;
+ return JS::HostABI::vm_to_abi(JS::VM::the());
}
-JS::Object& MessagePort::relevant_global_object() const
+GC::Ref<MessagePort> MessagePort::create(JS::Realm& realm)
{
- if (auto* worklet_global_scope = as_if<WorkletGlobalScope>(*m_global_event_target))
- return worklet_global_scope->realm().global_object();
- return HTML::relevant_global_object(relevant_window_or_worker_global_scope(*m_global_event_target));
+ return GC::Ref { *static_cast<MessagePort*>(web_rust_message_port_create(vm_abi(), &realm)) };
}
-void MessagePort::for_each_message_port(Function<void(MessagePort&)> callback)
+GC::Ref<MessagePort> MessagePort::create_from_transfer(JS::Realm& realm, TransferDataDecoder& data_holder)
{
- auto ports = all_message_ports();
- for (auto& port : ports)
- callback(port);
+ Bindings::RustTransferDataReader reader { .realm = realm, .data_holder = data_holder };
+ auto wrapper = MUST(JS::HostABI::completion_from_abi<JS::Value>(web_rust_message_port_transfer_receiving_steps(vm_abi(), &realm, &reader)));
+ return *Bindings::impl_from<MessagePort>(&wrapper.as_object());
}
-void MessagePort::finalize()
+void MessagePort::disentangle_ports_of_realm(JS::Realm& realm)
{
- Base::finalize();
- disentangle();
+ web_rust_message_port_disentangle_ports_of_realm(vm_abi(), &realm);
}
-void MessagePort::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_remote_port);
- visitor.visit(m_global_event_target);
- visitor.visit(m_message_event_target);
-}
-
-bool MessagePort::is_entangled() const
-{
- return m_remote_port || m_transport;
-}
-
-void MessagePort::set_message_event_target(GC::Ref<DOM::EventTarget> target)
-{
- m_message_event_target = target;
-}
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-steps
-WebIDL::ExceptionOr<void> MessagePort::transfer_steps(JS::Realm& realm, HTML::TransferDataEncoder& data_holder)
-{
- bool has_remote_port_handle = false;
- IPC::TransportHandle remote_port_handle;
- GC::Ptr<MessagePort> remote_port;
- OwnPtr<IPC::Transport> remote_port_transport;
-
- // 3. If value is entangled with another port remotePort:
- if (m_remote_port) {
- remote_port = m_remote_port;
-
- // NB: Same-agent ports do not need a transport until one endpoint is shipped. Keep the endpoint
- // remaining in this agent and transfer the other endpoint to the receiving agent.
- auto paired = MUST(IPC::Transport::create_paired());
- remote_port_transport = move(paired.local);
- remote_port_handle = move(paired.remote_handle);
- has_remote_port_handle = true;
- } else if (m_transport) {
- // NOTE: release_for_transfer() stops the IO thread before drain_transport() reads the message buffer
- // below (step 2). Stopping first ensures a consistent snapshot: no new messages arrive between
- // the drain and the handle being handed to the new owner.
- remote_port_handle = MUST(m_transport->release_for_transfer());
- has_remote_port_handle = true;
- }
-
- // 2. Set dataHolder.[[PortMessageQueue]] to value's port message queue.
-
- // NB: Drain any incoming transport state into this port before serializing it so received messages and
- // a pending shutdown move with the transferred port instead of being left behind on the old transport.
- drain_transport();
- TRY(encode_or_throw_data_clone_error(realm, data_holder, m_pending_incoming_messages));
- TRY(encode_or_throw_data_clone_error(realm, data_holder, m_pending_outgoing_messages));
- TRY(encode_or_throw_data_clone_error(realm, data_holder, m_should_shutdown_on_enable));
-
- if (has_remote_port_handle) {
- // 2. Set dataHolder.[[RemotePort]] to remotePort.
- TRY(encode_or_throw_data_clone_error(realm, data_holder, IPC_FILE_TAG));
- if (m_fail_next_transfer_for_testing) {
- m_fail_next_transfer_for_testing = false;
- return WebIDL::DataCloneError::create("Forced MessagePort transfer failure"_utf16);
- }
- TRY(encode_or_throw_data_clone_error(realm, data_holder, remote_port_handle));
- }
- // 4. Otherwise, set dataHolder.[[RemotePort]] to null.
- else {
- TRY(encode_or_throw_data_clone_error(realm, data_holder, static_cast<u8>(0)));
- }
-
- // NB: Commit the entanglement conversion only after every fallible encoding succeeds.
- // 1. Set value's has been shipped flag to true.
- m_has_been_shipped = true;
-
- if (remote_port) {
- // 1. Set remotePort's has been shipped flag to true.
- remote_port->m_has_been_shipped = true;
- remote_port->m_transport = move(remote_port_transport);
- remote_port->m_remote_port = nullptr;
- m_remote_port = nullptr;
-
- remote_port->m_transport->set_up_read_hook([weak_remote_port = GC::Weak { *remote_port }]() {
- if (auto remote_port = weak_remote_port.ptr())
- remote_port->read_from_transport();
- });
- remote_port->update_keep_alive();
- remote_port->flush_pending_outgoing_messages();
- } else if (has_remote_port_handle) {
- m_transport.clear();
- update_keep_alive();
- }
-
- m_pending_incoming_messages.clear();
- m_pending_outgoing_messages.clear();
- m_should_shutdown_on_enable = false;
-
- return {};
-}
-
-WebIDL::ExceptionOr<void> MessagePort::transfer_receiving_steps(JS::Realm& realm, HTML::TransferDataDecoder& data_holder)
-{
- // 1. Set value's has been shipped flag to true.
- m_has_been_shipped = true;
-
- // 2. Move all the tasks that are to fire message events in dataHolder.[[PortMessageQueue]] to the port message queue of value,
- // if any, leaving value's port message queue in its initial disabled state, and, if value's relevant global object is a Window,
- // associating the moved tasks with value's relevant global object's associated Document.
- m_pending_incoming_messages = TRY(decode_or_throw_data_clone_error<Vector<SerializedTransferRecord>>(realm, data_holder));
- m_pending_outgoing_messages = TRY(decode_or_throw_data_clone_error<Vector<SerializedTransferRecord>>(realm, data_holder));
- m_should_shutdown_on_enable = TRY(decode_or_throw_data_clone_error<bool>(realm, data_holder));
- auto fd_tag = TRY(decode_or_throw_data_clone_error<u8>(realm, data_holder));
-
- // 3. If dataHolder.[[RemotePort]] is not null, then entangle dataHolder.[[RemotePort]] and value.
- // (This will disentangle dataHolder.[[RemotePort]] from the original port that was transferred.)
- if (fd_tag == IPC_FILE_TAG) {
- auto handle = TRY(decode_or_throw_data_clone_error<IPC::TransportHandle>(realm, data_holder));
- m_transport = MUST(handle.create_transport());
- m_has_ever_been_entangled = true;
-
- m_transport->set_up_read_hook([weak_this = GC::Weak { *this }]() {
- if (auto port = weak_this.ptr())
- port->read_from_transport();
- });
- update_keep_alive();
-
- flush_pending_outgoing_messages();
- } else if (fd_tag != 0) {
- dbgln("Unexpected byte {:x} in MessagePort transfer data", fd_tag);
- VERIFY_NOT_REACHED();
- }
-
- return {};
-}
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#disentangle
-void MessagePort::disentangle()
-{
- if (m_remote_port) {
- m_remote_port->m_remote_port = nullptr;
- m_remote_port = nullptr;
- }
-
- if (m_transport) {
- m_transport->close_after_sending_all_pending_messages();
- m_transport.clear();
- }
-
- m_pending_incoming_messages.clear();
- m_pending_outgoing_messages.clear();
- m_should_shutdown_on_enable = false;
- m_message_event_target = nullptr;
- update_keep_alive();
-}
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
void MessagePort::entangle_with(MessagePort& remote_port)
{
- if (m_remote_port.ptr() == &remote_port)
- return;
-
- // 1. If one of the ports is already entangled, then disentangle it and the port that it was entangled with.
-
- if (is_entangled())
- disentangle();
- if (remote_port.is_entangled())
- remote_port.disentangle();
-
- // 2. Associate the two ports to be entangled, so that they form the two parts of a new channel.
- // (There is no MessageChannel object that represents this channel.)
- remote_port.m_remote_port = this;
- m_remote_port = &remote_port;
- remote_port.m_has_ever_been_entangled = true;
- m_has_ever_been_entangled = true;
-
- flush_pending_outgoing_messages();
- m_remote_port->flush_pending_outgoing_messages();
-}
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage
-WebIDL::ExceptionOr<void> MessagePort::post_message(JS::Realm& realm, JS::Value message, GC::RootVector<GC::Ref<JS::Object>> const& transfer)
-{
- // 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
- GC::Ptr<MessagePort> target_port = m_remote_port;
-
- // 2. Let options be «[ "transfer" → transfer ]».
- auto options = StructuredSerializeOptions { transfer };
-
- // 3. Run the message port post message steps providing this, targetPort, message and options.
- return message_port_post_message_steps(realm, target_port, message, options);
+ web_rust_message_port_entangle(vm_abi(), this, &remote_port);
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage-options
-WebIDL::ExceptionOr<void> MessagePort::post_message(JS::Realm& realm, JS::Value message, StructuredSerializeOptions const& options)
+GC::Ptr<MessagePort> MessagePort::entangled_port()
{
- // 1. Let targetPort be the port with which this is entangled, if any; otherwise let it be null.
- GC::Ptr<MessagePort> target_port = m_remote_port;
-
- // 2. Run the message port post message steps providing this, targetPort, message and options.
- return message_port_post_message_steps(realm, target_port, message, options);
+ return static_cast<MessagePort*>(web_rust_message_port_entangled_port(this));
}
-WebIDL::ExceptionOr<void> MessagePort::post_message(JS::Realm& realm, JS::Value message, Bindings::StructuredSerializeOptions const& options)
+void MessagePort::set_message_event_target(DOM::EventTarget& target)
{
- return post_message(realm, message, StructuredSerializeOptions { .transfer = options.transfer });
+ web_rust_message_port_set_message_event_target(this, &target);
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#message-port-post-message-steps
-WebIDL::ExceptionOr<void> MessagePort::message_port_post_message_steps(JS::Realm& realm, GC::Ptr<MessagePort> target_port, JS::Value message, StructuredSerializeOptions const& options)
-{
- // 1. Let transfer be options["transfer"].
- auto const& transfer = options.transfer;
-
- // 2. If transfer contains sourcePort, then throw a "DataCloneError" DOMException.
- if (Bindings::transfer_list_contains_message_port(transfer, *this))
- return WebIDL::DataCloneError::create("Cannot transfer a MessagePort to itself"_utf16);
-
- // 3. Let doomed be false.
- bool doomed = false;
-
- // 4. If targetPort is not null and transfer contains targetPort, then set doomed to true and optionally report to a developer console that the target port was posted to itself, causing the communication channel to be lost.
- if (target_port) {
- if (Bindings::transfer_list_contains_message_port(transfer, *target_port)) {
- doomed = true;
- dbgln("FIXME: Report to a developer console that the target port was posted to itself, causing the communication channel to be lost");
- }
- }
-
- // 5. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, transfer). Rethrow any exceptions.
- auto serialize_with_transfer_result = TRY(structured_serialize_with_transfer(realm, message, transfer));
-
- // 6. If targetPort is null, or if doomed is true, then return.
-
- if (doomed)
- return {};
-
- // 7. Add a task that runs the following steps to the port message queue of targetPort:
- if (m_remote_port && !m_has_been_shipped) {
- m_remote_port->m_pending_incoming_messages.append(move(serialize_with_transfer_result));
- queue_global_task(Task::Source::PostedMessage, m_remote_port->relevant_global_object(), GC::create_function(heap(), [target = GC::make_root(m_remote_port)] {
- if (target->m_enabled)
- target->dispatch_pending_messages();
- }));
- } else if (m_transport) {
- post_port_message(serialize_with_transfer_result);
- } else if (!is_detached() && !m_has_been_shipped && !m_has_ever_been_entangled) {
- // AD-HOC: A port can exist before it has a transport to send on. Keep the serialized record on the port
- // and flush it once the port becomes entangled.
- m_pending_outgoing_messages.append(move(serialize_with_transfer_result));
- }
-
- return {};
-}
-
-ErrorOr<void> MessagePort::send_message_on_transport(SerializedTransferRecord const& serialize_with_transfer_result)
+WebIDL::ExceptionOr<void> MessagePort::post_message(JS::Realm& realm, JS::Value message, GC::RootVector<GC::Ref<JS::Object>> const& transfer)
{
- IPC::MessageBuffer buffer;
- IPC::Encoder encoder(buffer);
- MUST(encoder.encode(serialize_with_transfer_result));
-
- TRY(buffer.transfer_message(*m_transport));
+ Vector<JSObject*> transfer_abi;
+ transfer_abi.ensure_capacity(transfer.size());
+ for (auto const& transferable : transfer)
+ transfer_abi.unchecked_append(JS::HostABI::object_to_abi(transferable.ptr()));
+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_message_port_post_message(vm_abi(), &realm, this, JS::HostABI::value_to_abi(message), transfer_abi.data(), transfer_abi.size())));
return {};
}
-void MessagePort::flush_pending_outgoing_messages()
-{
- if (m_remote_port && !m_has_been_shipped) {
- if (m_pending_outgoing_messages.is_empty())
- return;
-
- auto pending_outgoing_messages = move(m_pending_outgoing_messages);
- m_remote_port->m_pending_incoming_messages.extend(move(pending_outgoing_messages));
- queue_global_task(Task::Source::PostedMessage, m_remote_port->relevant_global_object(), GC::create_function(heap(), [target = GC::make_root(m_remote_port)] {
- if (target->m_enabled)
- target->dispatch_pending_messages();
- }));
- return;
- }
-
- if (!m_transport || !m_transport->is_open())
- return;
-
- auto pending_outgoing_messages = move(m_pending_outgoing_messages);
- for (auto const& pending_message : pending_outgoing_messages)
- post_port_message(pending_message);
-}
-
-void MessagePort::dispatch_pending_messages()
-{
- auto pending_messages = move(m_pending_incoming_messages);
- for (auto& pending_message : pending_messages)
- queue_message_task(move(pending_message));
-
- if (m_should_shutdown_on_enable) {
- m_should_shutdown_on_enable = false;
- auto& global = relevant_global_object();
- queue_global_task(Task::Source::PostedMessage, global, GC::create_function(GC::Heap::the(), [this] {
- this->close();
- }));
- }
-}
-
-void MessagePort::queue_message_task(SerializedTransferRecord&& serialize_with_transfer_result)
-{
- auto& global = relevant_global_object();
- auto message_task_generation = m_message_task_generation;
- queue_global_task(Task::Source::PostedMessage, global,
- GC::create_function(GC::Heap::the(), [this, message_task_generation, serialize_with_transfer_result = move(serialize_with_transfer_result)]() mutable {
- if (message_task_generation != m_message_task_generation)
- return;
- this->post_message_task_steps(serialize_with_transfer_result);
- }));
-}
-
-void MessagePort::drain_transport()
-{
- if (!m_transport)
- return;
-
- auto schedule_shutdown = m_transport->read_as_many_messages_as_possible_without_blocking([this](auto&& raw_message) {
- FixedMemoryStream stream { raw_message.bytes.bytes() };
- IPC::Decoder decoder { stream, raw_message.attachments };
-
- m_pending_incoming_messages.append(MUST(decoder.decode<SerializedTransferRecord>()));
- });
-
- // The peer is gone, so nothing more arrives; the pending messages are delivered once the port is enabled.
- if (schedule_shutdown == IPC::Transport::ShouldShutdown::Yes) {
- m_should_shutdown_on_enable = true;
- m_transport->close();
- }
-}
-
-void MessagePort::post_port_message(SerializedTransferRecord const& serialize_with_transfer_result)
-{
- if (!m_transport || !m_transport->is_open())
- return;
- if (auto result = send_message_on_transport(serialize_with_transfer_result); result.is_error()) {
- dbgln("Failed to post message: {}", result.error());
- disentangle();
- }
-}
-
-void MessagePort::read_from_transport()
-{
- if (!is_entangled())
- return;
-
- drain_transport();
-
- if (m_enabled)
- dispatch_pending_messages();
-}
-
-void MessagePort::post_message_task_steps(SerializedTransferRecord& serialize_with_transfer_result)
-{
- // 1. Let finalTargetPort be the MessagePort in whose port message queue the task now finds itself.
- // NOTE: This can be different from targetPort, if targetPort itself was transferred and thus all its tasks moved along with it.
- auto* final_target_port = this;
-
- // 2. Let messageEventTarget be finalTargetPort's message event target.
- GC::Ref<EventTarget> message_event_target = *final_target_port;
- if (final_target_port->m_message_event_target)
- message_event_target = *final_target_port->m_message_event_target;
-
- // 3. Let targetRealm be finalTargetPort's relevant realm.
- auto& target_realm = HTML::relevant_realm(final_target_port->relevant_global_object());
-
- // 4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm).
- // NB: The execution context must not stay on the stack while the event is dispatched, so that a microtask
- // checkpoint can be performed after each listener.
- auto deserialize_record_or_error = [&] {
- TemporaryExecutionContext context { target_realm };
- return structured_deserialize_with_transfer(serialize_with_transfer_result, target_realm);
- }();
- if (deserialize_record_or_error.is_error()) {
- // If this throws an exception, catch it, fire an event named messageerror at messageEventTarget, using MessageEvent, and then return.
- auto exception = deserialize_record_or_error.release_error();
- MessageEventInit event_init;
- message_event_target->dispatch_event(MessageEvent::create(target_realm.global_object(), HTML::EventNames::messageerror, event_init));
- return;
- }
- auto deserialize_record = deserialize_record_or_error.release_value();
-
- // 5. Let messageClone be deserializeRecord.[[Deserialized]].
- auto message_clone = deserialize_record.deserialized;
-
- // 6. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.
- // FIXME: Use a FrozenArray
- auto new_ports = Bindings::message_ports_from_transferred_values(deserialize_record.transferred_values);
-
- // 7. Fire an event named message at messageEventTarget, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.
- MessageEventInit event_init { {}, message_clone, Utf16String {}, Utf16String {}, move(new_ports), Empty {} };
- auto event = MessageEvent::create(target_realm.global_object(), HTML::EventNames::message, event_init);
- event->set_is_trusted(true);
- message_event_target->dispatch_event(event);
-}
-
void MessagePort::enable()
{
- if (!m_enabled) {
- m_enabled = true;
- update_keep_alive();
- if (m_transport) {
- read_from_transport();
- } else {
- dispatch_pending_messages();
- }
- }
+ web_rust_message_port_enable(vm_abi(), this);
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-start
-void MessagePort::start()
-{
- // The start() method steps are to enable this's port message queue, if it is not already enabled.
- enable();
-}
-
-// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-close
void MessagePort::close()
{
- // 1. Set this's [[Detached]] internal slot value to true.
- set_detached(true);
-
- // 2. If this is entangled, disentangle it.
- if (is_entangled())
- disentangle();
-
- m_pending_incoming_messages.clear();
- m_pending_outgoing_messages.clear();
- m_should_shutdown_on_enable = false;
+ web_rust_message_port_close(this);
}
void MessagePort::discard_pending_messages()
{
- m_pending_incoming_messages.clear();
- ++m_message_task_generation;
+ web_rust_message_port_discard_pending_messages(this);
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-messageeventtarget-onmessageerror
-void MessagePort::set_onmessageerror(GC::Ptr<WebIDL::CallbackType> value)
+WebIDL::ExceptionOr<void> MessagePort::transfer_steps(JS::Realm& realm, TransferDataEncoder& data_holder)
{
- set_event_handler_attribute(EventNames::messageerror, value);
+ Bindings::RustTransferDataWriter writer { .realm = realm, .data_holder = data_holder };
+ TRY(JS::HostABI::completion_from_abi<void>(web_rust_message_port_transfer_steps(vm_abi(), &realm, this, &writer)));
+ return {};
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-messageeventtarget-onmessageerror
-GC::Ptr<WebIDL::CallbackType> MessagePort::onmessageerror()
+bool MessagePort::is_detached() const
{
- return event_handler_attribute(EventNames::messageerror);
+ return web_rust_message_port_is_detached(const_cast<MessagePort*>(this));
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-messageeventtarget-onmessage
-void MessagePort::set_onmessage(GC::Ptr<WebIDL::CallbackType> value)
+size_t MessagePort::pending_outgoing_message_count() const
{
- set_event_handler_attribute(EventNames::message, value);
-
- // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:handler-messageeventtarget-onmessage
- // The first time a MessagePort object's onmessage IDL attribute is set, the port's port message queue must be enabled,
- // as if the start() method had been called.
- start();
+ return web_rust_message_port_pending_outgoing_message_count(const_cast<MessagePort*>(this));
}
-// https://html.spec.whatwg.org/multipage/web-messaging.html#handler-messageeventtarget-onmessage
-GC::Ptr<WebIDL::CallbackType> MessagePort::onmessage()
+void MessagePort::fail_next_transfer_for_testing()
{
- return event_handler_attribute(EventNames::message);
+ web_rust_message_port_fail_next_transfer_for_testing(this);
}
}
namespace Web::Bindings {
-GC::Ref<JS::HostObject> message_port(JS::Realm& realm, GC::Ref<HTML::MessagePort> message_port)
-{
- return wrap(host_defined_wrapper_world(realm), realm, message_port);
-}
-
-HTML::MessagePort* message_port_from_value(JS::Value value)
-{
- if (!value.is_object())
- return nullptr;
- return Bindings::impl_from<HTML::MessagePort>(&value.as_object());
-}
-
GC::RootVector<GC::Ref<HTML::MessagePort>> message_ports_from_transferred_values(Vector<GC::Root<JS::Object>> const& transferred_values)
{
GC::RootVector<GC::Ref<HTML::MessagePort>> ports;
for (auto const& object : transferred_values) {
- if (auto* message_port = message_port_from_value(object))
+ if (auto* message_port = impl_from<HTML::MessagePort>(object.ptr()))
ports.append(*message_port);
}
return ports;
}
-bool transfer_list_contains_message_port(GC::RootVector<GC::Ref<JS::Object>> const& transfer, HTML::MessagePort const& port)
-{
- for (auto const& handle : transfer) {
- if (message_port_from_value(handle) == &port)
- return true;
- }
- return false;
-}
-
-HTML::MessagePort* message_port_from_object(JS::Object& object)
-{
- return Bindings::impl_from<HTML::MessagePort>(&object);
-}
-
-void serialize_message_port_with_transfer(JS::Realm& realm, HTML::TransferDataEncoder& data_holder, GC::Ref<HTML::MessagePort> port)
-{
- auto port_wrapper = Bindings::message_port(realm, port);
- auto result = MUST(HTML::structured_serialize_with_transfer(realm, JS::Value { port_wrapper }, { { port_wrapper } }));
- data_holder.extend(move(result.transfer_data_holders));
-}
-
}
diff --git a/Libraries/LibWeb/HTML/MessagePort.h b/Libraries/LibWeb/HTML/MessagePort.h
index df3655a81c7..78dc901345d 100644
--- a/Libraries/LibWeb/HTML/MessagePort.h
+++ b/Libraries/LibWeb/HTML/MessagePort.h
@@ -8,136 +8,60 @@
#pragma once
-#include <AK/RefCounted.h>
-#include <AK/Weakable.h>
-#include <LibCore/Socket.h>
-#include <LibIPC/File.h>
-#include <LibIPC/Transport.h>
-#include <LibWeb/Bindings/Transferable.h>
-#include <LibWeb/DOM/EventTarget.h>
+#include <LibGC/Ptr.h>
+#include <LibGC/RootVector.h>
+#include <LibJS/Forward.h>
+#include <LibWeb/Bindings/MessagePort.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Export.h>
#include <LibWeb/Forward.h>
-
-namespace JS {
-
-class HostObject;
-
-}
-
-namespace Web::Bindings {
-
-struct StructuredSerializeOptions;
-
-}
+#include <LibWeb/WebIDL/ExceptionOr.h>
namespace Web::HTML {
-struct StructuredSerializeOptions;
-
// https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports
-class WEB_API MessagePort final
- : public DOM::EventTarget
- , public Bindings::Transferable {
- WEB_WRAPPABLE(MessagePort, DOM::EventTarget);
- GC_DECLARE_ALLOCATOR(MessagePort);
+class WEB_API MessagePort : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(MessagePort, message_port)
public:
- [[nodiscard]] static GC::Ref<MessagePort> create(GC::Ref<DOM::EventTarget> relevant_global_event_target);
+ [[nodiscard]] static GC::Ref<MessagePort> create(JS::Realm&);
- static void for_each_message_port(Function<void(MessagePort&)>);
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-receiving-steps
+ [[nodiscard]] static GC::Ref<MessagePort> create_from_transfer(JS::Realm&, TransferDataDecoder&);
- virtual ~MessagePort() override;
-
- JS::Object& relevant_global_object() const;
+ static void disentangle_ports_of_realm(JS::Realm&);
// https://html.spec.whatwg.org/multipage/web-messaging.html#entangle
void entangle_with(MessagePort&);
- void disentangle();
+ GC::Ptr<MessagePort> entangled_port();
- GC::Ptr<MessagePort> entangled_port() { return m_remote_port; }
- GC::Ptr<MessagePort const> entangled_port() const { return m_remote_port; }
- size_t pending_outgoing_message_count() const { return m_pending_outgoing_messages.size(); }
- void fail_next_transfer_for_testing() { m_fail_next_transfer_for_testing = true; }
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-event-target
+ void set_message_event_target(DOM::EventTarget&);
// https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage
WebIDL::ExceptionOr<void> post_message(JS::Realm&, JS::Value message, GC::RootVector<GC::Ref<JS::Object>> const& transfer);
- // https://html.spec.whatwg.org/multipage/web-messaging.html#dom-messageport-postmessage-options
- WebIDL::ExceptionOr<void> post_message(JS::Realm&, JS::Value message, StructuredSerializeOptions const& options);
- WebIDL::ExceptionOr<void> post_message(JS::Realm&, JS::Value message, Bindings::StructuredSerializeOptions const& options);
-
void enable();
- void start();
void close();
- void discard_pending_messages();
-
- void set_onmessageerror(GC::Ptr<WebIDL::CallbackType>);
- GC::Ptr<WebIDL::CallbackType> onmessageerror();
-
- void set_onmessage(GC::Ptr<WebIDL::CallbackType>);
- GC::Ptr<WebIDL::CallbackType> onmessage();
-
- // ^Transferable
- virtual WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, HTML::TransferDataEncoder&) override;
- virtual WebIDL::ExceptionOr<void> transfer_receiving_steps(JS::Realm&, HTML::TransferDataDecoder&) override;
- virtual HTML::TransferType primary_interface() const override { return HTML::TransferType::MessagePort; }
-
- void set_message_event_target(GC::Ref<DOM::EventTarget>);
-
- WebIDL::ExceptionOr<void> message_port_post_message_steps(JS::Realm&, GC::Ptr<MessagePort> target_port, JS::Value message, StructuredSerializeOptions const& options);
-
-private:
- explicit MessagePort(GC::Ref<DOM::EventTarget> relevant_global_event_target);
- virtual void finalize() override;
- virtual void visit_edges(Cell::Visitor&) override;
-
- bool is_entangled() const;
-
- void dispatch_pending_messages();
- void flush_pending_outgoing_messages();
- void queue_message_task(SerializedTransferRecord&&);
- void drain_transport();
- void post_message_task_steps(SerializedTransferRecord&);
- void post_port_message(SerializedTransferRecord const&);
- ErrorOr<void> send_message_on_transport(SerializedTransferRecord const&);
- void read_from_transport();
- void update_keep_alive();
-
- // The HTML spec implies(!) that this is MessagePort.[[RemotePort]]
- GC::Ptr<MessagePort> m_remote_port;
-
- // https://html.spec.whatwg.org/multipage/web-messaging.html#has-been-shipped
- bool m_has_been_shipped { false };
- bool m_has_ever_been_entangled { false };
- bool m_fail_next_transfer_for_testing { false };
+ void discard_pending_messages();
- OwnPtr<IPC::Transport> m_transport;
+ // https://html.spec.whatwg.org/multipage/web-messaging.html#message-ports:transfer-steps
+ WebIDL::ExceptionOr<void> transfer_steps(JS::Realm&, TransferDataEncoder&);
- GC::Ref<DOM::EventTarget> m_global_event_target;
+ // https://html.spec.whatwg.org/multipage/structured-data.html#detached
+ bool is_detached() const;
- // https://html.spec.whatwg.org/multipage/web-messaging.html#message-event-target
- GC::Ptr<DOM::EventTarget> m_message_event_target;
-
- Vector<SerializedTransferRecord> m_pending_incoming_messages;
- Vector<SerializedTransferRecord> m_pending_outgoing_messages;
- u64 m_message_task_generation { 0 };
- bool m_should_shutdown_on_enable { false };
- bool m_enabled { false };
- GC::Root<MessagePort> m_keep_alive;
+ size_t pending_outgoing_message_count() const;
+ void fail_next_transfer_for_testing();
};
}
namespace Web::Bindings {
-WEB_API GC::Ref<JS::HostObject> message_port(JS::Realm&, GC::Ref<HTML::MessagePort>);
-WEB_API HTML::MessagePort* message_port_from_value(JS::Value);
WEB_API GC::RootVector<GC::Ref<HTML::MessagePort>> message_ports_from_transferred_values(Vector<GC::Root<JS::Object>> const&);
-WEB_API bool transfer_list_contains_message_port(GC::RootVector<GC::Ref<JS::Object>> const&, HTML::MessagePort const&);
-WEB_API HTML::MessagePort* message_port_from_object(JS::Object&);
-WEB_API void serialize_message_port_with_transfer(JS::Realm&, HTML::TransferDataEncoder&, GC::Ref<HTML::MessagePort>);
}
diff --git a/Libraries/LibWeb/HTML/MessagePort.idl b/Libraries/LibWeb/HTML/MessagePort.idl
index 1b84404319b..5978e4056e7 100644
--- a/Libraries/LibWeb/HTML/MessagePort.idl
+++ b/Libraries/LibWeb/HTML/MessagePort.idl
@@ -1,13 +1,13 @@
// https://html.spec.whatwg.org/multipage/web-messaging.html#messageport
-[Exposed=(Window,Worker,AudioWorklet), Transferable]
+[Exposed=(Window,Worker,AudioWorklet), Transferable, ImplementedIn=Rust]
interface MessagePort : EventTarget {
- [NeedsCallerRealm] undefined postMessage(any message, sequence<object> transfer);
- [NeedsCallerRealm] undefined postMessage(any message, optional StructuredSerializeOptions options = {});
+ [NeedsCallerRealm, ImplementedAs=post_message] undefined postMessage(any message, sequence<object> transfer);
+ [NeedsCallerRealm, ImplementedAs=post_message_with_options] undefined postMessage(any message, optional StructuredSerializeOptions options = {});
undefined start();
undefined close();
// event handlers
- attribute EventHandler onmessage;
+ [ImplementedAs=set_onmessage] attribute EventHandler onmessage;
attribute EventHandler onmessageerror;
};
diff --git a/Libraries/LibWeb/HTML/SharedWorker.cpp b/Libraries/LibWeb/HTML/SharedWorker.cpp
index ac529f62dd9..fbfa684c1dc 100644
--- a/Libraries/LibWeb/HTML/SharedWorker.cpp
+++ b/Libraries/LibWeb/HTML/SharedWorker.cpp
@@ -63,7 +63,7 @@ WebIDL::ExceptionOr<GC::Ref<SharedWorker>> SharedWorker::create(WindowOrWorkerGl
return WebIDL::SyntaxError::create("SharedWorker constructed with invalid URL"_utf16);
// 6. Let outsidePort be a new MessagePort in outsideSettings's realm.
- auto outside_port = MessagePort::create(global_scope.this_impl());
+ auto outside_port = MessagePort::create(outside_settings.realm());
// 10. Let worker be this.
// AD-HOC: We do this first so that we can use `this`.
diff --git a/Libraries/LibWeb/HTML/Worker.cpp b/Libraries/LibWeb/HTML/Worker.cpp
index 29de4a1da91..cf1ba5ead71 100644
--- a/Libraries/LibWeb/HTML/Worker.cpp
+++ b/Libraries/LibWeb/HTML/Worker.cpp
@@ -71,14 +71,14 @@ WebIDL::ExceptionOr<GC::Ref<Worker>> Worker::create(WindowOrWorkerGlobalScopeMix
}
// 5. Let outsidePort be a new MessagePort in outsideSettings's realm.
- auto outside_port = MessagePort::create(global_scope.this_impl());
+ auto outside_port = MessagePort::create(outside_settings.realm());
// 8. Let worker be this.
// AD-HOC: AD-HOC: We do this first so that we can use `this`.
auto worker = GC::Heap::the().allocate<Worker>(compliant_script_url.to_utf8_but_should_be_ported_to_utf16(), options);
// 6. Set outsidePort's message event target to this.
- outside_port->set_message_event_target(worker);
+ outside_port->set_message_event_target(*worker);
// 7. Set this's outside port to outsidePort.
worker->m_outside_port = outside_port;
@@ -152,7 +152,7 @@ WebIDL::ExceptionOr<void> Worker::post_message(JS::Realm& realm, JS::Value messa
// when invoked, they immediately invoked the respective postMessage(message, transfer) and
// postMessage(message, options) on the port, with the same arguments, and returned the same return value.
- return m_outside_port->post_message(realm, message, options);
+ return m_outside_port->post_message(realm, message, options.transfer);
}
WebIDL::ExceptionOr<void> Worker::post_message(JS::Realm& realm, JS::Value message, Bindings::StructuredSerializeOptions const& options)
diff --git a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
index e7d31bc115c..c0b7df4dc44 100644
--- a/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
+++ b/Libraries/LibWeb/HTML/WorkerAgentParent.cpp
@@ -79,9 +79,7 @@ void WorkerAgentParent::start()
auto& realm = m_outside_settings->realm();
m_outside_settings->add_owned_worker_agent(*this);
- auto* global_scope = window_or_worker_global_scope_from_global_object(realm.global_object());
- VERIFY(global_scope);
- m_message_port = MessagePort::create(global_scope->this_impl());
+ m_message_port = MessagePort::create(realm);
m_message_port->entangle_with(*m_outside_port);
TransferDataEncoder data_holder;
@@ -90,7 +88,7 @@ void WorkerAgentParent::start()
// FIXME: Specification says this supposed to happen in step 11 of onComplete handler defined in https://html.spec.whatwg.org/multipage/workers.html#run-a-worker
// but that would require introducing a new IPC message type to communicate this from WebWorker to WebContent process,
// so let's do it here for now.
- m_outside_port->start();
+ m_outside_port->enable();
auto serialized_outside_settings = m_outside_settings->serialize();
diff --git a/Libraries/LibWeb/Streams/ReadableStream.cpp b/Libraries/LibWeb/Streams/ReadableStream.cpp
index 170eda7d07f..4a5f5b88f03 100644
--- a/Libraries/LibWeb/Streams/ReadableStream.cpp
+++ b/Libraries/LibWeb/Streams/ReadableStream.cpp
@@ -13,15 +13,10 @@
#include <LibWeb/Bindings/RustSerialization.h>
#include <LibWeb/Bindings/WrapperWorld.h>
#include <LibWeb/DOM/AbortSignal.h>
-#include <LibWeb/DOM/IDLEventListener.h>
-#include <LibWeb/HTML/EventNames.h>
-#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/StructuredSerialize.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/Page/RenderingStats.h>
#include <LibWeb/Streams/ReadableStream.h>
#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
-#include <LibWeb/WebIDL/CallbackType.h>
#include <LibWeb/WebIDL/ExceptionOrUtils.h>
namespace Web::Streams {
@@ -70,13 +65,6 @@ JSValue web_streams_abort_signal_reason(DOM::AbortSignal*);
bool web_streams_abort_signal_add_algorithm(DOM::AbortSignal*, JSObject* function, u64* id);
void web_streams_abort_signal_remove_algorithm(DOM::AbortSignal*, u64 id);
void web_streams_abort_signal_signal_abort(DOM::AbortSignal*, JSValue reason, void* realm);
-void web_streams_create_entangled_ports(void* realm, void** port1, void** port2);
-void web_streams_message_port_add_handlers(void* realm, HTML::MessagePort*, JSObject* on_message, JSObject* on_message_error);
-JSCompletion web_streams_message_port_post_message(void* realm, HTML::MessagePort*, JSValue message);
-void web_streams_message_port_disentangle(HTML::MessagePort*);
-void web_streams_message_port_enable(HTML::MessagePort*);
-void* web_streams_message_port_from_object(JSObject*);
-JSObject* web_streams_message_port_wrapper(void* realm, HTML::MessagePort*);
}
static JSVM* vm_abi()
@@ -353,67 +341,4 @@ void web_streams_abort_signal_signal_abort(DOM::AbortSignal* signal, JSValue rea
signal->signal_abort(JS::HostABI::value_from_abi(reason), realm_of(realm).global_object());
}
-void web_streams_create_entangled_ports(void* realm, void** port1, void** port2)
-{
- auto* global_scope = HTML::window_or_worker_global_scope_from_global_object(realm_of(realm).global_object());
- VERIFY(global_scope);
- auto first_port = HTML::MessagePort::create(global_scope->this_impl());
- auto second_port = HTML::MessagePort::create(global_scope->this_impl());
- first_port->entangle_with(second_port);
- *port1 = first_port.ptr();
- *port2 = second_port.ptr();
-}
-
-static void add_message_event_listener(JS::Realm& realm, HTML::MessagePort& port, Utf16FlyString const& name, JSObject* function)
-{
- auto& callback_object = *JS::HostABI::object_from_abi(function);
- auto callback = GC::Heap::the().allocate<WebIDL::CallbackType>(callback_object, realm);
- port.add_event_listener_without_options(name, DOM::IDLEventListener::create(callback));
-}
-
-void web_streams_message_port_add_handlers(void* realm, HTML::MessagePort* port, JSObject* on_message, JSObject* on_message_error)
-{
- add_message_event_listener(realm_of(realm), *port, HTML::EventNames::message, on_message);
- add_message_event_listener(realm_of(realm), *port, HTML::EventNames::messageerror, on_message_error);
-}
-
-JSCompletion web_streams_message_port_post_message(void* realm, HTML::MessagePort* port, JSValue message)
-{
- auto& js_realm = realm_of(realm);
-
- // 4. Let targetPort be the port with which port is entangled, if any; otherwise let it be null.
- auto target_port = port->entangled_port();
-
- // 5. Let options be «[ "transfer" → « » ]».
- HTML::StructuredSerializeOptions options;
-
- // 6. Run the message port post message steps providing targetPort, message, and options.
- auto result = port->message_port_post_message_steps(js_realm, target_port, JS::HostABI::value_from_abi(message), options);
- if (result.is_exception())
- return Bindings::completion_to_abi(js_realm, result.release_error());
- return Bindings::completion_to_abi(js_realm, JS::js_undefined());
-}
-
-void web_streams_message_port_disentangle(HTML::MessagePort* port)
-{
- port->disentangle();
-}
-
-void web_streams_message_port_enable(HTML::MessagePort* port)
-{
- port->enable();
-}
-
-void* web_streams_message_port_from_object(JSObject* object)
-{
- auto* port = Bindings::message_port_from_object(*JS::HostABI::object_from_abi(object));
- VERIFY(port);
- return port;
-}
-
-JSObject* web_streams_message_port_wrapper(void* realm, HTML::MessagePort* port)
-{
- return JS::HostABI::object_to_abi(Bindings::message_port(realm_of(realm), *port).ptr());
-}
-
}
diff --git a/Libraries/LibWeb/WebAudio/AudioContext.cpp b/Libraries/LibWeb/WebAudio/AudioContext.cpp
index 0d25637c3cc..32da77a219c 100644
--- a/Libraries/LibWeb/WebAudio/AudioContext.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioContext.cpp
@@ -8,8 +8,6 @@
#include <LibMedia/Sinks/AudioOutputFactory.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/HTML/HTMLMediaElement.h>
-#include <LibWeb/HTML/MessageChannel.h>
-#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/HTML/Window.h>
diff --git a/Libraries/LibWeb/WebAudio/AudioWorklet.cpp b/Libraries/LibWeb/WebAudio/AudioWorklet.cpp
index 548c42b3b8f..f00822ad387 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorklet.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioWorklet.cpp
@@ -29,7 +29,7 @@ GC::Ref<AudioWorklet> AudioWorklet::create(GC::Ref<BaseAudioContext> context)
AudioWorklet::AudioWorklet(GC::Ref<BaseAudioContext> context)
: HTML::Worklet(context->relevant_global_event_target())
, m_context(context)
- , m_port(HTML::MessagePort::create(context->relevant_global_event_target()))
+ , m_port(HTML::MessagePort::create(HTML::relevant_realm(context->relevant_global_object())))
{
}
@@ -72,7 +72,7 @@ GC::Ref<HTML::WorkletGlobalScope> AudioWorklet::create_global_scope()
// Bindings initialization requires the realm's [[HostDefined]] slot.
scope->initialize_web_interfaces_impl();
- auto scope_port = HTML::MessagePort::create(*scope);
+ auto scope_port = HTML::MessagePort::create(scope->realm());
m_port->entangle_with(*scope_port);
m_port->enable();
scope->set_port(scope_port);
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp
index 50ac2146c5b..2d543a53fcb 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioWorkletNode.cpp
@@ -68,7 +68,7 @@ WebIDL::ExceptionOr<GC::Ref<AudioWorkletNode>> AudioWorkletNode::construct_impl(
// 2. Let node be this value; initialize node's AudioNode base with context and options.
auto parameter_map = AudioParamMap::create();
- auto node_port = HTML::MessagePort::create(context->relevant_global_event_target());
+ auto node_port = HTML::MessagePort::create(HTML::relevant_realm(context->relevant_global_object()));
auto node = GC::Heap::the().allocate<AudioWorkletNode>(context, name, options.number_of_inputs, options.number_of_outputs, parameter_map, node_port);
AudioNodeDefaultOptions default_options;
@@ -93,7 +93,7 @@ WebIDL::ExceptionOr<GC::Ref<AudioWorkletNode>> AudioWorkletNode::construct_impl(
// disabled until the processor constructor has returned, so messages posted before (or during)
// construction are queued and delivered to listeners the constructor registered — even ones added
// with addEventListener() and no explicit start().
- auto processor_port = HTML::MessagePort::create(worklet_scope);
+ auto processor_port = HTML::MessagePort::create(worklet_scope.realm());
node_port->entangle_with(*processor_port);
node_port->enable();
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.cpp b/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.cpp
index b068ccb2dc6..af6e47f6d38 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.cpp
+++ b/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.cpp
@@ -30,11 +30,12 @@ WebIDL::ExceptionOr<GC::Ref<AudioWorkletProcessor>> AudioWorkletProcessor::const
return realm.vm().throw_completion<JS::TypeError>("AudioWorkletProcessor cannot be constructed directly; it is instantiated by AudioWorkletNode"sv);
// 2. Set this's port to the pending construction data's transferred port.
- return GC::Heap::the().allocate<AudioWorkletProcessor>(pending_data->port);
+ return GC::Heap::the().allocate<AudioWorkletProcessor>(*global_scope, pending_data->port);
}
-AudioWorkletProcessor::AudioWorkletProcessor(GC::Ref<HTML::MessagePort> port)
- : m_port(port)
+AudioWorkletProcessor::AudioWorkletProcessor(GC::Ref<AudioWorkletGlobalScope> global_scope, GC::Ref<HTML::MessagePort> port)
+ : m_global_scope(global_scope)
+ , m_port(port)
{
}
@@ -42,13 +43,14 @@ AudioWorkletProcessor::~AudioWorkletProcessor() = default;
GC::Ptr<Bindings::Wrappable> AudioWorkletProcessor::relevant_global_impl() const
{
- // Pin wrapper creation to the worklet realm: the processor's port lives on the worklet global.
- return m_port->relevant_global_impl();
+ // Pin wrapper creation to the worklet realm.
+ return m_global_scope;
}
void AudioWorkletProcessor::visit_edges(Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
+ visitor.visit(m_global_scope);
visitor.visit(m_port);
}
diff --git a/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h b/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h
index b557137a197..ea95b753fb5 100644
--- a/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h
+++ b/Libraries/LibWeb/WebAudio/AudioWorkletProcessor.h
@@ -28,13 +28,14 @@ public:
GC::Ref<HTML::MessagePort> port() const { return m_port; }
private:
- explicit AudioWorkletProcessor(GC::Ref<HTML::MessagePort>);
+ AudioWorkletProcessor(GC::Ref<AudioWorkletGlobalScope>, GC::Ref<HTML::MessagePort>);
// Ensures wrappers for this processor are created in the worklet realm, not the page realm.
virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
virtual void visit_edges(Cell::Visitor&) override;
+ GC::Ref<AudioWorkletGlobalScope> m_global_scope;
GC::Ref<HTML::MessagePort> m_port;
};
diff --git a/Libraries/LibWeb/WebSockets/WebSocket.cpp b/Libraries/LibWeb/WebSockets/WebSocket.cpp
index 7e27a871022..07c9ae99964 100644
--- a/Libraries/LibWeb/WebSockets/WebSocket.cpp
+++ b/Libraries/LibWeb/WebSockets/WebSocket.cpp
@@ -31,7 +31,6 @@
#include <LibWeb/HTML/EventHandler.h>
#include <LibWeb/HTML/EventNames.h>
#include <LibWeb/HTML/MessageEvent.h>
-#include <LibWeb/HTML/MessagePort.h>
#include <LibWeb/HTML/PolicyContainers.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 60a8dcada63..69479e0fd3d 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -52,7 +52,7 @@ ALLOWED_REALM_MENTIONS = {
"FileAPI": (4, 11, "Blob/FileList glue still creates streams, buffers, and lists in selected realms"),
"HTML": (
65,
- 201,
+ 196,
"HTML algorithms still contain structured serialization, including posted-message preparation, canvas, navigation transfer/reconstruction, worker/worklet, and event realm use, and cross-origin Window/Location property functions are created in the current realm; RemoteWindow mirrors Window's postMessage; "
"the C++ glue of the Rust structured serialization reads records and creates platform objects in a given realm",
),
@@ -70,7 +70,7 @@ ALLOWED_REALM_MENTIONS = {
41,
"service worker jobs, caches, and container promises still materialize results in selected realms",
),
- "Streams": (5, 14, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),
+ "Streams": (5, 13, "the C++ facade of the Rust streams creates streams and promises in caller-selected realms"),
"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),
"WebAssembly": (
2,
diff --git a/Services/WebWorker/WorkerHost.cpp b/Services/WebWorker/WorkerHost.cpp
index 2527eb888c1..18fbd74c80d 100644
--- a/Services/WebWorker/WorkerHost.cpp
+++ b/Services/WebWorker/WorkerHost.cpp
@@ -255,16 +255,14 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes
// (step 5) to connect_shared_worker_impl. Each connecting page gets its own pair
// since the connect event fires once per owner, not once at worker startup.
if (!is_shared) {
- inside_port = Web::HTML::MessagePort::create(worker_global_scope);
+ Web::HTML::TransferDataDecoder decoder { move(message_port_data) };
+ inside_port = Web::HTML::MessagePort::create_from_transfer(realm, decoder);
// 1. Set inside port's message event target to worker global scope.
- inside_port->set_message_event_target(worker_global_scope);
+ inside_port->set_message_event_target(*worker_global_scope);
// 2. Set worker global scope's inside port to inside port.
worker_global_scope->set_internal_port(*inside_port);
-
- Web::HTML::TransferDataDecoder decoder { move(message_port_data) };
- MUST(inside_port->transfer_receiving_steps(realm, decoder));
}
// 6. Create a new WorkerLocation object and associate it with worker global scope.
@@ -365,12 +363,10 @@ void WorkerHost::connect_shared_worker_impl(Web::HTML::TransferDataEncoder messa
VERIFY(m_inside_settings);
// 11.5.5. Let insidePort be a new MessagePort in insideSettings's realm.
- auto inside_port = Web::HTML::MessagePort::create(*m_worker_global_scope);
-
// 11.5.6. Entangle outsidePort and insidePort.
auto& realm = m_inside_settings->realm();
Web::HTML::TransferDataDecoder decoder { move(message_port_data) };
- MUST(inside_port->transfer_receiving_steps(realm, decoder));
+ auto inside_port = Web::HTML::MessagePort::create_from_transfer(realm, decoder);
// 11.5.7. Queue a global task on the DOM manipulation task source given workerGlobalScope to
// fire an event named connect at workerGlobalScope, using MessageEvent, with the data
diff --git a/Tests/LibWeb/TestStructuredSerializeFormat.cpp b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
index f696bfe2fee..a901cec059c 100644
--- a/Tests/LibWeb/TestStructuredSerializeFormat.cpp
+++ b/Tests/LibWeb/TestStructuredSerializeFormat.cpp
@@ -736,9 +736,9 @@ TEST_CASE(any_number_of_transferred_image_bitmaps_share_one_attachment)
values.append(wrapper);
}
auto buffer = MUST(JS::ArrayBuffer::create(realm, 1));
- auto port = Web::HTML::MessagePort::create(Web::DOM::EventTarget::create());
+ auto port = Web::HTML::MessagePort::create(realm);
transfer.append(buffer);
- transfer.append(Web::Bindings::message_port(realm, port));
+ transfer.append(Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, port));
#if !defined(AK_OS_WINDOWS)
// Receiving the batch must not retain one descriptor per bitmap, even with a small descriptor limit.
@@ -781,9 +781,7 @@ TEST_CASE(image_bitmap_with_padded_rows_transfers_its_pixels)
TEST_CASE(image_bitmaps_queued_on_a_transferred_message_port_keep_their_pixels)
{
auto& realm = test_realm();
- auto* window = Web::HTML::window_from_global_object(realm.global_object());
- VERIFY(window);
- auto port = Web::HTML::MessagePort::create(*window);
+ auto port = Web::HTML::MessagePort::create(realm);
static constexpr size_t count = IPC::MAX_MESSAGE_FD_COUNT + 1;
auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, { 1, 1 }));
bitmap->set_pixel(0, 0, Gfx::Color::Blue);
@@ -797,7 +795,7 @@ TEST_CASE(image_bitmaps_queued_on_a_transferred_message_port_keep_their_pixels)
MUST(port->post_message(realm, JS::Array::create_from(realm, values), transfer));
EXPECT_EQ(port->pending_outgoing_message_count(), 1u);
- auto port_wrapper = Web::Bindings::message_port(realm, port);
+ auto port_wrapper = Web::Bindings::wrap(Web::Bindings::host_defined_wrapper_world(realm), realm, port);
Array<GC::Ref<JS::Object>, 1> port_transfer { port_wrapper };
auto record = MUST(Web::HTML::structured_serialize_with_transfer(realm, port_wrapper, port_transfer));
EXPECT(port->is_detached());