Truly independent web browser
LibWeb: Let a FetchByteChannel waiter keep the body's prefix when due
Luke Wildeacf2e5e6358f
diff --git a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cppindex fe140bc692f..5b7e57ddb54 100644--- a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp+++ b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.cpp@@ -46,7 +46,8 @@ bool FetchByteChannel::is_due_locked(WakeOn const& wake_on) constreturn true;return wake_on.visit([&](BufferedAtLeast const& buffered_at_least) { return m_buffered_byte_count >= buffered_at_least.byte_count; },- [](EndOnly) { return false; });+ [](EndOnly) { return false; },+ [&](PrefixOf const& prefix_of) { return m_buffered_byte_count >= prefix_of.byte_count; });}void FetchByteChannel::wake_due_waiters_locked(PendingNotifications& notifications)@@ -54,11 +55,38 @@ void FetchByteChannel::wake_due_waiters_locked(PendingNotifications& notificatiom_armed_waiters.remove_all_matching([&](ArmedWaiter const& waiter) {if (!is_due_locked(waiter.wake_on))return false;+ keep_prefix_locked(waiter.ticket, waiter.wake_on);notifications.append(Wake { waiter.ticket });return true;});}+// A cancelled or transferred channel keeps nothing, so take_prefix() finds no prefix for it.+void FetchByteChannel::keep_prefix_locked(WakeTicket ticket, WakeOn const& wake_on)+{+ auto const* prefix_of = wake_on.get_pointer<PrefixOf>();+ if (!prefix_of || m_state.has<ConsumerCancelled>() || m_state.has<Transferred>())+ return;++ ByteBuffer prefix;+ auto append_up_to_limit = [&](ReadonlyBytes bytes) {+ auto length = min<u64>(bytes.size(), prefix_of->byte_count - prefix.size());+ prefix.append(bytes.trim(static_cast<size_t>(length)));+ };+ for (auto const& chunk : m_chunks) {+ if (prefix.size() == prefix_of->byte_count)+ break;+ append_up_to_limit(chunk.bytes());+ }+ if (prefix.size() < prefix_of->byte_count)+ append_up_to_limit(m_copied_tail.bytes());++ TakeResult kept { .taken = {}, .state = m_state, .buffered_byte_count = m_buffered_byte_count };+ if (!prefix.is_empty())+ kept.taken.append(Core::ImmutableBytes::adopt(move(prefix)));+ m_kept_prefixes.append({ ticket, move(kept) });+}+FetchByteChannel::WriteResult FetchByteChannel::write(Core::ImmutableBytes bytes){return write_bytes(move(bytes));@@ -187,6 +215,7 @@ FetchByteChannel::TerminateResult FetchByteChannel::cancel()auto result = TerminateResult::AlreadyTerminated;{MutexLocker locker { m_mutex };+ m_kept_prefixes.clear();// A Closed channel keeps its undrained buffer, which a Streams cancellation may still discard.if (m_state.has<Open>() || (m_state.has<Closed>() && m_buffered_byte_count > 0)) {m_state = ConsumerCancelled {};@@ -210,6 +239,7 @@ Vector<Core::ImmutableBytes> FetchByteChannel::transfer_out()Vector<Core::ImmutableBytes> undrained_bytes;{MutexLocker locker { m_mutex };+ m_kept_prefixes.clear();if (!m_state.has<Open>() && !m_state.has<Closed>())return {};@@ -311,26 +341,39 @@ WakeTicket FetchByteChannel::arm_waiter(WakeOn wake_on)VERIFY(m_consumer_sink);wake_on.visit([](BufferedAtLeast const& buffered_at_least) { VERIFY(buffered_at_least.byte_count > 0); },- [](EndOnly) { });+ [](EndOnly) { },+ [](PrefixOf const& prefix_of) { VERIFY(prefix_of.byte_count > 0); });PendingNotifications notifications;WakeTicket ticket { 0 };{MutexLocker locker { m_mutex };ticket = WakeTicket { m_next_ticket++ };- if (is_due_locked(wake_on))+ if (is_due_locked(wake_on)) {+ keep_prefix_locked(ticket, wake_on);notifications.append(Wake { ticket });- else+ } else {m_armed_waiters.append({ ticket, move(wake_on) });+ }}dispatch(notifications);return ticket;}+Optional<FetchByteChannel::TakeResult> FetchByteChannel::take_prefix(WakeTicket ticket)+{+ MutexLocker locker { m_mutex };+ auto index = m_kept_prefixes.find_first_index_if([&](KeptPrefix const& kept) { return kept.ticket == ticket; });+ if (!index.has_value())+ return {};+ return m_kept_prefixes.take(*index).prefix;+}+void FetchByteChannel::disarm_waiter(WakeTicket ticket){MutexLocker locker { m_mutex };m_armed_waiters.remove_first_matching([&](ArmedWaiter const& waiter) { return waiter.ticket == ticket; });+ m_kept_prefixes.remove_first_matching([&](KeptPrefix const& kept) { return kept.ticket == ticket; });}}diff --git a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.hindex 6a755cc7f2d..61548ae5e1b 100644--- a/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h+++ b/Libraries/LibWeb/Fetch/Engine/FetchByteChannel.h@@ -118,13 +118,21 @@ public:};// A waiter fires only once the channel ends: closes, errors, or is cancelled or transferred.struct EndOnly { };- using WakeOn = Variant<BufferedAtLeast, EndOnly>;+ // Fires as BufferedAtLeast does, and keeps a copy of the first byte_count bytes and the state from the moment it+ // is due, for take_prefix().+ struct PrefixOf {+ u64 byte_count;+ };+ using WakeOn = Variant<BufferedAtLeast, EndOnly, PrefixOf>;// Each call adds a waiter that fires once, and returns the ticket its wake will carry; a wake already due fires// before this returns, outside the lock. Waiters due at the same time fire in the order they were added.WakeTicket arm_waiter(WakeOn = BufferedAtLeast { 1 });void disarm_waiter(WakeTicket);+ // What a PrefixOf waiter kept, once. A cancellation, a transfer or disarming its ticket drops it unread.+ [[nodiscard]] Optional<TakeResult> take_prefix(WakeTicket);+private:FetchByteChannel(Watermarks, NonnullRefPtr<FetchByteChannelProducerSink>);@@ -148,6 +156,7 @@ private:[[nodiscard]] TerminateResult terminate_locked(State, PendingNotifications&);[[nodiscard]] bool is_due_locked(WakeOn const&) const;void wake_due_waiters_locked(PendingNotifications&);+ void keep_prefix_locked(WakeTicket, WakeOn const&);void dispatch(PendingNotifications const&);struct ArmedWaiter {@@ -155,6 +164,12 @@ private:WakeOn wake_on;};+ // A compact copy, so it holds none of the chunks' storage.+ struct KeptPrefix {+ WakeTicket ticket { 0 };+ TakeResult prefix;+ };+Watermarks const m_watermarks;NonnullRefPtr<FetchByteChannelProducerSink> const m_producer_sink;RefPtr<FetchByteChannelConsumerSink> m_consumer_sink;@@ -169,6 +184,7 @@ private:bool m_transport_ended { false };Optional<Core::ImmutableBytes> m_whole_body;Vector<ArmedWaiter, 2> m_armed_waiters;+ Vector<KeptPrefix, 1> m_kept_prefixes;u64 m_next_ticket { 1 };};diff --git a/Tests/LibWeb/TestFetchByteChannel.cpp b/Tests/LibWeb/TestFetchByteChannel.cppindex 853d7378dcc..eb03238aa93 100644--- a/Tests/LibWeb/TestFetchByteChannel.cpp+++ b/Tests/LibWeb/TestFetchByteChannel.cpp@@ -406,6 +406,133 @@ TEST_CASE(waiter_is_one_shot_and_disarmable)EXPECT(harness.take_events().is_empty());}+TEST_CASE(a_prefix_waiter_keeps_its_bytes_through_a_later_error)+{+ ChannelHarness harness;++ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 4 });+ EXPECT_EQ(harness.channel->write(bytes_of("head"sv)), WriteResult::Accepted);+ EXPECT_EQ(harness.channel->write(bytes_of("body"sv)), WriteResult::Accepted);+ EXPECT_EQ(harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) }), TerminateResult::Terminated);++ // The error empties the channel, while the waiter keeps what it saw the moment it was due.+ EXPECT(harness.channel->take_all().state.has<Errored>());+ auto kept = harness.channel->take_prefix(ticket);+ EXPECT(kept.has_value());+ EXPECT_EQ(flatten(*kept), "head"sv);+ EXPECT(kept->state.has<Open>());+}++TEST_CASE(a_prefix_waiter_keeps_every_byte_of_a_short_close)+{+ ChannelHarness harness;++ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 16 });+ EXPECT_EQ(harness.channel->write(bytes_of("short"sv)), WriteResult::Accepted);+ EXPECT(!harness.channel->take_prefix(ticket).has_value());+ EXPECT_EQ(harness.channel->close(), TerminateResult::Terminated);++ auto kept = harness.channel->take_prefix(ticket);+ EXPECT(kept.has_value());+ EXPECT_EQ(flatten(*kept), "short"sv);+ EXPECT(kept->state.has<Closed>());+}++TEST_CASE(a_prefix_waiter_keeps_no_bytes_of_an_early_error)+{+ ChannelHarness harness;++ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 16 });+ EXPECT_EQ(harness.channel->write(bytes_of("partial"sv)), WriteResult::Accepted);+ EXPECT_EQ(harness.channel->error({ .message = MUST(ByteBuffer::copy("failed"sv.bytes())) }), TerminateResult::Terminated);++ auto kept = harness.channel->take_prefix(ticket);+ EXPECT(kept.has_value());+ EXPECT(kept->taken.is_empty());+ EXPECT(kept->state.has<Errored>());+}++TEST_CASE(a_prefix_waiter_armed_with_its_bytes_buffered_keeps_them_at_once)+{+ ChannelHarness harness;++ EXPECT_EQ(harness.channel->write(bytes_of("already here"sv)), WriteResult::Accepted);+ (void)harness.take_events();+ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 7 });+ auto events = harness.take_events();+ EXPECT_EQ(events.size(), 1u);+ EXPECT_EQ(events[0].value, ticket.value());++ auto kept = harness.channel->take_prefix(ticket);+ EXPECT(kept.has_value());+ EXPECT_EQ(flatten(*kept), "already"sv);+}++TEST_CASE(a_kept_prefix_is_taken_once)+{+ ChannelHarness harness;++ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 1 });+ EXPECT_EQ(harness.channel->write(bytes_of("x"sv)), WriteResult::Accepted);+ EXPECT(harness.channel->take_prefix(ticket).has_value());+ EXPECT(!harness.channel->take_prefix(ticket).has_value());++ // Another waiter's ticket finds none.+ auto plain_ticket = harness.channel->arm_waiter();+ EXPECT(!harness.channel->take_prefix(plain_ticket).has_value());+}++TEST_CASE(disarming_cancelling_or_transferring_drops_a_kept_prefix)+{+ for (int ending = 0; ending < 3; ++ending) {+ ChannelHarness harness;+ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 4 });+ EXPECT_EQ(harness.channel->write(bytes_of("head"sv)), WriteResult::Accepted);+ if (ending == 0)+ harness.channel->disarm_waiter(ticket);+ else if (ending == 1)+ (void)harness.channel->cancel();+ else+ (void)harness.channel->transfer_out();+ EXPECT(!harness.channel->take_prefix(ticket).has_value());+ }+}++TEST_CASE(a_prefix_waiter_cancelled_or_transferred_before_its_bytes_keeps_nothing)+{+ for (bool cancel : { true, false }) {+ ChannelHarness harness;+ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 16 });+ EXPECT_EQ(harness.channel->write(bytes_of("some"sv)), WriteResult::Accepted);+ (void)harness.take_events();+ if (cancel)+ (void)harness.channel->cancel();+ else+ (void)harness.channel->transfer_out();++ // The ending wakes the waiter, which keeps nothing.+ bool woken = false;+ for (auto const& event : harness.take_events())+ woken |= event.kind == SinkEvent::Kind::Wake && event.value == ticket.value();+ EXPECT(woken);+ EXPECT(!harness.channel->take_prefix(ticket).has_value());+ }+}++TEST_CASE(keeping_and_taking_a_prefix_leaves_the_bytes_and_credit_alone)+{+ ChannelHarness harness;++ auto ticket = harness.channel->arm_waiter(FetchByteChannel::PrefixOf { 4 });+ EXPECT_EQ(harness.channel->write(bytes_of("headbody"sv)), WriteResult::Accepted);+ (void)harness.take_events();+ EXPECT_EQ(flatten(*harness.channel->take_prefix(ticket)), "head"sv);++ // Neither keeping nor taking the prefix granted credit or removed a byte.+ EXPECT(harness.take_events().is_empty());+ EXPECT_EQ(flatten(harness.channel->peek_up_to(64)), "headbody"sv);+}+TEST_CASE(a_drained_close_leaves_nothing_to_cancel){ChannelHarness harness;@@ -729,12 +856,15 @@ TEST_CASE(concurrent_writer_wakes_each_of_several_waiters_once)// Each round arms several waiters at once and disarms one of them while the writer decides which are due.auto end_ticket = channel->arm_waiter(FetchByteChannel::EndOnly {});Vector<WakeTicket> owed;+ Vector<WakeTicket> prefixes;Vector<WakeTicket> disarmed;u64 total_bytes_taken = 0;for (;;) {auto some = channel->arm_waiter(FetchByteChannel::BufferedAtLeast { 1 });owed.append(some);owed.append(channel->arm_waiter(FetchByteChannel::BufferedAtLeast { 32 }));+ prefixes.append(channel->arm_waiter(FetchByteChannel::PrefixOf { 8 }));+ owed.append(prefixes.last());auto unwanted = channel->arm_waiter(FetchByteChannel::BufferedAtLeast { 48 });channel->disarm_waiter(unwanted);disarmed.append(unwanted);@@ -766,6 +896,14 @@ TEST_CASE(concurrent_writer_wakes_each_of_several_waiters_once)EXPECT_EQ(consumer_sink->times_woken(ticket), 1u);for (auto ticket : disarmed)EXPECT(consumer_sink->times_woken(ticket) <= 1);++ // Each prefix waiter kept at most its limit, from an open or closed channel.+ for (auto ticket : prefixes) {+ auto kept = channel->take_prefix(ticket);+ EXPECT(kept.has_value());+ EXPECT(flatten(*kept).length() <= 8);+ EXPECT(kept->state.has<Open>() || kept->state.has<Closed>());+ }}TEST_CASE(concurrent_cancellation_rejects_every_later_write)