Skip to content

Truly independent web browser

LibWeb+WebWorker: Shut down a worker in order when it closes

Andreas Kling72de310dc2ca
diff --git a/Libraries/LibWeb/FileAPI/BlobURLStore.cpp b/Libraries/LibWeb/FileAPI/BlobURLStore.cpp
index 4fd4869d1e9..51fa5583eac 100644
--- a/Libraries/LibWeb/FileAPI/BlobURLStore.cpp
+++ b/Libraries/LibWeb/FileAPI/BlobURLStore.cpp
@@ -149,8 +149,11 @@ void remove_entry_from_blob_url_store(URL::URL const& url)
void run_unloading_cleanup_steps(GC::Ref<DOM::Document> document)
{
// 1. Let environment be the Document's relevant settings object.
- auto& environment = document->relevant_settings_object();
+ remove_entries_of_environment(document->relevant_settings_object(), document->page());
+}
+void remove_entries_of_environment(HTML::EnvironmentSettingsObject& environment, Page& page)
+{
// 2. Let store be the user agent’s blob URL store;
auto& store = FileAPI::blob_url_store();
@@ -164,7 +167,7 @@ void run_unloading_cleanup_steps(GC::Ref<DOM::Document> document)
});
// NB: Remove them from the browser process's store too, as revokeObjectURL would.
if (!urls.is_empty())
- document->page().client().page_did_remove_blob_url_entries(environment, urls);
+ page.client().page_did_remove_blob_url_entries(environment, urls);
}
// https://w3c.github.io/FileAPI/#blob-url-resolve
diff --git a/Libraries/LibWeb/FileAPI/BlobURLStore.h b/Libraries/LibWeb/FileAPI/BlobURLStore.h
index d5fdd59fad1..caae5128abf 100644
--- a/Libraries/LibWeb/FileAPI/BlobURLStore.h
+++ b/Libraries/LibWeb/FileAPI/BlobURLStore.h
@@ -40,4 +40,7 @@ Optional<BlobURLEntry const&> local_blob_url_entry(URL::URL const&);
void run_unloading_cleanup_steps(GC::Ref<DOM::Document>);
+// The steps of run_unloading_cleanup_steps() after the first, which a worker that closes runs for its own environment.
+WEB_API void remove_entries_of_environment(HTML::EnvironmentSettingsObject&, Page&);
+
}
diff --git a/Libraries/LibWeb/Platform/EventLoopPlugin.cpp b/Libraries/LibWeb/Platform/EventLoopPlugin.cpp
index a3fc3571573..50124596977 100644
--- a/Libraries/LibWeb/Platform/EventLoopPlugin.cpp
+++ b/Libraries/LibWeb/Platform/EventLoopPlugin.cpp
@@ -29,6 +29,8 @@ EventLoopPlugin::~EventLoopPlugin() = default;
void EventLoopPlugin::spin_until(GC::Root<GC::Function<bool()>> goal_condition)
{
Core::EventLoop::current().spin_until([goal_condition = move(goal_condition)]() {
+ // NB: A process that shuts down fast has nothing to unwind for. A worker event loop quits only once no script is
+ // waiting in here, as its agent has an ordered shutdown ahead of it.
if (Core::EventLoop::current().was_exit_requested())
::exit(0);
return goal_condition->function()();
diff --git a/Services/WebWorker/ConnectionFromClient.cpp b/Services/WebWorker/ConnectionFromClient.cpp
index 01b4170fbae..17f5984b381 100644
--- a/Services/WebWorker/ConnectionFromClient.cpp
+++ b/Services/WebWorker/ConnectionFromClient.cpp
@@ -128,21 +128,65 @@ void ConnectionFromClient::set_preferred_languages(Vector<String> preferred_lang
void ConnectionFromClient::close_worker()
{
- async_did_close_worker();
-
- // FIXME: Invoke a worker shutdown operation that implements the spec
- m_worker_host = nullptr;
+ begin_closing();
+}
- die();
+void ConnectionFromClient::begin_closing()
+{
+ if (m_worker_host)
+ m_worker_host->terminate();
+ else
+ Web::HTML::main_thread_event_loop().destroy_once_script_has_finished();
}
void ConnectionFromClient::die()
{
- // FIXME: When handling multiple workers in the same process,
- // this logic needs to be smarter (only when all workers are dead, etc).
+ if (m_shutdown_finished)
+ return;
+
+ // NB: Script waiting on a nested event loop would run on with a closed connection, and it cannot be stopped from
+ // here. Nothing else would end this process either, as the client that could is gone.
+ if (Web::HTML::main_thread_event_loop().is_spinning())
+ Core::Process::terminate_immediately(0);
+
+ begin_closing();
+}
+
+void ConnectionFromClient::did_lose_peer_during_sync_request()
+{
+ // NB: Whatever made the request cannot be unwound from here, and it cannot carry on without a response.
Core::Process::terminate_immediately(0);
}
+void ConnectionFromClient::release_agent_state()
+{
+ if (is_open())
+ async_did_close_worker();
+
+ if (m_worker_host)
+ m_worker_host->run_closing_steps();
+ m_worker_host = nullptr;
+
+ m_transformers.clear();
+ m_pending_transform_inits.clear();
+ m_requested_files.clear();
+ m_request_server_died_callback_for_testing = nullptr;
+ on_request_server_connection = nullptr;
+ on_image_decoder_connection = nullptr;
+ if (m_compositor_connection)
+ m_compositor_connection->on_compositor_lost = nullptr;
+ m_page_host = nullptr;
+}
+
+void ConnectionFromClient::finish_shutdown()
+{
+ m_shutdown_finished = true;
+ m_compositor_connection = nullptr;
+
+ // NB: What the worker reported last still has to reach the client.
+ transport().flush();
+}
+
void ConnectionFromClient::request_file(Web::FileRequest request)
{
auto request_id = ++last_id;
@@ -167,6 +211,10 @@ ConnectionFromClient::ConnectionFromClient(NonnullOwnPtr<IPC::Transport> transpo
// closed the connection — e.g. because the page terminated the worker while this process was still starting — shut
// down right away, rather than handle startup messages and make sync requests on a closed connection.
set_peer_owns_this_process(true);
+
+ Web::HTML::main_thread_event_loop().set_on_destroyed([] {
+ Core::EventLoop::current().quit(0);
+ });
}
ConnectionFromClient::~ConnectionFromClient() = default;
@@ -303,7 +351,7 @@ void ConnectionFromClient::run_transform_init(u64 transform_id, Web::HTML::Seria
m_transformers.set(transform_id, GC::make_root(transformer));
// Return transformed frames to the parent over IPC. Capturing `this` is safe because
- // the connection outlives the transformer; close_worker tears it down via die().
+ // the connection outlives the heap the transformer is in.
auto write_encoded_data = GC::create_function(realm.heap(), [this, transform_id](JS::Value chunk) {
auto* frame = chunk.is_object() ? Web::Bindings::impl_from<Web::WebRTC::RTCEncodedAudioFrame>(&chunk.as_object()) : nullptr;
if (!frame) {
diff --git a/Services/WebWorker/ConnectionFromClient.h b/Services/WebWorker/ConnectionFromClient.h
index 7b30f5feb94..d5390810f57 100644
--- a/Services/WebWorker/ConnectionFromClient.h
+++ b/Services/WebWorker/ConnectionFromClient.h
@@ -33,6 +33,12 @@ public:
virtual ~ConnectionFromClient() override;
virtual void die() override;
+ virtual void did_lose_peer_during_sync_request() override;
+
+ // The two ends of the shutdown of the worker agent, which go around Web::Bindings::shut_down_agent(). The connection
+ // outlives the heap, as cells in the heap use it until they are gone.
+ void release_agent_state();
+ void finish_shutdown();
virtual void set_font_service(IPC::TransportHandle, IPC::File catalog, u64 catalog_size, u64 generation) override;
virtual void close_worker() override;
@@ -93,10 +99,12 @@ private:
HashMap<u64, Web::HTML::SerializedTransferRecord> m_pending_transform_inits;
void run_transform_init(u64 transform_id, Web::HTML::SerializedTransferRecord options_record);
+ void begin_closing();
RefPtr<WorkerHost> m_worker_host;
Function<void()> m_request_server_died_callback_for_testing;
bool m_enable_test_mode { false };
+ bool m_shutdown_finished { false };
};
}
diff --git a/Services/WebWorker/WorkerHost.cpp b/Services/WebWorker/WorkerHost.cpp
index c71f8329540..39993e3d890 100644
--- a/Services/WebWorker/WorkerHost.cpp
+++ b/Services/WebWorker/WorkerHost.cpp
@@ -16,6 +16,7 @@
#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>
+#include <LibWeb/FileAPI/BlobURLStore.h>
#include <LibWeb/HTML/DedicatedWorkerGlobalScope.h>
#include <LibWeb/HTML/MessageEvent.h>
#include <LibWeb/HTML/MessagePort.h>
@@ -45,6 +46,38 @@ WorkerHost::WorkerHost(URL::URL url, Web::HTML::WorkerType type, String name)
WorkerHost::~WorkerHost() = default;
+void WorkerHost::terminate()
+{
+ m_worker_global_scope->terminate_a_worker();
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#run-a-worker
+void WorkerHost::run_closing_steps()
+{
+ // 16. Clear the worker global scope's map of active timers.
+ m_worker_global_scope->clear_map_of_active_timers();
+
+ // NB: The connection of an EventSource goes with the worker, whose global scope is not there for the finalizer of the
+ // EventSource to reach anymore.
+ m_worker_global_scope->forcibly_close_all_event_sources();
+
+ // 17. Disentangle all the ports in the list of the worker's ports.
+ Web::HTML::MessagePort::disentangle_ports_of_realm(Web::HTML::relevant_realm(*m_worker_global_scope));
+
+ // 18. Empty worker global scope's owner set.
+ m_worker_global_scope->owner_set().clear();
+
+ // AD-HOC: The File API only has these steps for a Document, but the blob URLs of a worker go away with it as well.
+ Web::FileAPI::remove_entries_of_environment(*m_inside_settings, *m_worker_global_scope->page());
+
+ // NB: The roots have to go before the heap does, and on_complete keeps this object alive until then.
+ m_console = nullptr;
+ m_worker_global_scope = nullptr;
+ m_inside_settings = nullptr;
+ m_pending_shared_worker_connections.clear();
+ m_on_script_ready = nullptr;
+}
+
void WorkerHost::notify_script_ran()
{
m_script_has_run = true;
@@ -239,6 +272,10 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes
// In both cases, let onComplete given script be the following steps:
RefPtr<WorkerHost> protected_this { *this };
auto on_complete_function = [protected_this, page, inside_settings, worker_global_scope, message_port_data = move(message_port_data), outside_settings_snapshot, url = m_url, is_shared](GC::Ptr<Web::HTML::Script> script) mutable {
+ // NB: A worker that was told to close while it fetched its script never runs it.
+ if (worker_global_scope->is_closing())
+ return;
+
auto& realm = inside_settings->realm();
// 1. If script is null or if script's error to rethrow is non-null, then:
@@ -322,13 +359,8 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes
// worker client is worker global scope's relevant settings object.
// 15. Event loop: Run the responsible event loop specified by inside settings until it is destroyed.
+ // NB: The event loop runs on from here, and the steps after it are in run_closing_steps().
inside_settings->responsible_event_loop().schedule();
-
- // FIXME: We need to react to the closing flag being set on the responsible event loop
- // And use that to shutdown the WorkerHost
- // FIXME: 16. Clear the worker global scope's map of active timers.
- // FIXME: 17. Disentangle all the ports in the list of the worker's ports.
- // FIXME: 18. Empty worker global scope's owner set.
};
auto on_complete = Web::HTML::create_on_fetch_script_complete(GC::Heap::the(), move(on_complete_function));
@@ -339,8 +371,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes
// onComplete and performFetch as defined below.
if (auto err = Web::HTML::fetch_classic_worker_script(m_url, outside_settings, destination, inside_settings, perform_fetch, on_complete); err.is_error()) {
dbgln("Failed to run worker script");
- // FIXME: Abort the worker properly
- TODO();
+ on_complete->function()(nullptr);
}
} else {
// -> "module":
@@ -349,8 +380,7 @@ void WorkerHost::run(GC::Ref<Web::Page> page, Web::HTML::TransferDataEncoder mes
VERIFY(m_type == Web::HTML::WorkerType::Module);
if (auto err = Web::HTML::fetch_module_worker_script_graph(m_url, outside_settings, destination, inside_settings, perform_fetch, on_complete, static_cast<Web::Fetch::Infrastructure::Request::CredentialsMode>(credentials)); err.is_error()) {
dbgln("Failed to run worker script");
- // FIXME: Abort the worker properly
- TODO();
+ on_complete->function()(nullptr);
}
}
}
diff --git a/Services/WebWorker/WorkerHost.h b/Services/WebWorker/WorkerHost.h
index c8a9b3851f3..e082028e276 100644
--- a/Services/WebWorker/WorkerHost.h
+++ b/Services/WebWorker/WorkerHost.h
@@ -33,6 +33,9 @@ public:
void run(GC::Ref<Web::Page>, Web::HTML::TransferDataEncoder message_port_data, Web::HTML::SerializedEnvironmentSettingsObject const&, Web::HTML::RequestCredentials, bool is_shared, URL::Origin origin, Web::HTML::EnvironmentId environment_id);
void connect_shared_worker(Web::HTML::TransferDataEncoder message_port_data, Web::HTML::SerializedEnvironmentSettingsObject);
+ void terminate();
+ void run_closing_steps();
+
GC::Ptr<Web::HTML::WorkerGlobalScope> global_scope() { return m_worker_global_scope.cell(); }
bool script_has_run() const { return m_script_has_run; }
diff --git a/Services/WebWorker/main.cpp b/Services/WebWorker/main.cpp
index f364ae98721..4b41f99b212 100644
--- a/Services/WebWorker/main.cpp
+++ b/Services/WebWorker/main.cpp
@@ -157,7 +157,20 @@ ErrorOr<int> ladybird_main(Main::Arguments arguments)
if (stats_log)
stats_log->start_sampling([&heap](JsonObject& values) { heap.add_stats(values); });
- return event_loop.exec();
+ auto exit_code = event_loop.exec();
+
+ // The worker has closed. This goes through its agent in order, as a thread that hosts a worker will have to, rather
+ // than leave it all to the end of the process.
+ stats_log = nullptr;
+ client->release_agent_state();
+ MediaClient::Client::set_transport_factory(nullptr);
+ Web::Bindings::shut_down_agent();
+ client->finish_shutdown();
+
+ // The client terminates a process that closes the connection, so the connection stays open until this process ends.
+ (void)move(client).leak_ref();
+
+ return exit_code;
}
static ErrorOr<void> connect_to_resource_loader(GC::Heap& heap, IPC::TransportHandle const& handle, Optional<int> client_id, Optional<Utf16String> const& top_level_site)