Skip to content

Truly independent web browser

LibWeb: Add the fetch executor and its inline implementation

Luke Wilde265e353305ab
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txt
index ca01a2e8ed7..6c5b5c10336 100644
--- a/Libraries/LibWeb/CMakeLists.txt
+++ b/Libraries/LibWeb/CMakeLists.txt
@@ -369,6 +369,8 @@ set(SOURCES
EventTiming/PerformanceEventTiming.cpp
Fetch/Body.cpp
Fetch/BodyInit.cpp
+ Fetch/Engine/FetchExecutor.cpp
+ Fetch/Engine/InlineFetchExecutor.cpp
Fetch/Fetching/Checks.cpp
Fetch/Fetching/FetchedDataReceiver.cpp
Fetch/Fetching/Fetching.cpp
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp
new file mode 100644
index 00000000000..52cf0f7a432
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/Fetch/Engine/FetchExecutor.h>
+
+namespace Web::Fetch::Engine {
+
+FetchExecutor::FetchExecutor(FetchExecutorServices services, NonnullOwnPtr<EngineCommandSink> engine)
+ : m_services(move(services))
+ , m_engine(move(engine))
+{
+}
+
+FetchExecutor::~FetchExecutor() = default;
+
+void FetchExecutor::post(EngineCommand command)
+{
+ if (m_shut_down.load(AK::MemoryOrder::memory_order_acquire))
+ return;
+
+ // The task keeps the executor, and so the engine, alive until it has run or been dropped.
+ auto run_command = [self = NonnullRefPtr(*this), command = move(command)]() mutable {
+ if (self->m_shut_down.load(AK::MemoryOrder::memory_order_acquire))
+ return;
+ self->m_engine->handle_command(move(command));
+ };
+ post_task(move(run_command));
+}
+
+void FetchExecutor::shutdown()
+{
+ m_shut_down.store(true, AK::MemoryOrder::memory_order_release);
+}
+
+}
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h
new file mode 100644
index 00000000000..102a6084a4f
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Engine/FetchExecutor.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Atomic.h>
+#include <AK/AtomicRefCounted.h>
+#include <AK/Function.h>
+#include <AK/NonnullOwnPtr.h>
+#include <LibWeb/Export.h>
+#include <LibWeb/Fetch/Engine/EngineCommand.h>
+#include <LibWeb/Fetch/Engine/EngineCommandSink.h>
+#include <LibWeb/Fetch/Engine/FetchExecutorServices.h>
+
+namespace Web::Fetch::Engine {
+
+// Commands reach the engine on its thread, in posting order, and never after shutdown.
+class WEB_API FetchExecutor : public AtomicRefCounted<FetchExecutor> {
+public:
+ virtual ~FetchExecutor();
+
+ void post(EngineCommand);
+
+ // Drops every command that has not started running; one that has started completes.
+ void shutdown();
+
+protected:
+ FetchExecutor(FetchExecutorServices, NonnullOwnPtr<EngineCommandSink>);
+
+ FetchExecutorServices const& services() const { return m_services; }
+
+ virtual void post_task(Function<void()>) = 0;
+
+private:
+ FetchExecutorServices m_services;
+ NonnullOwnPtr<EngineCommandSink> m_engine;
+ Atomic<bool> m_shut_down { false };
+};
+
+}
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchExecutorServices.h b/Libraries/LibWeb/Fetch/Engine/FetchExecutorServices.h
new file mode 100644
index 00000000000..b587bfe971f
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Engine/FetchExecutorServices.h
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/NonnullRefPtr.h>
+#include <LibCore/EventLoop.h>
+
+namespace Web::Fetch::Engine {
+
+struct FetchExecutorServices {
+ // Commands are posted to it; one posted after its death is dropped.
+ NonnullRefPtr<Core::WeakEventLoopReference> event_loop;
+};
+
+}
diff --git a/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp
new file mode 100644
index 00000000000..1d11ab93f94
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.cpp
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibWeb/Fetch/Engine/InlineFetchExecutor.h>
+
+namespace Web::Fetch::Engine {
+
+NonnullRefPtr<InlineFetchExecutor> InlineFetchExecutor::create(FetchExecutorServices services, NonnullOwnPtr<EngineCommandSink> engine)
+{
+ return adopt_ref(*new InlineFetchExecutor(move(services), move(engine)));
+}
+
+InlineFetchExecutor::InlineFetchExecutor(FetchExecutorServices services, NonnullOwnPtr<EngineCommandSink> engine)
+ : FetchExecutor(move(services), move(engine))
+{
+}
+
+void InlineFetchExecutor::post_task(Function<void()> task)
+{
+ auto loop = services().event_loop->take();
+ if (!loop)
+ return;
+ loop->deferred_invoke(move(task));
+}
+
+}
diff --git a/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h
new file mode 100644
index 00000000000..58bcbcb9b8e
--- /dev/null
+++ b/Libraries/LibWeb/Fetch/Engine/InlineFetchExecutor.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWeb/Export.h>
+#include <LibWeb/Fetch/Engine/FetchExecutor.h>
+
+namespace Web::Fetch::Engine {
+
+// Runs the engine as deferred work of the loop its services name.
+class WEB_API InlineFetchExecutor final : public FetchExecutor {
+public:
+ static NonnullRefPtr<InlineFetchExecutor> create(FetchExecutorServices, NonnullOwnPtr<EngineCommandSink>);
+
+private:
+ InlineFetchExecutor(FetchExecutorServices, NonnullOwnPtr<EngineCommandSink>);
+
+ virtual void post_task(Function<void()>) override;
+};
+
+}
diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txt
index ddd726ffffc..343ac476b8c 100644
--- a/Tests/LibWeb/CMakeLists.txt
+++ b/Tests/LibWeb/CMakeLists.txt
@@ -12,6 +12,7 @@ set(TEST_SOURCES
TestEventLoop.cpp
TestFaviconDecoding.cpp
TestFetchEngineMessages.cpp
+ TestFetchExecutor.cpp
TestFetchResponse.cpp
TestFetchURL.cpp
TestHTMLTokenizer.cpp
@@ -63,6 +64,7 @@ target_link_libraries(BenchmarkDisplayListRecording PRIVATE LibGC LibGfx LibIPC
target_link_libraries(TestAudioWorkletPipe PRIVATE LibCore LibThreading)
target_link_libraries(TestContentBlocker PRIVATE LibURL)
target_link_libraries(TestFetchEngineMessages PRIVATE LibCore LibIPC LibRequests)
+target_link_libraries(TestFetchExecutor PRIVATE LibCore LibIPC LibThreading)
if (NOT WIN32)
target_link_libraries(TestCSSSyntaxParser PRIVATE LibThreading)
endif()
diff --git a/Tests/LibWeb/TestFetchExecutor.cpp b/Tests/LibWeb/TestFetchExecutor.cpp
new file mode 100644
index 00000000000..9426eb3ab7a
--- /dev/null
+++ b/Tests/LibWeb/TestFetchExecutor.cpp
@@ -0,0 +1,190 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Atomic.h>
+#include <AK/ThreadID.h>
+#include <LibCore/EventLoop.h>
+#include <LibIPC/Transport.h>
+#include <LibTest/TestCase.h>
+#include <LibThreading/Thread.h>
+#include <LibWeb/Fetch/Engine/InlineFetchExecutor.h>
+
+using namespace Web::Fetch::Engine;
+
+namespace {
+
+// Records what reaches the engine, and on which thread.
+struct RecordedCommands {
+ Vector<u64> fetch_ids;
+ Vector<AK::ThreadID> threads;
+ Optional<IPC::TransportHandle> adopted_transport;
+};
+
+class RecordingSink final : public EngineCommandSink {
+public:
+ explicit RecordingSink(RecordedCommands& recorded)
+ : m_recorded(recorded)
+ {
+ }
+
+ virtual void handle_command(EngineCommand command) override
+ {
+ m_recorded.threads.append(AK::ThreadID::current());
+ command.visit(
+ [&](Command::Stop const& stop) { m_recorded.fetch_ids.append(stop.fetch_id.value()); },
+ [&](Command::AdoptNetworkTransport& adopt) { m_recorded.adopted_transport = move(adopt.handle); },
+ [](auto const&) { FAIL("unexpected command"); });
+ }
+
+private:
+ RecordedCommands& m_recorded;
+};
+
+FetchExecutorServices services_for_current_thread()
+{
+ return { .event_loop = Core::EventLoop::current_weak() };
+}
+
+// Each task the executor posts holds it until the task has run or been dropped.
+bool has_queued_tasks(InlineFetchExecutor const& executor)
+{
+ return executor.ref_count() > 1;
+}
+
+bool peer_has_hung_up(IPC::Transport& transport)
+{
+ return transport.read_as_many_messages_as_possible_without_blocking([](auto&&) { }) == IPC::Transport::ShouldShutdown::Yes;
+}
+
+void wait_for_peer_to_hang_up(IPC::Transport& transport)
+{
+ while (!peer_has_hung_up(transport))
+ transport.wait_until_readable();
+}
+
+}
+
+TEST_CASE(commands_run_on_the_loop_in_posting_order)
+{
+ Core::EventLoop loop;
+ RecordedCommands recorded;
+ auto executor = InlineFetchExecutor::create(services_for_current_thread(), make<RecordingSink>(recorded));
+
+ for (u64 id = 1; id <= 3; ++id)
+ executor->post(Command::Stop { .fetch_id = FetchId(id) });
+ EXPECT(recorded.fetch_ids.is_empty());
+
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(recorded.fetch_ids, (Vector<u64> { 1, 2, 3 }));
+ for (auto thread : recorded.threads)
+ EXPECT(thread.is_current_thread());
+}
+
+TEST_CASE(an_executor_on_another_thread_runs_its_commands_there)
+{
+ Core::EventLoop main_loop;
+ IGNORE_USE_IN_ESCAPING_LAMBDA auto main_loop_reference = Core::EventLoop::current_weak();
+ IGNORE_USE_IN_ESCAPING_LAMBDA RecordedCommands recorded;
+ IGNORE_USE_IN_ESCAPING_LAMBDA RefPtr<InlineFetchExecutor> executor;
+ IGNORE_USE_IN_ESCAPING_LAMBDA RefPtr<Core::WeakEventLoopReference> executor_loop;
+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> release { false };
+
+ auto thread = Threading::Thread::construct("FetchExecutor"sv, [&]() -> intptr_t {
+ Core::EventLoop loop;
+ auto created = InlineFetchExecutor::create(services_for_current_thread(), make<RecordingSink>(recorded));
+ main_loop_reference->take()->deferred_invoke([&, created, loop_reference = Core::EventLoop::current_weak()] {
+ executor = created;
+ executor_loop = loop_reference;
+ });
+ while (!release.load())
+ loop.pump(Core::EventLoop::WaitMode::WaitForEvents);
+ return 0;
+ });
+ thread->start();
+
+ while (!executor)
+ main_loop.pump(Core::EventLoop::WaitMode::WaitForEvents);
+ for (u64 id = 1; id <= 3; ++id)
+ executor->post(Command::Stop { .fetch_id = FetchId(id) });
+ executor->post(Command::AdoptNetworkTransport { .handle = {} });
+ executor_loop->take()->deferred_invoke([&] { release.store(true); });
+ MUST(thread->join());
+
+ EXPECT_EQ(recorded.fetch_ids, (Vector<u64> { 1, 2, 3 }));
+ EXPECT_EQ(recorded.threads.size(), 4u);
+ for (auto recorded_thread : recorded.threads) {
+ EXPECT(!recorded_thread.is_current_thread());
+ EXPECT_EQ(recorded_thread, recorded.threads.first());
+ }
+}
+
+TEST_CASE(a_command_posted_after_shutdown_is_destroyed_at_once)
+{
+ Core::EventLoop loop;
+ RecordedCommands recorded;
+ auto executor = InlineFetchExecutor::create(services_for_current_thread(), make<RecordingSink>(recorded));
+ auto pair = MUST(IPC::Transport::create_paired());
+
+ executor->shutdown();
+ executor->post(Command::AdoptNetworkTransport { .handle = move(pair.remote_handle) });
+ EXPECT(!has_queued_tasks(*executor));
+ wait_for_peer_to_hang_up(*pair.local);
+
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT(recorded.threads.is_empty());
+}
+
+TEST_CASE(a_command_posted_after_its_loop_is_gone_is_destroyed_at_once)
+{
+ RecordedCommands recorded;
+ RefPtr<InlineFetchExecutor> executor;
+ {
+ Core::EventLoop loop;
+ executor = InlineFetchExecutor::create(services_for_current_thread(), make<RecordingSink>(recorded));
+ }
+ auto pair = MUST(IPC::Transport::create_paired());
+
+ executor->post(Command::AdoptNetworkTransport { .handle = move(pair.remote_handle) });
+ EXPECT(!has_queued_tasks(*executor));
+ wait_for_peer_to_hang_up(*pair.local);
+ EXPECT(recorded.threads.is_empty());
+}
+
+TEST_CASE(a_pending_command_is_dropped_by_shutdown)
+{
+ Core::EventLoop loop;
+ RecordedCommands recorded;
+ auto executor = InlineFetchExecutor::create(services_for_current_thread(), make<RecordingSink>(recorded));
+ auto pair = MUST(IPC::Transport::create_paired());
+
+ executor->post(Command::AdoptNetworkTransport { .handle = move(pair.remote_handle) });
+ executor->shutdown();
+ EXPECT(has_queued_tasks(*executor));
+ EXPECT(!peer_has_hung_up(*pair.local));
+
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT(recorded.threads.is_empty());
+ EXPECT(!has_queued_tasks(*executor));
+ wait_for_peer_to_hang_up(*pair.local);
+}
+
+TEST_CASE(a_network_transport_is_adopted_exactly_once)
+{
+ Core::EventLoop loop;
+ RecordedCommands recorded;
+ auto executor = InlineFetchExecutor::create(services_for_current_thread(), make<RecordingSink>(recorded));
+ auto pair = MUST(IPC::Transport::create_paired());
+
+ executor->post(Command::AdoptNetworkTransport { .handle = move(pair.remote_handle) });
+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+
+ // The engine owns the handle until it drops it.
+ EXPECT(recorded.adopted_transport.has_value());
+ EXPECT(!has_queued_tasks(*executor));
+ EXPECT(!peer_has_hung_up(*pair.local));
+ recorded.adopted_transport.clear();
+ wait_for_peer_to_hang_up(*pair.local);
+}