Skip to content

Truly independent web browser

LibWeb: Implement Web Locks in Rust

Shannon Boothdb150e07d752
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
index e55e3d207f2..e8a89aca5a8 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/callback.rs
@@ -146,6 +146,10 @@ impl CallbackInterface {
}
impl PromiseCallbackFunction {
+ pub(crate) fn as_ptr(&self) -> *mut c_void {
+ self.0.0.as_ptr()
+ }
+
/// The callback function value of a JS value, https://webidl.spec.whatwg.org/#js-callback-function
pub(crate) fn from_js(vm: &Vm, value: Value) -> ThrowCompletionOr<Self> {
CallbackType::from_js(vm, value, true).map(Self)
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index f77ab9fefa7..0734e208883 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -530,9 +530,9 @@ unsafe impl<C: Trace> Trace for CapturedSteps<C> {
}
}
-impl<C: Trace + Copy + 'static> DeferredSteps for CapturedSteps<C> {
+impl<C: Trace + Clone + 'static> DeferredSteps for CapturedSteps<C> {
fn run(&self, vm: &Vm) {
- (self.steps)(vm, self.captures);
+ (self.steps)(vm, self.captures.clone());
}
}
@@ -554,7 +554,7 @@ impl EmbedderValue for PendingSteps {
const CLASS: &'static EmbedderClass<Self> = &PENDING_STEPS_CLASS;
}
-fn pending_steps<C: Trace + Copy + 'static>(vm: &Vm, captures: C, steps: fn(&Vm, C)) -> *mut c_void {
+pub(crate) fn pending_steps<C: Trace + Clone + 'static>(vm: &Vm, captures: C, steps: fn(&Vm, C)) -> *mut c_void {
PENDING_STEPS_CLASS
.allocate(vm, |_| {
let steps: Box<dyn DeferredSteps> = Box::new(CapturedSteps { captures, steps });
@@ -564,7 +564,7 @@ fn pending_steps<C: Trace + Copy + 'static>(vm: &Vm, captures: C, steps: fn(&Vm,
.cast()
}
-unsafe extern "C" fn run_pending_steps(vm: *mut c_void, cell: *mut c_void) {
+pub(crate) unsafe extern "C" fn run_pending_steps(vm: *mut c_void, cell: *mut c_void) {
// SAFETY: LibWeb passes the VM and the cell that pending_steps() made, which it kept alive.
let (vm, cell) = unsafe {
(
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 461118a08dc..fac8c144518 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -185,6 +185,16 @@ pub(crate) mod web_assembly;
)]
pub(crate) mod web_gl;
#[cfg(not(test))]
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every operation as one that can throw"
+)]
+pub(crate) mod web_locks;
+#[cfg(not(test))]
pub(crate) mod webidl;
#[cfg(not(test))]
pub(crate) mod webrtc;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_locks/abstract_operations.rs b/Libraries/LibWeb/Bindings/Rust/src/web_locks/abstract_operations.rs
new file mode 100644
index 00000000000..a61b6bbed03
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_locks/abstract_operations.rs
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::ffi::c_void;
+use std::collections::{HashMap, VecDeque};
+use std::hash::{BuildHasherDefault, DefaultHasher};
+
+use ak::Utf16String;
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, Realm, Trace, Visitor, Vm};
+
+use crate::bindings::callback::PromiseCallbackFunction;
+use crate::bindings::environment_settings_object::CppEnvironmentSettingsObject;
+use crate::bindings::interface::{Ref, cell_from_abi};
+use crate::bindings::promise::{pending_steps, run_pending_steps};
+use crate::web_locks::lock_manager::LockManager;
+use crate::web_locks::lock_request::LockRequestRef;
+
+unsafe extern "C" {
+ fn web_locks_environment_lock_manager(environment: *mut c_void) -> *mut c_void;
+ fn web_locks_queue_task(
+ realm: *mut c_void,
+ cell: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+ fn web_locks_queue_callback_task(
+ callback: *mut c_void,
+ cell: *mut c_void,
+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void),
+ );
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct LockRequestQueue(pub(crate) GcRefCell<VecDeque<LockRequestRef>>);
+
+static LOCK_REQUEST_QUEUE_CLASS: EmbedderClass<LockRequestQueue> = EmbedderClass::new("LockRequestQueue");
+
+impl EmbedderValue for LockRequestQueue {
+ const CLASS: &'static EmbedderClass<Self> = &LOCK_REQUEST_QUEUE_CLASS;
+}
+
+pub(crate) type LockRequestQueueRef = Gc<EmbedderCell<LockRequestQueue>>;
+
+// NB: A fixed hasher keeps the order of query()'s pending list the same from run to run.
+#[derive(Default)]
+pub(crate) struct LockRequestQueueMap(
+ pub(crate) HashMap<Utf16String, LockRequestQueueRef, BuildHasherDefault<DefaultHasher>>,
+);
+
+// SAFETY: Only the map's values contain cells.
+unsafe impl Trace for LockRequestQueueMap {
+ fn trace(&self, visitor: &mut Visitor) {
+ for queue in self.0.values() {
+ queue.trace(visitor);
+ }
+ }
+}
+
+impl LockRequestQueueMap {
+ // https://w3c.github.io/web-locks/#get-the-lock-request-queue
+ pub(crate) fn get_lock_request_queue(&mut self, vm: &Vm, name: &Utf16String) -> LockRequestQueueRef {
+ // 1. If queueMap[name] does not exist, set queueMap[name] to a new empty lock request queue.
+ let queue = *self.0.entry(name.clone()).or_insert_with(|| {
+ LOCK_REQUEST_QUEUE_CLASS.allocate(vm, |_| LockRequestQueue(GcRefCell::new(VecDeque::new())))
+ });
+
+ // 2. Return queueMap[name].
+ queue
+ }
+}
+
+// https://w3c.github.io/web-locks/#obtain-a-lock-manager
+pub(crate) fn obtain_lock_manager(environment: &CppEnvironmentSettingsObject) -> Ref<LockManager> {
+ // 1. Let map be the result of obtaining a local storage bottle map given environment and "web-locks".
+ // 2. If map is failure, then return failure.
+ // 3. Let bottle be map’s associated storage bottle.
+ // 4. Return bottle’s associated lock manager.
+
+ // FIXME: Spec issue: Storing and obtaining a lock manager in the environment's storage is currently not well
+ // defined. So we store a single instance per environment for now. See:
+ // https://w3c.github.io/web-locks/#issue-73644ca1
+ // SAFETY: The environment is live, and its settings object keeps its manager alive.
+ unsafe { cell_from_abi(web_locks_environment_lock_manager(environment.as_ptr())) }
+}
+
+pub(crate) fn queue_web_locks_task<C: Trace + Clone + 'static>(
+ vm: &Vm,
+ realm: Gc<Realm>,
+ captures: C,
+ steps: fn(&Vm, C),
+) {
+ let cell = pending_steps(vm, captures, steps);
+ // SAFETY: LibWeb retains the realm and the traced captures until the task runs.
+ unsafe { web_locks_queue_task(realm.as_ptr().cast(), cell, run_pending_steps) };
+}
+
+pub(crate) fn queue_web_locks_callback_task<C: Trace + Clone + 'static>(
+ vm: &Vm,
+ callback: &PromiseCallbackFunction,
+ captures: C,
+ steps: fn(&Vm, C),
+) {
+ let cell = pending_steps(vm, captures, steps);
+ // SAFETY: LibWeb retains the callback and the traced captures until the task runs.
+ unsafe { web_locks_queue_callback_task(callback.as_ptr(), cell, run_pending_steps) };
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock.rs b/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock.rs
new file mode 100644
index 00000000000..45277891593
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock.rs
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use ak::Utf16String;
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Value, Vm};
+
+use crate::bindings::interface::{Ref, Wrappable, allocate};
+use crate::bindings::promise::{WebIdlPromise, resolve_promise};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::web_locks::abstract_operations::queue_web_locks_task;
+use crate::web_locks::lock_manager::{LockManager, LockMode};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct Lock {
+ lock: LockDataRef,
+}
+
+impl Wrappable for Lock {}
+
+impl Lock {
+ pub(crate) fn create(vm: &Vm, lock: LockDataRef) -> Ref<Self> {
+ allocate(vm, |_| Self { lock })
+ }
+
+ // https://w3c.github.io/web-locks/#dom-lock-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The name getter’s steps are to return the associated lock’s name.
+ Ok(self.lock.name.clone())
+ }
+
+ // https://w3c.github.io/web-locks/#dom-lock-mode
+ pub(crate) fn mode(&self, _: &mut CallContext) -> WebIdlResult<LockMode> {
+ // The mode getter’s steps are to return the associated lock’s mode.
+ Ok(self.lock.mode)
+ }
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct LockData {
+ #[gc(untraced)]
+ pub(crate) client_id: Utf16String,
+ pub(crate) manager: Ref<LockManager>,
+ #[gc(untraced)]
+ pub(crate) name: Utf16String,
+ #[gc(untraced)]
+ pub(crate) mode: LockMode,
+ pub(crate) released_promise: WebIdlPromise,
+ pub(crate) waiting_promise: WebIdlPromise,
+}
+
+pub(crate) static LOCK_DATA_CLASS: EmbedderClass<LockData> = EmbedderClass::new("LockData");
+
+impl EmbedderValue for LockData {
+ const CLASS: &'static EmbedderClass<Self> = &LOCK_DATA_CLASS;
+}
+
+pub(crate) type LockDataRef = Gc<EmbedderCell<LockData>>;
+
+impl LockData {
+ // https://w3c.github.io/web-locks/#release-the-lock
+ pub(crate) fn release_lock(this: LockDataRef, vm: &Vm) {
+ // 1. Assert: these steps are running on the lock task queue.
+
+ // 2. Let manager be lock’s manager.
+ let manager = this.manager;
+
+ // 3. Let queueMap be manager’s lock request queue map.
+ let queue_map = &manager.lock_request_queue_map;
+
+ // 4. Let name be lock’s resource name.
+ let name = &this.name;
+
+ // 5. Let queue be the result of getting the lock request queue from queueMap for name.
+ let queue = queue_map.borrow_mut(vm).get_lock_request_queue(vm, name);
+
+ // 6. Remove lock from the manager’s held lock set.
+ manager.held_lock_set.borrow_mut(vm).retain(|lock| *lock != this);
+
+ // 7. Process the lock request queue queue.
+ LockManager::process_lock_request_queue(vm, queue);
+ }
+
+ // https://w3c.github.io/web-locks/#concept-lock
+ pub(crate) fn waiting_promise_settled(cx: &CallContext, lock: LockDataRef, _: Value) -> WebIdlResult<Value> {
+ // When lock lock’s waiting promise settles (fulfills or rejects), enqueue the following steps on the lock task
+ // queue:
+ queue_web_locks_task(cx.vm(), lock.manager.realm, lock, |vm, lock| {
+ // 1. Release the lock lock.
+ Self::release_lock(lock, vm);
+
+ // 2. Resolve lock’s released promise with lock’s waiting promise.
+ resolve_promise(
+ vm,
+ lock.released_promise,
+ Value::from_object(lock.waiting_promise.promise()),
+ );
+ });
+ Ok(Value::UNDEFINED)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock_manager.rs b/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock_manager.rs
new file mode 100644
index 00000000000..41d47ccfc39
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock_manager.rs
@@ -0,0 +1,527 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::cell::Cell;
+use core::ffi::c_void;
+
+use ak::{Utf16String, Utf16StringUnits};
+use libjs_rust::api::{Gc, GcRefCell, NativeFunction, PropertyKey, Realm, Trace, Value, Vm};
+
+use crate::bindings::callback::PromiseCallbackFunction;
+use crate::bindings::conversions::CppInterface;
+#[cfg(web_idl_bindings)]
+use crate::bindings::conversions::ToJs;
+use crate::bindings::environment_settings_object::{CppEnvironmentSettingsObject, relevant_settings_object};
+use crate::bindings::global_object::window_from_global_object;
+use crate::bindings::interface::{Ref, Wrappable, allocate, cell_into_abi, realm_arguments, wrap};
+use crate::bindings::promise::{
+ WebIdlPromise, create_promise, create_rejected_promise, create_rejected_promise_from_exception, react_to_promise,
+ reject_promise_with_exception, resolve_promise,
+};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::dom::abort_signal::AbortSignal;
+use crate::web_locks::abstract_operations::{
+ LockRequestQueueMap, LockRequestQueueRef, obtain_lock_manager, queue_web_locks_callback_task, queue_web_locks_task,
+};
+use crate::web_locks::lock::{LOCK_DATA_CLASS, Lock, LockData, LockDataRef};
+use crate::web_locks::lock_request::{LOCK_REQUEST_CLASS, LockRequest, LockRequestRef};
+
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+pub(crate) enum LockMode {
+ Shared,
+ #[default]
+ Exclusive,
+}
+
+#[derive(Default)]
+pub(crate) struct LockOptions {
+ pub(crate) mode: LockMode,
+ pub(crate) if_available: bool,
+ pub(crate) steal: bool,
+ pub(crate) signal: Option<CppInterface>,
+}
+
+pub(crate) struct LockManagerSnapshot {
+ pub(crate) held: Option<Vec<LockInfo>>,
+ pub(crate) pending: Option<Vec<LockInfo>>,
+}
+
+impl LockManagerSnapshot {
+ fn into_js(self, cx: &CallContext) -> Value {
+ // NB: The generated bindings convert the dictionary, which a build of the crate on its own leaves out.
+ #[cfg(web_idl_bindings)]
+ return ToJs::to_js(self, cx).expect("a lock manager snapshot converts to a JS value");
+ #[cfg(not(web_idl_bindings))]
+ {
+ let _ = (self, cx);
+ unreachable!("only the generated bindings resolve a promise with the dictionary")
+ }
+ }
+}
+
+pub(crate) struct LockInfo {
+ pub(crate) name: Option<Utf16String>,
+ pub(crate) mode: Option<LockMode>,
+ pub(crate) client_id: Option<Utf16String>,
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct LockManager {
+ pub(crate) held_lock_set: GcRefCell<Vec<LockDataRef>>,
+ pub(crate) lock_request_queue_map: GcRefCell<LockRequestQueueMap>,
+ environment: CppEnvironmentSettingsObject,
+ pub(crate) realm: Gc<Realm>,
+}
+
+impl Wrappable for LockManager {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+}
+
+impl LockManager {
+ pub(crate) fn create(vm: &Vm, realm: Gc<Realm>) -> Ref<Self> {
+ allocate(vm, |_| Self {
+ held_lock_set: GcRefCell::default(),
+ lock_request_queue_map: GcRefCell::default(),
+ environment: relevant_settings_object(realm.global_object()),
+ realm,
+ })
+ }
+
+ // https://w3c.github.io/web-locks/#dom-lockmanager-request
+ pub(crate) fn request(
+ &self,
+ cx: &mut CallContext,
+ name: Utf16String,
+ options: Option<LockOptions>,
+ callback: PromiseCallbackFunction,
+ ) -> WebIdlResult<WebIdlPromise> {
+ let vm = cx.vm();
+ let realm = self.realm;
+
+ // 1. If options was not passed, then let options be a new LockOptions dictionary with default members.
+ let options = options.unwrap_or_default();
+ let signal = options.signal.map(AbortSignal::from_wrapper);
+
+ // 2. Let environment be this’s relevant settings object.
+ let environment = &self.environment;
+
+ // 3. If environment’s relevant global object’s associated Document is not fully active, then return a promise
+ // rejected with a "InvalidStateError" DOMException.
+ if let Some(window) = window_from_global_object(environment.global_object())
+ && !window.associated_document().is_fully_active()
+ {
+ return Ok(create_rejected_promise_from_exception(
+ vm,
+ realm,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_utf8("Document is not fully active"),
+ ),
+ ));
+ }
+
+ // 4. Let manager be the result of obtaining a lock manager given environment. If that returned failure, then
+ // return a promise rejected with a "SecurityError" DOMException.
+ let manager = obtain_lock_manager(environment);
+
+ // 5. If name starts with U+002D HYPHEN-MINUS (-), then return a promise rejected with a "NotSupportedError"
+ // DOMException.
+ let starts_with_hyphen = match name.as_units() {
+ Utf16StringUnits::Ascii(units) | Utf16StringUnits::Latin1(units) => units.first() == Some(&b'-'),
+ Utf16StringUnits::Utf16(units) => units.first() == Some(&u16::from(b'-')),
+ };
+ if starts_with_hyphen {
+ return Ok(create_rejected_promise_from_exception(
+ vm,
+ realm,
+ Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("Lock names starting with '-' are reserved"),
+ ),
+ ));
+ }
+
+ // 6. If both options["steal"] and options["ifAvailable"] are true, then return a promise rejected with a
+ // "NotSupportedError" DOMException.
+ if options.steal && options.if_available {
+ return Ok(create_rejected_promise_from_exception(
+ vm,
+ realm,
+ Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("Lock options 'steal' and 'ifAvailable' cannot both be true"),
+ ),
+ ));
+ }
+
+ // 7. If options["steal"] is true and options["mode"] is not "exclusive", then return a promise rejected with a
+ // "NotSupportedError" DOMException.
+ if options.steal && options.mode != LockMode::Exclusive {
+ return Ok(create_rejected_promise_from_exception(
+ vm,
+ realm,
+ Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("Lock option 'steal' can only be used with exclusive locks"),
+ ),
+ ));
+ }
+
+ // 8. If options["signal"] exists, and either of options["steal"] or options["ifAvailable"] is true, then return
+ // a promise rejected with a "NotSupportedError" DOMException.
+ if signal.is_some() && (options.steal || options.if_available) {
+ return Ok(create_rejected_promise_from_exception(
+ vm,
+ realm,
+ Exception::Dom(
+ "NotSupportedError",
+ Utf16String::from_utf8("Lock option 'signal' cannot be combined with 'steal' or 'ifAvailable'"),
+ ),
+ ));
+ }
+
+ // 9. If options["signal"] exists and is aborted, then return a promise rejected with options["signal"]'s abort
+ // reason.
+ if let Some(signal) = &signal
+ && signal.aborted()
+ {
+ return Ok(create_rejected_promise(vm, realm, signal.reason()));
+ }
+
+ // 10. Let promise be a new promise.
+ let promise = create_promise(vm, realm);
+
+ // 11. Request a lock with promise, the current agent, environment’s id, manager, callback, name,
+ // options["mode"], options["ifAvailable"], options["steal"], and options["signal"].
+ Self::request_lock(
+ manager,
+ vm,
+ promise,
+ callback,
+ name,
+ options.mode,
+ options.if_available,
+ options.steal,
+ signal,
+ );
+
+ // 12. Return promise.
+ Ok(promise)
+ }
+
+ // https://w3c.github.io/web-locks/#dom-lockmanager-query
+ pub(crate) fn query(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {
+ let vm = cx.vm();
+
+ // 1. Let environment be this’s relevant settings object.
+ let environment = &self.environment;
+
+ // 2. If environment’s relevant global object’s associated Document is not fully active, then return a promise
+ // rejected with a "InvalidStateError" DOMException.
+ if let Some(window) = window_from_global_object(environment.global_object())
+ && !window.associated_document().is_fully_active()
+ {
+ return Ok(create_rejected_promise_from_exception(
+ vm,
+ self.realm,
+ Exception::Dom(
+ "InvalidStateError",
+ Utf16String::from_utf8("Document is not fully active"),
+ ),
+ ));
+ }
+
+ // 3. Let manager be the result of obtaining a lock manager given environment. If that returned failure, then
+ // return a promise rejected with a "SecurityError" DOMException.
+ let manager = obtain_lock_manager(environment);
+
+ // 4. Let promise be a new promise.
+ let promise = create_promise(vm, self.realm);
+
+ // 5. Enqueue the steps to snapshot the lock state for manager with promise to the lock task queue.
+ queue_web_locks_task(vm, self.realm, (manager, promise), |vm, (manager, promise)| {
+ manager.snapshot_lock_state(vm, promise);
+ });
+
+ // 6. Return promise.
+ Ok(promise)
+ }
+
+ // https://w3c.github.io/web-locks/#request-a-lock
+ #[allow(
+ clippy::too_many_arguments,
+ reason = "the specification gives the algorithm these parameters"
+ )]
+ fn request_lock(
+ manager: Ref<Self>,
+ vm: &Vm,
+ promise: WebIdlPromise,
+ callback: PromiseCallbackFunction,
+ name: Utf16String,
+ mode: LockMode,
+ if_available: bool,
+ steal: bool,
+ signal: Option<AbortSignal>,
+ ) -> LockRequestRef {
+ // 1. Let request be a new lock request (agent, clientId, manager, name, mode, callback, promise, signal).
+ let request = LOCK_REQUEST_CLASS.allocate(vm, |_| LockRequest {
+ client_id: Utf16String::from_utf8(&manager.environment.id()),
+ manager,
+ name,
+ mode,
+ callback,
+ promise,
+ signal,
+ abort_algorithm_id: Cell::new(None),
+ });
+
+ // 2. If signal is present, then add the algorithm signal to abort the request request with signal to signal.
+ if let Some(signal) = &request.signal {
+ let algorithm = NativeFunction::create(
+ vm,
+ (request, signal.clone()),
+ |vm, (request, signal): &(LockRequestRef, AbortSignal)| {
+ LockRequest::signal_to_abort_request(*request, vm, signal);
+ Ok(Value::UNDEFINED)
+ },
+ 0,
+ &PropertyKey::from_utf8(""),
+ Some(manager.realm),
+ None,
+ None,
+ );
+ request.abort_algorithm_id.set(signal.add_algorithm(algorithm));
+ }
+
+ // 3. Enqueue the following steps to the lock task queue:
+ queue_web_locks_task(
+ vm,
+ manager.realm,
+ (manager, request, if_available, steal),
+ |vm, (manager, request, if_available, steal)| {
+ // 1. Let queueMap be manager’s lock request queue map.
+ let queue_map = &manager.lock_request_queue_map;
+
+ // 2. Let queue be the result of getting the lock request queue from queueMap for name.
+ let queue = queue_map.borrow_mut(vm).get_lock_request_queue(vm, &request.name);
+
+ // 3. Let held be manager’s held lock set.
+ let held = &manager.held_lock_set;
+
+ // 4. If steal is true, then run these steps:
+ if steal {
+ // 1. For each lock of held:
+ let mut i = 0;
+ while i < held.borrow().len() {
+ let lock = held.borrow()[i];
+
+ // 1. If lock’s name is name, then run these steps:
+ if lock.name == request.name {
+ // 1. Remove lock from held.
+ held.borrow_mut(vm).remove(i);
+
+ // 2. Reject lock’s released promise with an "AbortError" DOMException.
+ reject_promise_with_exception(
+ vm,
+ lock.released_promise,
+ Exception::Dom("AbortError", Utf16String::from_utf8("Lock was stolen")),
+ );
+ } else {
+ i += 1;
+ }
+ }
+
+ // 2. Prepend request in queue.
+ queue.0.borrow_mut(vm).push_front(request);
+ }
+ // 5. Otherwise, run these steps:
+ else {
+ // 1. If ifAvailable is true and request is not grantable, then enqueue the following steps on
+ // callback’s relevant settings object’s responsible event loop:
+ if if_available && !LockRequest::is_grantable(request, vm) {
+ queue_web_locks_callback_task(vm, &request.callback, request, |vm, request| {
+ // 1. Let r be the result of invoking callback with null as the only argument.
+ let r = request.callback.invoke(None, &[Value::NULL]);
+
+ // 2. Resolve promise with r and abort these steps.
+ resolve_promise(vm, request.promise, Value::from_object(r.promise()));
+ });
+
+ // AD-HOC: Abort the enclosing queue steps so an unavailable request is not also granted later.
+ return;
+ }
+
+ // 2. Enqueue request in queue.
+ queue.0.borrow_mut(vm).push_back(request);
+ }
+
+ // 6. Process the lock request queue queue.
+ Self::process_lock_request_queue(vm, queue);
+ },
+ );
+
+ // 4. Return request.
+ request
+ }
+
+ // https://w3c.github.io/web-locks/#process-the-lock-request-queue
+ pub(crate) fn process_lock_request_queue(vm: &Vm, queue: LockRequestQueueRef) {
+ // 1. Assert: these steps are running on the lock task queue.
+
+ // 2. For each request of queue:
+ while let Some(request) = { queue.0.borrow().front().copied() } {
+ // 1. If request is not grantable, then return.
+ // NOTE: Only the first item in a queue is grantable. Therefore, if something is not grantable then all the
+ // following items are automatically not grantable.
+ if !LockRequest::is_grantable(request, vm) {
+ return;
+ }
+
+ // 2. Remove request from queue.
+ queue.0.borrow_mut(vm).pop_front();
+
+ // FIXME: 3. Let agent be request’s agent.
+
+ // 4. Let manager be request’s manager.
+ let manager = request.manager;
+
+ // 5. Let clientId be request’s clientId.
+ let client_id = request.client_id.clone();
+
+ // 6. Let name be request’s name.
+ let name = request.name.clone();
+
+ // 7. Let mode be request’s mode.
+ let mode = request.mode;
+
+ // 8. Let callback be request’s callback.
+ let callback = request.callback.clone();
+
+ // 9. Let p be request’s promise.
+ let p = request.promise;
+
+ // 10. Let signal be request’s signal.
+ let signal = request.signal.clone();
+
+ // 11. Let waiting be a new promise.
+ let waiting = create_promise(vm, manager.realm);
+
+ // 12. Let lock be a new lock with agent agent, clientId clientId, manager manager, mode mode, name name,
+ // released promise p, and waiting promise waiting.
+ let lock = LOCK_DATA_CLASS.allocate(vm, |_| LockData {
+ client_id,
+ manager,
+ name,
+ mode,
+ released_promise: p,
+ waiting_promise: waiting,
+ });
+
+ // 13. Append lock to manager’s held lock set.
+ manager.held_lock_set.borrow_mut(vm).push(lock);
+
+ // 14. Enqueue the following steps on callback’s relevant settings object’s responsible event loop:
+ queue_web_locks_callback_task(
+ vm,
+ &callback,
+ (manager, request, lock, signal, callback.clone(), waiting),
+ |vm, (manager, request, lock, signal, callback, waiting)| {
+ // 1. If signal is present, then run these steps:
+ if let Some(signal) = &signal {
+ // 1. If signal is aborted, then run these steps:
+ if signal.aborted() {
+ // 1. Enqueue the following step to the lock task queue:
+ queue_web_locks_task(vm, manager.realm, lock, |vm, lock| {
+ // 1. Release the lock lock.
+ LockData::release_lock(lock, vm);
+ });
+
+ // 2. Return.
+ return;
+ }
+
+ // 2. Remove the algorithm signal to abort the request request from signal.
+ if let Some(id) = request.abort_algorithm_id.get() {
+ signal.remove_algorithm(id);
+ }
+ }
+
+ // 2. Let r be the result of invoking callback with a new Lock object associated with lock as the
+ // only argument.
+ let cx = CallContext::new(vm, manager.realm);
+ let r = callback.invoke(None, &[Value::from_object(wrap(&cx, Lock::create(vm, lock)))]);
+
+ // 3. Resolve waiting with r.
+ resolve_promise(vm, waiting, Value::from_object(r.promise()));
+ },
+ );
+
+ react_to_promise(
+ vm,
+ waiting,
+ lock,
+ Some(LockData::waiting_promise_settled),
+ Some(LockData::waiting_promise_settled),
+ );
+ }
+ }
+
+ // https://w3c.github.io/web-locks/#snapshot-the-lock-state
+ fn snapshot_lock_state(&self, vm: &Vm, promise: WebIdlPromise) {
+ // 1. Assert: these steps are running on the lock task queue.
+
+ // 2. Let pending be a new list.
+ let mut pending = Vec::new();
+
+ // 3. For each queue of manager’s lock request queue map’s values:
+ for queue in self.lock_request_queue_map.borrow().0.values() {
+ // 1. For each request of queue:
+ for request in queue.0.borrow().iter() {
+ // 1. Append «[ "name" → request’s name, "mode" → request’s mode, "clientId" → request’s clientId ]»
+ // to pending.
+ pending.push(LockInfo {
+ name: Some(request.name.clone()),
+ mode: Some(request.mode),
+ client_id: Some(request.client_id.clone()),
+ });
+ }
+ }
+
+ // 4. Let held be a new list.
+ let mut held = Vec::new();
+
+ // 5. For each lock of manager’s held lock set:
+ for lock in self.held_lock_set.borrow().iter() {
+ // 1. Append «[ "name" → lock’s name, "mode" → lock’s mode, "clientId" → lock’s clientId ]» to held.
+ held.push(LockInfo {
+ name: Some(lock.name.clone()),
+ mode: Some(lock.mode),
+ client_id: Some(lock.client_id.clone()),
+ });
+ }
+
+ // 6. Resolve promise with «[ "held" → held, "pending" → pending ]».
+ let snapshot = LockManagerSnapshot {
+ held: Some(held),
+ pending: Some(pending),
+ };
+ let cx = CallContext::new(vm, self.realm);
+ resolve_promise(vm, promise, snapshot.into_js(&cx));
+ }
+}
+
+/// # Safety
+///
+/// The pointers must be the live VM and a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_web_locks_create_lock_manager(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(LockManager::create(vm, realm))
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock_request.rs b/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock_request.rs
new file mode 100644
index 00000000000..770c71be26a
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_locks/lock_request.rs
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use core::cell::Cell;
+
+use ak::Utf16String;
+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Vm};
+
+use crate::bindings::callback::PromiseCallbackFunction;
+use crate::bindings::interface::Ref;
+use crate::bindings::promise::{WebIdlPromise, reject_promise};
+use crate::dom::abort_signal::AbortSignal;
+use crate::web_locks::abstract_operations::queue_web_locks_task;
+use crate::web_locks::lock_manager::{LockManager, LockMode};
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct LockRequest {
+ #[gc(untraced)]
+ pub(crate) client_id: Utf16String,
+ pub(crate) manager: Ref<LockManager>,
+ #[gc(untraced)]
+ pub(crate) name: Utf16String,
+ #[gc(untraced)]
+ pub(crate) mode: LockMode,
+ pub(crate) callback: PromiseCallbackFunction,
+ pub(crate) promise: WebIdlPromise,
+ pub(crate) signal: Option<AbortSignal>,
+ pub(crate) abort_algorithm_id: Cell<Option<u64>>,
+}
+
+pub(crate) static LOCK_REQUEST_CLASS: EmbedderClass<LockRequest> = EmbedderClass::new("LockRequest");
+
+impl EmbedderValue for LockRequest {
+ const CLASS: &'static EmbedderClass<Self> = &LOCK_REQUEST_CLASS;
+}
+
+pub(crate) type LockRequestRef = Gc<EmbedderCell<LockRequest>>;
+
+impl LockRequest {
+ // https://w3c.github.io/web-locks/#abort-the-request
+ pub(crate) fn abort_request(this: LockRequestRef, vm: &Vm) {
+ // 1. Assert: these steps are running on the lock task queue.
+
+ // 2. Let manager be request’s manager.
+ let manager = this.manager;
+
+ // 3. Let name be request’s name.
+ let name = &this.name;
+
+ // 4. Let queueMap be manager’s lock request queue map.
+ let queue_map = &manager.lock_request_queue_map;
+
+ // 5. Let queue be the result of getting the lock request queue from queueMap for name.
+ let queue = queue_map.borrow_mut(vm).get_lock_request_queue(vm, name);
+
+ // 6. Remove request from queue.
+ queue.0.borrow_mut(vm).retain(|request| *request != this);
+
+ // 7. Process the lock request queue queue.
+ LockManager::process_lock_request_queue(vm, queue);
+ }
+
+ // https://w3c.github.io/web-locks/#signal-to-abort-the-request
+ pub(crate) fn signal_to_abort_request(this: LockRequestRef, vm: &Vm, signal: &AbortSignal) {
+ // 1. Enqueue the steps to abort the request request to the lock task queue.
+ queue_web_locks_task(vm, this.manager.realm, this, |vm, request| {
+ Self::abort_request(request, vm);
+ });
+
+ // 2. Reject request’s promise with signal’s abort reason.
+ reject_promise(vm, this.promise, signal.reason());
+ }
+
+ // https://w3c.github.io/web-locks/#grantable
+ pub(crate) fn is_grantable(this: LockRequestRef, vm: &Vm) -> bool {
+ // 1. Let manager be request’s manager.
+ let manager = this.manager;
+
+ // 2. Let queueMap be manager’s lock request queue map.
+ let queue_map = &manager.lock_request_queue_map;
+
+ // 3. Let name be request’s name.
+ let name = &this.name;
+
+ // 4. Let queue be the result of getting the lock request queue from queueMap for name.
+ let queue = queue_map.borrow_mut(vm).get_lock_request_queue(vm, name);
+
+ // 5. Let held be manager’s held lock set
+ let held = manager.held_lock_set.borrow();
+
+ // 6. Let mode be request’s mode
+ let mode = this.mode;
+
+ // 7. If queue is not empty and request is not the first item in queue, then return false.
+ if queue.0.borrow().front().is_some_and(|request| *request != this) {
+ return false;
+ }
+
+ // 8. If mode is "exclusive", then return true if no lock in held has name equal to name, and false otherwise.
+ if mode == LockMode::Exclusive {
+ return !held.iter().any(|lock| &lock.name == name);
+ }
+
+ // 9. Otherwise, mode is "shared"; return true if no lock in held has mode "exclusive" and has name equal to
+ // name, and false otherwise.
+ !held
+ .iter()
+ .any(|lock| lock.mode == LockMode::Exclusive && &lock.name == name)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_locks/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_locks/mod.rs
new file mode 100644
index 00000000000..087aa476429
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/web_locks/mod.rs
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+pub(crate) mod abstract_operations;
+pub(crate) mod lock;
+pub(crate) mod lock_manager;
+pub(crate) mod lock_request;
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index 85099c3a01a..cacfd5394bd 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -921,9 +921,7 @@ set(SOURCES
ViewTransition/ViewTransition.cpp
VisualLines.cpp
WebLocks/AbstractOperations.cpp
- WebLocks/Lock.cpp
WebLocks/LockManager.cpp
- WebLocks/LockRequest.cpp
WebLocks/NavigatorLocks.cpp
WebAssembly/WebAssembly.cpp
WebAudio/AnalyserNode.cpp
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 7ebbe4f33de..87c12b03514 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1247,9 +1247,7 @@ struct InputState;
namespace Web::WebLocks {
class Lock;
-class LockData;
class LockManager;
-class LockRequest;
class NavigatorLocks;
}
diff --git a/Libraries/LibWeb/WebLocks/AbstractOperations.cpp b/Libraries/LibWeb/WebLocks/AbstractOperations.cpp
index f21fd581e7a..f086aa92600 100644
--- a/Libraries/LibWeb/WebLocks/AbstractOperations.cpp
+++ b/Libraries/LibWeb/WebLocks/AbstractOperations.cpp
@@ -6,60 +6,43 @@
#include <AK/NeverDestroyed.h>
#include <LibGC/Function.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
#include <LibWeb/WebIDL/CallbackType.h>
-#include <LibWeb/WebLocks/AbstractOperations.h>
namespace Web::WebLocks {
+extern "C" {
+void web_locks_queue_task(JS::Realm*, GC::Cell*, void (*steps)(JSVM*, void*));
+void web_locks_queue_callback_task(WebIDL::CallbackType*, GC::Cell*, void (*steps)(JSVM*, void*));
+}
+
// https://w3c.github.io/web-locks/#lock-task-queue
-HTML::ParallelQueue& lock_task_queue()
+static HTML::ParallelQueue& lock_task_queue()
{
// A user agent has a lock task queue which is the result of starting a new parallel queue.
static NeverDestroyed<NonnullRefPtr<HTML::ParallelQueue>> queue { HTML::ParallelQueue::create() };
return **queue;
}
-void queue_web_locks_task(JS::Realm& realm, GC::Ref<GC::Function<void()>> steps)
+void web_locks_queue_task(JS::Realm* realm, GC::Cell* cell, void (*steps)(JSVM*, void*))
{
- lock_task_queue().enqueue(GC::create_function(realm.heap(), [realm = GC::Ref { realm }, steps]() {
+ lock_task_queue().enqueue(GC::create_function(realm->heap(), [realm = GC::Ref { *realm }, cell = GC::Ref { *cell }, steps] {
HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
- steps->function()();
+ steps(JS::HostABI::vm_to_abi(realm->vm()), cell.ptr());
}));
}
-void queue_web_locks_task_on_relevant_event_loop(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GC::Function<void()>> steps)
+void web_locks_queue_callback_task(WebIDL::CallbackType* callback, GC::Cell* cell, void (*steps)(JSVM*, void*))
{
auto& callback_context = callback->callback_context;
- HTML::queue_global_task(HTML::Task::Source::WebLocks, callback_context->global_object(), GC::create_function(callback_context->realm().heap(), [callback, steps]() {
+ HTML::queue_global_task(HTML::Task::Source::WebLocks, callback_context->global_object(), GC::create_function(callback_context->realm().heap(), [callback = GC::Ref { *callback }, cell = GC::Ref { *cell }, steps] {
HTML::TemporaryExecutionContext execution_context { callback->callback_context, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
- steps->function()();
+ steps(JS::HostABI::vm_to_abi(callback->callback_context->realm().vm()), cell.ptr());
}));
}
-// https://w3c.github.io/web-locks/#obtain-a-lock-manager
-LockManager& obtain_lock_manager(HTML::EnvironmentSettingsObject& environment)
-{
- // 1. Let map be the result of obtaining a local storage bottle map given environment and "web-locks".
- // 2. If map is failure, then return failure.
- // 3. Let bottle be map’s associated storage bottle.
- // 4. Return bottle’s associated lock manager.
-
- // FIXME: Spec issue: Storing and obtaining a lock manager in the environment's storage is currently not well
- // defined. So we store a single instance per environment for now. See:
- // https://w3c.github.io/web-locks/#issue-73644ca1
- return environment.lock_manager();
-}
-
-// https://w3c.github.io/web-locks/#get-the-lock-request-queue
-LockRequestQueue& get_lock_request_queue(LockRequestQueueMap& queue_map, Utf16String const& name)
-{
- // 1. If queueMap[name] does not exist, set queueMap[name] to a new empty lock request queue.
- // 2. Return queueMap[name].
- return queue_map.ensure(name);
-}
-
}
diff --git a/Libraries/LibWeb/WebLocks/AbstractOperations.h b/Libraries/LibWeb/WebLocks/AbstractOperations.h
deleted file mode 100644
index 6022b6eaec1..00000000000
--- a/Libraries/LibWeb/WebLocks/AbstractOperations.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/HashMap.h>
-#include <AK/Utf16String.h>
-#include <AK/Vector.h>
-#include <LibJS/Forward.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/HTML/EventLoop/Task.h>
-
-namespace Web::WebLocks {
-
-// https://w3c.github.io/web-locks/#lock-request-queue
-using LockRequestQueue = Vector<GC::Ref<LockRequest>>;
-
-// https://w3c.github.io/web-locks/#lock-manager-lock-request-queue-map
-using LockRequestQueueMap = HashMap<Utf16String, LockRequestQueue>;
-
-HTML::ParallelQueue& lock_task_queue();
-void queue_web_locks_task(JS::Realm&, GC::Ref<GC::Function<void()>> steps);
-void queue_web_locks_task_on_relevant_event_loop(GC::Ref<WebIDL::CallbackType> callback, GC::Ref<GC::Function<void()>> steps);
-
-LockManager& obtain_lock_manager(HTML::EnvironmentSettingsObject&);
-
-LockRequestQueue& get_lock_request_queue(LockRequestQueueMap&, Utf16String const& name);
-
-}
diff --git a/Libraries/LibWeb/WebLocks/Lock.cpp b/Libraries/LibWeb/WebLocks/Lock.cpp
deleted file mode 100644
index 9056caaae27..00000000000
--- a/Libraries/LibWeb/WebLocks/Lock.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Bindings/LockManager.h>
-#include <LibWeb/WebLocks/Lock.h>
-#include <LibWeb/WebLocks/LockManager.h>
-
-namespace Web::WebLocks {
-
-GC_DEFINE_ALLOCATOR(Lock);
-GC_DEFINE_ALLOCATOR(LockData);
-
-GC::Ref<Lock> Lock::create(JS::Realm& realm, GC::Ref<LockData> lock)
-{
- auto result = realm.create<Lock>(lock);
- return result;
-}
-
-Lock::Lock(GC::Ref<LockData> lock)
- : m_lock(lock)
-{
-}
-
-void Lock::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_lock);
-}
-
-// https://w3c.github.io/web-locks/#dom-lock-name
-Utf16String const& Lock::name() const
-{
- // The name getter’s steps are to return the associated lock’s name.
- return m_lock->name();
-}
-
-// https://w3c.github.io/web-locks/#dom-lock-mode
-Bindings::LockMode Lock::mode() const
-{
- // The mode getter’s steps are to return the associated lock’s mode.
- return m_lock->mode();
-}
-
-LockData::LockData(HTML::EnvironmentId client_id, GC::Ref<LockManager> manager, Bindings::LockMode mode, Utf16String name, GC::Ref<WebIDL::Promise> released_promise, GC::Ref<WebIDL::Promise> waiting_promise)
- : m_client_id(move(client_id))
- , m_manager(manager)
- , m_name(move(name))
- , m_mode(mode)
- , m_released_promise(released_promise)
- , m_waiting_promise(waiting_promise)
-{
-}
-
-void LockData::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_manager);
- visitor.visit(m_released_promise);
- visitor.visit(m_waiting_promise);
-}
-
-// https://w3c.github.io/web-locks/#release-the-lock
-void LockData::release_lock() const
-{
- // 1. Assert: these steps are running on the lock task queue.
-
- // 2. Let manager be lock’s manager.
- // 3. Let queueMap be manager’s lock request queue map.
- auto& queue_map = m_manager->lock_request_queue_map();
-
- // 4. Let name be lock’s resource name.
- // 5. Let queue be the result of getting the lock request queue from queueMap for name.
- auto& queue = get_lock_request_queue(queue_map, m_name);
-
- // 6. Remove lock from the manager’s held lock set.
- m_manager->held_lock_set().remove_first_matching([&](GC::Ref<LockData> held_lock) {
- return held_lock == GC::Ref { *this };
- });
-
- // 7. Process the lock request queue queue.
- m_manager->process_lock_request_queue(queue);
-}
-
-}
diff --git a/Libraries/LibWeb/WebLocks/Lock.h b/Libraries/LibWeb/WebLocks/Lock.h
index f8bd4927aba..87c9564f4e4 100644
--- a/Libraries/LibWeb/WebLocks/Lock.h
+++ b/Libraries/LibWeb/WebLocks/Lock.h
@@ -6,72 +6,13 @@
#pragma once
-#include <AK/Utf16String.h>
-#include <LibWeb/Bindings/LockManager.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Forward.h>
-#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
+#include <LibWeb/Bindings/Lock.h>
+#include <LibWeb/Bindings/RustInterface.h>
namespace Web::WebLocks {
-// https://w3c.github.io/web-locks/#lock
-class Lock final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(Lock, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(Lock);
-
-public:
- static GC::Ref<Lock> create(JS::Realm&, GC::Ref<LockData>);
- virtual ~Lock() override = default;
-
- Utf16String const& name() const;
- Bindings::LockMode mode() const;
-
-private:
- explicit Lock(GC::Ref<LockData>);
-
- virtual void visit_edges(Cell::Visitor& visitor) override;
-
- // https://w3c.github.io/web-locks/#ref-for-lock③
- GC::Ref<LockData> m_lock;
-};
-
-// https://w3c.github.io/web-locks/#lock-concept
-class LockData final : public JS::Cell {
- GC_CELL(LockData, JS::Cell);
- GC_DECLARE_ALLOCATOR(LockData);
-
-public:
- LockData(HTML::EnvironmentId client_id, GC::Ref<LockManager>, Bindings::LockMode, Utf16String name, GC::Ref<WebIDL::Promise> released_promise, GC::Ref<WebIDL::Promise> waiting_promise);
-
- void release_lock() const;
-
- HTML::EnvironmentId const& client_id() const { return m_client_id; }
- Utf16String const& name() const { return m_name; }
- Bindings::LockMode mode() const { return m_mode; }
-
- GC::Ref<WebIDL::Promise> released_promise() const { return m_released_promise; }
- GC::Ref<WebIDL::Promise> waiting_promise() const { return m_waiting_promise; }
-
-private:
- virtual void visit_edges(Cell::Visitor& visitor) override;
-
- // https://w3c.github.io/web-locks/#lock-concept-clientid
- HTML::EnvironmentId m_client_id;
-
- // https://w3c.github.io/web-locks/#lock-concept-manager
- GC::Ref<LockManager> m_manager;
-
- // https://w3c.github.io/web-locks/#lock-concept-name
- Utf16String m_name;
-
- // https://w3c.github.io/web-locks/#lock-concept-mode
- Bindings::LockMode m_mode;
-
- // https://w3c.github.io/web-locks/#lock-concept-released-promise
- GC::Ref<WebIDL::Promise> m_released_promise;
-
- // https://w3c.github.io/web-locks/#lock-concept-waiting-promise
- GC::Ref<WebIDL::Promise> m_waiting_promise;
+class Lock : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(Lock, lock)
};
}
diff --git a/Libraries/LibWeb/WebLocks/Lock.idl b/Libraries/LibWeb/WebLocks/Lock.idl
index 7a32a9c2e99..d83695eabb4 100644
--- a/Libraries/LibWeb/WebLocks/Lock.idl
+++ b/Libraries/LibWeb/WebLocks/Lock.idl
@@ -1,5 +1,5 @@
// https://w3c.github.io/web-locks/#lock
-[SecureContext, Exposed=(Window,Worker)]
+[SecureContext, Exposed=(Window,Worker), ImplementedIn=Rust]
interface Lock {
readonly attribute DOMString name;
readonly attribute LockMode mode;
diff --git a/Libraries/LibWeb/WebLocks/LockManager.cpp b/Libraries/LibWeb/WebLocks/LockManager.cpp
index 97899d56012..3660973f5b4 100644
--- a/Libraries/LibWeb/WebLocks/LockManager.cpp
+++ b/Libraries/LibWeb/WebLocks/LockManager.cpp
@@ -4,368 +4,26 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/Enumerate.h>
-#include <AK/NeverDestroyed.h>
-#include <LibJS/Runtime/Array.h>
-#include <LibJS/Runtime/PrimitiveString.h>
+#include <LibJS/HostClassBuilder.h>
#include <LibJS/Runtime/Realm.h>
-#include <LibJS/Runtime/Value.h>
-#include <LibWeb/Bindings/LockManager.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWeb/Bindings/WrapperWorld.h>
-#include <LibWeb/DOM/AbortSignal.h>
-#include <LibWeb/DOM/Document.h>
-#include <LibWeb/HTML/Window.h>
-#include <LibWeb/WebIDL/AbstractOperations.h>
-#include <LibWeb/WebIDL/DOMException.h>
-#include <LibWeb/WebIDL/Promise.h>
-#include <LibWeb/WebLocks/Lock.h>
+#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/WebLocks/LockManager.h>
-#include <LibWeb/WebLocks/LockRequest.h>
namespace Web::WebLocks {
-GC_DEFINE_ALLOCATOR(LockManager);
-
-GC::Ref<LockManager> LockManager::create(HTML::EnvironmentSettingsObject& environment)
-{
- return environment.heap().allocate<LockManager>(environment);
-}
-
-GC::Ptr<Bindings::Wrappable> LockManager::relevant_global_impl() const
-{
- return HTML::relevant_window_or_worker_global_scope(m_environment->global_object()).this_impl();
-}
-
-LockManager::LockManager(GC::Ref<HTML::EnvironmentSettingsObject> environment)
- : m_environment(environment)
-{
-}
-
-void LockManager::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_lock_request_queue_map);
- visitor.visit(m_held_lock_set);
- visitor.visit(m_environment);
-}
-
-// https://w3c.github.io/web-locks/#dom-lockmanager-request
-GC::Ref<WebIDL::Promise> LockManager::request(Utf16String const& name, GC::Ref<WebIDL::CallbackType> callback)
-{
- // 1. If options was not passed, then let options be a new LockOptions dictionary with default members.
- return request(name, {}, callback);
-}
-
-// https://w3c.github.io/web-locks/#dom-lockmanager-request
-GC::Ref<WebIDL::Promise> LockManager::request(Utf16String const& name, Bindings::LockOptions const& options, GC::Ref<WebIDL::CallbackType> callback)
-{
- // 2. Let environment be this’s relevant settings object.
- auto& environment = *m_environment;
-
- // 3. If environment’s relevant global object’s associated Document is not fully active, then return a promise
- // rejected with a "InvalidStateError" DOMException.
- if (auto* window = HTML::window_from_global_object(environment.global_object())) {
- if (!window->associated_document().is_fully_active())
- return WebIDL::create_rejected_promise_for(environment, WebIDL::InvalidStateError::create("Document is not fully active"_utf16));
- }
-
- // 4. Let manager be the result of obtaining a lock manager given environment. If that returned failure, then return
- // a promise rejected with a "SecurityError" DOMException.
- auto& manager = obtain_lock_manager(environment);
-
- // 5. If name starts with U+002D HYPHEN-MINUS (-), then return a promise rejected with a "NotSupportedError"
- // DOMException.
- if (name.utf16_view().starts_with(u"-"sv))
- return WebIDL::create_rejected_promise_for(environment, WebIDL::NotSupportedError::create("Lock names starting with '-' are reserved"_utf16));
-
- // 6. If both options["steal"] and options["ifAvailable"] are true, then return a promise rejected with a
- // "NotSupportedError" DOMException.
- if (options.steal && options.if_available)
- return WebIDL::create_rejected_promise_for(environment, WebIDL::NotSupportedError::create("Lock options 'steal' and 'ifAvailable' cannot both be true"_utf16));
-
- // 7. If options["steal"] is true and options["mode"] is not "exclusive", then return a promise rejected with a
- // "NotSupportedError" DOMException.
- if (options.steal && options.mode != Bindings::LockMode::Exclusive)
- return WebIDL::create_rejected_promise_for(environment, WebIDL::NotSupportedError::create("Lock option 'steal' can only be used with exclusive locks"_utf16));
-
- // 8. If options["signal"] exists, and either of options["steal"] or options["ifAvailable"] is true, then return a
- // promise rejected with a "NotSupportedError" DOMException.
- if (options.signal && (options.steal || options.if_available))
- return WebIDL::create_rejected_promise_for(environment, WebIDL::NotSupportedError::create("Lock option 'signal' cannot be combined with 'steal' or 'ifAvailable'"_utf16));
-
- // 9. If options["signal"] exists and is aborted, then return a promise rejected with options["signal"]'s abort reason.
- if (options.signal && options.signal->aborted())
- return WebIDL::create_rejected_promise_for(environment, options.signal->reason());
-
- // 10. Let promise be a new promise.
- auto promise = WebIDL::create_promise_for(environment);
-
- // 11. Request a lock with promise, the current agent, environment’s id, manager, callback, name, options["mode"],
- // options["ifAvailable"], options["steal"], and options["signal"].
- manager.request_lock(promise, callback, name, options.mode, options.if_available, options.steal, options.signal);
-
- // 12. Return promise.
- return promise;
-}
-
-// https://w3c.github.io/web-locks/#dom-lockmanager-query
-GC::Ref<WebIDL::Promise> LockManager::query()
-{
- auto& realm = m_environment->realm();
-
- // 1. Let environment be this’s relevant settings object.
- auto& environment = *m_environment;
-
- // 2. If environment’s relevant global object’s associated Document is not fully active, then return a promise
- // rejected with a "InvalidStateError" DOMException.
- if (auto* window = HTML::window_from_global_object(environment.global_object())) {
- if (!window->associated_document().is_fully_active())
- return WebIDL::create_rejected_promise_for(environment, WebIDL::InvalidStateError::create("Document is not fully active"_utf16));
- }
-
- // 3. Let manager be the result of obtaining a lock manager given environment. If that returned failure, then return
- // a promise rejected with a "SecurityError" DOMException.
- auto& manager = obtain_lock_manager(environment);
-
- // 4. Let promise be a new promise.
- auto promise = WebIDL::create_promise_for(environment);
-
- // 5. Enqueue the steps to snapshot the lock state for manager with promise to the lock task queue.
- queue_web_locks_task(realm, GC::create_function(heap(), [manager = GC::Ref { manager }, promise]() {
- manager->snapshot_lock_state(promise);
- }));
-
- // 6. Return promise.
- return promise;
-}
-
-// https://w3c.github.io/web-locks/#request-a-lock
-GC::Ref<LockRequest> LockManager::request_lock(GC::Ref<WebIDL::Promise> promise, GC::Ref<WebIDL::CallbackType> callback, Utf16String name, Bindings::LockMode mode, bool if_available, bool steal, GC::Ptr<DOM::AbortSignal> signal)
-{
- auto& environment = *m_environment;
-
- // 1. Let request be a new lock request (agent, clientId, manager, name, mode, callback, promise, signal).
- auto request = heap().allocate<LockRequest>(environment.id, *this, move(name), mode, callback, promise, signal);
-
- // 2. If signal is present, then add the algorithm signal to abort the request request with signal to signal.
- if (signal) {
- request->set_abort_algorithm_id(signal->add_abort_algorithm([request, signal]() {
- request->signal_to_abort_request(*signal);
- }));
- }
-
- // 3. Enqueue the following steps to the lock task queue:
- queue_web_locks_task(m_environment->realm(), GC::create_function(heap(), [this, request, if_available, steal]() {
- // 1. Let queueMap be manager’s lock request queue map.
- // 2. Let queue be the result of getting the lock request queue from queueMap for name.
- auto& queue = get_lock_request_queue(m_lock_request_queue_map, request->name());
-
- // 3. Let held be manager’s held lock set.
- // 4. If steal is true, then run these steps:
- if (steal) {
- // 1. For each lock of held:
- for (size_t i = 0; i < m_held_lock_set.size();) {
- auto lock = m_held_lock_set[i];
-
- // 1. If lock’s name is name, then run these steps:
- if (lock->name() == request->name()) {
- // 1. Remove lock from held.
- m_held_lock_set.remove(i);
-
- // 2. Reject lock’s released promise with an "AbortError" DOMException.
- WebIDL::reject_promise(lock->released_promise(), WebIDL::AbortError::create("Lock was stolen"_utf16));
- } else {
- ++i;
- }
- }
-
- // 2. Prepend request in queue.
- queue.prepend(request);
- }
- // 5. Otherwise, run these steps:
- else {
- // 1. If ifAvailable is true and request is not grantable, then enqueue the following steps on callback’s
- // relevant settings object’s responsible event loop:
- if (if_available && !request->is_grantable(queue)) {
- queue_web_locks_task_on_relevant_event_loop(request->callback(), GC::create_function(heap(), [request]() {
- // 1. Let r be the result of invoking callback with null as the only argument.
- auto result = WebIDL::invoke_promise_callback(request->callback(), {}, { { JS::js_null() } });
-
- // 2. Resolve promise with r and abort these steps.
- WebIDL::resolve_promise(request->promise(), result->promise());
- }));
-
- // NB: This request has completed with no lock. Continuing here would enqueue it and allow it to be
- // granted later, causing callback to be invoked a second time with a Lock.
- return;
- }
-
- // 2. Enqueue request in queue.
- queue.append(request);
- }
-
- // 6. Process the lock request queue queue.
- process_lock_request_queue(queue);
- }));
-
- // 4. Return request.
- return request;
+extern "C" {
+void* web_rust_web_locks_create_lock_manager(JSVM*, void* realm);
+LockManager* web_locks_environment_lock_manager(HTML::EnvironmentSettingsObject*);
}
-// https://w3c.github.io/web-locks/#process-the-lock-request-queue
-void LockManager::process_lock_request_queue(LockRequestQueue& queue)
+GC::Ref<LockManager> LockManager::create(HTML::EnvironmentSettingsObject& environment)
{
- auto& realm = m_environment->realm();
-
- // 1. Assert: these steps are running on the lock task queue.
-
- // 2. For each request of queue:
- for (size_t i = 0; i < queue.size();) {
- auto request = queue[i];
-
- // 1. If request is not grantable, then return.
- // NOTE: Only the first item in a queue is grantable. Therefore, if something is not grantable then all the
- // following items are automatically not grantable.
- if (!request->is_grantable(queue))
- return;
-
- // 2. Remove request from queue.
- queue.remove(i);
-
- // 3. Let agent be request’s agent.
-
- // 4. Let manager be request’s manager.
- auto& manager = request->manager();
-
- // 5. Let clientId be request’s clientId.
- auto const& client_id = request->client_id();
-
- // 6. Let name be request’s name.
- auto const& name = request->name();
-
- // 7. Let name be request’s name.
- auto mode = request->mode();
-
- // 8. Let callback be request’s callback.
- auto callback = request->callback();
-
- // 9. Let p be request’s promise.
- auto promise = request->promise();
-
- // 10. Let signal be request’s signal.
- auto signal = request->signal();
-
- // 11. Let waiting be a new promise.
- auto waiting = WebIDL::create_promise(realm);
-
- // 12. Let lock be a new lock with agent agent, clientId clientId, manager manager, mode mode, name name,
- // released promise p, and waiting promise waiting.
- auto lock = heap().allocate<LockData>(client_id, manager, mode, name, promise, waiting);
-
- // 13. Append lock to manager’s held lock set.
- manager.m_held_lock_set.append(lock);
-
- // 14. Enqueue the following steps on callback’s relevant settings object’s responsible event loop:
- queue_web_locks_task_on_relevant_event_loop(callback, GC::create_function(heap(), [this, request, lock, signal, callback, waiting]() {
- auto& realm = m_environment->realm();
-
- // 1. If signal is present, then run these steps:
- if (signal) {
- // 1. If signal is aborted, then run these steps:
- if (signal->aborted()) {
- // 1. Enqueue the following step to the lock task queue:
- queue_web_locks_task(realm, GC::create_function(heap(), [lock]() {
- // 1. Release the lock lock.
- lock->release_lock();
- }));
-
- // 2. Return.
- return;
- }
-
- // 2. Remove the algorithm signal to abort the request request from signal.
- if (auto abort_algorithm_id = request->abort_algorithm_id(); abort_algorithm_id.has_value())
- signal->remove_abort_algorithm(*abort_algorithm_id);
- }
-
- // 2. Let r be the result of invoking callback with a new Lock object associated with lock as the only argument.
- auto result = WebIDL::invoke_promise_callback(callback, {}, { { Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, Lock::create(realm, lock)) } });
-
- // 3. Resolve waiting with r.
- WebIDL::resolve_promise(waiting, result->promise());
- }));
-
- // https://w3c.github.io/web-locks/#waiting-promise-settles
- // When lock's waiting promise settles (fulfills or rejects), enqueue the following steps on the lock task queue:
- auto waiting_promise_settled_steps = GC::create_function(heap(), [this, lock](JS::Value) -> WebIDL::ExceptionOr<JS::Value> {
- auto& realm = m_environment->realm();
-
- queue_web_locks_task(realm, GC::create_function(heap(), [lock]() {
- // 1. Release the lock lock.
- lock->release_lock();
-
- // 2. Resolve lock's released promise with lock's waiting promise.
- WebIDL::resolve_promise(lock->released_promise(), lock->waiting_promise()->promise());
- }));
-
- return JS::js_undefined();
- });
-
- WebIDL::react_to_promise(waiting, waiting_promise_settled_steps, waiting_promise_settled_steps);
- }
+ return *static_cast<LockManager*>(web_rust_web_locks_create_lock_manager(JS::HostABI::vm_to_abi(environment.realm().vm()), &environment.realm()));
}
-// https://w3c.github.io/web-locks/#snapshot-the-lock-state
-void LockManager::snapshot_lock_state(GC::Ref<WebIDL::Promise> promise)
+LockManager* web_locks_environment_lock_manager(HTML::EnvironmentSettingsObject* environment)
{
- auto& realm = m_environment->realm();
- auto& vm = realm.vm();
-
- static NeverDestroyed<AK::Utf16FlyString> CLIENT_ID = "clientId"_utf16_fly_string;
- static NeverDestroyed<AK::Utf16FlyString> HELD = "held"_utf16_fly_string;
- static NeverDestroyed<AK::Utf16FlyString> MODE = "mode"_utf16_fly_string;
- static NeverDestroyed<AK::Utf16FlyString> NAME = "name"_utf16_fly_string;
- static NeverDestroyed<AK::Utf16FlyString> PENDING = "pending"_utf16_fly_string;
-
- auto create_lock_info_object = [&](auto lock) {
- auto lock_info = JS::Object::create(realm, realm.intrinsics().object_prototype());
- MUST(lock_info->create_data_property_or_throw(*NAME, JS::PrimitiveString::create(vm, lock->name())));
- MUST(lock_info->create_data_property_or_throw(*MODE, JS::PrimitiveString::create(vm, Bindings::idl_enum_to_string(lock->mode()))));
- MUST(lock_info->create_data_property_or_throw(*CLIENT_ID, JS::PrimitiveString::create(vm, Utf16String::from_utf8(lock->client_id().to_string()))));
-
- return lock_info;
- };
-
- // 1. Assert: these steps are running on the lock task queue.
-
- // 2. Let pending be a new list.
- auto pending = MUST(JS::Array::create(realm, 0));
- u32 pending_index = 0;
-
- // 3. For each queue of manager’s lock request queue map’s values:
- for (auto const& queue : m_lock_request_queue_map) {
- // 1. For each request of queue:
- for (auto request : queue.value) {
- // 1. Append «[ "name" → request’s name, "mode" → request’s mode, "clientId" → request’s clientId ]» to pending.
- MUST(pending->create_data_property_or_throw(pending_index++, create_lock_info_object(request)));
- }
- }
-
- // 4. Let held be a new list.
- auto held = MUST(JS::Array::create(realm, 0));
-
- // 5. For each lock of manager’s held lock set:
- for (auto [i, lock] : enumerate(m_held_lock_set)) {
- // 1. Append «[ "name" → lock’s name, "mode" → lock’s mode, "clientId" → lock’s clientId ]» to held.
- MUST(held->create_data_property_or_throw(i, create_lock_info_object(lock)));
- }
-
- // 6. Resolve promise with «[ "held" → held, "pending" → pending ]».
- auto snapshot = JS::Object::create(realm, realm.intrinsics().object_prototype());
- MUST(snapshot->create_data_property_or_throw(*HELD, held));
- MUST(snapshot->create_data_property_or_throw(*PENDING, pending));
- WebIDL::resolve_promise(promise, snapshot);
+ return environment->lock_manager().ptr();
}
}
diff --git a/Libraries/LibWeb/WebLocks/LockManager.h b/Libraries/LibWeb/WebLocks/LockManager.h
index 87125b0f666..ef9b8f02a63 100644
--- a/Libraries/LibWeb/WebLocks/LockManager.h
+++ b/Libraries/LibWeb/WebLocks/LockManager.h
@@ -6,49 +6,18 @@
#pragma once
+#include <LibJS/Forward.h>
#include <LibWeb/Bindings/LockManager.h>
-#include <LibWeb/Bindings/Wrappable.h>
+#include <LibWeb/Bindings/RustInterface.h>
#include <LibWeb/Forward.h>
-#include <LibWeb/WebIDL/Promise.h>
-#include <LibWeb/WebLocks/AbstractOperations.h>
namespace Web::WebLocks {
-class LockManager final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(LockManager, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(LockManager);
+class LockManager : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(LockManager, lock_manager)
public:
static GC::Ref<LockManager> create(HTML::EnvironmentSettingsObject&);
- virtual ~LockManager() override = default;
-
- GC::Ref<WebIDL::Promise> request(Utf16String const& name, GC::Ref<WebIDL::CallbackType>);
- GC::Ref<WebIDL::Promise> request(Utf16String const& name, Bindings::LockOptions const&, GC::Ref<WebIDL::CallbackType>);
- GC::Ref<WebIDL::Promise> query();
-
- void process_lock_request_queue(LockRequestQueue&);
-
- LockRequestQueueMap& lock_request_queue_map() { return m_lock_request_queue_map; }
- Vector<GC::Ref<LockData>>& held_lock_set() { return m_held_lock_set; }
- JS::Realm& relevant_realm() const { return m_environment->realm(); }
-
-private:
- explicit LockManager(GC::Ref<HTML::EnvironmentSettingsObject>);
-
- virtual void visit_edges(Cell::Visitor&) override;
- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;
-
- GC::Ref<LockRequest> request_lock(GC::Ref<WebIDL::Promise>, GC::Ref<WebIDL::CallbackType>, Utf16String name, Bindings::LockMode, bool if_available, bool steal, GC::Ptr<DOM::AbortSignal>);
-
- void snapshot_lock_state(GC::Ref<WebIDL::Promise>);
-
- // https://w3c.github.io/web-locks/#lock-manager-held-lock-set
- Vector<GC::Ref<LockData>> m_held_lock_set;
-
- // https://w3c.github.io/web-locks/#lock-manager-lock-request-queue-map
- LockRequestQueueMap m_lock_request_queue_map;
-
- GC::Ref<HTML::EnvironmentSettingsObject> m_environment;
};
}
diff --git a/Libraries/LibWeb/WebLocks/LockManager.idl b/Libraries/LibWeb/WebLocks/LockManager.idl
index 6a35e6c68f2..3d8d178a94f 100644
--- a/Libraries/LibWeb/WebLocks/LockManager.idl
+++ b/Libraries/LibWeb/WebLocks/LockManager.idl
@@ -1,8 +1,8 @@
// https://w3c.github.io/web-locks/#lockmanager
-[SecureContext, Exposed=(Window,Worker)]
+[SecureContext, Exposed=(Window,Worker), ImplementedIn=Rust]
interface LockManager {
- Promise<any> request(DOMString name, LockGrantedCallback callback);
- Promise<any> request(DOMString name, LockOptions options, LockGrantedCallback callback);
+ [ImplementedAs=request] Promise<any> request(DOMString name, LockGrantedCallback callback);
+ [ImplementedAs=request] Promise<any> request(DOMString name, LockOptions options, LockGrantedCallback callback);
Promise<LockManagerSnapshot> query();
};
diff --git a/Libraries/LibWeb/WebLocks/LockRequest.cpp b/Libraries/LibWeb/WebLocks/LockRequest.cpp
deleted file mode 100644
index f693317d28c..00000000000
--- a/Libraries/LibWeb/WebLocks/LockRequest.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#include <LibWeb/Bindings/LockManager.h>
-#include <LibWeb/DOM/AbortSignal.h>
-#include <LibWeb/WebLocks/Lock.h>
-#include <LibWeb/WebLocks/LockManager.h>
-#include <LibWeb/WebLocks/LockRequest.h>
-
-namespace Web::WebLocks {
-
-GC_DEFINE_ALLOCATOR(LockRequest);
-
-LockRequest::LockRequest(HTML::EnvironmentId client_id, GC::Ref<LockManager> manager, Utf16String name, Bindings::LockMode mode, GC::Ref<WebIDL::CallbackType> callback, GC::Ref<WebIDL::Promise> promise, GC::Ptr<DOM::AbortSignal> signal)
- : m_client_id(move(client_id))
- , m_manager(manager)
- , m_name(move(name))
- , m_mode(mode)
- , m_callback(callback)
- , m_promise(promise)
- , m_signal(signal)
-{
-}
-
-void LockRequest::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_manager);
- visitor.visit(m_callback);
- visitor.visit(m_promise);
- visitor.visit(m_signal);
-}
-
-// https://w3c.github.io/web-locks/#abort-the-request
-void LockRequest::abort_request()
-{
- // 1. Assert: these steps are running on the lock task queue.
-
- // 2. Let manager be request’s manager.
- // 3. Let name be request’s name.
- // 4. Let queueMap be manager’s lock request queue map.
- auto& queue_map = m_manager->lock_request_queue_map();
-
- // 5. Let queue be the result of getting the lock request queue from queueMap for name.
- auto& queue = get_lock_request_queue(queue_map, m_name);
-
- // 6. Remove request from queue.
- queue.remove_first_matching([&](GC::Ref<LockRequest> queued_request) {
- return queued_request == GC::Ref { *this };
- });
-
- // 7. Process the lock request queue queue.
- m_manager->process_lock_request_queue(queue);
-}
-
-// https://w3c.github.io/web-locks/#signal-to-abort-the-request
-void LockRequest::signal_to_abort_request(GC::Ref<DOM::AbortSignal> signal)
-{
- // 1. Enqueue the steps to abort the request request to the lock task queue.
- queue_web_locks_task(m_manager->relevant_realm(), GC::create_function(heap(), [this]() {
- abort_request();
- }));
-
- // 2. Reject request’s promise with signal’s abort reason.
- WebIDL::reject_promise(m_manager->relevant_realm(), m_promise, signal->reason());
-}
-
-// https://w3c.github.io/web-locks/#grantable
-bool LockRequest::is_grantable(LockRequestQueue const& queue) const
-{
- // 1. Let manager be request’s manager.
- // 2. Let queueMap be manager’s lock request queue map.
- // 3. Let name be request’s name.
- // 4. Let queue be the result of getting the lock request queue from queueMap for name.
- // NB: Every caller already has the queue this request belongs to. We avoid repeating an invocation to get the queue
- // from the queue map here as the repeated HashMap::ensure might rehash the table and invalidate references.
-
- // 5. Let held be manager’s held lock set
- auto const& held = m_manager->held_lock_set();
-
- // 6. Let mode be request’s mode
-
- // 7. If queue is not empty and request is not the first item in queue, then return false.
- if (!queue.is_empty() && queue.first() != GC::Ref { *this })
- return false;
-
- // 8. If mode is "exclusive", then return true if no lock in held has name equal to name, and false otherwise.
- if (m_mode == Bindings::LockMode::Exclusive) {
- return !held.contains([&](GC::Ref<LockData> lock) {
- return lock->name() == m_name;
- });
- }
-
- // 9. Otherwise, mode is "shared"; return true if no lock in held has mode "exclusive" and has name equal to name,
- // and false otherwise.
- return !held.contains([&](GC::Ref<LockData> lock) {
- return lock->mode() == Bindings::LockMode::Exclusive && lock->name() == m_name;
- });
-}
-
-}
diff --git a/Libraries/LibWeb/WebLocks/LockRequest.h b/Libraries/LibWeb/WebLocks/LockRequest.h
deleted file mode 100644
index 63e9d2388ae..00000000000
--- a/Libraries/LibWeb/WebLocks/LockRequest.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Utf16String.h>
-#include <LibJS/Heap/Cell.h>
-#include <LibWeb/DOM/AbortSignal.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/WebLocks/AbstractOperations.h>
-#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>
-
-namespace Web::WebLocks {
-
-// https://w3c.github.io/web-locks/#lock-request
-class LockRequest final : public JS::Cell {
- GC_CELL(LockRequest, JS::Cell);
- GC_DECLARE_ALLOCATOR(LockRequest);
-
-public:
- LockRequest(HTML::EnvironmentId client_id, GC::Ref<LockManager>, Utf16String name, Bindings::LockMode, GC::Ref<WebIDL::CallbackType>, GC::Ref<WebIDL::Promise>, GC::Ptr<DOM::AbortSignal>);
-
- void abort_request();
- void signal_to_abort_request(GC::Ref<DOM::AbortSignal> signal);
-
- bool is_grantable(LockRequestQueue const&) const;
-
- HTML::EnvironmentId const& client_id() const { return m_client_id; }
- LockManager& manager() const { return m_manager; }
-
- Utf16String const& name() const { return m_name; }
- Bindings::LockMode mode() const { return m_mode; }
-
- GC::Ref<WebIDL::CallbackType> callback() const { return m_callback; }
- GC::Ref<WebIDL::Promise> promise() const { return m_promise; }
-
- GC::Ptr<DOM::AbortSignal> signal() const { return m_signal; }
- Optional<DOM::AbortSignal::AbortAlgorithmID> abort_algorithm_id() const { return m_abort_algorithm_id; }
- void set_abort_algorithm_id(Optional<DOM::AbortSignal::AbortAlgorithmID> abort_algorithm_id) { m_abort_algorithm_id = abort_algorithm_id; }
-
-private:
- virtual void visit_edges(Cell::Visitor& visitor) override;
-
- HTML::EnvironmentId m_client_id;
- GC::Ref<LockManager> m_manager;
- Utf16String m_name;
- Bindings::LockMode m_mode;
- GC::Ref<WebIDL::CallbackType> m_callback;
- GC::Ref<WebIDL::Promise> m_promise;
- GC::Ptr<DOM::AbortSignal> m_signal;
- Optional<DOM::AbortSignal::AbortAlgorithmID> m_abort_algorithm_id;
-};
-
-}
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 30003ee7f33..3ded26a038a 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -99,7 +99,7 @@ ALLOWED_REALM_MENTIONS = {
),
"WebDriver": (2, 7, "WebDriver execute/JSON conversion still materializes JS values for automation"),
"WebGL": (4, 8, "WebGL contexts are created in the realm of their canvas, and their events in it"),
- "WebLocks": (6, 7, "Web Locks queue/callback algorithms still use callback and promise realms"),
+ "WebLocks": (2, 4, "the C++ glue creates a Rust LockManager and schedules Rust steps in selected realms"),
"WebRTC": (
13,
22,
diff --git a/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index ff17bd6b0fe..c8e182e7912 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -3,6 +3,8 @@ Layout/input/pdf-viewer.pdf
Text/input/PDF/jbig2-image.html
[LoadFromHttpServer]
+Text/input/wpt-import/web-locks/acquire.https.any.worker.html
+Text/input/wpt-import/web-locks/signal.https.any.worker.html
Text/input/wpt-import/html/semantics/forms/the-input-element/input-untrusted-key-event.html
Text/input/wpt-import/html/browsers/origin/origin-keyed-agent-clusters/
; These custom-element fixtures fetch a detached document by XHR.
diff --git a/Tests/LibWeb/Text/expected/wpt-import/web-locks/acquire.https.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/web-locks/acquire.https.any.worker.txt
new file mode 100644
index 00000000000..3b4c04a9c4f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/web-locks/acquire.https.any.worker.txt
@@ -0,0 +1,16 @@
+Harness status: OK
+
+Found 11 tests
+
+11 Pass
+Pass navigator.locks.request requires a name and a callback
+Pass mode must be "shared" or "exclusive"
+Pass The 'steal' and 'ifAvailable' options are mutually exclusive
+Pass The 'steal' option must be used with exclusive locks
+Pass The 'signal' and 'steal' options are mutually exclusive
+Pass The 'signal' and 'ifAvailable' options are mutually exclusive
+Pass callback must be a function
+Pass navigator.locks.request's returned promise resolves after lock is released
+Pass Returned Promise rejects if callback throws synchronously
+Pass Returned Promise rejects if callback throws asynchronously
+Pass If callback throws a thenable, its then() should not be invoked
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/web-locks/secure-context.https.any.txt b/Tests/LibWeb/Text/expected/wpt-import/web-locks/secure-context.https.any.txt
new file mode 100644
index 00000000000..c4bb8b8b6a6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/web-locks/secure-context.https.any.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass API presence in secure contexts
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/web-locks/signal.https.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/web-locks/signal.https.any.worker.txt
new file mode 100644
index 00000000000..e1180517794
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/web-locks/signal.https.any.worker.txt
@@ -0,0 +1,18 @@
+Harness status: OK
+
+Found 13 tests
+
+13 Pass
+Pass The signal option must be an AbortSignal
+Pass Passing an already aborted signal aborts
+Pass Passing an already aborted signal rejects with the custom abort reason.
+Pass Passing an already aborted signal rejects with the default abort reason.
+Pass An aborted request results in AbortError
+Pass Abort after a timeout
+Pass Signal that is not aborted
+Pass Synchronously signaled abort
+Pass Abort signaled after lock granted
+Pass Abort signaled after lock released
+Pass Abort should process the next pending lock request
+Pass Aborted promise should reject with the custom abort reason
+Pass Aborted promise should reject with the default abort reason
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/wpt-import/web-locks/acquire.https.any.worker.html b/Tests/LibWeb/Text/input/wpt-import/web-locks/acquire.https.any.worker.html
new file mode 100644
index 00000000000..7b4fd65e90f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/web-locks/acquire.https.any.worker.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Web Locks API: navigator.locks.request method</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<div id=log></div>
+<script>
+fetch_tests_from_worker(new Worker("../web-locks/acquire.https.any.worker.js"));
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/web-locks/acquire.https.any.worker.js b/Tests/LibWeb/Text/input/wpt-import/web-locks/acquire.https.any.worker.js
new file mode 100644
index 00000000000..46ca30b264c
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/web-locks/acquire.https.any.worker.js
@@ -0,0 +1,11 @@
+
+self.GLOBAL = {
+ isWindow: function() { return false; },
+ isWorker: function() { return true; },
+ isShadowRealm: function() { return false; },
+};
+importScripts("/resources/testharness.js");
+self.META_TITLE = "Web Locks API: navigator.locks.request method";
+importScripts("resources/helpers.js")
+importScripts("/web-locks/acquire.https.any.js");
+done();
diff --git a/Tests/LibWeb/Text/input/wpt-import/web-locks/secure-context.https.any.html b/Tests/LibWeb/Text/input/wpt-import/web-locks/secure-context.https.any.html
new file mode 100644
index 00000000000..88874ca8911
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/web-locks/secure-context.https.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Web Locks API: API requires secure context</title>
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../web-locks/secure-context.https.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/web-locks/secure-context.https.any.js b/Tests/LibWeb/Text/input/wpt-import/web-locks/secure-context.https.any.js
new file mode 100644
index 00000000000..29ae7aea475
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/web-locks/secure-context.https.any.js
@@ -0,0 +1,14 @@
+// META: title=Web Locks API: API requires secure context
+// META: global=window,dedicatedworker,sharedworker,serviceworker
+
+'use strict';
+
+test(t => {
+ assert_true(self.isSecureContext);
+ assert_idl_attribute(navigator, 'locks',
+ 'navigator.locks exists in secure context');
+ assert_true('LockManager' in self,
+ 'LockManager is present in secure contexts');
+ assert_true('Lock' in self,
+ 'Lock interface is present in secure contexts');
+}, 'API presence in secure contexts');
diff --git a/Tests/LibWeb/Text/input/wpt-import/web-locks/signal.https.any.worker.html b/Tests/LibWeb/Text/input/wpt-import/web-locks/signal.https.any.worker.html
new file mode 100644
index 00000000000..6e7aa2af3b7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/web-locks/signal.https.any.worker.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>Web Locks API: AbortSignal integration</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<div id=log></div>
+<script>
+fetch_tests_from_worker(new Worker("../web-locks/signal.https.any.worker.js"));
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/web-locks/signal.https.any.worker.js b/Tests/LibWeb/Text/input/wpt-import/web-locks/signal.https.any.worker.js
new file mode 100644
index 00000000000..88f14285052
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/web-locks/signal.https.any.worker.js
@@ -0,0 +1,11 @@
+
+self.GLOBAL = {
+ isWindow: function() { return false; },
+ isWorker: function() { return true; },
+ isShadowRealm: function() { return false; },
+};
+importScripts("/resources/testharness.js");
+self.META_TITLE = "Web Locks API: AbortSignal integration";
+importScripts("resources/helpers.js")
+importScripts("/web-locks/signal.https.any.js");
+done();