Truly independent web browser
LibWeb: Port storage shelves, buckets, bottles and mirrors to Rust
Shannon Boothd1824f58492b
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rsindex 80cd4744bf4..c8903f50f2d 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/environment_settings_object.rs@@ -8,12 +8,25 @@use core::ffi::c_void;+use core::ptr::NonNull;+use libjs_rust::api::{Gc, Object, Trace};use crate::bindings::cpp_cell::CppCell;unsafe extern "C" {fn web_bindings_relevant_settings_object(global_object: *mut c_void) -> *mut c_void;+ fn web_bindings_environment_settings_object_global_object(settings_object: *mut c_void) -> *mut c_void;+ fn web_bindings_environment_settings_object_id(+ settings_object: *mut c_void,+ id: *mut c_void,+ on_id: unsafe extern "C" fn(*mut c_void, ak::Span<'_, u8>),+ );+}++unsafe extern "C" fn on_id(id: *mut c_void, bytes: ak::Span<'_, u8>) {+ // SAFETY: id is the string of the caller, and LibWeb lends the id, which is ASCII, for the call.+ unsafe { *id.cast::<String>() = String::from_utf8_lossy(bytes.as_slice()).into_owned() };}/// https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object@@ -33,4 +46,20 @@ impl CppEnvironmentSettingsObject {pub(crate) fn as_ptr(&self) -> *mut c_void {self.0.as_ptr()}++ /// https://html.spec.whatwg.org/multipage/webappapis.html#concept-environment-id+ pub(crate) fn id(&self) -> String {+ let mut id = String::new();+ // SAFETY: The settings object is live, and the id outlives the call.+ unsafe { web_bindings_environment_settings_object_id(self.as_ptr(), (&raw mut id).cast(), on_id) };+ id+ }++ /// https://html.spec.whatwg.org/multipage/webappapis.html#concept-settings-object-global+ pub(crate) fn global_object(&self) -> Gc<Object> {+ // SAFETY: The settings object is live, and LibWeb returns its live global object.+ let global_object = unsafe { web_bindings_environment_settings_object_global_object(self.as_ptr()) };+ // SAFETY: The global object is live.+ unsafe { Gc::from_non_null(NonNull::new(global_object.cast()).expect("a settings object has a global object")) }+ }}diff --git a/Libraries/LibWeb/Bindings/Rust/src/ffi_test_stubs.rs b/Libraries/LibWeb/Bindings/Rust/src/ffi_test_stubs.rsnew file mode 100644index 00000000000..232ae709c85--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/ffi_test_stubs.rs@@ -0,0 +1,21 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The AK functions that unit tests reference without linking AK. The tests only use short ASCII strings, which live+//! in the word itself.++#[unsafe(no_mangle)]+extern "C" fn ladybird_utf16_string_unref(_raw: usize) {}++#[unsafe(no_mangle)]+extern "C" fn ladybird_utf16_string_create_uninitialized(_length: usize, _has_latin1_storage: bool) -> usize {+ unreachable!("no unit test makes a string the host owns");+}++#[unsafe(no_mangle)]+extern "C" fn ladybird_utf16_string_from_utf8(_data: *const u8, _length: usize) -> usize {+ unreachable!("no unit test makes a string the host owns");+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rsindex 682924551aa..f345e5e95cd 100644--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs@@ -22,15 +22,17 @@ use super::broadcast_channel::{BROADCAST_CHANNEL_MESSAGE_CLASS, BroadcastChanneluse super::image_bitmap::ImageBitmap;use super::image_data::ImageData;use super::message_port::MessagePort;-use super::storage::{Storage, StorageType, dispatch_storage_events};+use super::storage::{Storage, StorageType};use super::storage_event::{StorageEvent, StorageEventInit};use crate::bindings::CallContext;use crate::bindings::conversions::UsvString;+use crate::bindings::environment_settings_object::relevant_settings_object;use crate::bindings::event_target::CppEventTarget;use crate::bindings::interface::{Interface, Ref, cell_from_abi, cell_into_abi, realm_arguments};use crate::dom::event::EventInit;use crate::html::structured_serialize::message_record::MessageRecord;-use crate::storage_api::storage_bottle::StorageBottle;+use crate::storage_api::storage_area_mirror::StorageEndpointType;+use crate::storage_api::storage_bottle::{obtain_a_local_storage_bottle_map, obtain_a_session_storage_bottle_map};use crate::storage_api::storage_key::StorageKey;/// The implementation of the object whose cell C++ lends, for as long as C++ keeps the cell alive.@@ -396,33 +398,64 @@ pub unsafe extern "C" fn web_rust_broadcast_channel_deliver_message_locally(BroadcastChannel::deliver_message_locally(vm, message, None);}-/// A new Storage object of the type, 0 for "local" and 1 for "session", whose map is the bottle, in the realm of the-/// Window it is for.+/// A new Storage object of the type, 0 for "local" and 1 for "session", for the Window of the realm, whose map is a new+/// storage proxy map over the bottle for the realm's settings object: steps 2 to 4 of the localStorage and+/// sessionStorage getters. Null when obtaining the bottle map fails.////// # Safety///-/// The pointers must be the live VM, a live realm and a live StorageAPI::StorageBottle.+/// The pointers must be the live VM and the live realm of a Window.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_rust_html_create_storage(vm: *mut c_void,realm: *mut c_void,storage_type: u8,- map: *mut c_void,) -> *mut c_void {- // SAFETY: The caller passes the live VM, a live realm and a live bottle.- let ((vm, realm), map) = unsafe { (realm_arguments(vm, realm), StorageBottle::from_raw(map)) };- cell_into_abi(Storage::create(vm, realm, StorageType::from_abi(storage_type), map))+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ let storage_type = StorageType::from_abi(storage_type);+ let environment = relevant_settings_object(realm.global_object());+ let map = match storage_type {+ StorageType::Local => obtain_a_local_storage_bottle_map(&environment, StorageEndpointType::LocalStorage),+ StorageType::Session => obtain_a_session_storage_bottle_map(&environment, StorageEndpointType::SessionStorage),+ };+ map.map_or(core::ptr::null_mut(), |map| {+ cell_into_abi(Storage::create(vm, realm, storage_type, map))+ })}-/// The StorageAPI::StorageBottle that is the map of the Storage object.+/// Loads the map of the Storage object now rather than on first access, so changes other processes make start+/// arriving.////// # Safety////// `storage` must be the live cell of a Storage object.#[unsafe(no_mangle)]-pub unsafe extern "C" fn web_rust_html_storage_map(storage: *mut c_void) -> *mut c_void {- // SAFETY: The caller passes a live Storage object, which keeps its map alive.- unsafe { object_from_abi::<Storage>(storage) }.map().as_ptr()+pub unsafe extern "C" fn web_rust_html_storage_connect(storage: *mut c_void) {+ // SAFETY: The caller passes a live Storage object.+ unsafe { object_from_abi::<Storage>(storage) }.map().connect();+}++/// Calls `on_item` with each key of the map of the Storage object and its value, raw AK::Utf16Strings that Rust lends+/// for the call.+///+/// # Safety+///+/// `storage` must be the live cell of a Storage object.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_html_storage_for_each_item(+ storage: *mut c_void,+ ctx: *mut c_void,+ on_item: unsafe extern "C" fn(*mut c_void, usize, usize),+) {+ // SAFETY: The caller passes a live Storage object.+ let map = unsafe { object_from_abi::<Storage>(storage) }.map();+ for key in map.keys() {+ if let Some(value) = map.get(&key) {+ // SAFETY: The strings outlive the call.+ unsafe { on_item(ctx, key.raw_identity(), value.raw_identity()) };+ }+ }}/// The Event of a new StorageEvent in the realm whose type is the empty string and whose attributes are their@@ -451,48 +484,3 @@ pub unsafe extern "C" fn web_rust_html_create_storage_event(vm: *mut c_void, rea.event().as_ptr()}--/// Fires the storage events for a change that another process made to a storage area of the type whose storage key-/// has the origin, which C++ lends, with the page of its traversable navigable, for a "session" type, the strings, raw-/// AK::Utf16Strings that C++ hands over, and the URL, which C++ lends.-///-/// # Safety-///-/// The VM must be live, the origin must be one that C++ lends, and every string that the flag next to it says is-/// there must be one that C++ hands over.-#[unsafe(no_mangle)]-#[allow(clippy::too_many_arguments, reason = "a change has these parts")]-pub unsafe extern "C" fn web_rust_html_dispatch_storage_events_for_remote_change(- vm: *mut c_void,- storage_type: u8,- origin: *const FfiOrigin,- has_session_page: bool,- session_page: u64,- has_key: bool,- key: usize,- has_old_value: bool,- old_value: usize,- has_new_value: bool,- new_value: usize,- url: ak::Span<'_, u8>,-) {- // SAFETY: The caller passes the live VM.- let vm = unsafe { &*vm.cast::<Vm>() };- // SAFETY: The caller lends the origin for the call.- let storage_key = StorageKey {- origin: unsafe { (*origin).to_origin() },- };- // SAFETY: The caller hands over the strings that the flags say are there.- let string = |is_there: bool, raw: usize| is_there.then(|| unsafe { Utf16String::from_raw_owned(raw) });- dispatch_storage_events(- vm,- StorageType::from_abi(storage_type),- &storage_key,- has_session_page.then_some(session_page),- string(has_key, key),- string(has_old_value, old_value),- string(has_new_value, new_value),- &String::from_utf8_lossy(url.as_slice()),- None,- );-}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex 5b4a7feaa82..58a9eb1bae3 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -27,6 +27,8 @@ mod rust_demangle;mod rust_panic;pub(crate) mod ak_format;+#[cfg(test)]+mod ffi_test_stubs;#[cfg(not(test))]#[allow(@@ -131,7 +133,6 @@ pub(crate) mod notifications_api;allow(dead_code, reason = "only the generated bindings use the interfaces"))]pub(crate) mod speech;-#[cfg(not(test))]#[cfg_attr(not(web_idl_bindings),allow(dead_code, reason = "only the generated bindings use the interfaces")diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/exports.rsindex 54edd70c4a1..4a73568c512 100644--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/exports.rs@@ -4,12 +4,50 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The C ABI of the Storage Standard's interfaces implemented in Rust, which LibWeb's C++ code calls.+//! The C ABI of the Storage Standard's interfaces and storage bottles implemented in Rust, which LibWeb's C++ code+//! calls. Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.cpp connects the mirrors of the bottles to the process+//! that owns the storage areas, and hands them what it relays.use core::ffi::c_void;+use core::ptr::NonNull;+use std::rc::Rc;+use ak::Utf16String;+use libjs_rust::api::Vm;++use super::storage_area_mirror::{+ RemoteChanges, Requester, StorageAreaConnection, StorageAreaMirror, StorageAreaMirrorClient, StorageEndpointType,+ set_storage_area_mirror_client,+};use super::storage_manager::StorageManager;use crate::bindings::interface::{cell_into_abi, realm_arguments};+use crate::html::storage::{StorageType, dispatch_storage_events};++unsafe extern "C" {+ fn web_storage_api_storage_area_mirror_client_connect(+ client: *mut c_void,+ page_id: u64,+ endpoint_type: u8,+ environment: *mut c_void,+ connection: *mut c_void,+ on_connection: unsafe extern "C" fn(*mut c_void, bool, u64, *const usize, *const usize, usize, u64),+ );+ fn web_storage_api_storage_area_mirror_client_disconnect(client: *mut c_void, id: u64);+ fn web_storage_api_storage_area_mirror_client_set_item(+ client: *mut c_void,+ id: u64,+ key: usize,+ value: usize,+ document_url: ak::Span<'_, u8>,+ );+ fn web_storage_api_storage_area_mirror_client_remove_item(+ client: *mut c_void,+ id: u64,+ key: usize,+ document_url: ak::Span<'_, u8>,+ );+ fn web_storage_api_storage_area_mirror_client_clear(client: *mut c_void, id: u64, document_url: ak::Span<'_, u8>);+}/// A new StorageManager in the realm, the StorageManager object of the realm's settings object.///@@ -25,3 +63,231 @@ pub unsafe extern "C" fn web_rust_storage_api_create_storage_manager(let (vm, realm) = unsafe { realm_arguments(vm, realm) };cell_into_abi(StorageManager::create(vm, realm))}++/// The StorageAPI::StorageAreaMirrorClient that LibWeb's C++ code connects the mirrors to.+struct CppStorageAreaMirrorClient(NonNull<c_void>);++/// Strings that C++ hands over, as raw AK::Utf16Strings.+///+/// # Safety+///+/// `raws` must be null or point to `count` raw strings that C++ hands over.+unsafe fn adopt_strings(raws: *const usize, count: usize) -> Vec<Utf16String> {+ if count == 0 {+ return Vec::new();+ }+ // SAFETY: The caller passes count raw strings.+ let raws = unsafe { ak::slice_from_raw_parts(raws, count) };+ // SAFETY: The caller hands over every string.+ raws.iter()+ .map(|&raw| unsafe { Utf16String::from_raw_owned(raw) })+ .collect()+}++unsafe extern "C" fn on_connection(+ connection: *mut c_void,+ has_id: bool,+ id: u64,+ keys: *const usize,+ values: *const usize,+ count: usize,+ usage: u64,+) {+ // SAFETY: connection is the connection of the caller, and LibWeb hands over count keys and as many values.+ unsafe {+ *connection.cast::<StorageAreaConnection>() = StorageAreaConnection {+ id: has_id.then_some(id),+ keys: adopt_strings(keys, count),+ values: adopt_strings(values, count),+ usage,+ };+ }+}++impl StorageAreaMirrorClient for CppStorageAreaMirrorClient {+ fn connect_to_storage_area(+ &self,+ requester: &Requester<'_>,+ endpoint_type: StorageEndpointType,+ ) -> StorageAreaConnection {+ let mut connection = StorageAreaConnection::default();+ // SAFETY: The client and the requester's settings object are live, and the connection outlives the call.+ unsafe {+ web_storage_api_storage_area_mirror_client_connect(+ self.0.as_ptr(),+ requester.page_id,+ endpoint_type as u8,+ requester.environment,+ (&raw mut connection).cast(),+ on_connection,+ );+ }+ connection+ }++ fn disconnect_from_storage_area(&self, id: u64) {+ // SAFETY: The client is live.+ unsafe { web_storage_api_storage_area_mirror_client_disconnect(self.0.as_ptr(), id) };+ }++ fn set_storage_item(&self, id: u64, key: &Utf16String, value: &Utf16String, document_url: &str) {+ // SAFETY: The client is live, and the strings and the URL are lent for the call.+ unsafe {+ web_storage_api_storage_area_mirror_client_set_item(+ self.0.as_ptr(),+ id,+ key.raw_identity(),+ value.raw_identity(),+ ak::Span::new(document_url.as_bytes()),+ );+ }+ }++ fn remove_storage_item(&self, id: u64, key: &Utf16String, document_url: &str) {+ // SAFETY: The client is live, and the key and the URL are lent for the call.+ unsafe {+ web_storage_api_storage_area_mirror_client_remove_item(+ self.0.as_ptr(),+ id,+ key.raw_identity(),+ ak::Span::new(document_url.as_bytes()),+ );+ }+ }++ fn clear_storage_area(&self, id: u64, document_url: &str) {+ // SAFETY: The client is live, and the URL is lent for the call.+ unsafe {+ web_storage_api_storage_area_mirror_client_clear(+ self.0.as_ptr(),+ id,+ ak::Span::new(document_url.as_bytes()),+ );+ }+ }+}++/// Connects the mirrors to the client, or leaves every mirror detached for null.+///+/// # Safety+///+/// `client` must be null or a StorageAPI::StorageAreaMirrorClient that lives until it is replaced.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_storage_api_set_storage_area_mirror_client(client: *mut c_void) {+ set_storage_area_mirror_client(+ NonNull::new(client)+ .map(|client| Rc::new(CppStorageAreaMirrorClient(client)) as Rc<dyn StorageAreaMirrorClient>),+ );+}++// Every change another party made to a mirrored map calls for the storage events the spec's broadcast fires, on every+// Storage object here that shares the map.+fn dispatch(vm: &Vm, changes: Option<RemoteChanges>) {+ let Some(RemoteChanges { mirror, changes }) = changes else {+ return;+ };+ let storage_type = match mirror.endpoint_type() {+ StorageEndpointType::SessionStorage => StorageType::Session,+ _ => StorageType::Local,+ };+ for change in changes {+ dispatch_storage_events(+ vm,+ storage_type,+ mirror.storage_key(),+ mirror.session_page(),+ change.key,+ change.old_value,+ change.new_value,+ &change.url,+ None,+ );+ }+}++/// The change another process made to the storage area, with the strings, raw AK::Utf16Strings that C++ hands over,+/// and the URL, which C++ lends.+///+/// # Safety+///+/// The VM must be live, and every string that the flag next to it says is there must be one that C++ hands over.+#[unsafe(no_mangle)]+#[allow(clippy::too_many_arguments, reason = "a change has these parts")]+pub unsafe extern "C" fn web_rust_storage_api_storage_area_did_change(+ vm: *mut c_void,+ id: u64,+ has_key: bool,+ key: usize,+ has_old_value: bool,+ old_value: usize,+ has_new_value: bool,+ new_value: usize,+ url: ak::Span<'_, u8>,+) {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ // SAFETY: The caller hands over the strings that the flags say are there.+ let string = |is_there: bool, raw: usize| is_there.then(|| unsafe { Utf16String::from_raw_owned(raw) });+ let changes = StorageAreaMirror::did_change(+ id,+ string(has_key, key),+ string(has_old_value, old_value),+ string(has_new_value, new_value),+ String::from_utf8_lossy(url.as_slice()).into_owned(),+ );+ dispatch(vm, changes);+}++#[unsafe(no_mangle)]+pub extern "C" fn web_rust_storage_api_storage_area_did_acknowledge_write(id: u64) {+ StorageAreaMirror::did_acknowledge_write(id);+}++/// The owner refused the oldest write it hasn't answered, and its map is the keys and the values, raw+/// AK::Utf16Strings that C++ hands over.+///+/// # Safety+///+/// The VM must be live, and `keys` and `values` must each point to `count` strings that C++ hands over.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_storage_api_storage_area_did_refuse_write(+ vm: *mut c_void,+ id: u64,+ keys: *const usize,+ values: *const usize,+ count: usize,+) {+ // SAFETY: The caller passes the live VM and hands over the strings.+ let (vm, keys, values) = unsafe {+ (+ &*vm.cast::<Vm>(),+ adopt_strings(keys, count),+ adopt_strings(values, count),+ )+ };+ dispatch(vm, StorageAreaMirror::did_refuse_write(id, keys, values));+}++/// The owner's map is now the keys and the values, raw AK::Utf16Strings that C++ hands over.+///+/// # Safety+///+/// The VM must be live, and `keys` and `values` must each point to `count` strings that C++ hands over.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_storage_api_storage_area_did_reset(+ vm: *mut c_void,+ id: u64,+ keys: *const usize,+ values: *const usize,+ count: usize,+) {+ // SAFETY: The caller passes the live VM and hands over the strings.+ let (vm, keys, values) = unsafe {+ (+ &*vm.cast::<Vm>(),+ adopt_strings(keys, count),+ adopt_strings(values, count),+ )+ };+ dispatch(vm, StorageAreaMirror::did_reset(id, keys, values));+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rsindex 0be87b6bbc0..4b6bdd6a965 100644--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/mod.rs@@ -6,8 +6,15 @@//! The Storage Standard, https://storage.spec.whatwg.org/+#[cfg(not(test))]pub(crate) mod exports;+pub(crate) mod storage_area_mirror;+#[cfg(not(test))]pub(crate) mod storage_bottle;+#[cfg(not(test))]+pub(crate) mod storage_endpoint;pub(crate) mod storage_key;+#[cfg(not(test))]pub(crate) mod storage_manager;+#[cfg(not(test))]pub(crate) mod storage_shelf;diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_area_mirror.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_area_mirror.rsnew file mode 100644index 00000000000..0449b8d0db4--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_area_mirror.rs@@ -0,0 +1,1188 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! This process's copies of the maps of storage bottles, https://storage.spec.whatwg.org/#storage-bottle++use core::ffi::c_void;+use std::cell::RefCell;+use std::collections::{HashMap, HashSet};+use std::rc::{Rc, Weak};++use ak::{Utf16String, Utf16StringUnits};++use crate::storage_api::storage_key::StorageKey;++/// The value cannot be stored, as the bottle's quota does not leave room for it.+#[derive(Debug, PartialEq, Eq)]+pub(crate) struct QuotaExceeded;++/// https://storage.spec.whatwg.org/#storage-identifier+///+/// The storage identifiers of the registered endpoints, as StorageAPI::StorageEndpointType numbers them.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[repr(u8)]+pub(crate) enum StorageEndpointType {+ Caches = 0,+ IndexedDB = 1,+ LocalStorage = 2,+ ServiceWorkerRegistrations = 3,+ SessionStorage = 4,+}++impl StorageEndpointType {+ pub(crate) const COUNT: usize = 5;+}++/// Bytes a string contributes toward a storage bottle's quota: its UTF-8 length, with a lone surrogate counted as the+/// three bytes it is written as. The process that keeps a bottle and the processes that mirror it measure the same+/// way, so a write one accepts is a write the other accepts.+pub(crate) fn storage_quota_size(string: &Utf16String) -> u64 {+ quota_size_of_units(string.as_units())+}++// NB: Counted without encoding, as every write measures its key and value, and building the UTF-8 string would cost a+// copy of each on the path meant to be fast.+fn quota_size_of_units(units: Utf16StringUnits<'_>) -> u64 {+ match units {+ Utf16StringUnits::Ascii(units) => units.len() as u64,+ Utf16StringUnits::Latin1(units) => units.iter().map(|&unit| if unit < 0x80 { 1 } else { 2 }).sum(),+ Utf16StringUnits::Utf16(units) => {+ let mut size = 0;+ let mut index = 0;+ while index < units.len() {+ let unit = units[index];+ let is_pair = (0xd800..0xdc00).contains(&unit)+ && units.get(index + 1).is_some_and(|next| (0xdc00..0xe000).contains(next));+ if is_pair {+ size += 4;+ index += 2;+ continue;+ }+ size += match unit {+ 0..0x80 => 1,+ 0x80..0x800 => 2,+ _ => 3,+ };+ index += 1;+ }+ size+ }+ }+}++/// What the process that owns the storage areas answers when this process connects to one: the area's id and+/// everything the bottle holds. No id means the area couldn't be resolved, and the mirror stays detached.+#[derive(Default)]+pub(crate) struct StorageAreaConnection {+ pub(crate) id: Option<u64>,+ pub(crate) keys: Vec<Utf16String>,+ pub(crate) values: Vec<Utf16String>,+ pub(crate) usage: u64,+}++/// The page and environment a bottle asks on behalf of, which the owner resolves to the area. A mirror outlives the+/// document that first asked for it, so every call names its own requester.+pub(crate) struct Requester<'a> {+ pub(crate) page_id: u64,+ pub(crate) environment_id: &'a str,+ /// The environment settings object, which only the client reads, to name the environment to the owner.+ pub(crate) environment: *mut c_void,+}++/// The process's one link to the storage areas' owner. WebContent connects it to the browser process; a process+/// without one leaves every mirror detached.+pub(crate) trait StorageAreaMirrorClient {+ fn connect_to_storage_area(+ &self,+ requester: &Requester<'_>,+ endpoint_type: StorageEndpointType,+ ) -> StorageAreaConnection;+ fn disconnect_from_storage_area(&self, id: u64);+ fn set_storage_item(&self, id: u64, key: &Utf16String, value: &Utf16String, document_url: &str);+ fn remove_storage_item(&self, id: u64, key: &Utf16String, document_url: &str);+ fn clear_storage_area(&self, id: u64, document_url: &str);+}++// The mirrors this process holds, by the key a bottle finds them with and by the area id the owner's messages name.+// Weak, so a mirror lives exactly as long as some bottle addresses it; each mirror removes itself when it dies.+#[derive(Default)]+struct MirrorRegistry {+ by_key: HashMap<String, Weak<StorageAreaMirror>>,+ by_id: HashMap<u64, Weak<StorageAreaMirror>>,+}++thread_local! {+ static CLIENT: RefCell<Option<Rc<dyn StorageAreaMirrorClient>>> = const { RefCell::new(None) };+ static REGISTRY: RefCell<MirrorRegistry> = RefCell::new(MirrorRegistry::default());+}++pub(crate) fn set_storage_area_mirror_client(client: Option<Rc<dyn StorageAreaMirrorClient>>) {+ CLIENT.set(client);+}++fn client() -> Option<Rc<dyn StorageAreaMirrorClient>> {+ // NB: A mirror that dies as the thread exits finds no client to disconnect through.+ CLIENT.try_with(|client| client.borrow().clone()).ok().flatten()+}++fn registry_key_for(endpoint_type: StorageEndpointType, session_page: Option<u64>, storage_key: &StorageKey) -> String {+ let endpoint = endpoint_type as u8;+ let storage_key = storage_key.origin.serialize();+ match session_page {+ Some(page) => format!("{endpoint}/{page}/{storage_key}"),+ None => format!("{endpoint}//{storage_key}"),+ }+}++fn requester_key(requester: &Requester<'_>) -> String {+ format!("{}/{}", requester.page_id, requester.environment_id)+}++// An entry's quota size is kept beside its value, so overwriting or removing it never measures the old value again.+struct Entry {+ value: Utf16String,+ quota_size: u64,+}++// The entries in the order their keys were first set, as AK's OrderedHashMap keeps them: setting a key that exists+// keeps its place, and removing one keeps the others' order.+#[derive(Default)]+struct OrderedEntries {+ slots: Vec<Option<(Utf16String, Entry)>>,+ positions: HashMap<Utf16String, usize>,+}++impl OrderedEntries {+ fn len(&self) -> usize {+ self.positions.len()+ }++ fn is_empty(&self) -> bool {+ self.positions.is_empty()+ }++ fn contains_key(&self, key: &Utf16String) -> bool {+ self.positions.contains_key(key)+ }++ fn get(&self, key: &Utf16String) -> Option<&Entry> {+ let position = *self.positions.get(key)?;+ self.slots[position].as_ref().map(|(_, entry)| entry)+ }++ fn set(&mut self, key: Utf16String, entry: Entry) {+ if let Some(&position) = self.positions.get(&key) {+ self.slots[position] = Some((key, entry));+ return;+ }+ self.positions.insert(key.clone(), self.slots.len());+ self.slots.push(Some((key, entry)));+ }++ fn remove(&mut self, key: &Utf16String) -> Option<Entry> {+ let position = self.positions.remove(key)?;+ let (_, entry) = self.slots[position].take()?;+ // Removed entries leave a hole, which is cheap; once holes outnumber entries, the slots are packed again.+ if self.slots.len() > 2 * self.positions.len() + 16 {+ self.slots.retain(Option::is_some);+ for (position, (key, _)) in self.slots.iter().flatten().enumerate() {+ *self.positions.get_mut(key).expect("every live slot has a position") = position;+ }+ }+ Some(entry)+ }++ fn clear(&mut self) {+ self.slots.clear();+ self.positions.clear();+ }++ fn iter(&self) -> impl Iterator<Item = (&Utf16String, &Entry)> {+ self.slots.iter().flatten().map(|(key, entry)| (key, entry))+ }+}++// The map as this process sees it, and the quota it takes up.+#[derive(Default)]+struct MapCopy {+ entries: OrderedEntries,+ quota_used: u64,+}++impl MapCopy {+ fn apply_set(&mut self, key: Utf16String, value: Utf16String, quota_size: u64) {+ if let Some(existing) = self.entries.get(&key) {+ self.quota_used -= existing.quota_size;+ }+ self.quota_used += quota_size;+ self.entries.set(key, Entry { value, quota_size });+ }++ fn apply_remove(&mut self, key: &Utf16String) {+ if let Some(existing) = self.entries.remove(key) {+ self.quota_used -= existing.quota_size;+ }+ }++ fn apply_clear(&mut self) {+ self.entries.clear();+ self.quota_used = 0;+ }+}++// A write this process applied and sent, until the owner acknowledges or refuses it. A null key is a clear; a null+// value is a removal.+struct PendingWrite {+ key: Option<Utf16String>,+ new_value: Option<Utf16String>,+}++#[derive(Default)]+struct MirrorState {+ map: MapCopy,+ id: Option<u64>,+ primed: bool,+ failed_requesters: HashSet<String>,++ // The writes the owner hasn't answered yet are the ones from first_pending_write on. Answered ones stay in place+ // until the queue drains, so a script that queues thousands of writes in one task costs nothing more per answer.+ pending_writes: Vec<PendingWrite>,+ first_pending_write: usize,+ pending_count_by_key: HashMap<Utf16String, u32>,+ pending_clear_count: u32,+}++impl MirrorState {+ fn push_pending_write(&mut self, key: Option<Utf16String>, new_value: Option<Utf16String>) {+ match &key {+ Some(key) => *self.pending_count_by_key.entry(key.clone()).or_insert(0) += 1,+ None => self.pending_clear_count += 1,+ }+ self.pending_writes.push(PendingWrite { key, new_value });+ }++ fn pop_pending_write(&mut self) -> PendingWrite {+ // The owner answers every write, in the order they were sent.+ assert!(+ self.first_pending_write < self.pending_writes.len(),+ "the owner answers only writes this process sent"+ );+ let write = PendingWrite {+ key: self.pending_writes[self.first_pending_write].key.take(),+ new_value: self.pending_writes[self.first_pending_write].new_value.take(),+ };+ self.first_pending_write += 1;+ if self.first_pending_write == self.pending_writes.len() {+ self.pending_writes.clear();+ self.first_pending_write = 0;+ }+ match &write.key {+ Some(key) => {+ let count = self+ .pending_count_by_key+ .get_mut(key)+ .expect("a pending write of a key is counted");+ *count -= 1;+ if *count == 0 {+ self.pending_count_by_key.remove(key);+ }+ }+ None => {+ assert!(self.pending_clear_count > 0, "a pending clear is counted");+ self.pending_clear_count -= 1;+ }+ }+ write+ }++ // The owner hasn't applied these yet, so whatever state it just described predates them.+ fn reapply_pending_writes(&mut self) {+ let Self {+ map,+ pending_writes,+ first_pending_write,+ ..+ } = self;+ for write in &pending_writes[*first_pending_write..] {+ match (&write.key, &write.new_value) {+ (None, _) => map.apply_clear(),+ (Some(key), Some(value)) => map.apply_set(+ key.clone(),+ value.clone(),+ storage_quota_size(key) + storage_quota_size(value),+ ),+ (Some(key), None) => map.apply_remove(key),+ }+ }+ }++ // A change another process made, as the owner serialized it. One that reached the owner before a write this+ // process still has pending predates that write, so the mirror already shows the later state and leaves it be.+ // While a clear is pending, that goes for every change.+ fn apply_remote_change(&mut self, key: Option<&Utf16String>, new_value: Option<&Utf16String>) {+ if self.pending_clear_count > 0 {+ return;+ }++ let Some(key) = key else {+ // The owner emptied the bottle before applying this process's pending writes, so those come back on top.+ self.map.apply_clear();+ self.reapply_pending_writes();+ return;+ };++ if self.pending_count_by_key.contains_key(key) {+ return;+ }++ match new_value {+ Some(value) => self.map.apply_set(+ key.clone(),+ value.clone(),+ storage_quota_size(key) + storage_quota_size(value),+ ),+ None => self.map.apply_remove(key),+ }+ }+}++/// A change another party made to a mirrored map, as the owner relayed it (or, after a reset, as the diff shows it),+/// for the storage events it calls for. A null key is a clear.+pub(crate) struct RemoteChange {+ pub(crate) key: Option<Utf16String>,+ pub(crate) old_value: Option<Utf16String>,+ pub(crate) new_value: Option<Utf16String>,+ pub(crate) url: String,+}++/// The changes to report for one mirror.+pub(crate) struct RemoteChanges {+ pub(crate) mirror: Rc<StorageAreaMirror>,+ pub(crate) changes: Vec<RemoteChange>,+}++/// https://storage.spec.whatwg.org/#storage-bottle+///+/// This process's copy of one storage bottle's map. The map itself is kept by the browser process, which makes it+/// available across agent cluster boundaries this way: a process loads the map once, with one synchronous round trip+/// that also registers it for every later change, and from then on answers reads from the copy, applies writes to the+/// copy before sending them, and applies the changes other processes make as the owner relays them. Every storage+/// bottle in this process for the same area shares one mirror, so two windows of one origin can't see different maps.+pub(crate) struct StorageAreaMirror {+ endpoint_type: StorageEndpointType,+ session_page: Option<u64>,+ storage_key: StorageKey,+ quota: Option<u64>,+ registry_key: String,+ state: RefCell<MirrorState>,+}++impl Drop for StorageAreaMirror {+ fn drop(&mut self) {+ let id = self.state.get_mut().id;+ // NB: A mirror that dies as the thread exits finds the registry gone, and nothing left to remove itself from.+ let _ = REGISTRY.try_with(|registry| {+ let mut registry = registry.borrow_mut();+ registry.by_key.remove(&self.registry_key);+ if let Some(id) = id {+ registry.by_id.remove(&id);+ }+ });+ if let (Some(id), Some(client)) = (id, client()) {+ client.disconnect_from_storage_area(id);+ }+ }+}++fn mirror_for(id: u64) -> Option<Rc<StorageAreaMirror>> {+ REGISTRY.with_borrow(|registry| registry.by_id.get(&id).and_then(Weak::upgrade))+}++impl StorageAreaMirror {+ /// One mirror per storage key for local storage, and per page and storage key for session storage: a page's+ /// documents all belong to one traversable, and the traversable is what partitions session storage.+ pub(crate) fn obtain(+ endpoint_type: StorageEndpointType,+ session_page: Option<u64>,+ storage_key: &StorageKey,+ quota: Option<u64>,+ ) -> Rc<Self> {+ let key = registry_key_for(endpoint_type, session_page, storage_key);+ if let Some(live) = REGISTRY.with_borrow(|registry| registry.by_key.get(&key).and_then(Weak::upgrade)) {+ return live;+ }++ let mirror = Rc::new(Self {+ endpoint_type,+ session_page,+ storage_key: storage_key.clone(),+ quota,+ registry_key: key.clone(),+ state: RefCell::new(MirrorState::default()),+ });+ REGISTRY.with_borrow_mut(|registry| registry.by_key.insert(key, Rc::downgrade(&mirror)));+ mirror+ }++ pub(crate) fn endpoint_type(&self) -> StorageEndpointType {+ self.endpoint_type+ }++ pub(crate) fn storage_key(&self) -> &StorageKey {+ &self.storage_key+ }++ pub(crate) fn session_page(&self) -> Option<u64> {+ self.session_page+ }++ /// Loads the map now rather than on first access, so changes other processes make start arriving.+ pub(crate) fn connect(self: &Rc<Self>, requester: &Requester<'_>) {+ self.ensure_primed(requester);+ }++ // False when the owner couldn't resolve the requester's area; that requester is then not asked about again, but+ // another requester of the same mirror still can be (the first may have been a page on its way out).+ fn ensure_primed(self: &Rc<Self>, requester: &Requester<'_>) -> bool {+ if self.state.borrow().primed {+ return true;+ }+ let Some(client) = client() else {+ return false;+ };++ let key = requester_key(requester);+ if self.state.borrow().failed_requesters.contains(&key) {+ return false;+ }++ // One round trip loads the map and registers this process for every change after it, so nothing is missed or+ // seen twice.+ let connection = client.connect_to_storage_area(requester, self.endpoint_type);+ let mut state = self.state.borrow_mut();+ let Some(id) = connection.id else {+ state.failed_requesters.insert(key);+ return false;+ };++ // The owner sends one value per key. Taking the shorter of the two would prime a map that's quietly missing+ // entries, and nothing downstream could tell that from an empty bottle.+ assert_eq!(+ connection.keys.len(),+ connection.values.len(),+ "the owner sends one value per key"+ );++ state.id = Some(id);+ REGISTRY.with_borrow_mut(|registry| registry.by_id.insert(id, Rc::downgrade(self)));+ for (key, value) in connection.keys.into_iter().zip(connection.values) {+ let quota_size = storage_quota_size(&key) + storage_quota_size(&value);+ state.map.entries.set(key, Entry { value, quota_size });+ }+ state.map.quota_used = connection.usage;+ state.primed = true;+ state.failed_requesters.clear();+ true+ }++ pub(crate) fn size(self: &Rc<Self>, requester: &Requester<'_>) -> usize {+ if !self.ensure_primed(requester) {+ return 0;+ }+ self.state.borrow().map.entries.len()+ }++ pub(crate) fn keys(self: &Rc<Self>, requester: &Requester<'_>) -> Vec<Utf16String> {+ if !self.ensure_primed(requester) {+ return Vec::new();+ }+ self.state+ .borrow()+ .map+ .entries+ .iter()+ .map(|(key, _)| key.clone())+ .collect()+ }++ pub(crate) fn get(self: &Rc<Self>, requester: &Requester<'_>, key: &Utf16String) -> Option<Utf16String> {+ if !self.ensure_primed(requester) {+ return None;+ }+ self.state+ .borrow()+ .map+ .entries+ .get(key)+ .map(|entry| entry.value.clone())+ }++ /// The value the key had, or the quota's refusal. The write is applied here and sent on without waiting.+ pub(crate) fn set(+ self: &Rc<Self>,+ requester: &Requester<'_>,+ key: &Utf16String,+ value: &Utf16String,+ document_url: &str,+ ) -> Result<Option<Utf16String>, QuotaExceeded> {+ // OPTIMIZATION: An item too large to ever fit is refused before loading the map, so storing one enormous string+ // into a bottle this process hasn't read yet costs no round trip. Quota is measured in UTF-8 bytes, and a UTF-16+ // code unit never encodes to fewer than one of those, so the code unit count is a lower bound.+ if let Some(quota) = self.quota+ && (key.length_in_code_units() + value.length_in_code_units()) as u64 > quota+ {+ return Err(QuotaExceeded);+ }++ if !self.ensure_primed(requester) {+ return Err(QuotaExceeded);+ }++ let (id, old_value) = {+ let mut state = self.state.borrow_mut();+ let (old_value, replaced_size) = state.map.entries.get(key).map_or((None, 0), |existing| {+ (Some(existing.value.clone()), existing.quota_size)+ });++ // The same rule the owner applies, so a write accepted here is one the owner accepts too — unless another+ // process filled the bottle in between, which the owner then refuses and this mirror hears of.+ let new_size = storage_quota_size(key) + storage_quota_size(value);+ if let Some(quota) = self.quota+ && state.map.quota_used - replaced_size + new_size > quota+ {+ return Err(QuotaExceeded);+ }++ state.map.apply_set(key.clone(), value.clone(), new_size);+ state.push_pending_write(Some(key.clone()), Some(value.clone()));+ (state.id.expect("a primed mirror has an id"), old_value)+ };+ if let Some(client) = client() {+ client.set_storage_item(id, key, value, document_url);+ }+ Ok(old_value)+ }++ /// The value removed, if the key existed.+ pub(crate) fn remove(+ self: &Rc<Self>,+ requester: &Requester<'_>,+ key: &Utf16String,+ document_url: &str,+ ) -> Option<Utf16String> {+ if !self.ensure_primed(requester) {+ return None;+ }++ let (id, old_value) = {+ let mut state = self.state.borrow_mut();+ let old_value = state.map.entries.get(key)?.value.clone();+ state.map.apply_remove(key);+ state.push_pending_write(Some(key.clone()), None);+ (state.id.expect("a primed mirror has an id"), old_value)+ };+ if let Some(client) = client() {+ client.remove_storage_item(id, key, document_url);+ }+ Some(old_value)+ }++ /// False when there was nothing to clear.+ pub(crate) fn clear(self: &Rc<Self>, requester: &Requester<'_>, document_url: &str) -> bool {+ if !self.ensure_primed(requester) {+ return false;+ }++ let id = {+ let mut state = self.state.borrow_mut();+ if state.map.entries.is_empty() {+ return false;+ }+ state.map.apply_clear();+ state.push_pending_write(None, None);+ state.id.expect("a primed mirror has an id")+ };+ if let Some(client) = client() {+ client.clear_storage_area(id, document_url);+ }+ true+ }++ fn reset_to(&self, keys: Vec<Utf16String>, values: Vec<Utf16String>) -> Vec<RemoteChange> {+ assert_eq!(keys.len(), values.len(), "the owner sends one value per key");++ let mut state = self.state.borrow_mut();+ let old_entries = core::mem::take(&mut state.map.entries);+ state.map.quota_used = 0;+ for (key, value) in keys.into_iter().zip(values) {+ let quota_size = storage_quota_size(&key) + storage_quota_size(&value);+ state.map.apply_set(key, value, quota_size);+ }+ state.reapply_pending_writes();++ // AD-HOC: The spec's broadcast fires an event for each change a script makes, and never for a write refused after+ // the fact; it has no such thing. Whatever differs from before is a change this process's windows didn't+ // see being made, so each gets an event for it — the window whose write was refused included.+ let url = self.storage_key.origin.serialize();+ let mut changes = Vec::new();+ for (key, entry) in old_entries.iter() {+ let now = state.map.entries.get(key).map(|now| now.value.clone());+ if now.as_ref() != Some(&entry.value) {+ changes.push(RemoteChange {+ key: Some(key.clone()),+ old_value: Some(entry.value.clone()),+ new_value: now,+ url: url.clone(),+ });+ }+ }+ for (key, entry) in state.map.entries.iter() {+ if !old_entries.contains_key(key) {+ changes.push(RemoteChange {+ key: Some(key.clone()),+ old_value: None,+ new_value: Some(entry.value.clone()),+ url: url.clone(),+ });+ }+ }+ changes+ }++ /// What the owner relays, found by area id. A change for an area this process no longer mirrors is dropped.+ pub(crate) fn did_change(+ id: u64,+ key: Option<Utf16String>,+ old_value: Option<Utf16String>,+ new_value: Option<Utf16String>,+ url: String,+ ) -> Option<RemoteChanges> {+ let mirror = mirror_for(id)?;+ mirror+ .state+ .borrow_mut()+ .apply_remote_change(key.as_ref(), new_value.as_ref());+ Some(RemoteChanges {+ mirror,+ changes: vec![RemoteChange {+ key,+ old_value,+ new_value,+ url,+ }],+ })+ }++ pub(crate) fn did_acknowledge_write(id: u64) {+ if let Some(mirror) = mirror_for(id) {+ mirror.state.borrow_mut().pop_pending_write();+ }+ }++ pub(crate) fn did_refuse_write(id: u64, keys: Vec<Utf16String>, values: Vec<Utf16String>) -> Option<RemoteChanges> {+ let mirror = mirror_for(id)?;++ // Only a set can be refused: it was applied here on the strength of a quota check another process's write+ // overtook. The owner's map puts this one back in agreement.+ let refused = mirror.state.borrow_mut().pop_pending_write();+ assert!(+ refused.key.is_some() && refused.new_value.is_some(),+ "the owner refuses only a set"+ );+ let changes = mirror.reset_to(keys, values);+ Some(RemoteChanges { mirror, changes })+ }++ pub(crate) fn did_reset(id: u64, keys: Vec<Utf16String>, values: Vec<Utf16String>) -> Option<RemoteChanges> {+ let mirror = mirror_for(id)?;+ let changes = mirror.reset_to(keys, values);+ Some(RemoteChanges { mirror, changes })+ }+}++#[cfg(test)]+mod tests {+ use std::cell::{Cell, RefCell};++ use liburl_rust::origin::{Host, Origin};+ use liburl_rust::url::HostKind;++ use super::*;++ // Only short ASCII strings live without AK's C++, which unit tests don't link.+ fn string(string: &str) -> Utf16String {+ assert!(string.is_ascii() && string.len() < size_of::<usize>());+ Utf16String::from_utf8(string)+ }++ fn some(value: &str) -> Option<Utf16String> {+ Some(string(value))+ }++ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ enum Kind {+ Connect,+ Disconnect,+ Set,+ Remove,+ Clear,+ }++ struct Sent {+ kind: Kind,+ id: Option<u64>,+ key: Option<Utf16String>,+ value: Option<Utf16String>,+ url: String,+ }++ #[derive(Default)]+ struct FakeClient {+ sent: RefCell<Vec<Sent>>,+ // What the next connect answers with.+ keys: RefCell<Vec<Utf16String>>,+ values: RefCell<Vec<Utf16String>>,+ usage: Cell<u64>,+ detached: Cell<bool>,+ next_id: Cell<u64>,+ }++ impl FakeClient {+ fn record(+ &self,+ kind: Kind,+ id: Option<u64>,+ key: Option<&Utf16String>,+ value: Option<&Utf16String>,+ url: &str,+ ) {+ self.sent.borrow_mut().push(Sent {+ kind,+ id,+ key: key.cloned(),+ value: value.cloned(),+ url: url.to_owned(),+ });+ }++ fn count(&self, kind: Kind) -> usize {+ self.sent.borrow().iter().filter(|sent| sent.kind == kind).count()+ }++ fn last_id(&self) -> u64 {+ self.sent+ .borrow()+ .last()+ .and_then(|sent| sent.id)+ .expect("a message names an area")+ }+ }++ impl StorageAreaMirrorClient for FakeClient {+ fn connect_to_storage_area(&self, _: &Requester<'_>, _: StorageEndpointType) -> StorageAreaConnection {+ self.record(Kind::Connect, None, None, None, "");+ if self.detached.get() {+ return StorageAreaConnection::default();+ }+ let id = self.next_id.get() + 1;+ self.next_id.set(id);+ StorageAreaConnection {+ id: Some(id),+ keys: self.keys.borrow().clone(),+ values: self.values.borrow().clone(),+ usage: self.usage.get(),+ }+ }++ fn disconnect_from_storage_area(&self, id: u64) {+ self.record(Kind::Disconnect, Some(id), None, None, "");+ }++ fn set_storage_item(&self, id: u64, key: &Utf16String, value: &Utf16String, url: &str) {+ self.record(Kind::Set, Some(id), Some(key), Some(value), url);+ }++ fn remove_storage_item(&self, id: u64, key: &Utf16String, url: &str) {+ self.record(Kind::Remove, Some(id), Some(key), None, url);+ }++ fn clear_storage_area(&self, id: u64, url: &str) {+ self.record(Kind::Clear, Some(id), None, None, url);+ }+ }++ const URL: &str = "https://a.example/page.html";+ const LOCAL_STORAGE_QUOTA: u64 = 5 * 1024 * 1024;++ fn requester(page_id: u64, environment_id: &str) -> Requester<'_> {+ Requester {+ page_id,+ environment_id,+ environment: core::ptr::null_mut(),+ }+ }++ struct Fixture {+ client: Rc<FakeClient>,+ }++ impl Fixture {+ fn new() -> Self {+ let client = Rc::new(FakeClient::default());+ set_storage_area_mirror_client(Some(client.clone()));+ Self { client }+ }++ fn requester(&self) -> Requester<'static> {+ requester(1, "environment")+ }++ fn mirror(&self, host: &str) -> Rc<StorageAreaMirror> {+ self.mirror_with_quota(host, Some(LOCAL_STORAGE_QUOTA))+ }++ fn mirror_with_quota(&self, host: &str, quota: Option<u64>) -> Rc<StorageAreaMirror> {+ StorageAreaMirror::obtain(StorageEndpointType::LocalStorage, None, &key_for(host), quota)+ }+ }++ impl Drop for Fixture {+ fn drop(&mut self) {+ set_storage_area_mirror_client(None);+ }+ }++ fn key_for(host: &str) -> StorageKey {+ StorageKey {+ origin: Origin::Tuple {+ scheme: "https".to_owned(),+ host: Host {+ kind: HostKind::Domain,+ serialization: host.to_owned(),+ },+ port: None,+ domain: None,+ },+ }+ }++ impl StorageAreaMirror {+ fn quota_used(&self) -> u64 {+ self.state.borrow().map.quota_used+ }++ fn pending_write_count(&self) -> usize {+ let state = self.state.borrow();+ state.pending_writes.len() - state.first_pending_write+ }+ }++ fn quota_of(key: &str, value: &str) -> u64 {+ storage_quota_size(&string(key)) + storage_quota_size(&string(value))+ }++ #[test]+ fn prime_once_per_area_and_share_between_bottles() {+ let f = Fixture::new();+ *f.client.keys.borrow_mut() = vec![string("a")];+ *f.client.values.borrow_mut() = vec![string("1")];+ f.client.usage.set(2);++ let first = f.mirror("shared.example");+ let second = f.mirror("shared.example");+ assert!(Rc::ptr_eq(&first, &second));++ let other_page = StorageAreaMirror::obtain(+ StorageEndpointType::SessionStorage,+ Some(7),+ &key_for("shared.example"),+ None,+ );+ assert!(!Rc::ptr_eq(&other_page, &first));++ assert_eq!(f.client.count(Kind::Connect), 0);+ assert_eq!(first.get(&f.requester(), &string("a")), some("1"));+ assert_eq!(second.size(&f.requester()), 1);+ assert!(second.keys(&f.requester()) == vec![string("a")]);+ assert_eq!(f.client.count(Kind::Connect), 1);+ assert_eq!(first.quota_used(), 2);+ }++ #[test]+ fn local_write_applies_sends_and_tracks_pending_until_acked() {+ let f = Fixture::new();+ let mirror = f.mirror("write.example");++ assert_eq!(mirror.set(&f.requester(), &string("k"), &string("v"), URL), Ok(None));+ assert_eq!(mirror.get(&f.requester(), &string("k")), some("v"));+ assert_eq!(f.client.count(Kind::Set), 1);+ {+ let sent = f.client.sent.borrow();+ let last = sent.last().expect("the write was sent");+ assert_eq!(last.key, some("k"));+ assert_eq!(last.value, some("v"));+ assert_eq!(last.url, URL);+ }+ assert_eq!(mirror.pending_write_count(), 1);++ let id = f.client.last_id();+ StorageAreaMirror::did_acknowledge_write(id);+ assert_eq!(mirror.pending_write_count(), 0);++ // Overwrite returns the old value; removal returns the removed value; clear reports whether there was anything.+ assert_eq!(+ mirror.set(&f.requester(), &string("k"), &string("w"), URL),+ Ok(some("v"))+ );+ assert_eq!(mirror.remove(&f.requester(), &string("k"), URL), some("w"));+ assert_eq!(mirror.remove(&f.requester(), &string("k"), URL), None);+ assert_eq!(f.client.count(Kind::Remove), 1);+ assert!(!mirror.clear(&f.requester(), URL));+ assert_eq!(f.client.count(Kind::Clear), 0);+ let _ = mirror.set(&f.requester(), &string("k"), &string("v"), URL);+ assert!(mirror.clear(&f.requester(), URL));+ assert_eq!(f.client.count(Kind::Clear), 1);+ assert_eq!(mirror.size(&f.requester()), 0);+ }++ #[test]+ fn remote_changes_apply_except_over_pending_local_writes() {+ let f = Fixture::new();+ *f.client.keys.borrow_mut() = vec![string("a"), string("b")];+ *f.client.values.borrow_mut() = vec![string("1"), string("2")];+ f.client.usage.set(4);+ let mirror = f.mirror("remote.example");++ let _ = mirror.set(&f.requester(), &string("a"), &string("mine"), URL);+ let id = f.client.last_id();++ // The owner serialized this change before our pending write, so our mirror already reflects the later state.+ let reported = StorageAreaMirror::did_change(+ id,+ some("a"),+ some("1"),+ some("theirs"),+ "https://remote.example/other.html".to_owned(),+ )+ .expect("the area is mirrored");+ assert_eq!(mirror.get(&f.requester(), &string("a")), some("mine"));+ assert_eq!(reported.changes.len(), 1);+ assert_eq!(reported.changes[0].key, some("a"));+ assert_eq!(reported.changes[0].new_value, some("theirs"));+ assert_eq!(reported.changes[0].url, "https://remote.example/other.html");++ // A change to another key applies.+ let _ = StorageAreaMirror::did_change(id, some("b"), some("2"), some("3"), URL.to_owned());+ assert_eq!(mirror.get(&f.requester(), &string("b")), some("3"));+ let _ = StorageAreaMirror::did_change(id, some("b"), some("3"), None, URL.to_owned());+ assert_eq!(mirror.get(&f.requester(), &string("b")), None);++ StorageAreaMirror::did_acknowledge_write(id);+ let _ = StorageAreaMirror::did_change(id, some("a"), some("mine"), some("later"), URL.to_owned());+ assert_eq!(mirror.get(&f.requester(), &string("a")), some("later"));++ // While a local clear is unacknowledged, every incoming change predates it.+ mirror.clear(&f.requester(), URL);+ let _ = StorageAreaMirror::did_change(id, some("c"), None, some("4"), URL.to_owned());+ let _ = StorageAreaMirror::did_change(id, None, None, None, URL.to_owned());+ assert_eq!(mirror.size(&f.requester()), 0);+ StorageAreaMirror::did_acknowledge_write(id);+ let _ = StorageAreaMirror::did_change(id, some("c"), None, some("4"), URL.to_owned());+ assert_eq!(mirror.get(&f.requester(), &string("c")), some("4"));+ assert_eq!(mirror.quota_used(), 2);+ }++ #[test]+ fn refusal_resets_to_the_snapshot_reapplies_pending_writes_and_reports_the_diff() {+ let f = Fixture::new();+ let mirror = f.mirror("refused.example");++ let _ = mirror.set(&f.requester(), &string("big"), &string("xxxx"), URL);+ let id = f.client.last_id();+ let _ = mirror.set(&f.requester(), &string("b"), &string("2"), URL);+ assert_eq!(mirror.pending_write_count(), 2);++ // The owner refused the first write; the snapshot shows what another process stored in the meantime.+ let reported = StorageAreaMirror::did_refuse_write(id, vec![string("a")], vec![string("1")])+ .expect("the area is mirrored");++ assert_eq!(mirror.get(&f.requester(), &string("big")), None);+ assert_eq!(mirror.get(&f.requester(), &string("a")), some("1"));+ assert_eq!(mirror.get(&f.requester(), &string("b")), some("2"));+ assert_eq!(mirror.pending_write_count(), 1);+ assert_eq!(mirror.quota_used(), 4);++ // Two keys changed from the mirror's point of view: the refused one vanished, and "a" appeared.+ assert_eq!(reported.changes.len(), 2);+ let big = reported+ .changes+ .iter()+ .find(|change| change.key == some("big"))+ .expect("the refused key is reported");+ assert_eq!(big.old_value, some("xxxx"));+ assert_eq!(big.new_value, None);+ let a = reported+ .changes+ .iter()+ .find(|change| change.key == some("a"))+ .expect("the new key is reported");+ assert_eq!(a.old_value, None);+ assert_eq!(a.new_value, some("1"));++ // A reset from the browser takes the same path, with nothing pending to re-apply afterwards.+ StorageAreaMirror::did_acknowledge_write(id);+ let _ = StorageAreaMirror::did_reset(id, Vec::new(), Vec::new());+ assert_eq!(mirror.size(&f.requester()), 0);+ assert_eq!(mirror.quota_used(), 0);+ }++ // A script can queue thousands of writes in one task; their acknowledgments arrive after it yields. Each one has to+ // be cheap, and a refusal in the middle of the stream replays only the writes the owner hasn't answered yet.+ #[test]+ fn a_long_queue_of_pending_writes_drains_in_order_and_a_refusal_replays_only_the_outstanding_ones() {+ let f = Fixture::new();+ let mirror = f.mirror("queue.example");++ const WRITE_COUNT: usize = 5000;+ for i in 0..WRITE_COUNT {+ let _ = mirror.set(&f.requester(), &string(&i.to_string()), &string("v"), URL);+ }+ assert_eq!(mirror.pending_write_count(), WRITE_COUNT);+ let id = f.client.last_id();++ for _ in 0..WRITE_COUNT - 2 {+ StorageAreaMirror::did_acknowledge_write(id);+ }+ assert_eq!(mirror.pending_write_count(), 2);++ // The owner refused the second-to-last write and describes an empty bottle: everything acknowledged is gone from+ // it, and only the last write is still in flight on top.+ let reported = StorageAreaMirror::did_refuse_write(id, Vec::new(), Vec::new()).expect("the area is mirrored");+ assert_eq!(mirror.pending_write_count(), 1);+ assert_eq!(mirror.size(&f.requester()), 1);+ let last = (WRITE_COUNT - 1).to_string();+ assert_eq!(mirror.get(&f.requester(), &string(&last)), some("v"));+ assert_eq!(+ mirror.get(&f.requester(), &string(&(WRITE_COUNT - 2).to_string())),+ None+ );+ assert_eq!(mirror.quota_used(), quota_of(&last, "v"));++ // The diff reports every acknowledged write as gone, and nothing for the one still pending.+ assert_eq!(reported.changes.len(), WRITE_COUNT - 1);++ StorageAreaMirror::did_acknowledge_write(id);+ assert_eq!(mirror.pending_write_count(), 0);+ }++ #[test]+ fn quota_used_matches_the_jar_rule_after_mixed_writes() {+ let f = Fixture::new();+ let mirror = f.mirror_with_quota("quota.example", Some(12));++ let _ = mirror.set(&f.requester(), &string("k1"), &string("ab"), URL);+ let _ = mirror.set(&f.requester(), &string("k2"), &string("value"), URL);+ let _ = mirror.set(&f.requester(), &string("k1"), &string("x"), URL);+ let _ = mirror.remove(&f.requester(), &string("k2"), URL);+ assert_eq!(mirror.quota_used(), quota_of("k1", "x"));++ // A write that would exceed the quota is refused locally and leaves the mirror untouched.+ let result = mirror.set(&f.requester(), &string("k3333"), &string("yyyyyyy"), URL);+ assert_eq!(result, Err(QuotaExceeded));+ assert_eq!(mirror.get(&f.requester(), &string("k3333")), None);+ assert_eq!(mirror.quota_used(), quota_of("k1", "x"));+ assert_eq!(f.client.count(Kind::Set), 3);++ // One too large to ever fit is refused before the mirror is even primed.+ let fresh = Rc::new(FakeClient::default());+ set_storage_area_mirror_client(Some(fresh.clone()));+ let unprimed = f.mirror_with_quota("unprimed.example", Some(12));+ assert_eq!(+ unprimed.set(&f.requester(), &string("kkkkkkk"), &string("zzzzzzz"), URL),+ Err(QuotaExceeded)+ );+ assert!(fresh.sent.borrow().is_empty());+ set_storage_area_mirror_client(Some(f.client.clone()));+ }++ #[test]+ fn quota_size_is_the_length_in_utf8() {+ assert_eq!(quota_size_of_units(Utf16StringUnits::Ascii(b"abc")), 3);+ assert_eq!(quota_size_of_units(Utf16StringUnits::Latin1(&[0x61, 0xe9, 0xe9])), 5);+ assert_eq!(+ quota_size_of_units(Utf16StringUnits::Utf16(&[0x7f, 0x80, 0x7ff, 0x800, 0xffff])),+ 11+ );+ // A surrogate pair is one code point of four bytes, and a lone surrogate is written as three.+ assert_eq!(quota_size_of_units(Utf16StringUnits::Utf16(&[0xd83d, 0xde00])), 4);+ assert_eq!(quota_size_of_units(Utf16StringUnits::Utf16(&[0xd83d, 0x61, 0xde00])), 7);+ }++ #[test]+ fn detached_mirror_reads_empty_and_refuses_writes() {+ let f = Fixture::new();+ f.client.detached.set(true);+ let mirror = f.mirror("detached.example");++ assert_eq!(mirror.size(&f.requester()), 0);+ assert_eq!(mirror.get(&f.requester(), &string("k")), None);+ assert_eq!(+ mirror.set(&f.requester(), &string("k"), &string("v"), URL),+ Err(QuotaExceeded)+ );+ assert_eq!(mirror.remove(&f.requester(), &string("k"), URL), None);+ assert!(!mirror.clear(&f.requester(), URL));+ assert_eq!(f.client.count(Kind::Connect), 1);+ assert_eq!(f.client.count(Kind::Set), 0);+ }++ #[test]+ fn a_failed_connect_detaches_only_the_requester_it_failed_for() {+ let f = Fixture::new();+ f.client.detached.set(true);+ let mirror = f.mirror("partly.example");+ let closing_page = requester(9, "closing");++ // A page the browser can't resolve (it's closing) reads empty and can't write; it isn't asked about again.+ assert_eq!(mirror.size(&closing_page), 0);+ assert_eq!(+ mirror.set(&closing_page, &string("k"), &string("v"), URL),+ Err(QuotaExceeded)+ );+ assert_eq!(f.client.count(Kind::Connect), 1);+ assert_eq!(mirror.size(&closing_page), 0);+ assert_eq!(f.client.count(Kind::Connect), 1);++ // Another document of the origin in this process, which the browser does resolve, still gets its storage.+ f.client.detached.set(false);+ *f.client.keys.borrow_mut() = vec![string("a")];+ *f.client.values.borrow_mut() = vec![string("1")];+ f.client.usage.set(2);+ assert_eq!(mirror.get(&f.requester(), &string("a")), some("1"));+ assert_eq!(f.client.count(Kind::Connect), 2);+ assert!(mirror.set(&f.requester(), &string("k"), &string("v"), URL).is_ok());+ // And once the mirror is connected, every requester reads it.+ assert_eq!(mirror.size(&closing_page), 2);+ }++ #[test]+ fn the_last_bottle_disconnects_the_mirror() {+ let f = Fixture::new();+ {+ let mirror = f.mirror("lastbottle.example");+ let _another = f.mirror("lastbottle.example");+ mirror.size(&f.requester());+ assert_eq!(f.client.count(Kind::Disconnect), 0);+ }+ assert_eq!(f.client.count(Kind::Disconnect), 1);++ // A mirror that was never primed has nothing to disconnect from.+ {+ let _never = f.mirror("never.example");+ }+ assert_eq!(f.client.count(Kind::Disconnect), 1);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rsindex 546c236acaf..cd73bab2b8e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs@@ -1,4 +1,6 @@/*+ * Copyright (c) 2024-2025, Shannon Booth <[email protected]>+ * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>* Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause@@ -6,128 +8,213 @@//! Storage bottles, https://storage.spec.whatwg.org/#storage-bottle-use core::ffi::c_void;+use std::rc::Rc;use ak::Utf16String;-use libjs_rust::api::Trace;--use crate::bindings::cpp_cell::CppCell;--unsafe extern "C" {- fn web_storage_api_storage_bottle_size(bottle: *mut c_void) -> usize;- fn web_storage_api_storage_bottle_keys(- bottle: *mut c_void,- keys: *mut c_void,- append: unsafe extern "C" fn(*mut c_void, usize),- );- fn web_storage_api_storage_bottle_get(bottle: *mut c_void, key: usize, value: *mut usize) -> bool;- /// 0 when the quota refuses the value, 1 for a new key, and 2 for a key that had the old value.- fn web_storage_api_storage_bottle_set(- bottle: *mut c_void,- key: usize,- value: usize,- document_url: ak::Span<'_, u8>,- old_value: *mut usize,- ) -> u8;- fn web_storage_api_storage_bottle_remove(bottle: *mut c_void, key: usize, document_url: ak::Span<'_, u8>);- fn web_storage_api_storage_bottle_clear(bottle: *mut c_void, document_url: ak::Span<'_, u8>);- fn web_storage_api_storage_bottle_quota(bottle: *mut c_void, quota: *mut u64) -> bool;+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Visitor, Vm};++use crate::bindings::environment_settings_object::CppEnvironmentSettingsObject;+use crate::bindings::global_object::window_from_global_object;+pub(crate) use crate::storage_api::storage_area_mirror::QuotaExceeded;+use crate::storage_api::storage_area_mirror::{Requester, StorageAreaMirror, StorageEndpointType};+use crate::storage_api::storage_endpoint::StorageEndpoint;+use crate::storage_api::storage_key::{StorageKey, obtain_a_storage_key};++/// https://storage.spec.whatwg.org/#storage-type+/// A storage type is "local" or "session".+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum StorageType {+ Local,+ Session,}-/// The value cannot be stored, as the bottle's quota does not leave room for it.-pub(crate) struct QuotaExceeded;--/// A storage bottle of LibWeb's C++ code, StorageAPI::StorageBottle. Its map is this process's mirror of the one the-/// browser process keeps.-#[derive(Trace)]-#[gc(crate = libjs_rust)]-pub(crate) struct StorageBottle(CppCell);+/// https://storage.spec.whatwg.org/#storage-bottle+///+/// NB: The bottle's map lives in the browser process; what a bottle here holds is this process's mirror of it, shared+/// with every other bottle in the process for the same area. Each bottle object is one storage proxy map over it.+pub(crate) struct StorageBottle {+ environment: CppEnvironmentSettingsObject,+ environment_id: String,+ page_id: u64,+ // https://storage.spec.whatwg.org/#storage-bottle-quota+ // A storage bottle also has a quota, which is null or a number representing a conservative estimate of the total+ // amount of bytes it can hold. Null indicates the lack of a limit.+ quota: Option<u64>,+ mirror: Rc<StorageAreaMirror>,+}-unsafe extern "C" fn append_key(keys: *mut c_void, key: usize) {- // SAFETY: keys is the list of the caller, and LibWeb hands over the key.- unsafe { (*keys.cast::<Vec<Utf16String>>()).push(Utf16String::from_raw_owned(key)) };+// SAFETY: The settings object is the only cell a bottle holds.+unsafe impl Trace for StorageBottle {+ fn trace(&self, visitor: &mut Visitor) {+ self.environment.trace(visitor);+ }}impl StorageBottle {- /// # Safety- ///- /// `bottle` must be a live StorageAPI::StorageBottle.- pub(crate) unsafe fn from_raw(bottle: *mut c_void) -> Self {- // SAFETY: The caller passes a live bottle.- Self(unsafe { CppCell::from_raw(bottle) })+ fn create(environment: &CppEnvironmentSettingsObject, endpoint: &StorageEndpoint, key: &StorageKey) -> Self {+ let window =+ window_from_global_object(environment.global_object()).expect("a storage bottle map is a Window's");+ let page_id = window.page_id();+ // Session storage is partitioned by the traversable, and a page's documents all belong to one traversable, so+ // a session bottle's mirror is found by its page as well as its storage key.+ let session_page = (endpoint.identifier == StorageEndpointType::SessionStorage).then_some(page_id);+ Self {+ environment: environment.clone(),+ environment_id: environment.id(),+ page_id,+ quota: endpoint.quota,+ mirror: StorageAreaMirror::obtain(endpoint.identifier, session_page, key, endpoint.quota),+ }}- pub(crate) fn as_ptr(&self) -> *mut c_void {- self.0.as_ptr()+ fn requester(&self) -> Requester<'_> {+ Requester {+ page_id: self.page_id,+ environment_id: &self.environment_id,+ environment: self.environment.as_ptr(),+ }+ }++ /// Loads the map now rather than on first access, so changes other processes make start arriving.+ pub(crate) fn connect(&self) {+ self.mirror.connect(&self.requester());}pub(crate) fn size(&self) -> usize {- // SAFETY: The bottle is live.- unsafe { web_storage_api_storage_bottle_size(self.as_ptr()) }+ self.mirror.size(&self.requester())}/// https://infra.spec.whatwg.org/#map-getting-the-keyspub(crate) fn keys(&self) -> Vec<Utf16String> {- let mut keys: Vec<Utf16String> = Vec::new();- // SAFETY: The bottle is live, and the keys outlive the call.- unsafe { web_storage_api_storage_bottle_keys(self.as_ptr(), (&raw mut keys).cast(), append_key) };- keys+ self.mirror.keys(&self.requester())}pub(crate) fn get(&self, key: &Utf16String) -> Option<Utf16String> {- let mut value = 0;- // SAFETY: The bottle is live, and the key and the value outlive the call.- let exists = unsafe { web_storage_api_storage_bottle_get(self.as_ptr(), key.raw_identity(), &raw mut value) };- // SAFETY: LibWeb hands over the value it found.- exists.then(|| unsafe { Utf16String::from_raw_owned(value) })+ self.mirror.get(&self.requester(), key)}- /// The value the key had, if it existed, or the refusal of the bottle's quota.+ /// The value the key had, or the quota's refusal.pub(crate) fn set(&self,key: &Utf16String,value: &Utf16String,document_url: &str,) -> Result<Option<Utf16String>, QuotaExceeded> {- let mut old_value = 0;- // SAFETY: The bottle is live, and the strings and the old value outlive the call.- let result = unsafe {- web_storage_api_storage_bottle_set(- self.as_ptr(),- key.raw_identity(),- value.raw_identity(),- ak::Span::new(document_url.as_bytes()),- &raw mut old_value,- )- };- match result {- 0 => Err(QuotaExceeded),- 1 => Ok(None),- // SAFETY: LibWeb hands over the old value.- _ => Ok(Some(unsafe { Utf16String::from_raw_owned(old_value) })),- }+ self.mirror.set(&self.requester(), key, value, document_url)}pub(crate) fn remove(&self, key: &Utf16String, document_url: &str) {- // SAFETY: The bottle is live, and the strings outlive the call.- unsafe {- web_storage_api_storage_bottle_remove(- self.as_ptr(),- key.raw_identity(),- ak::Span::new(document_url.as_bytes()),- );- }+ let _ = self.mirror.remove(&self.requester(), key, document_url);}pub(crate) fn clear(&self, document_url: &str) {- // SAFETY: The bottle is live, and the URL outlives the call.- unsafe { web_storage_api_storage_bottle_clear(self.as_ptr(), ak::Span::new(document_url.as_bytes())) };+ self.mirror.clear(&self.requester(), document_url);}- /// https://storage.spec.whatwg.org/#storage-bottle-quotapub(crate) fn quota(&self) -> Option<u64> {- let mut quota = 0;- // SAFETY: The bottle is live, and the quota outlives the call.- unsafe { web_storage_api_storage_bottle_quota(self.as_ptr(), &raw mut quota) }.then_some(quota)+ self.quota}}++type BottleMap = [Option<StorageBottle>; StorageEndpointType::COUNT];++// https://storage.spec.whatwg.org/#storage-bucket+// A storage bucket is a place for storage endpoints to store data.+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct StorageBucket {+ // A storage bucket has a bottle map of storage identifiers to storage bottles.+ bottle_map: BottleMap,+}++static STORAGE_BUCKET_CLASS: EmbedderClass<StorageBucket> = EmbedderClass::new("StorageBucket");++impl EmbedderValue for StorageBucket {+ const CLASS: &'static EmbedderClass<Self> = &STORAGE_BUCKET_CLASS;+}++impl StorageBucket {+ pub(crate) fn create(+ vm: &Vm,+ environment: &CppEnvironmentSettingsObject,+ key: &StorageKey,+ storage_type: StorageType,+ ) -> Gc<EmbedderCell<Self>> {+ // 1. Let bucket be null.+ // 2. If type is "local", then set bucket to a new local storage bucket.+ // 3. Otherwise:+ // 1. Assert: type is "session".+ // 2. Set bucket to a new session storage bucket.+ STORAGE_BUCKET_CLASS.allocate(vm, |_| {+ let mut bottle_map = core::array::from_fn(|_| None);++ // 4. For each endpoint of registered storage endpoints whose types contain type, set bucket’s bottle map[endpoint’s identifier] to a new storage bottle whose quota is endpoint’s quota.+ for endpoint in StorageEndpoint::registered_endpoints() {+ if endpoint.storage_type == storage_type {+ bottle_map[endpoint.identifier as usize] = Some(StorageBottle::create(environment, &endpoint, key));+ }+ }++ // 5. Return bucket.+ StorageBucket { bottle_map }+ })+ }+}++/// https://storage.spec.whatwg.org/#obtain-a-storage-bottle-map+fn obtain_a_storage_bottle_map(+ storage_type: StorageType,+ environment: &CppEnvironmentSettingsObject,+ identifier: StorageEndpointType,+) -> Option<StorageBottle> {+ // 1. Let shed be null.+ // 2. If type is "local", then set shed to the user agent’s storage shed.+ // 3. Otherwise:+ // 1. Assert: type is "session".+ // 2. Set shed to environment’s global object’s associated Document’s node navigable’s traversable navigable’s storage shed.+ // NB: Both sheds are kept by the browser process, in a StorageJar, which the bottle returned here mirrors. The+ // bottle names environment, from which the browser process obtains the storage key itself.++ // 4. Let shelf be the result of running obtain a storage shelf, with shed, environment, and type.+ // 5. If shelf is failure, then return failure.+ let storage_key = obtain_a_storage_key(environment)?;++ // 6. Let bucket be shelf’s bucket map["default"].+ // 7. Let bottle be bucket’s bottle map[identifier].+ // NB: The bucket's bottle map holds a bottle for each registered storage endpoint whose types contain type, with+ // that endpoint's quota.+ let endpoint = StorageEndpoint::registered_endpoints()+ .into_iter()+ .find(|endpoint| endpoint.identifier == identifier)+ .expect("the storage endpoint is registered");+ assert!(+ endpoint.storage_type == storage_type,+ "the endpoint supports the storage type"+ );++ // 8. Let proxyMap be a new storage proxy map whose backing map is bottle’s map.+ // 9. Append proxyMap to bottle’s proxy map reference set.+ // 10. Return proxyMap.+ Some(StorageBottle::create(environment, &endpoint, &storage_key))+}++/// https://storage.spec.whatwg.org/#obtain-a-local-storage-bottle-map+pub(crate) fn obtain_a_local_storage_bottle_map(+ environment: &CppEnvironmentSettingsObject,+ identifier: StorageEndpointType,+) -> Option<StorageBottle> {+ // To obtain a local storage bottle map, given an environment settings object environment and storage identifier+ // identifier, return the result of running obtain a storage bottle map with "local", environment, and identifier.+ obtain_a_storage_bottle_map(StorageType::Local, environment, identifier)+}++/// https://storage.spec.whatwg.org/#obtain-a-session-storage-bottle-map+pub(crate) fn obtain_a_session_storage_bottle_map(+ environment: &CppEnvironmentSettingsObject,+ identifier: StorageEndpointType,+) -> Option<StorageBottle> {+ // To obtain a session storage bottle map, given an environment settings object environment and storage identifier+ // identifier, return the result of running obtain a storage bottle map with "session", environment, and+ // identifier.+ obtain_a_storage_bottle_map(StorageType::Session, environment, identifier)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_endpoint.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_endpoint.rsnew file mode 100644index 00000000000..13af9d2f543--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_endpoint.rs@@ -0,0 +1,77 @@+/*+ * Copyright (c) 2024-2025, Shannon Booth <[email protected]>+ * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Storage endpoints, https://storage.spec.whatwg.org/#storage-endpoint++use core::ffi::c_void;++use crate::storage_api::storage_area_mirror::StorageEndpointType;+use crate::storage_api::storage_bottle::StorageType;++unsafe extern "C" {+ fn web_storage_api_for_each_registered_endpoint(+ endpoints: *mut c_void,+ on_endpoint: unsafe extern "C" fn(*mut c_void, u8, bool, bool, u64),+ );+}++// https://storage.spec.whatwg.org/#storage-endpoint+//+// A storage endpoint is a local or session storage API that uses the infrastructure defined by this+// standard, most notably storage bottles, to keep track of its storage needs.+pub(crate) struct StorageEndpoint {+ // https://storage.spec.whatwg.org/#storage-endpoint-identifier+ // A storage endpoint has an identifier, which is a storage identifier.+ pub(crate) identifier: StorageEndpointType,++ // https://storage.spec.whatwg.org/#storage-endpoint-types+ // A storage endpoint also has types, which is a set of storage types.+ // NOTE: We do not implement this as a set as it is not necessary in the current implementation.+ pub(crate) storage_type: StorageType,++ // https://storage.spec.whatwg.org/#storage-endpoint-quota+ // A storage endpoint also has a quota, which is null or a number representing a recommended quota (in bytes) for each storage bottle corresponding to this storage endpoint.+ pub(crate) quota: Option<u64>,+}++unsafe extern "C" fn on_endpoint(+ endpoints: *mut c_void,+ identifier: u8,+ is_session: bool,+ has_quota: bool,+ quota: u64,+) {+ let identifier = match identifier {+ 0 => StorageEndpointType::Caches,+ 1 => StorageEndpointType::IndexedDB,+ 2 => StorageEndpointType::LocalStorage,+ 3 => StorageEndpointType::ServiceWorkerRegistrations,+ 4 => StorageEndpointType::SessionStorage,+ _ => panic!("LibWeb passes a registered storage endpoint"),+ };+ // SAFETY: endpoints is the vector of the caller, which outlives the call.+ unsafe { &mut *endpoints.cast::<Vec<StorageEndpoint>>() }.push(StorageEndpoint {+ identifier,+ storage_type: if is_session {+ StorageType::Session+ } else {+ StorageType::Local+ },+ quota: has_quota.then_some(quota),+ });+}++impl StorageEndpoint {+ /// https://storage.spec.whatwg.org/#registered-storage-endpoints+ pub(crate) fn registered_endpoints() -> Vec<Self> {+ let mut endpoints = Vec::new();+ // SAFETY: The vector outlives the call, which copies the registered endpoints from LibWebCommon.+ unsafe { web_storage_api_for_each_registered_endpoint((&raw mut endpoints).cast(), on_endpoint) };+ endpoints+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rsindex 39bc8d3fbc7..ecd02735378 100644--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_key.rs@@ -7,13 +7,17 @@//! Storage keys, https://storage.spec.whatwg.org/#storage-keys+#[cfg(not(test))]use core::ffi::c_void;+#[cfg(not(test))]use liburl_rust::FfiOrigin;use liburl_rust::origin::Origin;+#[cfg(not(test))]use crate::bindings::environment_settings_object::CppEnvironmentSettingsObject;+#[cfg(not(test))]unsafe extern "C" {fn web_storage_api_obtain_a_storage_key(environment: *mut c_void,@@ -44,12 +48,14 @@ impl PartialEq for StorageKey {}}+#[cfg(not(test))]unsafe extern "C" fn on_origin(ctx: *mut c_void, ffi_origin: *const FfiOrigin) {// SAFETY: ctx is the origin of the caller, and LibWeb lends the origin for the call.unsafe { *ctx.cast::<Option<Origin>>() = Some((*ffi_origin).to_origin()) };}/// https://storage.spec.whatwg.org/#obtain-a-storage-key+#[cfg(not(test))]pub(crate) fn obtain_a_storage_key(environment: &CppEnvironmentSettingsObject) -> Option<StorageKey> {let mut origin: Option<Origin> = None;// SAFETY: The environment settings object is live, and the origin outlives the call.@@ -58,6 +64,7 @@ pub(crate) fn obtain_a_storage_key(environment: &CppEnvironmentSettingsObject) -}/// https://storage.spec.whatwg.org/#obtain-a-storage-key-for-non-storage-purposes+#[cfg(not(test))]pub(crate) fn obtain_a_storage_key_for_non_storage_purposes(environment: &CppEnvironmentSettingsObject) -> StorageKey {let mut origin: Option<Origin> = None;// SAFETY: The environment settings object is live, and the origin outlives the call.diff --git a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_shelf.rs b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_shelf.rsindex 637bb54d194..6307a9efeee 100644--- a/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_shelf.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_shelf.rs@@ -1,4 +1,5 @@/*+ * Copyright (c) 2024-2025, Shannon Booth <[email protected]>* Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause@@ -10,19 +11,24 @@ use core::ffi::c_void;use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, Trace, Vm};-use crate::bindings::cpp_cell::CppCell;use crate::bindings::environment_settings_object::CppEnvironmentSettingsObject;+use crate::storage_api::storage_bottle::{StorageBucket, StorageType};+use crate::storage_api::storage_key::{StorageKey, obtain_a_storage_key};unsafe extern "C" {- fn web_storage_api_obtain_a_local_storage_shelf(environment: *mut c_void) -> *mut c_void;- fn web_storage_api_storage_shelf_storage_usage(shelf: *mut c_void) -> u64;- fn web_storage_api_storage_shelf_storage_quota(shelf: *mut c_void) -> u64;+ fn web_storage_api_storage_usage(environment: *mut c_void) -> u64;}-/// A storage shelf of LibWeb's C++ code, StorageAPI::StorageShelf.+// https://storage.spec.whatwg.org/#storage-shelf+// A storage shelf exists for each storage key within a storage shed. It holds a bucket map, which is a map of strings to storage buckets.+type BucketMap = Vec<(String, Gc<EmbedderCell<StorageBucket>>)>;+#[derive(Trace)]#[gc(crate = libjs_rust)]-pub(crate) struct StorageShelf(CppCell);+pub(crate) struct StorageShelf {+ environment: CppEnvironmentSettingsObject,+ bucket_map: BucketMap,+}static STORAGE_SHELF_CLASS: EmbedderClass<StorageShelf> = EmbedderClass::new("StorageShelf");@@ -31,16 +37,46 @@ impl EmbedderValue for StorageShelf {}impl StorageShelf {+ // https://storage.spec.whatwg.org/#create-a-storage-shelf+ fn create(+ vm: &Vm,+ environment: &CppEnvironmentSettingsObject,+ key: &StorageKey,+ storage_type: StorageType,+ ) -> Gc<EmbedderCell<Self>> {+ // 1. Let shelf be a new storage shelf.+ STORAGE_SHELF_CLASS.allocate(vm, |_| {+ // 2. Set shelf’s bucket map["default"] to the result of running create a storage bucket with type.+ let bucket_map = vec![(+ "default".to_owned(),+ StorageBucket::create(vm, environment, key, storage_type),+ )];+ // 3. Return shelf.+ StorageShelf {+ environment: environment.clone(),+ bucket_map,+ }+ })+ }+/// https://storage.spec.whatwg.org/#storage-usagepub(crate) fn storage_usage(&self) -> u64 {- // SAFETY: The shelf is live.- unsafe { web_storage_api_storage_shelf_storage_usage(self.0.as_ptr()) }+ // The storage usage of a storage shelf is an implementation-defined rough estimate of the amount of bytes used+ // by it.+ // SAFETY: The environment settings object is live.+ unsafe { web_storage_api_storage_usage(self.environment.as_ptr()) }}/// https://storage.spec.whatwg.org/#storage-quota+ #[allow(clippy::unused_self, reason = "every shelf has the same quota")]pub(crate) fn storage_quota(&self) -> u64 {- // SAFETY: The shelf is live.- unsafe { web_storage_api_storage_shelf_storage_quota(self.0.as_ptr()) }+ // "The storage quota of a storage shelf is an implementation-defined conservative estimate of the total amount of+ // bytes it can hold. This amount should be less than the total storage space on the device. It must not be a+ // function of the available storage space on the device."+ // The bottles with a quota of their own (localStorage, sessionStorage) hold a few MiB each, and the rest (Cache+ // Storage, IndexedDB, service worker registrations) are unbounded, so the shelf reports the 10 GiB a site may+ // reasonably put in those. Nothing about the device goes into the figure.+ 10 * 1024 * 1024 * 1024}}@@ -49,12 +85,14 @@ pub(crate) fn obtain_a_local_storage_shelf(vm: &Vm,environment: &CppEnvironmentSettingsObject,) -> Option<Gc<EmbedderCell<StorageShelf>>> {- // SAFETY: The environment settings object is live.- let shelf = unsafe { web_storage_api_obtain_a_local_storage_shelf(environment.as_ptr()) };- if shelf.is_null() {- return None;- }- // SAFETY: LibWeb returns a live shelf.- let shelf = unsafe { CppCell::from_raw(shelf) };- Some(STORAGE_SHELF_CLASS.allocate(vm, |_| StorageShelf(shelf)))+ // To obtain a local storage shelf, given an environment settings object environment, return the result of running+ // obtain a storage shelf with the user agent’s storage shed, environment, and "local".++ // FIXME: This should be implemented in a way that works for Workers.+ let key = obtain_a_storage_key(environment)?;++ // AD-HOC: The user agent's storage shed is kept by the browser process, in a StorageJar. This shelf is a transient+ // helper for computing estimate()'s usage and quota — so a standalone shelf is functionally equivalent to+ // the spec's requirement to obtain one from a shed.+ Some(StorageShelf::create(vm, environment, &key, StorageType::Local))}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 0d76babd749..e84b615d509 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -124,6 +124,8 @@ bool web_bindings_document_is_fully_active(DOM::Document*);URL::FFI::RustUrl web_bindings_document_url(DOM::Document*);HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object);HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject* global_object);+JSObject* web_bindings_environment_settings_object_global_object(HTML::EnvironmentSettingsObject*);+void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject*, void* ctx, void (*on_id)(void*, ReadonlyBytes));bool web_bindings_worker_global_scope_is_closing(HTML::WorkerGlobalScope*);void web_bindings_with_temporary_execution_context(void* realm, bool callbacks_enabled, void* context, void (*steps)(void*));bool web_bindings_object_implements_interface(JSObject* object, u16 interface_name);@@ -254,6 +256,16 @@ HTML::EnvironmentSettingsObject* web_bindings_relevant_settings_object(JSObject*return &HTML::relevant_settings_object(*JS::HostABI::object_from_abi(global_object));}+JSObject* web_bindings_environment_settings_object_global_object(HTML::EnvironmentSettingsObject* settings_object)+{+ return JS::HostABI::object_to_abi(&settings_object->global_object());+}++void web_bindings_environment_settings_object_id(HTML::EnvironmentSettingsObject* settings_object, void* ctx, void (*on_id)(void*, ReadonlyBytes))+{+ on_id(ctx, settings_object->id.to_string().bytes());+}+HTML::WorkerGlobalScope* web_bindings_worker_global_scope_from_global_object(JSObject* global_object){return Bindings::worker_global_scope_from_global_object(*JS::HostABI::object_from_abi(global_object));diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 9947ac310c7..020a05a33ff 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -778,11 +778,9 @@ set(SOURCESSRI/IntegrityPolicy.cppSRI/SRI.cppStorageAPI/NavigatorStorage.cpp- StorageAPI/StorageAreaMirror.cpp- StorageAPI/StorageBottle.cpp+ StorageAPI/StorageAreaMirrorClient.cppStorageAPI/StorageKey.cppStorageAPI/StorageManager.cpp- StorageAPI/StorageShelf.cppStreams/ReadableStream.cppStreams/TransformStream.cppStreams/WritableStream.cppdiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex e4bb22718e9..9b35f33ccd6 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -1068,10 +1068,7 @@ class WritableStream;namespace Web::StorageAPI {class NavigatorStorage;-class StorageBottle;-class StorageBucket;class StorageManager;-class StorageShelf;}diff --git a/Libraries/LibWeb/HTML/Storage.cpp b/Libraries/LibWeb/HTML/Storage.cppindex c732c1a4783..90b636da9e3 100644--- a/Libraries/LibWeb/HTML/Storage.cpp+++ b/Libraries/LibWeb/HTML/Storage.cpp@@ -7,62 +7,52 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/String.h>#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Realm.h>-#include <LibURL/RustIntegration.h>-#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Storage.h>#include <LibWeb/HTML/Window.h>-#include <LibWebCommon/StorageAPI/StorageKey.h>namespace Web::HTML {extern "C" {// Defined in Bindings/Rust/src/html/exports.rs.-void* web_rust_html_create_storage(JSVM*, void* realm, u8 type, StorageAPI::StorageBottle* map);-StorageAPI::StorageBottle* web_rust_html_storage_map(Storage*);-void web_rust_html_dispatch_storage_events_for_remote_change(JSVM*, u8 type, URL::FFI::FfiOrigin const* origin, bool has_session_page, u64 session_page, bool has_key, FlatPtr key, bool has_old_value, FlatPtr old_value, bool has_new_value, FlatPtr new_value, ReadonlyBytes url);+void* web_rust_html_create_storage(JSVM*, void* realm, u8 type);+void web_rust_html_storage_connect(Storage*);+void web_rust_html_storage_for_each_item(Storage*, void* ctx, void (*on_item)(void*, FlatPtr key, FlatPtr value));// Declared on the Rust side in Bindings/Rust/src/html/storage.rs.Storage* web_html_window_storage(Window*, u8 type);}-GC::Ref<Storage> Storage::create(Window& window, Type type, GC::Ref<StorageAPI::StorageBottle> storage_bottle)+GC::Ptr<Storage> Storage::create(Window& window, Type type){auto& realm = relevant_realm(window);- return *static_cast<Storage*>(web_rust_html_create_storage(JS::HostABI::vm_to_abi(realm.vm()), &realm, to_underlying(type), storage_bottle.ptr()));+ return static_cast<Storage*>(web_rust_html_create_storage(JS::HostABI::vm_to_abi(realm.vm()), &realm, to_underlying(type)));}-StorageAPI::StorageBottle& Storage::map()+void Storage::connect(){- return *web_rust_html_storage_map(this);+ web_rust_html_storage_connect(this);}-void Storage::dump()+void Storage::for_each_item(Function<void(Utf16String const& key, Utf16String const& value)> const& callback){- auto keys = map().keys();- dbgln("Storage ({} key(s))", keys.size());- size_t i = 0;- for (auto const& key : keys) {- auto value = map().get(key);- dbgln("[{}] \"{}\": \"{}\"", i, key, value.value());- ++i;- }+ web_rust_html_storage_for_each_item(this, const_cast<void*>(static_cast<void const*>(&callback)), [](void* ctx, FlatPtr key, FlatPtr value) {+ (*static_cast<Function<void(Utf16String const&, Utf16String const&)> const*>(ctx))(Utf16String::from_raw(key), Utf16String::from_raw(value));+ });}-void Storage::dispatch_storage_events_for_remote_change(Type type, StorageAPI::StorageKey const& storage_key, Optional<PageId> session_page, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)+void Storage::dump(){- auto raw = [](Optional<Utf16String> const& string) -> FlatPtr {- if (!string.has_value())- return 0;- return Utf16String { *string }.into_raw();- };- URL::RustIntegration::lend_origin_to_ffi(storage_key.origin, [&](URL::FFI::FfiOrigin const& origin) {- web_rust_html_dispatch_storage_events_for_remote_change(JS::HostABI::vm_to_abi(Bindings::main_thread_vm()), to_underlying(type), &origin, session_page.has_value(), session_page.has_value() ? session_page->value() : 0, key.has_value(), raw(key), old_value.has_value(), raw(old_value), new_value.has_value(), raw(new_value), url.bytes());+ Vector<String> lines;+ for_each_item([&](auto const& key, auto const& value) {+ lines.append(MUST(String::formatted("[{}] \"{}\": \"{}\"", lines.size(), key, value)));});+ dbgln("Storage ({} key(s))", lines.size());+ for (auto const& line : lines)+ dbgln("{}", line);}Storage* web_html_window_storage(Window* window, u8 type)diff --git a/Libraries/LibWeb/HTML/Storage.h b/Libraries/LibWeb/HTML/Storage.hindex a5d16f6dfa6..3d55da5285f 100644--- a/Libraries/LibWeb/HTML/Storage.h+++ b/Libraries/LibWeb/HTML/Storage.h@@ -9,13 +9,11 @@#pragma once-#include <AK/Optional.h>-#include <AK/String.h>+#include <AK/Function.h>#include <AK/Utf16String.h>#include <LibWeb/Bindings/RustInterface.h>#include <LibWeb/Bindings/Storage.h>#include <LibWeb/Export.h>-#include <LibWeb/StorageAPI/StorageBottle.h>namespace Web::HTML {@@ -32,19 +30,17 @@ public:Session,};- [[nodiscard]] static GC::Ref<Storage> create(Window&, Type, GC::Ref<StorageAPI::StorageBottle>);-- StorageAPI::StorageBottle& map();-- void dump();+ // A new Storage object of the type for the window, whose map is a new storage proxy map over the bottle for the+ // window's relevant settings object, or null when obtaining the bottle map fails.+ [[nodiscard]] static GC::Ptr<Storage> create(Window&, Type);// A window listening for storage events has its storage connected so that changes made in other processes reach// it; a map is otherwise only loaded on first access.- void connect() { map().connect(); }+ void connect();- // Fires the storage events that a change another process made calls for on every Storage object in this process- // that shares the changed map.- static void dispatch_storage_events_for_remote_change(Type, StorageAPI::StorageKey const&, Optional<PageId> session_page, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url);+ void for_each_item(Function<void(Utf16String const& key, Utf16String const& value)> const&);++ void dump();};}diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cppindex 7f6d37d8e92..f0c5ed65100 100644--- a/Libraries/LibWeb/HTML/Window.cpp+++ b/Libraries/LibWeb/HTML/Window.cpp@@ -91,13 +91,11 @@#include <LibWeb/RequestIdleCallback/IdleDeadline.h>#include <LibWeb/Selection/Selection.h>#include <LibWeb/Speech/SpeechSynthesis.h>-#include <LibWeb/StorageAPI/StorageBottle.h>#include <LibWeb/ViewTransition/ViewTransition.h>#include <LibWeb/WebIDL/AbstractOperations.h>#include <LibWeb/WebIDL/ExceptionOrUtils.h>#include <LibWeb/WebIDL/Promise.h>#include <LibWebCommon/Infra/CharacterTypes.h>-#include <LibWebCommon/StorageAPI/StorageEndpoint.h>namespace Web::Bindings {@@ -783,20 +781,18 @@ WebIDL::ExceptionOr<GC::Ref<Storage>> Window::local_storage()return GC::Ref { *storage };// 2. Let map be the result of running obtain a local storage bottle map with this's relevant settings object and "localStorage".- auto map = StorageAPI::obtain_a_local_storage_bottle_map(this->relevant_settings_object(), StorageAPI::StorageEndpointType::LocalStorage);-// 3. If map is failure, then throw a "SecurityError" DOMException.- if (!map)- return WebIDL::SecurityError::create("localStorage is not available"_utf16);-// 4. Let storage be a new Storage object whose map is map.- auto storage = Storage::create(*this, Storage::Type::Local, *map);+ // NB: The bottle map is Rust's, so Storage::create() obtains it, and returns null for failure.+ auto storage = Storage::create(*this, Storage::Type::Local);+ if (!storage)+ return WebIDL::SecurityError::create("localStorage is not available"_utf16);// 5. Set this's associated Document's local storage holder to storage.associated_document.set_local_storage_holder(storage);// 6. Return storage.- return storage;+ return GC::Ref { *storage };}// https://html.spec.whatwg.org/multipage/webstorage.html#dom-sessionstorage@@ -808,20 +804,18 @@ WebIDL::ExceptionOr<GC::Ref<Storage>> Window::session_storage()return GC::Ref { *storage };// 2. Let map be the result of running obtain a session storage bottle map with this's relevant settings object and "sessionStorage".- auto map = StorageAPI::obtain_a_session_storage_bottle_map(this->relevant_settings_object(), StorageAPI::StorageEndpointType::SessionStorage);-// 3. If map is failure, then throw a "SecurityError" DOMException.- if (!map)- return WebIDL::SecurityError::create("sessionStorage is not available"_utf16);-// 4. Let storage be a new Storage object whose map is map.- auto storage = Storage::create(*this, Storage::Type::Session, *map);+ // NB: The bottle map is Rust's, so Storage::create() obtains it, and returns null for failure.+ auto storage = Storage::create(*this, Storage::Type::Session);+ if (!storage)+ return WebIDL::SecurityError::create("sessionStorage is not available"_utf16);// 5. Set this's associated Document's session storage holder to storage.associated_document.set_session_storage_holder(storage);// 6. Return storage.- return storage;+ return GC::Ref { *storage };}// https://html.spec.whatwg.org/multipage/interaction.html#sticky-activationdiff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.cpp b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.cppdeleted file mode 100644index b384e402b3d..00000000000--- a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.cpp+++ /dev/null@@ -1,372 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/StorageAPI/StorageAreaMirror.h>--namespace Web::StorageAPI {--static StorageAreaMirrorClient* s_client = nullptr;--void set_storage_area_mirror_client(StorageAreaMirrorClient* client)-{- s_client = client;-}--// The mirrors this process holds, by the key a bottle finds them with and by the area id the owner's messages name.-// Weak, so a mirror lives exactly as long as some bottle addresses it; each mirror removes itself when it dies.-struct MirrorRegistry {- AK_ALLOC_WITH_KMALLOC;-- HashMap<String, WeakPtr<StorageAreaMirror>> by_key;- HashMap<StorageAreaId, WeakPtr<StorageAreaMirror>> by_id;-};--static MirrorRegistry& registry()-{- // Outlives the process, rather than running a destructor at exit.- static auto* registry = new MirrorRegistry;- return *registry;-}--static String registry_key_for(StorageEndpointType endpoint_type, Optional<PageId> session_page, StorageKey const& storage_key)-{- if (session_page.has_value())- return MUST(String::formatted("{}/{}/{}", to_underlying(endpoint_type), *session_page, storage_key.to_string()));- return MUST(String::formatted("{}//{}", to_underlying(endpoint_type), storage_key.to_string()));-}--NonnullRefPtr<StorageAreaMirror> StorageAreaMirror::obtain(StorageEndpointType endpoint_type, Optional<PageId> session_page, StorageKey const& storage_key, Optional<u64> quota)-{- auto key = registry_key_for(endpoint_type, session_page, storage_key);- if (auto existing = registry().by_key.find(key); existing != registry().by_key.end()) {- if (auto live = existing->value.strong_ref())- return live.release_nonnull();- }-- auto mirror = adopt_ref(*new StorageAreaMirror(endpoint_type, session_page, storage_key, quota, key));- registry().by_key.set(key, mirror->make_weak_ptr());- return mirror;-}--StorageAreaMirror::StorageAreaMirror(StorageEndpointType endpoint_type, Optional<PageId> session_page, StorageKey storage_key, Optional<u64> quota, String registry_key)- : m_endpoint_type(endpoint_type)- , m_session_page(session_page)- , m_storage_key(move(storage_key))- , m_quota(quota)- , m_registry_key(move(registry_key))-{-}--StorageAreaMirror::~StorageAreaMirror()-{- registry().by_key.remove(m_registry_key);- if (m_id.has_value()) {- registry().by_id.remove(*m_id);- if (s_client)- s_client->disconnect_from_storage_area(*m_id);- }-}--static String requester_key(StorageAreaMirror::Requester const& requester)-{- return MUST(String::formatted("{}/{}", requester.page_id, requester.environment_id));-}--bool StorageAreaMirror::ensure_primed(Requester const& requester)-{- if (m_primed)- return true;- if (!s_client)- return false;-- auto key = requester_key(requester);- if (m_failed_requesters.contains(key))- return false;-- // One round trip loads the map and registers this process for every change after it, so nothing is missed or- // seen twice.- auto connection = s_client->connect_to_storage_area(requester.page_id, m_endpoint_type, requester.environment_id);- if (!connection.id.has_value()) {- m_failed_requesters.set(move(key));- return false;- }-- // The owner sends one value per key. Taking the shorter of the two would prime a map that's quietly missing- // entries, and nothing downstream could tell that from an empty bottle.- VERIFY(connection.keys.size() == connection.values.size());-- m_id = connection.id;- registry().by_id.set(*m_id, make_weak_ptr());- for (size_t i = 0; i < connection.keys.size(); ++i) {- auto quota_size = storage_quota_size(connection.keys[i]) + storage_quota_size(connection.values[i]);- m_entries.set(move(connection.keys[i]), Entry { move(connection.values[i]), quota_size });- }- m_quota_used = connection.usage;- m_primed = true;- m_failed_requesters.clear();- return true;-}--size_t StorageAreaMirror::size(Requester const& requester)-{- if (!ensure_primed(requester))- return 0;- return m_entries.size();-}--Vector<Utf16String> StorageAreaMirror::keys(Requester const& requester)-{- if (!ensure_primed(requester))- return {};- Vector<Utf16String> keys;- keys.ensure_capacity(m_entries.size());- for (auto const& entry : m_entries)- keys.unchecked_append(entry.key);- return keys;-}--Optional<Utf16String> StorageAreaMirror::get(Requester const& requester, Utf16View key)-{- if (!ensure_primed(requester))- return {};- auto entry = m_entries.find(Utf16String::from_utf16(key));- if (entry == m_entries.end())- return {};- return entry->value.value;-}--WebView::StorageSetResult StorageAreaMirror::set(Requester const& requester, Utf16View key, Utf16View value, String const& document_url)-{- // OPTIMIZATION: An item too large to ever fit is refused before loading the map, so storing one enormous string- // into a bottle this process hasn't read yet costs no round trip. Quota is measured in UTF-8 bytes, and a UTF-16- // code unit never encodes to fewer than one of those, so the code unit count is a lower bound.- if (m_quota.has_value() && key.length_in_code_units() + value.length_in_code_units() > *m_quota)- return WebView::StorageOperationError::QuotaExceededError;-- if (!ensure_primed(requester))- return WebView::StorageOperationError::QuotaExceededError;-- auto owned_key = Utf16String::from_utf16(key);- auto owned_value = Utf16String::from_utf16(value);-- Optional<Utf16String> old_value;- u64 replaced_size = 0;- if (auto existing = m_entries.find(owned_key); existing != m_entries.end()) {- old_value = existing->value.value;- replaced_size = existing->value.quota_size;- }-- // The same rule the owner applies, so a write accepted here is one the owner accepts too — unless another- // process filled the bottle in between, which the owner then refuses and this mirror hears of.- auto new_size = storage_quota_size(key) + storage_quota_size(value);- if (m_quota.has_value() && m_quota_used - replaced_size + new_size > *m_quota)- return WebView::StorageOperationError::QuotaExceededError;-- apply_set(owned_key, owned_value, new_size);- push_pending_write(owned_key, owned_value);- s_client->set_storage_item(*m_id, owned_key, owned_value, document_url);- return old_value;-}--Optional<Utf16String> StorageAreaMirror::remove(Requester const& requester, Utf16View key, String const& document_url)-{- if (!ensure_primed(requester))- return {};-- auto owned_key = Utf16String::from_utf16(key);- auto existing = m_entries.find(owned_key);- if (existing == m_entries.end())- return {};-- auto old_value = existing->value.value;- apply_remove(owned_key);- push_pending_write(owned_key, {});- s_client->remove_storage_item(*m_id, owned_key, document_url);- return old_value;-}--bool StorageAreaMirror::clear(Requester const& requester, String const& document_url)-{- if (!ensure_primed(requester) || m_entries.is_empty())- return false;-- apply_clear();- push_pending_write({}, {});- s_client->clear_storage_area(*m_id, document_url);- return true;-}--void StorageAreaMirror::apply_set(Utf16String const& key, Utf16String const& value, u64 quota_size)-{- if (auto existing = m_entries.find(key); existing != m_entries.end())- m_quota_used -= existing->value.quota_size;- m_quota_used += quota_size;- m_entries.set(key, Entry { value, quota_size });-}--void StorageAreaMirror::apply_remove(Utf16String const& key)-{- if (auto existing = m_entries.find(key); existing != m_entries.end()) {- m_quota_used -= existing->value.quota_size;- m_entries.remove(existing);- }-}--void StorageAreaMirror::apply_clear()-{- m_entries.clear();- m_quota_used = 0;-}--void StorageAreaMirror::push_pending_write(Optional<Utf16String> key, Optional<Utf16String> new_value)-{- if (key.has_value())- ++m_pending_count_by_key.ensure(*key);- else- ++m_pending_clear_count;- m_pending_writes.append({ move(key), move(new_value) });-}--StorageAreaMirror::PendingWrite StorageAreaMirror::pop_pending_write()-{- // The owner answers every write, in the order they were sent.- VERIFY(m_first_pending_write < m_pending_writes.size());- auto write = move(m_pending_writes[m_first_pending_write++]);- if (m_first_pending_write == m_pending_writes.size()) {- m_pending_writes.clear();- m_first_pending_write = 0;- }- if (write.key.has_value()) {- auto count = m_pending_count_by_key.get(*write.key);- VERIFY(count.has_value() && *count > 0);- if (*count == 1)- m_pending_count_by_key.remove(*write.key);- else- m_pending_count_by_key.set(*write.key, *count - 1);- } else {- VERIFY(m_pending_clear_count > 0);- --m_pending_clear_count;- }- return write;-}--// The owner hasn't applied these yet, so whatever state it just described predates them.-void StorageAreaMirror::reapply_pending_writes()-{- for (auto const& write : m_pending_writes.span().slice(m_first_pending_write)) {- if (!write.key.has_value())- apply_clear();- else if (write.new_value.has_value())- apply_set(*write.key, *write.new_value, storage_quota_size(*write.key) + storage_quota_size(*write.new_value));- else- apply_remove(*write.key);- }-}--void StorageAreaMirror::reset_to(Vector<Utf16String> keys, Vector<Utf16String> values)-{- VERIFY(keys.size() == values.size());-- auto old_entries = move(m_entries);- m_entries.clear();- m_quota_used = 0;- for (size_t i = 0; i < keys.size(); ++i)- apply_set(keys[i], values[i], storage_quota_size(keys[i]) + storage_quota_size(values[i]));- reapply_pending_writes();-- if (!on_remote_change)- return;-- // AD-HOC: The spec's broadcast fires an event for each change a script makes, and never for a write refused after- // the fact; it has no such thing. Whatever differs from before is a change this process's windows didn't- // see being made, so each gets an event for it — the window whose write was refused included.- auto url = m_storage_key.to_string();- for (auto const& entry : old_entries) {- Optional<Utf16String> now;- if (auto it = m_entries.find(entry.key); it != m_entries.end())- now = it->value.value;- if (now != entry.value.value)- on_remote_change(entry.key, entry.value.value, now, url);- }- for (auto const& entry : m_entries) {- if (!old_entries.contains(entry.key))- on_remote_change(entry.key, {}, entry.value.value, url);- }-}--// A change another process made, as the owner serialized it. One that reached the owner before a write this process-// still has pending predates that write, so the mirror already shows the later state and leaves it be. While a clear-// is pending, that goes for every change.-void StorageAreaMirror::apply_remote_change(Optional<Utf16String> const& key, Optional<Utf16String> const& new_value)-{- if (m_pending_clear_count > 0)- return;-- if (!key.has_value()) {- // The owner emptied the bottle before applying this process's pending writes, so those come back on top.- apply_clear();- reapply_pending_writes();- return;- }-- if (m_pending_count_by_key.contains(*key))- return;-- if (new_value.has_value())- apply_set(*key, *new_value, storage_quota_size(*key) + storage_quota_size(*new_value));- else- apply_remove(*key);-}--static RefPtr<StorageAreaMirror> mirror_for(StorageAreaId id)-{- auto entry = registry().by_id.find(id);- if (entry == registry().by_id.end())- return {};- return entry->value.strong_ref();-}--void StorageAreaMirror::did_change(StorageAreaId id, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)-{- auto mirror = mirror_for(id);- if (!mirror)- return;-- mirror->apply_remote_change(key, new_value);- if (mirror->on_remote_change)- mirror->on_remote_change(key, old_value, new_value, url);-}--void StorageAreaMirror::did_acknowledge_write(StorageAreaId id)-{- auto mirror = mirror_for(id);- if (!mirror)- return;- mirror->pop_pending_write();-}--void StorageAreaMirror::did_refuse_write(StorageAreaId id, Vector<Utf16String> keys, Vector<Utf16String> values)-{- auto mirror = mirror_for(id);- if (!mirror)- return;-- // Only a set can be refused: it was applied here on the strength of a quota check another process's write- // overtook. The owner's map puts this one back in agreement.- auto refused = mirror->pop_pending_write();- VERIFY(refused.key.has_value() && refused.new_value.has_value());- mirror->reset_to(move(keys), move(values));-}--void StorageAreaMirror::did_reset(StorageAreaId id, Vector<Utf16String> keys, Vector<Utf16String> values)-{- auto mirror = mirror_for(id);- if (!mirror)- return;- mirror->reset_to(move(keys), move(values));-}--}diff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.hdeleted file mode 100644index 650bbf60bfe..00000000000--- a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h+++ /dev/null@@ -1,154 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Function.h>-#include <AK/HashMap.h>-#include <AK/HashTable.h>-#include <AK/NonnullRefPtr.h>-#include <AK/Optional.h>-#include <AK/RefCounted.h>-#include <AK/String.h>-#include <AK/Utf16String.h>-#include <AK/Vector.h>-#include <AK/WeakPtr.h>-#include <AK/Weakable.h>-#include <LibWeb/Export.h>-#include <LibWeb/StorageAPI/StorageKey.h>-#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>-#include <LibWebCommon/Page/PageId.h>-#include <LibWebCommon/StorageAPI/StorageAreaId.h>-#include <LibWebCommon/StorageAPI/StorageEndpoint.h>-#include <LibWebCommon/WebView/StorageSetResult.h>--namespace Web::StorageAPI {--// What the process that owns the storage areas answers when this process connects to one: the area's id and-// everything the bottle holds. No id means the area couldn't be resolved, and the mirror stays detached.-struct StorageAreaConnection {- Optional<StorageAreaId> id;- Vector<Utf16String> keys;- Vector<Utf16String> values;- u64 usage { 0 };-};--// The process's one link to the storage areas' owner. WebContent connects it to the browser process; a process without-// one (a unit test) leaves every mirror detached.-class WEB_API StorageAreaMirrorClient {-public:- virtual ~StorageAreaMirrorClient() = default;-- virtual StorageAreaConnection connect_to_storage_area(PageId, StorageEndpointType, HTML::EnvironmentId const&) = 0;- virtual void disconnect_from_storage_area(StorageAreaId) = 0;- virtual void set_storage_item(StorageAreaId, Utf16String const& key, Utf16String const& value, String const& document_url) = 0;- virtual void remove_storage_item(StorageAreaId, Utf16String const& key, String const& document_url) = 0;- virtual void clear_storage_area(StorageAreaId, String const& document_url) = 0;-};--WEB_API void set_storage_area_mirror_client(StorageAreaMirrorClient*);--// https://storage.spec.whatwg.org/#storage-bottle-// This process's copy of one storage bottle's map. The map itself is kept by the browser process, which makes it-// available across agent cluster boundaries this way: a process loads the map once, with one synchronous round trip-// that also registers it for every later change, and from then on answers reads from the copy, applies writes to the-// copy before sending them, and applies the changes other processes make as the owner relays them. Every storage-// bottle in this process for the same area shares one mirror, so two windows of one origin can't see different maps.-class WEB_API StorageAreaMirror final- : public RefCounted<StorageAreaMirror>- , public Weakable<StorageAreaMirror> {-public:- // The page and environment a bottle asks on behalf of, which the owner resolves to the area. A mirror outlives- // the document that first asked for it, so every call names its own requester.- struct Requester {- PageId page_id;- HTML::EnvironmentId environment_id;- };-- // One mirror per storage key for local storage, and per page and storage key for session storage: a page's- // documents all belong to one traversable, and the traversable is what partitions session storage.- static NonnullRefPtr<StorageAreaMirror> obtain(StorageEndpointType, Optional<PageId> session_page, StorageKey const&, Optional<u64> quota);- ~StorageAreaMirror();-- // Loads the map now rather than on first access, so changes other processes make start arriving.- void connect(Requester const& requester) { ensure_primed(requester); }-- size_t size(Requester const&);- Vector<Utf16String> keys(Requester const&);- Optional<Utf16String> get(Requester const&, Utf16View key);- // The value the key had, or the quota's refusal. The write is applied here and sent on without waiting.- WebView::StorageSetResult set(Requester const&, Utf16View key, Utf16View value, String const& document_url);- // The value removed, if the key existed.- Optional<Utf16String> remove(Requester const&, Utf16View key, String const& document_url);- // False when there was nothing to clear.- bool clear(Requester const&, String const& document_url);-- // What the owner relays, found by area id. A change for an area this process no longer mirrors is dropped.- static void did_change(StorageAreaId, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url);- static void did_acknowledge_write(StorageAreaId);- static void did_refuse_write(StorageAreaId, Vector<Utf16String> keys, Vector<Utf16String> values);- static void did_reset(StorageAreaId, Vector<Utf16String> keys, Vector<Utf16String> values);-- // Every change another party made to the map, as the owner relayed it (or, after a reset, as the diff shows it),- // for the storage events it calls for. A null key is a clear.- Function<void(Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)> on_remote_change;-- StorageEndpointType endpoint_type() const { return m_endpoint_type; }- StorageKey const& storage_key() const { return m_storage_key; }- Optional<PageId> session_page() const { return m_session_page; }-- u64 quota_used() const { return m_quota_used; }- size_t pending_write_count() const { return m_pending_writes.size() - m_first_pending_write; }--private:- StorageAreaMirror(StorageEndpointType, Optional<PageId> session_page, StorageKey, Optional<u64> quota, String registry_key);-- // A write this process applied and sent, until the owner acknowledges or refuses it. A null key is a clear; a- // null value is a removal.- struct PendingWrite {- Optional<Utf16String> key;- Optional<Utf16String> new_value;- };-- // An entry's quota size is kept beside its value, so overwriting or removing it never measures the old value again.- struct Entry {- Utf16String value;- u64 quota_size { 0 };- };-- // False when the owner couldn't resolve the requester's area; that requester is then not asked about again, but- // another requester of the same mirror still can be (the first may have been a page on its way out).- bool ensure_primed(Requester const&);- void apply_set(Utf16String const& key, Utf16String const& value, u64 quota_size);- void apply_remove(Utf16String const& key);- void apply_clear();- void push_pending_write(Optional<Utf16String> key, Optional<Utf16String> new_value);- PendingWrite pop_pending_write();- void reapply_pending_writes();- void reset_to(Vector<Utf16String> keys, Vector<Utf16String> values);- void apply_remote_change(Optional<Utf16String> const& key, Optional<Utf16String> const& new_value);-- StorageEndpointType m_endpoint_type;- Optional<PageId> m_session_page;- StorageKey m_storage_key;- Optional<u64> m_quota;- String m_registry_key;-- OrderedHashMap<Utf16String, Entry> m_entries;- u64 m_quota_used { 0 };- Optional<StorageAreaId> m_id;- bool m_primed { false };- HashTable<String> m_failed_requesters;-- // The writes the owner hasn't answered yet are the ones from m_first_pending_write on. Answered ones stay in place- // until the queue drains, so a script that queues thousands of writes in one task costs nothing more per answer.- Vector<PendingWrite> m_pending_writes;- size_t m_first_pending_write { 0 };- HashMap<Utf16String, u32> m_pending_count_by_key;- u32 m_pending_clear_count { 0 };-};--}diff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.cpp b/Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.cppnew file mode 100644index 00000000000..105272407d3--- /dev/null+++ b/Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.cpp@@ -0,0 +1,120 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibJS/HostClassBuilder.h>+#include <LibWeb/Bindings/MainThreadVM.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/StorageAPI/StorageAreaMirrorClient.h>++namespace Web::StorageAPI {++extern "C" {++// Defined in Bindings/Rust/src/storage_api/exports.rs.+void web_rust_storage_api_set_storage_area_mirror_client(StorageAreaMirrorClient*);+void web_rust_storage_api_storage_area_did_change(JSVM*, u64 id, bool has_key, FlatPtr key, bool has_old_value, FlatPtr old_value, bool has_new_value, FlatPtr new_value, ReadonlyBytes url);+void web_rust_storage_api_storage_area_did_acknowledge_write(u64 id);+void web_rust_storage_api_storage_area_did_refuse_write(JSVM*, u64 id, FlatPtr const* keys, FlatPtr const* values, size_t count);+void web_rust_storage_api_storage_area_did_reset(JSVM*, u64 id, FlatPtr const* keys, FlatPtr const* values, size_t count);++// Declared on the Rust side in Bindings/Rust/src/storage_api/exports.rs and storage_endpoint.rs.+void web_storage_api_storage_area_mirror_client_connect(StorageAreaMirrorClient*, u64 page_id, u8 endpoint_type, HTML::EnvironmentSettingsObject*, void* ctx, void (*on_connection)(void*, bool has_id, u64 id, FlatPtr const* keys, FlatPtr const* values, size_t count, u64 usage));+void web_storage_api_storage_area_mirror_client_disconnect(StorageAreaMirrorClient*, u64 id);+void web_storage_api_storage_area_mirror_client_set_item(StorageAreaMirrorClient*, u64 id, FlatPtr key, FlatPtr value, ReadonlyBytes document_url);+void web_storage_api_storage_area_mirror_client_remove_item(StorageAreaMirrorClient*, u64 id, FlatPtr key, ReadonlyBytes document_url);+void web_storage_api_storage_area_mirror_client_clear(StorageAreaMirrorClient*, u64 id, ReadonlyBytes document_url);+void web_storage_api_for_each_registered_endpoint(void* ctx, void (*on_endpoint)(void*, u8 identifier, bool is_session, bool has_quota, u64 quota));+}++void set_storage_area_mirror_client(StorageAreaMirrorClient* client)+{+ web_rust_storage_api_set_storage_area_mirror_client(client);+}++static FlatPtr raw_or_zero(Optional<Utf16String> const& string)+{+ if (!string.has_value())+ return 0;+ return Utf16String { *string }.into_raw();+}++static Vector<FlatPtr> into_raw(Vector<Utf16String>&& strings)+{+ Vector<FlatPtr> raws;+ raws.ensure_capacity(strings.size());+ for (auto& string : strings)+ raws.unchecked_append(move(string).into_raw());+ return raws;+}++static JSVM* vm()+{+ return JS::HostABI::vm_to_abi(Bindings::main_thread_vm());+}++void storage_area_did_change(StorageAreaId id, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url)+{+ web_rust_storage_api_storage_area_did_change(vm(), id.value(), key.has_value(), raw_or_zero(key), old_value.has_value(), raw_or_zero(old_value), new_value.has_value(), raw_or_zero(new_value), url.bytes());+}++void storage_area_did_acknowledge_write(StorageAreaId id)+{+ web_rust_storage_api_storage_area_did_acknowledge_write(id.value());+}++void storage_area_did_refuse_write(StorageAreaId id, Vector<Utf16String> keys, Vector<Utf16String> values)+{+ VERIFY(keys.size() == values.size());+ auto raw_keys = into_raw(move(keys));+ auto raw_values = into_raw(move(values));+ web_rust_storage_api_storage_area_did_refuse_write(vm(), id.value(), raw_keys.data(), raw_values.data(), raw_keys.size());+}++void storage_area_did_reset(StorageAreaId id, Vector<Utf16String> keys, Vector<Utf16String> values)+{+ VERIFY(keys.size() == values.size());+ auto raw_keys = into_raw(move(keys));+ auto raw_values = into_raw(move(values));+ web_rust_storage_api_storage_area_did_reset(vm(), id.value(), raw_keys.data(), raw_values.data(), raw_keys.size());+}++void web_storage_api_storage_area_mirror_client_connect(StorageAreaMirrorClient* client, u64 page_id, u8 endpoint_type, HTML::EnvironmentSettingsObject* environment, void* ctx, void (*on_connection)(void*, bool has_id, u64 id, FlatPtr const* keys, FlatPtr const* values, size_t count, u64 usage))+{+ auto connection = client->connect_to_storage_area(PageId { page_id }, static_cast<StorageEndpointType>(endpoint_type), environment->id);+ // The keys and the values cross with one count.+ VERIFY(connection.keys.size() == connection.values.size());+ auto keys = into_raw(move(connection.keys));+ auto values = into_raw(move(connection.values));+ on_connection(ctx, connection.id.has_value(), connection.id.has_value() ? connection.id->value() : 0, keys.data(), values.data(), keys.size(), connection.usage);+}++void web_storage_api_storage_area_mirror_client_disconnect(StorageAreaMirrorClient* client, u64 id)+{+ client->disconnect_from_storage_area(StorageAreaId { id });+}++void web_storage_api_storage_area_mirror_client_set_item(StorageAreaMirrorClient* client, u64 id, FlatPtr key, FlatPtr value, ReadonlyBytes document_url)+{+ client->set_storage_item(StorageAreaId { id }, Utf16String::from_raw(key), Utf16String::from_raw(value), MUST(String::from_utf8(document_url)));+}++void web_storage_api_storage_area_mirror_client_remove_item(StorageAreaMirrorClient* client, u64 id, FlatPtr key, ReadonlyBytes document_url)+{+ client->remove_storage_item(StorageAreaId { id }, Utf16String::from_raw(key), MUST(String::from_utf8(document_url)));+}++void web_storage_api_storage_area_mirror_client_clear(StorageAreaMirrorClient* client, u64 id, ReadonlyBytes document_url)+{+ client->clear_storage_area(StorageAreaId { id }, MUST(String::from_utf8(document_url)));+}++void web_storage_api_for_each_registered_endpoint(void* ctx, void (*on_endpoint)(void*, u8 identifier, bool is_session, bool has_quota, u64 quota))+{+ for (auto const& endpoint : StorageEndpoint::registered_endpoints())+ on_endpoint(ctx, to_underlying(endpoint.identifier), endpoint.type == StorageType::Session, endpoint.quota.has_value(), endpoint.quota.value_or(0));+}++}diff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.h b/Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.hnew file mode 100644index 00000000000..71643aa229d--- /dev/null+++ b/Libraries/LibWeb/StorageAPI/StorageAreaMirrorClient.h@@ -0,0 +1,52 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Optional.h>+#include <AK/String.h>+#include <AK/Utf16String.h>+#include <AK/Vector.h>+#include <LibWeb/Export.h>+#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>+#include <LibWebCommon/Page/PageId.h>+#include <LibWebCommon/StorageAPI/StorageAreaId.h>+#include <LibWebCommon/StorageAPI/StorageEndpoint.h>++namespace Web::StorageAPI {++// What the process that owns the storage areas answers when this process connects to one: the area's id and+// everything the bottle holds. No id means the area couldn't be resolved, and the mirror stays detached.+struct StorageAreaConnection {+ Optional<StorageAreaId> id;+ Vector<Utf16String> keys;+ Vector<Utf16String> values;+ u64 usage { 0 };+};++// The process's one link to the storage areas' owner, for the mirrors of the storage bottles, which are implemented+// in Rust (Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_area_mirror.rs). WebContent connects it to the+// browser process; a process without one leaves every mirror detached.+class WEB_API StorageAreaMirrorClient {+public:+ virtual ~StorageAreaMirrorClient() = default;++ virtual StorageAreaConnection connect_to_storage_area(PageId, StorageEndpointType, HTML::EnvironmentId const&) = 0;+ virtual void disconnect_from_storage_area(StorageAreaId) = 0;+ virtual void set_storage_item(StorageAreaId, Utf16String const& key, Utf16String const& value, String const& document_url) = 0;+ virtual void remove_storage_item(StorageAreaId, Utf16String const& key, String const& document_url) = 0;+ virtual void clear_storage_area(StorageAreaId, String const& document_url) = 0;+};++WEB_API void set_storage_area_mirror_client(StorageAreaMirrorClient*);++// What the owner relays, found by area id. A change for an area this process no longer mirrors is dropped.+WEB_API void storage_area_did_change(StorageAreaId, Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url);+WEB_API void storage_area_did_acknowledge_write(StorageAreaId);+WEB_API void storage_area_did_refuse_write(StorageAreaId, Vector<Utf16String> keys, Vector<Utf16String> values);+WEB_API void storage_area_did_reset(StorageAreaId, Vector<Utf16String> keys, Vector<Utf16String> values);++}diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp b/Libraries/LibWeb/StorageAPI/StorageBottle.cppdeleted file mode 100644index f86fb20f025..00000000000--- a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp+++ /dev/null@@ -1,229 +0,0 @@-/*- * Copyright (c) 2024-2025, Shannon Booth <[email protected]>- * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Storage.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/StorageAPI/StorageBottle.h>-#include <LibWeb/StorageAPI/StorageKey.h>-#include <LibWebCommon/StorageAPI/StorageEndpoint.h>--namespace Web::StorageAPI {--GC_DEFINE_ALLOCATOR(StorageBottle);-GC_DEFINE_ALLOCATOR(StorageBucket);--void StorageBucket::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- for (auto& entry : m_bottle_map)- visitor.visit(entry);-}--StorageBucket::StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type)-{- // 1. Let bucket be null.- // 2. If type is "local", then set bucket to a new local storage bucket.- // 3. Otherwise:- // 1. Assert: type is "session".- // 2. Set bucket to a new session storage bucket.-- // 4. For each endpoint of registered storage endpoints whose types contain type, set bucket’s bottle map[endpoint’s identifier] to a new storage bottle whose quota is endpoint’s quota.- for (auto const& endpoint : StorageEndpoint::registered_endpoints()) {- if (endpoint.type == type)- m_bottle_map[to_underlying(endpoint.identifier)] = StorageBottle::create(page, endpoint, environment_id, key);- }-- // 5. Return bucket.-}--// https://storage.spec.whatwg.org/#obtain-a-storage-bottle-map-GC::Ptr<StorageBottle> obtain_a_storage_bottle_map(StorageType type, HTML::EnvironmentSettingsObject& environment, StorageEndpointType endpoint_type)-{- // 1. Let shed be null.- // 2. If type is "local", then set shed to the user agent’s storage shed.- // 3. Otherwise:- // 1. Assert: type is "session".- // 2. Set shed to environment’s global object’s associated Document’s node navigable’s traversable navigable’s storage shed.- // NB: Both sheds are kept by the browser process, in a StorageJar, which the bottle returned here mirrors. The- // bottle names environment, from which the browser process obtains the storage key itself.-- // 4. Let shelf be the result of running obtain a storage shelf, with shed, environment, and type.- // 5. If shelf is failure, then return failure.- auto key = obtain_a_storage_key(environment);- if (!key.has_value())- return {};-- // 6. Let bucket be shelf’s bucket map["default"].- // 7. Let bottle be bucket’s bottle map[identifier].- // NB: The bucket's bottle map holds a bottle for each registered storage endpoint whose types contain type, with- // that endpoint's quota.- auto endpoint = StorageEndpoint::registered_endpoints().first_matching([&](auto const& endpoint) { return endpoint.identifier == endpoint_type; });- VERIFY(endpoint.has_value() && endpoint->type == type);-- // 8. Let proxyMap be a new storage proxy map whose backing map is bottle’s map.- // 9. Append proxyMap to bottle’s proxy map reference set.- // 10. Return proxyMap.- auto& page = HTML::relevant_window(environment.global_object()).page();- return StorageBottle::create(page, *endpoint, environment.id, *key);-}--// https://storage.spec.whatwg.org/#obtain-a-local-storage-bottle-map-GC::Ptr<StorageBottle> obtain_a_local_storage_bottle_map(HTML::EnvironmentSettingsObject& environment, StorageEndpointType identifier)-{- // To obtain a local storage bottle map, given an environment settings object environment and storage identifier identifier,- // return the result of running obtain a storage bottle map with "local", environment, and identifier.- return obtain_a_storage_bottle_map(StorageType::Local, environment, identifier);-}--// https://storage.spec.whatwg.org/#obtain-a-session-storage-bottle-map-GC::Ptr<StorageBottle> obtain_a_session_storage_bottle_map(HTML::EnvironmentSettingsObject& environment, StorageEndpointType identifier)-{- // To obtain a session storage bottle map, given an environment settings object environment and storage identifier identifier,- // return the result of running obtain a storage bottle map with "session", environment, and identifier.- return obtain_a_storage_bottle_map(StorageType::Session, environment, identifier);-}--GC::Ref<StorageBottle> StorageBottle::create(GC::Ref<Page> page, StorageEndpoint const& endpoint, HTML::EnvironmentId environment_id, StorageKey const& key)-{- return GC::Heap::the().allocate<StorageBottle>(page, endpoint.identifier, move(environment_id), key, endpoint.quota);-}--StorageBottle::StorageBottle(GC::Ref<Page> page, StorageEndpointType endpoint_type, HTML::EnvironmentId environment_id, StorageKey const& key, Optional<u64> quota)- : m_page(page)- , m_environment_id(move(environment_id))- , m_quota(quota)- // Session storage is partitioned by the traversable, and a page's documents all belong to one traversable, so- // a session bottle's mirror is found by its page as well as its storage key.- , m_mirror(StorageAreaMirror::obtain(endpoint_type, endpoint_type == StorageEndpointType::SessionStorage ? Optional<PageId> { page->client().id() } : Optional<PageId> {}, key, quota))-{- // A change another process made calls for the storage events the spec's broadcast fires, on every Storage object- // here that shares the map. The mirror is shared, so the first bottle for it hooks this up for all of them.- if (!m_mirror->on_remote_change) {- m_mirror->on_remote_change = [mirror = m_mirror->make_weak_ptr()](Optional<Utf16String> const& key, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value, String const& url) {- if (!mirror)- return;- auto type = mirror->endpoint_type() == StorageEndpointType::SessionStorage ? HTML::Storage::Type::Session : HTML::Storage::Type::Local;- HTML::Storage::dispatch_storage_events_for_remote_change(type, mirror->storage_key(), mirror->session_page(), key, old_value, new_value, url);- };- }-}--void StorageBottle::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_page);-}--StorageAreaMirror::Requester StorageBottle::requester() const-{- return { m_page->client().id(), m_environment_id };-}--void StorageBottle::connect() const-{- m_mirror->connect(requester());-}--size_t StorageBottle::size() const-{- return m_mirror->size(requester());-}--Vector<Utf16String> StorageBottle::keys() const-{- return m_mirror->keys(requester());-}--Optional<Utf16String> StorageBottle::get(Utf16View key) const-{- return m_mirror->get(requester(), key);-}--StorageSetResult StorageBottle::set(Utf16View key, Utf16View value, String const& document_url)-{- return m_mirror->set(requester(), key, value, document_url);-}--void StorageBottle::clear(String const& document_url)-{- m_mirror->clear(requester(), document_url);-}--void StorageBottle::remove(Utf16View key, String const& document_url)-{- (void)m_mirror->remove(requester(), key, document_url);-}--// Declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_bottle.rs.-extern "C" {--size_t web_storage_api_storage_bottle_size(StorageBottle*);-void web_storage_api_storage_bottle_keys(StorageBottle*, void* keys, void (*append)(void* keys, FlatPtr key));-bool web_storage_api_storage_bottle_get(StorageBottle*, FlatPtr key, FlatPtr* value);-u8 web_storage_api_storage_bottle_set(StorageBottle*, FlatPtr key, FlatPtr value, ReadonlyBytes document_url, FlatPtr* old_value);-void web_storage_api_storage_bottle_remove(StorageBottle*, FlatPtr key, ReadonlyBytes document_url);-void web_storage_api_storage_bottle_clear(StorageBottle*, ReadonlyBytes document_url);-bool web_storage_api_storage_bottle_quota(StorageBottle*, u64* quota);-}--size_t web_storage_api_storage_bottle_size(StorageBottle* bottle)-{- return bottle->size();-}--void web_storage_api_storage_bottle_keys(StorageBottle* bottle, void* keys, void (*append)(void* keys, FlatPtr key))-{- for (auto& key : bottle->keys())- append(keys, move(key).into_raw());-}--bool web_storage_api_storage_bottle_get(StorageBottle* bottle, FlatPtr key, FlatPtr* value)-{- auto key_string = Utf16String::from_raw(key);- auto found = bottle->get(key_string);- if (!found.has_value())- return false;- *value = found.release_value().into_raw();- return true;-}--u8 web_storage_api_storage_bottle_set(StorageBottle* bottle, FlatPtr key, FlatPtr value, ReadonlyBytes document_url, FlatPtr* old_value)-{- auto key_string = Utf16String::from_raw(key);- auto value_string = Utf16String::from_raw(value);- auto result = bottle->set(key_string, value_string, MUST(String::from_utf8(document_url)));- if (result.has<WebView::StorageOperationError>())- return 0;- auto& existing = result.get<Optional<Utf16String>>();- if (!existing.has_value())- return 1;- *old_value = existing.release_value().into_raw();- return 2;-}--void web_storage_api_storage_bottle_remove(StorageBottle* bottle, FlatPtr key, ReadonlyBytes document_url)-{- auto key_string = Utf16String::from_raw(key);- bottle->remove(key_string, MUST(String::from_utf8(document_url)));-}--void web_storage_api_storage_bottle_clear(StorageBottle* bottle, ReadonlyBytes document_url)-{- bottle->clear(MUST(String::from_utf8(document_url)));-}--bool web_storage_api_storage_bottle_quota(StorageBottle* bottle, u64* quota)-{- if (!bottle->quota().has_value())- return false;- *quota = *bottle->quota();- return true;-}--}diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.h b/Libraries/LibWeb/StorageAPI/StorageBottle.hdeleted file mode 100644index 066ef6cdb70..00000000000--- a/Libraries/LibWeb/StorageAPI/StorageBottle.h+++ /dev/null@@ -1,97 +0,0 @@-/*- * Copyright (c) 2024-2025, Shannon Booth <[email protected]>- * Copyright (c) 2025, Aliaksandr Kalenik <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <AK/NonnullRefPtr.h>-#include <AK/String.h>-#include <LibGC/Heap.h>-#include <LibGC/Ptr.h>-#include <LibWeb/Export.h>-#include <LibWeb/Forward.h>-#include <LibWeb/Page/Page.h>-#include <LibWeb/StorageAPI/StorageAreaMirror.h>-#include <LibWeb/StorageAPI/StorageKey.h>-#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>-#include <LibWebCommon/StorageAPI/StorageEndpoint.h>-#include <LibWebCommon/StorageAPI/StorageType.h>-#include <LibWebCommon/WebView/StorageSetResult.h>--namespace Web::StorageAPI {--using StorageSetResult = Variant<WebView::StorageOperationError, Optional<Utf16String>>;--// https://storage.spec.whatwg.org/#storage-bottle-// NB: The bottle's map lives in the browser process; what a bottle here holds is this process's mirror of it, shared-// with every other bottle in the process for the same area. Each bottle object is one storage proxy map over it.-class WEB_API StorageBottle : public GC::Cell {- GC_CELL(StorageBottle, GC::Cell);- GC_DECLARE_ALLOCATOR(StorageBottle);--public:- static GC::Ref<StorageBottle> create(GC::Ref<Page>, StorageEndpoint const&, HTML::EnvironmentId, StorageKey const&);-- virtual ~StorageBottle() = default;-- // A storage bottle also has a proxy map reference set, which is initially an empty set- GC::Ref<StorageBottle> proxy() { return *this; }-- // Connects the mirror now rather than on first access, so changes other processes make start arriving.- void connect() const;-- size_t size() const;- Vector<Utf16String> keys() const;- Optional<Utf16String> get(Utf16View) const;- // The URL is the document's, carried to the storage events other processes fire for the change.- StorageSetResult set(Utf16View key, Utf16View value, String const& document_url);- void clear(String const& document_url);- void remove(Utf16View, String const& document_url);-- Optional<u64> quota() const { return m_quota; }-- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- StorageBottle(GC::Ref<Page>, StorageEndpointType, HTML::EnvironmentId, StorageKey const&, Optional<u64> quota);-- StorageAreaMirror::Requester requester() const;-- GC::Ref<Page> m_page;- HTML::EnvironmentId m_environment_id;- Optional<u64> m_quota;- NonnullRefPtr<StorageAreaMirror> m_mirror;-};--using BottleMap = Array<GC::Ptr<StorageBottle>, to_underlying(StorageEndpointType::Count)>;--// https://storage.spec.whatwg.org/#storage-bucket-// A storage bucket is a place for storage endpoints to store data.-class StorageBucket : public GC::Cell {- GC_CELL(StorageBucket, GC::Cell);- GC_DECLARE_ALLOCATOR(StorageBucket);--public:- static GC::Ref<StorageBucket> create(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type) { return GC::Heap::the().allocate<StorageBucket>(page, move(environment_id), key, type); }-- BottleMap& bottle_map() { return m_bottle_map; }- BottleMap const& bottle_map() const { return m_bottle_map; }-- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- explicit StorageBucket(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type);-- // A storage bucket has a bottle map of storage identifiers to storage bottles.- BottleMap m_bottle_map;-};--GC::Ptr<StorageBottle> obtain_a_local_storage_bottle_map(HTML::EnvironmentSettingsObject&, StorageEndpointType endpoint_type);-GC::Ptr<StorageBottle> obtain_a_session_storage_bottle_map(HTML::EnvironmentSettingsObject&, StorageEndpointType endpoint_type);-GC::Ptr<StorageBottle> obtain_a_storage_bottle_map(StorageType, HTML::EnvironmentSettingsObject&, StorageEndpointType endpoint_type);--}diff --git a/Libraries/LibWeb/StorageAPI/StorageManager.cpp b/Libraries/LibWeb/StorageAPI/StorageManager.cppindex ab4b8bfab06..f49393af721 100644--- a/Libraries/LibWeb/StorageAPI/StorageManager.cpp+++ b/Libraries/LibWeb/StorageAPI/StorageManager.cpp@@ -8,6 +8,9 @@#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/Realm.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Window.h>+#include <LibWeb/Page/Page.h>#include <LibWeb/StorageAPI/StorageManager.h>namespace Web::StorageAPI {@@ -16,6 +19,9 @@ extern "C" {// Defined in Bindings/Rust/src/storage_api/exports.rs.void* web_rust_storage_api_create_storage_manager(JSVM*, void* realm);++// Declared on the Rust side in Bindings/Rust/src/storage_api/storage_shelf.rs.+u64 web_storage_api_storage_usage(HTML::EnvironmentSettingsObject*);}GC::Ref<StorageManager> StorageManager::create(JS::Realm& realm)@@ -23,4 +29,11 @@ GC::Ref<StorageManager> StorageManager::create(JS::Realm& realm)return *static_cast<StorageManager*>(web_rust_storage_api_create_storage_manager(JS::HostABI::vm_to_abi(realm.vm()), &realm));}+u64 web_storage_api_storage_usage(HTML::EnvironmentSettingsObject* environment)+{+ // FIXME: This should be implemented in a way that works for Workers.+ auto& window = HTML::relevant_window(environment->global_object());+ return window.page().client().page_did_request_storage_usage(environment->id);+}+}diff --git a/Libraries/LibWeb/StorageAPI/StorageShelf.cpp b/Libraries/LibWeb/StorageAPI/StorageShelf.cppdeleted file mode 100644index 1bfa96cdfbd..00000000000--- a/Libraries/LibWeb/StorageAPI/StorageShelf.cpp+++ /dev/null@@ -1,95 +0,0 @@-/*- * Copyright (c) 2024-2025, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Page/Page.h>-#include <LibWeb/StorageAPI/StorageShelf.h>--namespace Web::StorageAPI {--GC_DEFINE_ALLOCATOR(StorageShelf);--void StorageShelf::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_page);- visitor.visit(m_bucket_map);-}--// https://storage.spec.whatwg.org/#create-a-storage-shelf-StorageShelf::StorageShelf(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type)- : m_page(page)- , m_environment_id(move(environment_id))-{- // 1. Let shelf be a new storage shelf.- // 2. Set shelf’s bucket map["default"] to the result of running create a storage bucket with type.- m_bucket_map.set("default"_string, StorageBucket::create(page, m_environment_id, key, type));- // 3. Return shelf.-}--u64 StorageShelf::storage_usage() const-{- return m_page->client().page_did_request_storage_usage(m_environment_id);-}--// https://storage.spec.whatwg.org/#storage-quota-u64 StorageShelf::storage_quota() const-{- // "The storage quota of a storage shelf is an implementation-defined conservative estimate of the total amount of- // bytes it can hold. This amount should be less than the total storage space on the device. It must not be a- // function of the available storage space on the device."- // The bottles with a quota of their own (localStorage, sessionStorage) hold a few MiB each, and the rest (Cache- // Storage, IndexedDB, service worker registrations) are unbounded, so the shelf reports the 10 GiB a site may- // reasonably put in those. Nothing about the device goes into the figure.- return 10 * GiB;-}--// https://storage.spec.whatwg.org/#obtain-a-local-storage-shelf-GC::Ptr<StorageShelf> obtain_a_local_storage_shelf(HTML::EnvironmentSettingsObject& settings)-{- // To obtain a local storage shelf, given an environment settings object environment, return the result of running- // obtain a storage shelf with the user agent’s storage shed, environment, and "local".-- // FIXME: This should be implemented in a way that works for Workers.- auto& window = HTML::relevant_window(settings.realm().global_object());-- auto key = obtain_a_storage_key(settings);- if (!key.has_value())- return {};-- // AD-HOC: The user agent's storage shed is kept by the browser process, in a StorageJar. This shelf is a transient- // helper for computing estimate()'s usage and quota — so a standalone shelf is functionally equivalent to- // the spec's requirement to obtain one from a shed.- return StorageShelf::create(window.page(), settings.id, *key, StorageType::Local);-}--// Declared on the Rust side in Libraries/LibWeb/Bindings/Rust/src/storage_api/storage_shelf.rs.-extern "C" {--StorageShelf* web_storage_api_obtain_a_local_storage_shelf(HTML::EnvironmentSettingsObject*);-u64 web_storage_api_storage_shelf_storage_usage(StorageShelf*);-u64 web_storage_api_storage_shelf_storage_quota(StorageShelf*);-}--StorageShelf* web_storage_api_obtain_a_local_storage_shelf(HTML::EnvironmentSettingsObject* environment)-{- return obtain_a_local_storage_shelf(*environment).ptr();-}--u64 web_storage_api_storage_shelf_storage_usage(StorageShelf* shelf)-{- return shelf->storage_usage();-}--u64 web_storage_api_storage_shelf_storage_quota(StorageShelf* shelf)-{- return shelf->storage_quota();-}--}diff --git a/Libraries/LibWeb/StorageAPI/StorageShelf.h b/Libraries/LibWeb/StorageAPI/StorageShelf.hdeleted file mode 100644index f13333f5823..00000000000--- a/Libraries/LibWeb/StorageAPI/StorageShelf.h+++ /dev/null@@ -1,48 +0,0 @@-/*- * Copyright (c) 2024-2025, Shannon Booth <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/HashMap.h>-#include <AK/String.h>-#include <LibGC/Heap.h>-#include <LibGC/Ptr.h>-#include <LibWeb/StorageAPI/StorageBottle.h>-#include <LibWebCommon/HTML/Scripting/EnvironmentId.h>-#include <LibWebCommon/StorageAPI/StorageType.h>--namespace Web::StorageAPI {--// https://storage.spec.whatwg.org/#storage-shelf-// A storage shelf exists for each storage key within a storage shed. It holds a bucket map, which is a map of strings to storage buckets.-using BucketMap = OrderedHashMap<String, GC::Ref<StorageBucket>>;--class StorageShelf : public GC::Cell {- GC_CELL(StorageShelf, GC::Cell);- GC_DECLARE_ALLOCATOR(StorageShelf);--public:- static GC::Ref<StorageShelf> create(GC::Ref<Page> page, HTML::EnvironmentId environment_id, StorageKey const& key, StorageType type) { return GC::Heap::the().allocate<StorageShelf>(page, move(environment_id), key, type); }-- BucketMap& bucket_map() { return m_bucket_map; }- BucketMap const& bucket_map() const { return m_bucket_map; }-- u64 storage_usage() const;- u64 storage_quota() const;-- virtual void visit_edges(GC::Cell::Visitor& visitor) override;--private:- explicit StorageShelf(GC::Ref<Page>, HTML::EnvironmentId, StorageKey const&, StorageType);-- GC::Ref<Page> m_page;- HTML::EnvironmentId m_environment_id;- BucketMap m_bucket_map;-};--GC::Ptr<StorageShelf> obtain_a_local_storage_shelf(HTML::EnvironmentSettingsObject&);--}diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cppindex c6f2a4cf803..897601a9a4e 100644--- a/Services/WebContent/ConnectionFromClient.cpp+++ b/Services/WebContent/ConnectionFromClient.cpp@@ -1387,18 +1387,13 @@ void ConnectionFromClient::inspect_storage(Web::PageId page_id, Web::StorageAPI:return;}- auto& map = storage_or_error.value()->map();JsonArray storage_items;- for (auto const& name : map.keys()) {- auto value = map.get(name);- if (!value.has_value())- continue;-+ storage_or_error.value()->for_each_item([&](auto const& name, auto const& value) {JsonObject item;item.set("name"sv, name.to_utf8());- item.set("value"sv, value.release_value().to_utf8());+ item.set("value"sv, value.to_utf8());storage_items.must_append(move(item));- }+ });async_did_inspect_storage(page_id, request_id, storage_items.serialized());}@@ -1435,22 +1430,22 @@ void ConnectionFromClient::clear_storage_area(Web::StorageAPI::StorageAreaId arevoid ConnectionFromClient::storage_area_changed(Web::StorageAPI::StorageAreaId area_id, Optional<Utf16String> key, Optional<Utf16String> old_value, Optional<Utf16String> new_value, String url){- Web::StorageAPI::StorageAreaMirror::did_change(area_id, key, old_value, new_value, url);+ Web::StorageAPI::storage_area_did_change(area_id, key, old_value, new_value, url);}void ConnectionFromClient::storage_area_write_acknowledged(Web::StorageAPI::StorageAreaId area_id){- Web::StorageAPI::StorageAreaMirror::did_acknowledge_write(area_id);+ Web::StorageAPI::storage_area_did_acknowledge_write(area_id);}void ConnectionFromClient::storage_area_write_refused(Web::StorageAPI::StorageAreaId area_id, Vector<Utf16String> keys, Vector<Utf16String> values){- Web::StorageAPI::StorageAreaMirror::did_refuse_write(area_id, move(keys), move(values));+ Web::StorageAPI::storage_area_did_refuse_write(area_id, move(keys), move(values));}void ConnectionFromClient::storage_area_reset(Web::StorageAPI::StorageAreaId area_id, Vector<Utf16String> keys, Vector<Utf16String> values){- Web::StorageAPI::StorageAreaMirror::did_reset(area_id, move(keys), move(values));+ Web::StorageAPI::storage_area_did_reset(area_id, move(keys), move(values));}void ConnectionFromClient::inspect_dom_node(Web::PageId page_id, WebView::DOMNodeProperties::Type property_type, Web::UniqueNodeID node_id, Optional<Web::CSS::PseudoElement> pseudo_element, JsonValue options_value)diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.hindex b5650ee9d68..b49ea4504d4 100644--- a/Services/WebContent/ConnectionFromClient.h+++ b/Services/WebContent/ConnectionFromClient.h@@ -27,7 +27,7 @@#include <LibWeb/Loader/FileRequest.h>#include <LibWeb/Page/Page.h>#include <LibWeb/Platform/Timer.h>-#include <LibWeb/StorageAPI/StorageAreaMirror.h>+#include <LibWeb/StorageAPI/StorageAreaMirrorClient.h>#include <LibWebCommon/CSS/PreferredColorScheme.h>#include <LibWebCommon/CSS/PreferredContrast.h>#include <LibWebCommon/CSS/PreferredMotion.h>diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex 8689d4a9860..8095350ead1 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -49,7 +49,6 @@ set(TEST_SOURCESTestSharedCompiledStyleSheet.cppTestSimpleRealm.cppTestSourceHighlighter.cpp- TestStorageAreaMirror.cppTestStructuredSerializeCorpus.cppTestStructuredSerializeDurability.cppTestStructuredSerializeFormat.cppdiff --git a/Tests/LibWeb/TestStorageAreaMirror.cpp b/Tests/LibWeb/TestStorageAreaMirror.cppdeleted file mode 100644index 93642ac031b..00000000000--- a/Tests/LibWeb/TestStorageAreaMirror.cpp+++ /dev/null@@ -1,383 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Vector.h>-#include <LibTest/TestCase.h>-#include <LibURL/Parser.h>-#include <LibWeb/StorageAPI/StorageAreaMirror.h>-#include <LibWebCommon/StorageAPI/StorageEndpoint.h>--using Web::StorageAPI::StorageAreaId;-using Web::StorageAPI::StorageAreaMirror;-using Web::StorageAPI::StorageEndpointType;--namespace {--struct Sent {- enum class Kind : u8 {- Connect,- Disconnect,- Set,- Remove,- Clear,- };-- Kind kind;- Optional<StorageAreaId> area_id;- Utf16String key;- Utf16String value;- String url;-};--class FakeClient final : public Web::StorageAPI::StorageAreaMirrorClient {-public:- Vector<Sent> sent;- // What the next connect answers with.- Vector<Utf16String> keys;- Vector<Utf16String> values;- u64 usage { 0 };- bool detached { false };- u64 next_id { 1 };-- virtual Web::StorageAPI::StorageAreaConnection connect_to_storage_area(Web::PageId, StorageEndpointType, Web::HTML::EnvironmentId const&) override- {- sent.append({ Sent::Kind::Connect, {}, {}, {}, {} });- if (detached)- return {};- return { StorageAreaId { next_id++ }, keys, values, usage };- }- virtual void disconnect_from_storage_area(StorageAreaId area_id) override- {- sent.append({ Sent::Kind::Disconnect, area_id, {}, {}, {} });- }- virtual void set_storage_item(StorageAreaId area_id, Utf16String const& key, Utf16String const& value, String const& url) override- {- sent.append({ Sent::Kind::Set, area_id, key, value, url });- }- virtual void remove_storage_item(StorageAreaId area_id, Utf16String const& key, String const& url) override- {- sent.append({ Sent::Kind::Remove, area_id, key, {}, url });- }- virtual void clear_storage_area(StorageAreaId area_id, String const& url) override- {- sent.append({ Sent::Kind::Clear, area_id, {}, {}, url });- }-};--struct Reported {- Optional<Utf16String> key;- Optional<Utf16String> old_value;- Optional<Utf16String> new_value;- String url;-};--struct Fixture {- FakeClient client;- StorageAreaMirror::Requester requester { Web::PageId { 1 }, Web::HTML::EnvironmentId::generate() };- String const url = "https://a.example/page.html"_string;-- Fixture() { Web::StorageAPI::set_storage_area_mirror_client(&client); }- ~Fixture() { Web::StorageAPI::set_storage_area_mirror_client(nullptr); }-- static Web::StorageAPI::StorageKey key_for(StringView origin)- {- return { URL::Parser::basic_parse(origin)->origin() };- }-- NonnullRefPtr<StorageAreaMirror> mirror(StringView origin = "https://a.example"sv)- {- return StorageAreaMirror::obtain(StorageEndpointType::LocalStorage, {}, key_for(origin), Web::StorageAPI::StorageEndpoint::LOCAL_STORAGE_QUOTA);- }-- static Vector<Reported>& record(StorageAreaMirror& mirror, Vector<Reported>& reports)- {- mirror.on_remote_change = [&reports](auto const& key, auto const& old_value, auto const& new_value, auto const& url) {- reports.append({ key, old_value, new_value, url });- };- return reports;- }-};--size_t count(Vector<Sent> const& sent, Sent::Kind kind)-{- size_t n = 0;- for (auto const& entry : sent)- n += entry.kind == kind;- return n;-}--}--TEST_CASE(prime_once_per_area_and_share_between_bottles)-{- Fixture f;- f.client.keys = { "a"_utf16 };- f.client.values = { "1"_utf16 };- f.client.usage = 2;-- auto first = f.mirror("https://shared.example"sv);- auto second = f.mirror("https://shared.example"sv);- EXPECT_EQ(first.ptr(), second.ptr());-- auto other_page = StorageAreaMirror::obtain(StorageEndpointType::SessionStorage, Web::PageId { 7 }, Fixture::key_for("https://shared.example"sv), {});- EXPECT(other_page.ptr() != first.ptr());-- EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 0u);- EXPECT_EQ(first->get(f.requester, "a"_utf16), Optional<Utf16String> { "1"_utf16 });- EXPECT_EQ(second->size(f.requester), 1u);- EXPECT_EQ(second->keys(f.requester), Vector { "a"_utf16 });- EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);- EXPECT_EQ(first->quota_used(), 2u);-}--TEST_CASE(local_write_applies_sends_and_tracks_pending_until_acked)-{- Fixture f;- auto mirror = f.mirror("https://write.example"sv);-- auto result = mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url);- EXPECT(result.has<Optional<Utf16String>>());- EXPECT_EQ(result.get<Optional<Utf16String>>(), Optional<Utf16String> {});- EXPECT_EQ(mirror->get(f.requester, "k"_utf16), Optional<Utf16String> { "v"_utf16 });- EXPECT_EQ(count(f.client.sent, Sent::Kind::Set), 1u);- EXPECT_EQ(f.client.sent.last().key, "k"_utf16);- EXPECT_EQ(f.client.sent.last().value, "v"_utf16);- EXPECT_EQ(f.client.sent.last().url, f.url);- EXPECT_EQ(mirror->pending_write_count(), 1u);-- auto id = *f.client.sent.last().area_id;- StorageAreaMirror::did_acknowledge_write(id);- EXPECT_EQ(mirror->pending_write_count(), 0u);-- // Overwrite returns the old value; removal returns the removed value; clear reports whether there was anything.- EXPECT_EQ(mirror->set(f.requester, "k"_utf16, "w"_utf16, f.url).get<Optional<Utf16String>>(), Optional<Utf16String> { "v"_utf16 });- EXPECT_EQ(mirror->remove(f.requester, "k"_utf16, f.url), Optional<Utf16String> { "w"_utf16 });- EXPECT_EQ(mirror->remove(f.requester, "k"_utf16, f.url), Optional<Utf16String> {});- EXPECT_EQ(count(f.client.sent, Sent::Kind::Remove), 1u);- EXPECT(!mirror->clear(f.requester, f.url));- EXPECT_EQ(count(f.client.sent, Sent::Kind::Clear), 0u);- mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url);- EXPECT(mirror->clear(f.requester, f.url));- EXPECT_EQ(count(f.client.sent, Sent::Kind::Clear), 1u);- EXPECT_EQ(mirror->size(f.requester), 0u);-}--TEST_CASE(remote_changes_apply_except_over_pending_local_writes)-{- Fixture f;- f.client.keys = { "a"_utf16, "b"_utf16 };- f.client.values = { "1"_utf16, "2"_utf16 };- f.client.usage = 4;- auto mirror = f.mirror("https://remote.example"sv);- Vector<Reported> reports;- Fixture::record(*mirror, reports);-- mirror->set(f.requester, "a"_utf16, "mine"_utf16, f.url);- auto id = *f.client.sent.last().area_id;-- // The owner serialized this change before our pending write, so our mirror already reflects the later state.- StorageAreaMirror::did_change(id, "a"_utf16, "1"_utf16, "theirs"_utf16, "https://remote.example/other.html"_string);- EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "mine"_utf16 });- EXPECT_EQ(reports.size(), 1u);- EXPECT_EQ(reports[0].key, Optional<Utf16String> { "a"_utf16 });- EXPECT_EQ(reports[0].new_value, Optional<Utf16String> { "theirs"_utf16 });- EXPECT_EQ(reports[0].url, "https://remote.example/other.html"_string);-- // A change to another key applies.- StorageAreaMirror::did_change(id, "b"_utf16, "2"_utf16, "3"_utf16, f.url);- EXPECT_EQ(mirror->get(f.requester, "b"_utf16), Optional<Utf16String> { "3"_utf16 });- StorageAreaMirror::did_change(id, "b"_utf16, "3"_utf16, {}, f.url);- EXPECT_EQ(mirror->get(f.requester, "b"_utf16), Optional<Utf16String> {});- EXPECT_EQ(reports.size(), 3u);-- StorageAreaMirror::did_acknowledge_write(id);- StorageAreaMirror::did_change(id, "a"_utf16, "mine"_utf16, "later"_utf16, f.url);- EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "later"_utf16 });-- // While a local clear is unacknowledged, every incoming change predates it.- mirror->clear(f.requester, f.url);- StorageAreaMirror::did_change(id, "c"_utf16, {}, "4"_utf16, f.url);- StorageAreaMirror::did_change(id, {}, {}, {}, f.url);- EXPECT_EQ(mirror->size(f.requester), 0u);- EXPECT_EQ(reports.size(), 6u);- StorageAreaMirror::did_acknowledge_write(id);- StorageAreaMirror::did_change(id, "c"_utf16, {}, "4"_utf16, f.url);- EXPECT_EQ(mirror->get(f.requester, "c"_utf16), Optional<Utf16String> { "4"_utf16 });- EXPECT_EQ(mirror->quota_used(), 2u);-}--TEST_CASE(refusal_resets_to_the_snapshot_reapplies_pending_writes_and_reports_the_diff)-{- Fixture f;- auto mirror = f.mirror("https://refused.example"sv);- Vector<Reported> reports;- Fixture::record(*mirror, reports);-- mirror->set(f.requester, "big"_utf16, "xxxx"_utf16, f.url);- auto id = *f.client.sent.last().area_id;- mirror->set(f.requester, "b"_utf16, "2"_utf16, f.url);- EXPECT_EQ(mirror->pending_write_count(), 2u);-- // The owner refused the first write; the snapshot shows what another process stored in the meantime.- StorageAreaMirror::did_refuse_write(id, { "a"_utf16 }, { "1"_utf16 });-- EXPECT_EQ(mirror->get(f.requester, "big"_utf16), Optional<Utf16String> {});- EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "1"_utf16 });- EXPECT_EQ(mirror->get(f.requester, "b"_utf16), Optional<Utf16String> { "2"_utf16 });- EXPECT_EQ(mirror->pending_write_count(), 1u);- EXPECT_EQ(mirror->quota_used(), 4u);-- // Two keys changed from the mirror's point of view: the refused one vanished, and "a" appeared.- EXPECT_EQ(reports.size(), 2u);- bool saw_big = false;- bool saw_a = false;- for (auto const& report : reports) {- if (report.key == Optional<Utf16String> { "big"_utf16 }) {- saw_big = true;- EXPECT_EQ(report.old_value, Optional<Utf16String> { "xxxx"_utf16 });- EXPECT_EQ(report.new_value, Optional<Utf16String> {});- }- if (report.key == Optional<Utf16String> { "a"_utf16 }) {- saw_a = true;- EXPECT_EQ(report.old_value, Optional<Utf16String> {});- EXPECT_EQ(report.new_value, Optional<Utf16String> { "1"_utf16 });- }- }- EXPECT(saw_big);- EXPECT(saw_a);-- // A reset from the browser takes the same path, with nothing pending to re-apply afterwards.- StorageAreaMirror::did_acknowledge_write(id);- StorageAreaMirror::did_reset(id, {}, {});- EXPECT_EQ(mirror->size(f.requester), 0u);- EXPECT_EQ(mirror->quota_used(), 0u);-}--// A script can queue thousands of writes in one task; their acknowledgments arrive after it yields. Each one has to be-// cheap, and a refusal in the middle of the stream replays only the writes the owner hasn't answered yet.-TEST_CASE(a_long_queue_of_pending_writes_drains_in_order_and_a_refusal_replays_only_the_outstanding_ones)-{- Fixture f;- auto mirror = f.mirror("https://queue.example"sv);- Vector<Reported> reports;- Fixture::record(*mirror, reports);-- constexpr size_t write_count = 5000;- for (size_t i = 0; i < write_count; ++i)- mirror->set(f.requester, Utf16String::number(i), "v"_utf16, f.url);- EXPECT_EQ(mirror->pending_write_count(), write_count);- auto id = *f.client.sent.last().area_id;-- for (size_t i = 0; i < write_count - 2; ++i)- StorageAreaMirror::did_acknowledge_write(id);- EXPECT_EQ(mirror->pending_write_count(), 2u);-- // The owner refused the second-to-last write and describes an empty bottle: everything acknowledged is gone from- // it, and only the last write is still in flight on top.- StorageAreaMirror::did_refuse_write(id, {}, {});- EXPECT_EQ(mirror->pending_write_count(), 1u);- EXPECT_EQ(mirror->size(f.requester), 1u);- EXPECT_EQ(mirror->get(f.requester, Utf16String::number(write_count - 1)), Optional<Utf16String> { "v"_utf16 });- EXPECT_EQ(mirror->get(f.requester, Utf16String::number(write_count - 2)), Optional<Utf16String> {});- EXPECT_EQ(mirror->quota_used(), Web::StorageAPI::storage_quota_size(Utf16String::number(write_count - 1)) + Web::StorageAPI::storage_quota_size("v"_utf16));-- // The diff reports every acknowledged write as gone, and nothing for the one still pending.- EXPECT_EQ(reports.size(), write_count - 1);-- StorageAreaMirror::did_acknowledge_write(id);- EXPECT_EQ(mirror->pending_write_count(), 0u);-}--TEST_CASE(quota_used_matches_the_jar_rule_after_mixed_writes)-{- Fixture f;- auto mirror = f.mirror("https://quota.example"sv);- auto size = [](Utf16String const& key, Utf16String const& value) {- return Web::StorageAPI::storage_quota_size(key) + Web::StorageAPI::storage_quota_size(value);- };-- mirror->set(f.requester, "k1"_utf16, "éé"_utf16, f.url);- mirror->set(f.requester, "k2"_utf16, "value"_utf16, f.url);- mirror->set(f.requester, "k1"_utf16, "x"_utf16, f.url);- (void)mirror->remove(f.requester, "k2"_utf16, f.url);- EXPECT_EQ(mirror->quota_used(), size("k1"_utf16, "x"_utf16));-- // A write that would exceed the quota is refused locally and leaves the mirror untouched.- auto too_large = Utf16String::repeated('y', Web::StorageAPI::StorageEndpoint::LOCAL_STORAGE_QUOTA - 2);- auto result = mirror->set(f.requester, "k3"_utf16, too_large, f.url);- EXPECT(result.has<WebView::StorageOperationError>());- EXPECT_EQ(mirror->get(f.requester, "k3"_utf16), Optional<Utf16String> {});- EXPECT_EQ(mirror->quota_used(), size("k1"_utf16, "x"_utf16));- EXPECT_EQ(count(f.client.sent, Sent::Kind::Set), 3u);-- // One too large to ever fit is refused before the mirror is even primed.- FakeClient fresh;- Web::StorageAPI::set_storage_area_mirror_client(&fresh);- auto unprimed = f.mirror("https://unprimed.example"sv);- auto enormous = Utf16String::repeated('z', Web::StorageAPI::StorageEndpoint::LOCAL_STORAGE_QUOTA + 1);- EXPECT(unprimed->set(f.requester, "k"_utf16, enormous, f.url).has<WebView::StorageOperationError>());- EXPECT(fresh.sent.is_empty());- Web::StorageAPI::set_storage_area_mirror_client(&f.client);-}--TEST_CASE(detached_mirror_reads_empty_and_refuses_writes)-{- Fixture f;- f.client.detached = true;- auto mirror = f.mirror("https://detached.example"sv);-- EXPECT_EQ(mirror->size(f.requester), 0u);- EXPECT_EQ(mirror->get(f.requester, "k"_utf16), Optional<Utf16String> {});- EXPECT(mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url).has<WebView::StorageOperationError>());- EXPECT_EQ(mirror->remove(f.requester, "k"_utf16, f.url), Optional<Utf16String> {});- EXPECT(!mirror->clear(f.requester, f.url));- EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);- EXPECT_EQ(count(f.client.sent, Sent::Kind::Set), 0u);-}--TEST_CASE(a_failed_connect_detaches_only_the_requester_it_failed_for)-{- Fixture f;- f.client.detached = true;- auto mirror = f.mirror("https://partly.example"sv);- StorageAreaMirror::Requester closing_page { Web::PageId { 9 }, Web::HTML::EnvironmentId::generate() };-- // A page the browser can't resolve (it's closing) reads empty and can't write; it isn't asked about again.- EXPECT_EQ(mirror->size(closing_page), 0u);- EXPECT(mirror->set(closing_page, "k"_utf16, "v"_utf16, f.url).has<WebView::StorageOperationError>());- EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);- EXPECT_EQ(mirror->size(closing_page), 0u);- EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 1u);-- // Another document of the origin in this process, which the browser does resolve, still gets its storage.- f.client.detached = false;- f.client.keys = { "a"_utf16 };- f.client.values = { "1"_utf16 };- f.client.usage = 2;- EXPECT_EQ(mirror->get(f.requester, "a"_utf16), Optional<Utf16String> { "1"_utf16 });- EXPECT_EQ(count(f.client.sent, Sent::Kind::Connect), 2u);- EXPECT(mirror->set(f.requester, "k"_utf16, "v"_utf16, f.url).has<Optional<Utf16String>>());- // And once the mirror is connected, every requester reads it.- EXPECT_EQ(mirror->size(closing_page), 2u);-}--TEST_CASE(the_last_bottle_disconnects_the_mirror)-{- Fixture f;- {- auto mirror = f.mirror("https://lastbottle.example"sv);- auto another = f.mirror("https://lastbottle.example"sv);- mirror->size(f.requester);- EXPECT_EQ(count(f.client.sent, Sent::Kind::Disconnect), 0u);- }- EXPECT_EQ(count(f.client.sent, Sent::Kind::Disconnect), 1u);-- // A mirror that was never primed has nothing to disconnect from.- {- auto never = f.mirror("https://never.example"sv);- }- EXPECT_EQ(count(f.client.sent, Sent::Kind::Disconnect), 1u);-}