Skip to content

Truly independent web browser

LibWeb: Fire storage events in every process that shares the storage

sideshowbarker8865e60ef40e
diff --git a/Libraries/LibWeb/DOM/EventTarget.cpp b/Libraries/LibWeb/DOM/EventTarget.cpp
index 81f1d395193..39a76660563 100644
--- a/Libraries/LibWeb/DOM/EventTarget.cpp
+++ b/Libraries/LibWeb/DOM/EventTarget.cpp
@@ -50,6 +50,7 @@
#include <LibWeb/HTML/Navigable.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
+#include <LibWeb/HTML/Storage.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
@@ -376,6 +377,27 @@ static void update_needs_beforeunload_check(EventTarget& event_target, DOMEventL
navigable->page().update_needs_beforeunload_check();
}
+// A storage event made in another process reaches this one only through the mirror of the map it changed, and a
+// window that has never touched its storage has no mirror. So the moment a window starts listening for storage
+// events, its Storage objects are created, which connects the mirrors and brings the events.
+static void connect_storage_for_storage_event_listener(EventTarget& event_target, DOMEventListener const& listener)
+{
+ if (listener.type != HTML::EventNames::storage)
+ return;
+
+ auto* window = as_if<HTML::Window>(event_target);
+ if (!window)
+ return;
+ auto document = window->associated_document_if_any();
+ if (!document || !document->is_fully_active())
+ return;
+
+ if (auto local_storage = window->local_storage(); !local_storage.is_error())
+ local_storage.value()->connect();
+ if (auto session_storage = window->session_storage(); !session_storage.is_error())
+ session_storage.value()->connect();
+}
+
static void notify_page_that_window_listens_for_gamepad_events(EventTarget& event_target, DOMEventListener const& listener)
{
if (!first_is_one_of(listener.type, Gamepad::EventNames::gamepadconnected, Gamepad::EventNames::gamepaddisconnected))
@@ -469,6 +491,7 @@ void EventTarget::add_an_event_listener(DOMEventListener& listener)
update_needs_beforeunload_check(*this, listener);
event_listener_list_changed();
notify_page_that_window_listens_for_gamepad_events(*this, listener);
+ connect_storage_for_storage_event_listener(*this, listener);
}
// 6. If listener’s signal is not null, then add the following abort steps to it:
diff --git a/Libraries/LibWeb/HTML/Storage.cpp b/Libraries/LibWeb/HTML/Storage.cpp
index 0f6c044b4bd..59cc1bc9852 100644
--- a/Libraries/LibWeb/HTML/Storage.cpp
+++ b/Libraries/LibWeb/HTML/Storage.cpp
@@ -95,7 +95,8 @@ WebIDL::ExceptionOr<void> Storage::set_item(Utf16View key, Utf16View value)
// 4. If value cannot be stored, then throw a "QuotaExceededError" DOMException.
// 5. Set this's map[key] to value.
- auto result = m_storage_bottle->set(key, value, m_window->associated_document().url().serialize());
+ auto url = m_window->associated_document().url().serialize();
+ auto result = m_storage_bottle->set(key, value, url);
if (result.has<WebView::StorageOperationError>())
return WebIDL::QuotaExceededError::create(Utf16String::formatted("Unable to store more than {} bytes in storage", *m_storage_bottle->quota()));
@@ -117,7 +118,7 @@ WebIDL::ExceptionOr<void> Storage::set_item(Utf16View key, Utf16View value)
Optional<Utf16View> old_value_view;
if (old_value.has_value())
old_value_view = old_value->utf16_view();
- broadcast(key, old_value_view, value);
+ broadcast(key, old_value_view, value, url);
return {};
}
@@ -132,13 +133,14 @@ void Storage::remove_item(Utf16View key)
return;
// 3. Remove this's map[key].
- m_storage_bottle->remove(key, m_window->associated_document().url().serialize());
+ auto url = m_window->associated_document().url().serialize();
+ m_storage_bottle->remove(key, url);
// 4. Reorder this.
reorder();
// 5. Broadcast this with key, oldValue, and null.
- broadcast(key, old_value->utf16_view(), {});
+ broadcast(key, old_value->utf16_view(), {}, url);
}
// https://html.spec.whatwg.org/multipage/webstorage.html#dom-storage-clear
@@ -149,10 +151,11 @@ void Storage::clear()
return;
// 2. Clear this's map.
- m_storage_bottle->clear(m_window->associated_document().url().serialize());
+ auto url = m_window->associated_document().url().serialize();
+ m_storage_bottle->clear(url);
// 3. Broadcast this with null, null, and null.
- broadcast({}, {}, {});
+ broadcast({}, {}, {}, url);
}
// https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-reorder
@@ -178,13 +181,34 @@ static GC::Ptr<Storage> obtain_storage_for_window(Window& window, Storage::Type
}
// https://html.spec.whatwg.org/multipage/webstorage.html#concept-storage-broadcast
-void Storage::broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value, Optional<Utf16View> new_value)
+void Storage::broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value, Optional<Utf16View> new_value, String const& url)
{
// 1. Let thisDocument be storage's relevant global object's associated Document.
- auto const& this_document = m_window->associated_document();
-
// 2. Let url be the serialization of thisDocument's URL.
- auto url = utf16_string_from_url_ascii(this_document.url().serialize());
+ // NB: The caller serialized it, for the bottle; it is the same document's URL.
+
+ // NB: The map lives in the browser process and is mirrored here; the mirror told the browser of this change
+ // before this runs, and the browser relays it to every other process mirroring the map, where steps 3 and 4
+ // run for the Storage objects there. Here they run for this process's, excluding this one.
+ auto to_utf16_string = [](Optional<Utf16View> value) -> Optional<Utf16String> {
+ if (!value.has_value())
+ return {};
+ return Utf16String::from_utf16(*value);
+ };
+ // NB: The key the bottle is kept under, not the bare origin: Every file: document shares one bottle (see "obtain
+ // a storage key"), so each hears the others' changes. A window that has no key has no bottle to have written.
+ auto storage_key = StorageAPI::obtain_a_storage_key(relevant_settings_object(*m_window));
+ if (!storage_key.has_value())
+ return;
+ Optional<PageId> session_page;
+ if (type() == Type::Session)
+ session_page = m_window->page().client().id();
+ dispatch_storage_events_for_remote_change(type(), *storage_key, session_page, to_utf16_string(key), to_utf16_string(old_value), to_utf16_string(new_value), url, this);
+}
+
+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_string, GC::Ptr<Storage> excluded_storage)
+{
+ auto url = utf16_string_from_url_ascii(url_string);
// 3. Let remoteStorages be all Storage objects excluding storage whose:
GC::RootVector<GC::Ref<Storage>> remote_storages;
@@ -196,21 +220,25 @@ void Storage::broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value,
// windows, and initialize any storage objects as part of this loop.
Window::for_each_active([&](auto& window) {
// * type is storage's type
- auto storage = obtain_storage_for_window(window, type());
+ auto storage = obtain_storage_for_window(window, type);
if (!storage)
return IterationDecision::Continue;
// "excluding storage"
- if (storage == GC::Ref { *this })
+ if (storage == excluded_storage)
return IterationDecision::Continue;
// * relevant settings object's origin is same origin with storage's relevant settings object's origin
- if (!relevant_settings_object(*m_window).origin().is_same_origin(relevant_settings_object(*storage->m_window).origin()))
+ // NB: A storage key is an origin, and two keys are equal when their origins are same origin. Compared as the
+ // keys the bottles are kept under, so the file: documents that share one bottle hear each other.
+ auto window_storage_key = StorageAPI::obtain_a_storage_key(relevant_settings_object(window));
+ if (!window_storage_key.has_value() || *window_storage_key != storage_key)
return IterationDecision::Continue;
// * and, if type is "session", whose relevant settings object's associated Document's node navigable's traversable navigable
// is thisDocument's node navigable's traversable navigable.
- if (type() == Type::Session) {
+ // NB: A page's documents all belong to one traversable, so the page stands for the traversable here.
+ if (type == Type::Session) {
auto& storage_document = storage->m_window->associated_document();
// NB: It is possible the remote storage may have not been fully teared down immediately at the point it's
@@ -218,12 +246,7 @@ void Storage::broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value,
if (!storage_document.navigable())
return IterationDecision::Continue;
- // NB: It is possible for this storage's document to have lost its navigable if script holds a reference to
- // the Storage object after its browsing context has navigated to a new document.
- if (!this_document.navigable())
- return IterationDecision::Continue;
-
- if (storage_document.navigable()->traversable_navigable() != this_document.navigable()->traversable_navigable())
+ if (!session_page.has_value() || window.page().client().id() != *session_page)
return IterationDecision::Continue;
}
@@ -234,27 +257,17 @@ void Storage::broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value,
if (remote_storages.is_empty())
return;
- auto to_utf16_string = [](Optional<Utf16View> value) -> Optional<Utf16String> {
- if (!value.has_value())
- return {};
- auto view = value.value();
- return Utf16String::from_utf16(view);
- };
- auto event_key = to_utf16_string(key);
- auto event_old_value = to_utf16_string(old_value);
- auto event_new_value = to_utf16_string(new_value);
-
// 4. For each remoteStorage of remoteStorages: queue a global task on the DOM manipulation task source given remoteStorage's relevant
// global object to fire an event named storage at remoteStorage's relevant global object, using StorageEvent, with key initialized
// to key, oldValue initialized to oldValue, newValue initialized to newValue, url initialized to url, and storageArea initialized to
// remoteStorage.
for (auto remote_storage : remote_storages) {
auto& remote_window = remote_storage->m_window;
- queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*remote_window), GC::create_function(GC::Heap::the(), [event_key, event_old_value, event_new_value, url, remote_storage, remote_window] {
+ queue_global_task(Task::Source::DOMManipulation, relevant_global_object(*remote_window), GC::create_function(GC::Heap::the(), [key, old_value, new_value, url, remote_storage, remote_window] {
StorageEventInit init;
- init.key = event_key;
- init.old_value = event_old_value;
- init.new_value = event_new_value;
+ init.key = key;
+ init.old_value = old_value;
+ init.new_value = new_value;
init.url = move(url);
init.storage_area = remote_storage;
remote_window->dispatch_event(StorageEvent::create(EventNames::storage, init, HighResolutionTime::current_high_resolution_time(relevant_global_object(*remote_window))));
diff --git a/Libraries/LibWeb/HTML/Storage.h b/Libraries/LibWeb/HTML/Storage.h
index fe016d4bc55..9a0a45ce71f 100644
--- a/Libraries/LibWeb/HTML/Storage.h
+++ b/Libraries/LibWeb/HTML/Storage.h
@@ -49,6 +49,15 @@ public:
void dump() const;
+ // 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() const { m_storage_bottle->connect(); }
+
+ // Fires the storage events a change calls for on every Storage object in this process that shares the changed
+ // map, except excluded_storage: that is the one whose script made the change, when the change was made here.
+ // A change another process made has no such object, and every Storage here gets the event.
+ 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, GC::Ptr<Storage> excluded_storage);
+
private:
Storage(Window&, Type, GC::Ref<StorageAPI::StorageBottle>);
@@ -58,7 +67,7 @@ private:
// ^Wrappable
virtual Vector<Utf16FlyString> supported_property_names() const override;
void reorder();
- void broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value, Optional<Utf16View> new_value);
+ void broadcast(Optional<Utf16View> key, Optional<Utf16View> old_value, Optional<Utf16View> new_value, String const& url);
GC::Ref<Window> m_window;
Type m_type {};
diff --git a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h
index 8dbcf39ba1d..650bbf60bfe 100644
--- a/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h
+++ b/Libraries/LibWeb/StorageAPI/StorageAreaMirror.h
@@ -73,6 +73,9 @@ public:
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);
diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp b/Libraries/LibWeb/StorageAPI/StorageBottle.cpp
index 342f092a3b7..89dfc599e84 100644
--- a/Libraries/LibWeb/StorageAPI/StorageBottle.cpp
+++ b/Libraries/LibWeb/StorageAPI/StorageBottle.cpp
@@ -7,6 +7,7 @@
#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>
@@ -101,6 +102,16 @@ StorageBottle::StorageBottle(GC::Ref<Page> page, StorageEndpointType endpoint_ty
// 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, nullptr);
+ };
+ }
}
void StorageBottle::visit_edges(GC::Cell::Visitor& visitor)
@@ -114,6 +125,11 @@ 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());
diff --git a/Libraries/LibWeb/StorageAPI/StorageBottle.h b/Libraries/LibWeb/StorageAPI/StorageBottle.h
index 6d9966a96fc..3fcbc8deeb0 100644
--- a/Libraries/LibWeb/StorageAPI/StorageBottle.h
+++ b/Libraries/LibWeb/StorageAPI/StorageBottle.h
@@ -40,6 +40,9 @@ public:
// 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;
diff --git a/Tests/LibWeb/Text/data/storage-event-file-document-iframe.html b/Tests/LibWeb/Text/data/storage-event-file-document-iframe.html
new file mode 100644
index 00000000000..5171040ff37
--- /dev/null
+++ b/Tests/LibWeb/Text/data/storage-event-file-document-iframe.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<script>
+ // The parent names the key it will write, and writes only once this acknowledges it; events for any other key
+ // belong to some other test and are ignored.
+ let key = null;
+ let reported = false;
+ window.addEventListener("message", event => {
+ key = event.data;
+ parent.postMessage("ready", "*");
+ });
+ window.addEventListener("storage", event => {
+ if (event.key !== key || reported)
+ return;
+ reported = true;
+ parent.postMessage(`key-is-ours=${event.key === key} oldValue=${event.oldValue} newValue=${event.newValue} storageArea-is-localStorage=${event.storageArea === localStorage}`, "*");
+ });
+</script>
diff --git a/Tests/LibWeb/Text/expected/HTML/storage-events-reach-another-file-document.txt b/Tests/LibWeb/Text/expected/HTML/storage-events-reach-another-file-document.txt
new file mode 100644
index 00000000000..3104a4ee4c6
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/storage-events-reach-another-file-document.txt
@@ -0,0 +1 @@
+iframe got storage event: key-is-ours=true oldValue=null newValue=between-file-documents storageArea-is-localStorage=true
diff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txt
new file mode 100644
index 00000000000..8ec99affacc
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/storage-events-cross-processes.txt
@@ -0,0 +1,12 @@
+peer saw key="a" oldValue=null newValue="1" url-is-actor=true storageArea-is-localStorage=true
+peer saw key="a" oldValue="1" newValue="2" url-is-actor=true storageArea-is-localStorage=true
+peer saw key="a" oldValue="2" newValue=null url-is-actor=true storageArea-is-localStorage=true
+peer saw key="b" oldValue=null newValue="1" url-is-actor=true storageArea-is-localStorage=true
+peer saw key=null oldValue=null newValue=null url-is-actor=true storageArea-is-localStorage=true
+peer saw 5 events for 6 operations (one changed nothing)
+racing writes: neither threw: true
+racing writes: events in total: 2; on one side only: true
+racing writes: accepted write seen once: true; its value: <3145728 chars>
+racing writes: refused write reverted once: true; its old value: <3145728 chars>; storageArea is localStorage: true
+racing writes: the loser's own window saw the revert: true
+racing writes: one key kept: 1
diff --git a/Tests/LibWeb/Text/input/HTML/storage-events-reach-another-file-document.html b/Tests/LibWeb/Text/input/HTML/storage-events-reach-another-file-document.html
new file mode 100644
index 00000000000..48a79bfacf7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/storage-events-reach-another-file-document.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Every file: document keeps its storage in one shared bottle (its storage key is the file: origin, whatever the
+ // path), so a change one of them makes has to fire the storage event in the others — in this process and in any
+ // other — the same as for two documents of one http origin.
+ //
+ // That one bottle is shared with every other file: test running at the same time, too. So this test writes a key
+ // of its own, the iframe reports only the events for that key, and nothing here clears the bottle. The iframe
+ // acknowledges the key before the parent writes: the message and the storage event come from different task
+ // sources, so nothing else orders them.
+ asyncTest(done => {
+ const key = "storage-events-reach-another-file-document-" + Date.now() + "-" + Math.random();
+ window.addEventListener("message", event => {
+ if (event.data === "ready") {
+ localStorage.setItem(key, "between-file-documents");
+ return;
+ }
+ println("iframe got storage event: " + event.data);
+ localStorage.removeItem(key);
+ done();
+ });
+ const iframe = document.createElement("iframe");
+ iframe.src = "../../data/storage-event-file-document-iframe.html";
+ iframe.onload = () => iframe.contentWindow.postMessage(key, "*");
+ document.body.appendChild(iframe);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.html
new file mode 100644
index 00000000000..578ab4e421b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/storage-events-cross-processes.html
@@ -0,0 +1,175 @@
+<!DOCTYPE html>
+<script src="../../include.js"></script>
+<script>
+ // A storage event has to reach every same-origin window, in whatever process it lives: the browser relays each
+ // change to every process mirroring the storage, and that process fires the event on its own Storage objects. The
+ // peer below never touches localStorage before listening, so listening alone has to connect it. The actor drives
+ // the peer over a BroadcastChannel and reports to this page; the peer reports every event it gets as it gets it,
+ // and the actor waits for the expected count before moving on.
+ //
+ // The peer runs in a second process because it's opened with noopener on a cross-site trampoline host, and the
+ // trampoline's navigation to the same-origin peer page is a cross-site top-level navigation in a browsing context
+ // group of one — which site isolation hands to a new WebContent process.
+ asyncTest(async (done) => {
+ const httpServer = httpTestServer();
+ const host = uniqueLocalhostHostname("storage-events");
+ const runId = crypto.randomUUID();
+ const channelName = `storage-events-${runId}`;
+ const htmlHeaders = { "Content-Type": "text/html" };
+
+ const describeEvent = `
+ const describe = (e) => ({
+ type: "event",
+ key: e.key,
+ oldValue: e.oldValue === null ? null : (e.oldValue.length > 64 ? "<" + e.oldValue.length + " chars>" : e.oldValue),
+ newValue: e.newValue === null ? null : (e.newValue.length > 64 ? "<" + e.newValue.length + " chars>" : e.newValue),
+ url: e.url,
+ isLocalStorage: e.storageArea === localStorage,
+ });`;
+
+ const peerUrl = new URL(
+ await httpServer.createEcho("GET", `/storage-events-peer-${runId}`, {
+ status: 200,
+ headers: htmlHeaders,
+ body: `<!DOCTYPE html><script>
+ ${describeEvent}
+ const channel = new BroadcastChannel(${JSON.stringify(channelName)});
+ addEventListener("storage", (e) => channel.postMessage(describe(e)));
+ channel.onmessage = (e) => {
+ const command = e.data;
+ if (command.op === "setBig") {
+ let threw = false;
+ try {
+ localStorage.setItem(command.key, "p".repeat(command.size));
+ } catch {
+ threw = true;
+ }
+ channel.postMessage({ type: "written", threw });
+ } else if (command.op === "close") {
+ window.close();
+ }
+ };
+ channel.postMessage({ type: "ready" });
+ <\/script>`,
+ })
+ );
+ peerUrl.hostname = host;
+
+ const trampolineUrl = new URL(
+ await httpServer.createEcho("GET", `/storage-events-trampoline-${runId}`, {
+ status: 200,
+ headers: htmlHeaders,
+ body: `<!DOCTYPE html><script>location.replace(${JSON.stringify(peerUrl.href)});<\/script>`,
+ })
+ );
+ trampolineUrl.hostname = uniqueLocalhostHostname("storage-events-trampoline");
+
+ const actorUrl = new URL(
+ await httpServer.createEcho("GET", `/storage-events-actor-${runId}`, {
+ status: 200,
+ headers: htmlHeaders,
+ body: `<!DOCTYPE html><script>
+ ${describeEvent}
+ const report = (line) => opener.postMessage(line, "*");
+ const channel = new BroadcastChannel(${JSON.stringify(channelName)});
+ const peerEvents = [];
+ const ownEvents = [];
+ const replies = [];
+ let waiter = null;
+ const wake = () => {
+ if (waiter && waiter.ready()) {
+ const resolve = waiter.resolve;
+ waiter = null;
+ resolve();
+ }
+ };
+ const waitFor = (ready) => new Promise((resolve) => {
+ waiter = { ready, resolve };
+ wake();
+ });
+ channel.onmessage = (e) => {
+ if (e.data.type === "event")
+ peerEvents.push(e.data);
+ else
+ replies.push(e.data);
+ wake();
+ };
+ addEventListener("storage", (e) => {
+ ownEvents.push(describe(e));
+ wake();
+ });
+ const nextReply = async () => {
+ await waitFor(() => replies.length > 0);
+ return replies.shift();
+ };
+ const formatEvent = (event) => "key=" + JSON.stringify(event.key)
+ + " oldValue=" + JSON.stringify(event.oldValue)
+ + " newValue=" + JSON.stringify(event.newValue)
+ + " url-is-actor=" + (event.url === location.href)
+ + " storageArea-is-localStorage=" + event.isLocalStorage;
+ (async () => {
+ localStorage.clear();
+ window.open(${JSON.stringify(trampolineUrl.href)}, "_blank", "noopener");
+ await nextReply();
+
+ localStorage.setItem("a", "1");
+ localStorage.setItem("a", "2");
+ localStorage.setItem("a", "2");
+ localStorage.removeItem("a");
+ localStorage.setItem("b", "1");
+ localStorage.clear();
+ await waitFor(() => peerEvents.length >= 5);
+ for (const event of peerEvents)
+ report("peer saw " + formatEvent(event));
+ report("peer saw " + peerEvents.length + " events for 6 operations (one changed nothing)");
+ peerEvents.length = 0;
+
+ // Two writes that fit alone but not together, each made from a mirror that can't know about the
+ // other: the actor writes in the task that posts the peer's command, and that command reaches
+ // the peer ahead of the actor's change. So both are accepted locally, and the owner refuses
+ // whichever reaches it second. The loser's process then hears the refusal, falls back in line
+ // with the owner, and fires a storage event for the value that vanished — on the window that
+ // wrote it, which is the one that most needs to know.
+ const size = 3 * 1024 * 1024;
+ const peerWritten = nextReply();
+ channel.postMessage({ op: "setBig", key: "peerBig", size });
+ let actorThrew = false;
+ try {
+ localStorage.setItem("actorBig", "a".repeat(size));
+ } catch {
+ actorThrew = true;
+ }
+ const peerThrew = (await peerWritten).threw;
+ report("racing writes: neither threw: " + !(actorThrew || peerThrew));
+ await waitFor(() => peerEvents.length + ownEvents.length >= 2);
+ const events = [...peerEvents, ...ownEvents];
+ const bigKey = (key) => key === "actorBig" || key === "peerBig";
+ const accepted = events.filter((event) => bigKey(event.key) && event.newValue !== null);
+ const reverted = events.filter((event) => bigKey(event.key) && event.newValue === null);
+ report("racing writes: events in total: " + events.length + "; on one side only: " + (peerEvents.length === 0 || ownEvents.length === 0));
+ report("racing writes: accepted write seen once: " + (accepted.length === 1) + "; its value: " + accepted[0]?.newValue);
+ report("racing writes: refused write reverted once: " + (reverted.length === 1) + "; its old value: " + reverted[0]?.oldValue + "; storageArea is localStorage: " + reverted[0]?.isLocalStorage);
+ report("racing writes: the loser's own window saw the revert: " + (reverted.length === 1 && (reverted[0].key === "actorBig") === (ownEvents.includes(reverted[0]))));
+ report("racing writes: one key kept: " + localStorage.length);
+
+ localStorage.clear();
+ channel.postMessage({ op: "close" });
+ report("done");
+ })();
+ <\/script>`,
+ })
+ );
+ actorUrl.hostname = host;
+
+ let actor = null;
+ addEventListener("message", (event) => {
+ if (event.data === "done") {
+ actor.close();
+ done();
+ return;
+ }
+ println(event.data);
+ });
+ actor = window.open(actorUrl);
+ });
+</script>