Truly independent web browser
LibWeb: Add FetchBodyDeliveryGate and WholeBodyTransport
Luke Wildecc71a4e61ecd
diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex baf05c18fd0..0579be25b73 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -365,9 +365,11 @@ set(SOURCESEventTiming/PerformanceEventTiming.cppFetch/Body.cppFetch/BodyInit.cpp+ Fetch/Engine/FetchBodyDeliveryGate.cppFetch/Engine/FetchByteChannel.cppFetch/Engine/FetchExecutor.cppFetch/Engine/InlineFetchExecutor.cpp+ Fetch/Engine/WholeBodyTransport.cppFetch/Fetching/Checks.cppFetch/Fetching/FetchedDataReceiver.cppFetch/Fetching/Fetching.cppdiff --git a/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cpp b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cppnew file mode 100644index 00000000000..0e68d660a96--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.cpp@@ -0,0 +1,159 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibCore/EventLoop.h>+#include <LibRequests/Request.h>+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>++namespace Web::Fetch::Engine {++// A command posted after the gate's loop is gone is dropped.+class FetchBodyDeliveryGateSink final : public FetchByteChannelProducerSink {+public:+ explicit FetchBodyDeliveryGateSink(NonnullRefPtr<FetchBodyDeliveryGate> gate)+ : m_producer_loop(Core::EventLoop::current_weak())+ , m_gate(move(gate))+ {+ }++ virtual void grant_credit(u64 byte_count) override+ {+ post([byte_count](FetchBodyDeliveryGate& gate) { gate.grant_credit(byte_count); });+ }++ virtual void consumer_cancelled() override+ {+ post([](FetchBodyDeliveryGate& gate) { gate.consumer_cancelled(); });+ }++private:+ void post(Function<void(FetchBodyDeliveryGate&)> command)+ {+ auto loop = m_producer_loop->take();+ if (!loop)+ return;+ loop->deferred_invoke([gate = m_gate, command = move(command)] { command(*gate); });+ }++ NonnullRefPtr<Core::WeakEventLoopReference> m_producer_loop;+ NonnullRefPtr<FetchBodyDeliveryGate> m_gate;+};++class RequestTransportAdapter final : public FetchBodyDeliveryGate::Transport {+public:+ explicit RequestTransportAdapter(NonnullRefPtr<Requests::Request> request)+ : m_request(move(request))+ {+ }++ virtual void resume_body_delivery_up_to(u64 byte_count) override { m_request->resume_body_delivery_up_to(byte_count); }+ virtual void pause_body_delivery() override { m_request->set_body_delivery_paused(true); }+ virtual void stop() override { m_request->stop(); }++private:+ NonnullRefPtr<Requests::Request> m_request;+};++NonnullRefPtr<FetchBodyDeliveryGate> FetchBodyDeliveryGate::create(NavigationHold navigation_hold)+{+ return adopt_ref(*new FetchBodyDeliveryGate(navigation_hold));+}++FetchBodyDeliveryGate::FetchBodyDeliveryGate(NavigationHold navigation_hold)+ : m_hold_allowance(navigation_hold == NavigationHold::Held ? 0 : unbounded)+{+}++FetchBodyDeliveryGate::~FetchBodyDeliveryGate()+{+ VERIFY(!m_transport);+}++NonnullRefPtr<FetchByteChannelProducerSink> FetchBodyDeliveryGate::create_channel_sink()+{+ return adopt_ref(*new FetchBodyDeliveryGateSink(*this));+}++void FetchBodyDeliveryGate::attach_transport(NonnullRefPtr<Transport> transport)+{+ if (m_terminated) {+ transport->stop();+ return;+ }+ m_transport = move(transport);+ apply_to_transport();+}++void FetchBodyDeliveryGate::attach_transport(NonnullRefPtr<Requests::Request> request)+{+ attach_transport(adopt_ref(*new RequestTransportAdapter(move(request))));+}++void FetchBodyDeliveryGate::Transport::misbehaved(StringView reason)+{+ dbgln("FetchBodyDeliveryGate: The transport misbehaved: {}", reason);+ VERIFY_NOT_REACHED();+}++FetchBodyDeliveryGate::DeliveryResult FetchBodyDeliveryGate::did_deliver(u64 byte_count)+{+ auto allowance = min(m_channel_allowance, m_hold_allowance);+ if (byte_count > allowance - min(allowance, m_delivered_byte_count)) {+ if (m_transport)+ m_transport->misbehaved("The transport delivered more than it was allowed"sv);+ return DeliveryResult::Rejected;+ }+ m_delivered_byte_count += byte_count;+ return DeliveryResult::Accepted;+}++void FetchBodyDeliveryGate::release_hold_up_to(u64 byte_count)+{+ if (m_hold_allowance == unbounded)+ return;+ m_hold_allowance = max(m_hold_allowance, m_delivered_byte_count + byte_count);+ apply_to_transport();+}++void FetchBodyDeliveryGate::release_hold()+{+ m_hold_allowance = unbounded;+ apply_to_transport();+}++void FetchBodyDeliveryGate::grant_credit(u64 byte_count)+{+ m_channel_allowance += byte_count;+ apply_to_transport();+}++void FetchBodyDeliveryGate::consumer_cancelled()+{+ m_terminated = true;+ if (auto transport = exchange(m_transport, nullptr))+ transport->stop();+}++void FetchBodyDeliveryGate::detach_transport()+{+ m_terminated = true;+ m_transport = nullptr;+}++void FetchBodyDeliveryGate::apply_to_transport()+{+ if (!m_transport)+ return;++ auto allowance = min(m_channel_allowance, m_hold_allowance);+ auto remaining = allowance - min(allowance, m_delivered_byte_count);+ if (remaining > 0)+ m_transport->resume_body_delivery_up_to(remaining);+ else+ m_transport->pause_body_delivery();+}++}diff --git a/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.hnew file mode 100644index 00000000000..2b5d113516e--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h@@ -0,0 +1,83 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/AtomicRefCounted.h>+#include <AK/NumericLimits.h>+#include <AK/RefCounted.h>+#include <AK/RefPtr.h>+#include <AK/Weakable.h>+#include <LibRequests/Forward.h>+#include <LibWeb/Export.h>+#include <LibWeb/Fetch/Engine/FetchByteChannel.h>++namespace Web::Fetch::Engine {++// The transport may deliver only up to the smaller of the channel's credit and the navigation hold. Every method+// runs on the loop the gate was created on.+class WEB_API FetchBodyDeliveryGate final : public AtomicRefCounted<FetchBodyDeliveryGate> {+public:+ enum class NavigationHold : u8 {+ None,+ Held,+ };++ class WEB_API Transport : public RefCounted<Transport>+ , public Weakable<Transport> {+ public:+ virtual ~Transport() = default;+ virtual void resume_body_delivery_up_to(u64 byte_count) = 0;+ virtual void pause_body_delivery() = 0;+ virtual void stop() = 0;++ // Called for a delivery no honest transport could have made.+ virtual void misbehaved(StringView reason);+ };++ [[nodiscard]] static NonnullRefPtr<FetchBodyDeliveryGate> create(NavigationHold);+ ~FetchBodyDeliveryGate();++ [[nodiscard]] NonnullRefPtr<FetchByteChannelProducerSink> create_channel_sink();++ // Allowances granted before the transport exists are applied on attach.+ void attach_transport(NonnullRefPtr<Transport>);+ void attach_transport(NonnullRefPtr<Requests::Request>);++ enum class DeliveryResult : u8 {+ Accepted,+ Rejected,+ };++ // Delivery consumes both allowances; a delivery past them is reported to the transport and rejected.+ [[nodiscard]] DeliveryResult did_deliver(u64 byte_count);++ // Permits this many further bytes from the current delivery point.+ void release_hold_up_to(u64 byte_count);+ void release_hold();++ void consumer_cancelled();++ // A detached transport is never touched again.+ void detach_transport();++ void grant_credit(u64 byte_count);++private:+ explicit FetchBodyDeliveryGate(NavigationHold);++ static constexpr u64 unbounded = NumericLimits<u64>::max();++ void apply_to_transport();++ u64 m_channel_allowance { 0 };+ u64 m_hold_allowance { 0 };+ u64 m_delivered_byte_count { 0 };+ bool m_terminated { false };+ RefPtr<Transport> m_transport;+};++}diff --git a/Libraries/LibWeb/Fetch/Engine/WholeBodyTransport.cpp b/Libraries/LibWeb/Fetch/Engine/WholeBodyTransport.cppnew file mode 100644index 00000000000..2573de986c2--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/WholeBodyTransport.cpp@@ -0,0 +1,101 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibCore/EventLoop.h>+#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>++namespace Web::Fetch::Engine {++NonnullRefPtr<WholeBodyTransport> WholeBodyTransport::create()+{+ return adopt_ref(*new WholeBodyTransport);+}++void WholeBodyTransport::attach_to(FetchBodyDeliveryGate& gate)+{+ VERIFY(!m_attached);+ m_attached = true;+ gate.attach_transport(*this);+}++void WholeBodyTransport::set_body(Core::ImmutableBytes body, OnData on_data)+{+ VERIFY(m_attached);+ VERIFY(!m_body.has_value());+ m_body = move(body);+ m_on_data = move(on_data);+ schedule_delivery();+}++void WholeBodyTransport::when_delivered(Function<void()> on_delivered)+{+ VERIFY(!m_on_delivered);+ m_on_delivered = move(on_delivered);+ schedule_delivery();+}++void WholeBodyTransport::set_on_stop(Function<void()> on_stop)+{+ m_on_stop = move(on_stop);+}++void WholeBodyTransport::resume_body_delivery_up_to(u64 byte_count)+{+ m_allowance = byte_count;+ schedule_delivery();+}++void WholeBodyTransport::pause_body_delivery()+{+ m_allowance = 0;+}++void WholeBodyTransport::stop()+{+ m_stopped = true;+ m_body.clear();+ m_on_data = nullptr;+ m_on_delivered = nullptr;+ if (auto on_stop = move(m_on_stop))+ on_stop();+}++void WholeBodyTransport::schedule_delivery()+{+ if (m_stopped || m_delivery_scheduled)+ return;++ m_delivery_scheduled = true;+ Core::deferred_invoke([self = NonnullRefPtr(*this)] {+ self->m_delivery_scheduled = false;+ self->deliver();+ });+}++void WholeBodyTransport::deliver()+{+ if (!m_body.has_value())+ return;++ auto body_size = m_body->size();+ while (!m_stopped && m_delivered_byte_count < body_size && m_allowance > 0) {+ auto offset = m_delivered_byte_count;+ auto length = static_cast<size_t>(min<u64>(body_size - offset, m_allowance));+ m_delivered_byte_count += length;+ m_allowance -= length;+ m_on_data(Requests::ResponseData::from_file_backed_payload(*m_body, offset, length));+ }++ if (m_stopped || m_delivered_byte_count < body_size)+ return;++ m_on_data = nullptr;+ m_on_stop = nullptr;+ if (auto on_delivered = move(m_on_delivered))+ on_delivered();+}++}diff --git a/Libraries/LibWeb/Fetch/Engine/WholeBodyTransport.h b/Libraries/LibWeb/Fetch/Engine/WholeBodyTransport.hnew file mode 100644index 00000000000..9aaf32a72fe--- /dev/null+++ b/Libraries/LibWeb/Fetch/Engine/WholeBodyTransport.h@@ -0,0 +1,57 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <LibCore/ImmutableBytes.h>+#include <LibRequests/Request.h>+#include <LibWeb/Export.h>+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>++namespace Web::Fetch::Engine {++// Delivers a body that is available all at once, in pieces no larger than the gate allows. Every method runs on the+// loop the transport was created on.+class WEB_API WholeBodyTransport final : public FetchBodyDeliveryGate::Transport {+public:+ using OnData = Function<void(Requests::ResponseData)>;++ [[nodiscard]] static NonnullRefPtr<WholeBodyTransport> create();++ void attach_to(FetchBodyDeliveryGate&);+ [[nodiscard]] bool is_attached() const { return m_attached; }++ void set_body(Core::ImmutableBytes, OnData);++ // Runs once every byte of the body has been delivered, or never if the transport stops first.+ void when_delivered(Function<void()>);++ // Runs once if the transport stops before delivering the whole body.+ void set_on_stop(Function<void()>);++ virtual void resume_body_delivery_up_to(u64 byte_count) override;+ virtual void pause_body_delivery() override;+ virtual void stop() override;++private:+ WholeBodyTransport() = default;++ void schedule_delivery();+ void deliver();++ Optional<Core::ImmutableBytes> m_body;+ OnData m_on_data;+ Function<void()> m_on_delivered;+ Function<void()> m_on_stop;+ size_t m_delivered_byte_count { 0 };+ u64 m_allowance { 0 };+ bool m_attached { false };+ bool m_delivery_scheduled { false };+ bool m_stopped { false };+};++}diff --git a/Tests/LibWeb/CMakeLists.txt b/Tests/LibWeb/CMakeLists.txtindex 7484471e168..5e08a27554f 100644--- a/Tests/LibWeb/CMakeLists.txt+++ b/Tests/LibWeb/CMakeLists.txt@@ -11,6 +11,7 @@ set(TEST_SOURCESTestDump.cppTestEventLoop.cppTestFaviconDecoding.cpp+ TestFetchBodyDeliveryGate.cppTestFetchByteChannel.cppTestFetchEngineMessages.cppTestFetchExecutor.cpp@@ -73,6 +74,7 @@ if (NOT WIN32)endif()target_link_libraries(TestDownloadReader PRIVATE LibGC LibJS LibURL)target_link_libraries(TestFaviconDecoding PRIVATE LibCore LibGC LibGfx LibJS)+target_link_libraries(TestFetchBodyDeliveryGate PRIVATE LibCore LibThreading)target_link_libraries(TestFetchByteChannel PRIVATE LibThreading)target_link_libraries(TestFetchResponse PRIVATE LibGC LibHTTP LibJS LibRequests LibURL)target_link_libraries(TestFetchURL PRIVATE LibURL)diff --git a/Tests/LibWeb/TestFetchBodyDeliveryGate.cpp b/Tests/LibWeb/TestFetchBodyDeliveryGate.cppnew file mode 100644index 00000000000..117ce810e4b--- /dev/null+++ b/Tests/LibWeb/TestFetchBodyDeliveryGate.cpp@@ -0,0 +1,432 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <AK/Atomic.h>+#include <AK/Time.h>+#include <LibCore/EventLoop.h>+#include <LibTest/TestCase.h>+#include <LibThreading/Thread.h>+#include <LibWeb/Fetch/Engine/FetchBodyDeliveryGate.h>+#include <LibWeb/Fetch/Engine/WholeBodyTransport.h>++namespace {++using Web::Fetch::Engine::FetchBodyDeliveryGate;+using Web::Fetch::Engine::WholeBodyTransport;+using DeliveryResult = FetchBodyDeliveryGate::DeliveryResult;+using NavigationHold = FetchBodyDeliveryGate::NavigationHold;++// Spins until the condition holds, or returns false once a minute has passed.+template<typename Condition>+bool spin_until_or_timeout(Condition condition)+{+ auto deadline = MonotonicTime::now() + AK::Duration::from_seconds(60);+ for (u64 spins = 0; !condition(); ++spins) {+ AK::atomic_pause();+ if ((spins % 4096) == 0 && MonotonicTime::now() > deadline)+ return false;+ }+ return true;+}++struct TransportCall {+ enum class Op : u8 {+ Resume,+ Pause,+ Stop,+ };+ Op op;+ u64 value { 0 };++ bool operator==(TransportCall const&) const = default;+};++struct RecordingTransport final : FetchBodyDeliveryGate::Transport {+ virtual void resume_body_delivery_up_to(u64 byte_count) override { calls.append({ TransportCall::Op::Resume, byte_count }); }+ virtual void pause_body_delivery() override { calls.append({ TransportCall::Op::Pause, 0 }); }+ virtual void stop() override { calls.append({ TransportCall::Op::Stop, 0 }); }++ virtual void misbehaved(StringView reason) override+ {+ if (!records_misbehavior) {+ FetchBodyDeliveryGate::Transport::misbehaved(reason);+ return;+ }+ misbehaviors.append(ByteString { reason });+ }++ Vector<TransportCall> take_calls() { return move(calls); }++ Vector<TransportCall> calls;+ bool records_misbehavior { false };+ Vector<ByteString> misbehaviors;+};++struct GateHarness {+ explicit GateHarness(NavigationHold hold)+ : gate(FetchBodyDeliveryGate::create(hold))+ , transport(adopt_ref(*new RecordingTransport))+ {+ }++ ~GateHarness() { gate->detach_transport(); }++ NonnullRefPtr<FetchBodyDeliveryGate> gate;+ NonnullRefPtr<RecordingTransport> transport;+};++}++TEST_CASE(a_delivery_beyond_the_allowance_dies)+{+ GateHarness harness { NavigationHold::None };+ harness.gate->attach_transport(harness.transport);+ harness.gate->grant_credit(10);+ EXPECT_EQ(harness.gate->did_deliver(10), DeliveryResult::Accepted);+ EXPECT_DEATH("the transport delivered more than it was allowed", (void)harness.gate->did_deliver(1));+}++TEST_CASE(a_rejected_delivery_leaves_the_allowance_unspent)+{+ GateHarness harness { NavigationHold::None };+ harness.transport->records_misbehavior = true;+ harness.gate->attach_transport(harness.transport);+ harness.gate->grant_credit(10);++ EXPECT_EQ(harness.gate->did_deliver(4), DeliveryResult::Accepted);+ EXPECT_EQ(harness.gate->did_deliver(7), DeliveryResult::Rejected);+ EXPECT_EQ(harness.transport->misbehaviors, (Vector<ByteString> { "The transport delivered more than it was allowed" }));+ EXPECT_EQ(harness.gate->did_deliver(6), DeliveryResult::Accepted);+}++TEST_CASE(destroying_an_attached_gate_dies)+{+ EXPECT_DEATH("a gate is detached before it is destroyed", [] {+ auto gate = FetchBodyDeliveryGate::create(NavigationHold::None);+ gate->attach_transport(adopt_ref(*new RecordingTransport));+ }());+}++TEST_CASE(navigation_hold_blocks_credited_delivery)+{+ GateHarness harness { NavigationHold::Held };+ harness.gate->attach_transport(harness.transport);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Pause } }));++ // Channel demand alone must never release the navigation hold.+ harness.gate->grant_credit(100);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Pause } }));+}++TEST_CASE(bounded_hold_release_permits_bytes_from_the_current_delivery_point)+{+ GateHarness harness { NavigationHold::Held };+ harness.gate->attach_transport(harness.transport);+ harness.gate->grant_credit(100);+ (void)harness.transport->take_calls();++ harness.gate->release_hold_up_to(10);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 10 } }));++ // A further bounded release counts from what has been delivered since.+ EXPECT_EQ(harness.gate->did_deliver(10), DeliveryResult::Accepted);+ harness.gate->release_hold_up_to(5);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 5 } }));+}++TEST_CASE(hold_release_cannot_bypass_channel_backpressure)+{+ GateHarness harness { NavigationHold::Held };+ harness.gate->attach_transport(harness.transport);+ harness.gate->grant_credit(10);+ (void)harness.transport->take_calls();++ // The full hold release leaves the channel's credit as the only bound.+ harness.gate->release_hold();+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 10 } }));++ EXPECT_EQ(harness.gate->did_deliver(10), DeliveryResult::Accepted);+ harness.gate->release_hold();+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Pause } }));++ harness.gate->grant_credit(30);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 30 } }));+}++TEST_CASE(delivery_consumes_the_smaller_of_both_allowances)+{+ GateHarness harness { NavigationHold::Held };+ harness.gate->attach_transport(harness.transport);+ harness.gate->grant_credit(100);+ harness.gate->release_hold_up_to(20);+ (void)harness.transport->take_calls();++ EXPECT_EQ(harness.gate->did_deliver(15), DeliveryResult::Accepted);+ harness.gate->grant_credit(50);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 5 } }));+}++TEST_CASE(allowances_granted_before_attach_apply_at_attach)+{+ GateHarness harness { NavigationHold::None };+ harness.gate->grant_credit(40);+ harness.gate->attach_transport(harness.transport);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 40 } }));+}++TEST_CASE(attach_after_termination_stops_the_transport)+{+ GateHarness harness { NavigationHold::None };+ harness.gate->consumer_cancelled();+ harness.gate->attach_transport(harness.transport);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Stop } }));+}++TEST_CASE(consumer_cancellation_stops_an_attached_transport_once)+{+ GateHarness harness { NavigationHold::None };+ harness.gate->attach_transport(harness.transport);+ harness.gate->grant_credit(10);+ (void)harness.transport->take_calls();++ harness.gate->consumer_cancelled();+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Stop } }));++ harness.gate->consumer_cancelled();+ harness.gate->grant_credit(10);+ harness.gate->release_hold();+ EXPECT(harness.transport->take_calls().is_empty());+}++TEST_CASE(detached_transport_is_never_touched_again)+{+ // Teardown detaches the gate before the channel cancellation reaches it.+ GateHarness harness { NavigationHold::None };+ harness.gate->attach_transport(harness.transport);+ (void)harness.transport->take_calls();++ harness.gate->detach_transport();+ harness.gate->consumer_cancelled();+ harness.gate->grant_credit(10);+ harness.gate->release_hold();+ EXPECT(harness.transport->take_calls().is_empty());+}++TEST_CASE(channel_sink_posts_commands_onto_the_creating_loop)+{+ Core::EventLoop loop;+ GateHarness harness { NavigationHold::None };+ harness.gate->attach_transport(harness.transport);+ (void)harness.transport->take_calls();++ auto sink = harness.gate->create_channel_sink();+ sink->grant_credit(25);+ EXPECT(harness.transport->take_calls().is_empty());++ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Resume, 25 } }));++ sink->consumer_cancelled();+ loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.transport->take_calls(), (Vector { TransportCall { TransportCall::Op::Stop } }));+}++// A command posted after the gate's loop is gone is dropped rather than run on the poster's thread.+TEST_CASE(channel_sink_drops_commands_once_the_creating_loop_is_gone)+{+ Core::EventLoop main_loop;+ IGNORE_USE_IN_ESCAPING_LAMBDA RefPtr<Web::Fetch::Engine::FetchByteChannelProducerSink> sink;+ IGNORE_USE_IN_ESCAPING_LAMBDA RefPtr<RecordingTransport> transport;+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> loop_gone { false };+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> commands_posted { false };+ IGNORE_USE_IN_ESCAPING_LAMBDA Atomic<bool> timed_out { false };++ // The gate outlives its loop, on its own thread, until the commands have been posted.+ auto owner = Threading::Thread::construct("gate owner"sv, [&]() -> intptr_t {+ auto gate = FetchBodyDeliveryGate::create(NavigationHold::None);+ {+ Core::EventLoop loop;+ transport = adopt_ref(*new RecordingTransport);+ gate->attach_transport(*transport);+ (void)transport->take_calls();+ sink = gate->create_channel_sink();+ }+ loop_gone.store(true);+ if (!spin_until_or_timeout([&] { return commands_posted.load(); }))+ timed_out.store(true);+ gate->detach_transport();+ return 0;+ });+ owner->start();++ if (spin_until_or_timeout([&] { return loop_gone.load(); })) {+ sink->grant_credit(25);+ sink->consumer_cancelled();+ } else {+ timed_out.store(true);+ }+ commands_posted.store(true);+ MUST(owner->join());++ main_loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(!timed_out.load());+ EXPECT(transport->take_calls().is_empty());+}++namespace {++struct WholeBodyHarness {+ explicit WholeBodyHarness(NavigationHold hold)+ : gate(FetchBodyDeliveryGate::create(hold))+ , transport(WholeBodyTransport::create())+ {+ transport->attach_to(gate);+ }++ ~WholeBodyHarness() { gate->detach_transport(); }++ void set_body(size_t size)+ {+ auto body = MUST(ByteBuffer::create_zeroed(size));+ transport->set_body(Core::ImmutableBytes::adopt(move(body)), [this](Requests::ResponseData data) {+ EXPECT_EQ(gate->did_deliver(data.bytes().size()), DeliveryResult::Accepted);+ deliveries.append(data.bytes().size());+ });+ }++ Vector<size_t> take_deliveries() { return move(deliveries); }++ Core::EventLoop loop;+ NonnullRefPtr<FetchBodyDeliveryGate> gate;+ NonnullRefPtr<WholeBodyTransport> transport;+ Vector<size_t> deliveries;+};++}++TEST_CASE(whole_body_transport_delivers_within_the_allowance)+{+ WholeBodyHarness harness { NavigationHold::None };+ harness.gate->grant_credit(300);+ harness.set_body(1000);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 300 }));++ harness.gate->grant_credit(500);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 500 }));++ harness.gate->grant_credit(1000);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 200 }));+}++TEST_CASE(whole_body_transport_reports_delivery_after_the_last_piece)+{+ WholeBodyHarness harness { NavigationHold::None };+ harness.gate->grant_credit(600);+ harness.set_body(1000);++ bool delivered = false;+ harness.transport->when_delivered([&] { delivered = true; });+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(!delivered);++ harness.gate->grant_credit(400);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 600, 400 }));+ EXPECT(delivered);+}++TEST_CASE(whole_body_transport_reports_delivery_only_once_it_has_a_body)+{+ WholeBodyHarness harness { NavigationHold::None };+ harness.gate->grant_credit(1000);++ bool delivered = false;+ harness.transport->when_delivered([&] { delivered = true; });+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(!delivered);++ harness.set_body(100);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 100 }));+ EXPECT(delivered);+}++TEST_CASE(whole_body_transport_waits_for_the_navigation_hold)+{+ WholeBodyHarness harness { NavigationHold::Held };+ harness.gate->grant_credit(1000);+ harness.set_body(100);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(harness.take_deliveries().is_empty());++ harness.gate->release_hold();+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 100 }));+}++TEST_CASE(whole_body_transport_stops_when_the_consumer_cancels)+{+ WholeBodyHarness harness { NavigationHold::None };+ harness.gate->grant_credit(100);+ harness.set_body(1000);++ bool delivered = false;+ harness.transport->when_delivered([&] { delivered = true; });+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 100 }));++ harness.gate->consumer_cancelled();+ harness.gate->grant_credit(1000);+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT(harness.take_deliveries().is_empty());+ EXPECT(!delivered);+}++namespace {++struct CallbackMarker final : public RefCounted<CallbackMarker> { };++}++TEST_CASE(stopping_a_whole_body_transport_releases_its_callbacks_and_runs_its_stop_steps_once)+{+ WholeBodyHarness harness { NavigationHold::None };+ harness.gate->grant_credit(100);+ auto marker = adopt_ref(*new CallbackMarker);+ auto body = MUST(ByteBuffer::create_zeroed(1000));+ harness.transport->set_body(Core::ImmutableBytes::adopt(move(body)), [&harness, marker](Requests::ResponseData data) {+ EXPECT_EQ(harness.gate->did_deliver(data.bytes().size()), DeliveryResult::Accepted);+ });+ harness.transport->when_delivered([marker] { });+ int stop_steps_run = 0;+ harness.transport->set_on_stop([&] { ++stop_steps_run; });+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(marker->ref_count(), 3u);++ harness.transport->stop();+ EXPECT_EQ(marker->ref_count(), 1u);+ EXPECT_EQ(stop_steps_run, 1);++ harness.transport->stop();+ EXPECT_EQ(stop_steps_run, 1);+}++TEST_CASE(a_whole_body_transport_runs_no_stop_steps_after_delivering_the_whole_body)+{+ WholeBodyHarness harness { NavigationHold::None };+ harness.gate->grant_credit(1000);+ harness.set_body(100);+ bool stop_steps_ran = false;+ harness.transport->set_on_stop([&] { stop_steps_ran = true; });+ harness.loop.pump(Core::EventLoop::WaitMode::PollForEvents);+ EXPECT_EQ(harness.take_deliveries(), (Vector<size_t> { 100 }));++ harness.transport->stop();+ EXPECT(!stop_steps_ran);+}