Skip to content

Truly independent web browser

LibWeb: Let the parser reuse speculative fetches' responses

Shannon Booth01e0cc53832d
diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cpp
index e00017e6e6a..6db25a6b7ba 100644
--- a/Libraries/LibWeb/DOM/Document.cpp
+++ b/Libraries/LibWeb/DOM/Document.cpp
@@ -1457,6 +1457,7 @@ WebIDL::ExceptionOr<Document*> Document::open(Optional<Utf16String> const&, Opti
m_html_parser_end_state->cancel();
m_html_parser_end_state = nullptr;
}
+ HTML::discard_speculative_preloads(*this);
// INTEROP: The HTML Standard leaves discarding pending scripts unspecified. Blink and WebKit discard their
// parser script runner's pending parsing-blocking and deferred scripts when replacing the parser, and
diff --git a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
index 5f18dfb9486..2a2fd2fd5b9 100644
--- a/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/HTMLParser.cpp
@@ -53,6 +53,7 @@
#include <LibWeb/HTML/Parser/ParserScriptingMode.h>
#include <LibWeb/HTML/Parser/SpeculativeHTMLParser.h>
#include <LibWeb/HTML/PolicyContainers.h>
+#include <LibWeb/HTML/PreloadEntry.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/ExceptionReporter.h>
#include <LibWeb/HTML/Scripting/SimilarOriginWindowAgent.h>
@@ -657,6 +658,9 @@ void HTMLParser::the_end(GC::Ref<DOM::Document> document, GC::Ptr<HTMLParser> pa
if (parser)
parser->m_tokenizer.undefine_insertion_point();
+ // NB: The normal parser fetches nothing more.
+ discard_speculative_preloads(*document);
+
// 3. Update the current document readiness to "interactive".
document->update_readiness(HTML::DocumentReadyState::Interactive);
@@ -2579,6 +2583,7 @@ void HTMLParser::abort()
// 2. Stop the speculative HTML parser for this HTML parser.
stop_the_speculative_html_parser();
+ discard_speculative_preloads(*m_document);
// 3. Update the current document readiness to "interactive".
m_document->update_readiness(DocumentReadyState::Interactive);
diff --git a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
index fefbf5bb565..c0ee73c7081 100644
--- a/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
+++ b/Libraries/LibWeb/HTML/Parser/SpeculativeHTMLParser.cpp
@@ -4,22 +4,29 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/AnyOf.h>
#include <AK/Assertions.h>
#include <AK/FFIHelpers.h>
#include <LibGC/Heap.h>
+#include <LibHTTP/Cache/Utilities.h>
#include <LibJS/Runtime/Realm.h>
#include <LibWeb/CSS/Parser/Parser.h>
#include <LibWeb/DOM/Document.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Responses.h>
#include <LibWeb/HTML/CORSSettingAttribute.h>
+#include <LibWeb/HTML/Parser/HTMLParser.h>
#include <LibWeb/HTML/Parser/SpeculativeHTMLParser.h>
#include <LibWeb/HTML/PotentialCORSRequest.h>
+#include <LibWeb/HTML/PreloadEntry.h>
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Scripting/Fetching.h>
#include <LibWeb/HTMLTokenizerRustFFI.h>
+#include <LibWebCommon/Fetch/Infrastructure/HTTP/Statuses.h>
#include <LibWebCommon/ReferrerPolicy/ReferrerPolicy.h>
namespace Web::HTML {
@@ -133,12 +140,49 @@ void issue_speculative_fetch(JS::Realm& realm, DOM::Document& document, URL::URL
auto request = create_potential_CORS_request(url, destination, cors_setting);
request->set_client(&document.relevant_settings_object());
+ // AD-HOC: The spec expects caching rules, which are not yet fully specified, to stop the normal parser from fetching
+ // the same resource again. A response the HTTP cache can't store would be fetched twice, so once the
+ // speculative fetch succeeds, offer its response to the normal parser's fetch the way a preload is, through
+ // the document's map of preloaded resources. That fetch still runs main fetch's checks before using it.
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input {};
- auto algorithms = Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input));
+ fetch_algorithms_input.process_response_consume_body = [&realm, document = GC::Ref { document }, parser = GC::Weak { document.active_parser() }, request](GC::Ref<Fetch::Infrastructure::Response> response, Fetch::Infrastructure::FetchAlgorithms::BodyBytes body_bytes) {
+ auto* byte_sequence = body_bytes.get_pointer<Core::ImmutableBytes>();
+ if (response->is_network_error() || !byte_sequence)
+ return;
+
+ // NB: Only the parser that fetched it may still use the response.
+ if (!parser || document->active_parser() != parser.ptr())
+ return;
+
+ auto key = create_a_preload_key(*request);
+ if (document->map_of_preloaded_resources().contains(key))
+ return;
+
+ // NB: The server may have changed a failed or no-store response since, so fetch it again.
+ auto internal_response = response->unsafe_response();
+ if (!Fetch::Infrastructure::is_ok_status(internal_response->status()))
+ return;
+ if (auto cache_control = internal_response->header_list()->get("Cache-Control"sv); cache_control.has_value() && HTTP::contains_cache_control_directive(*cache_control, "no-store"sv))
+ return;
+
+ // NB: The preload key doesn't hold the request headers a response varies on, and the normal parser's request
+ // may send others (e.g. a script may have set a cookie since). Accept-Encoding doesn't change in between.
+ auto vary_field_names = HTTP::vary_field_names(*internal_response->header_list());
+ if (!vary_field_names.has_value() || any_of(*vary_field_names, [](auto const& name) { return name != "accept-encoding"sv; }))
+ return;
+
+ // NB: Keep the filtered response, which main fetch uses as is. Unfiltered, it would be treated as same-origin.
+ internal_response->set_body(Fetch::Infrastructure::byte_sequence_as_body(realm, byte_sequence->bytes()));
+
+ auto entry = PreloadEntry::create();
+ entry->response = response;
+ entry->is_speculative = true;
+ document->map_of_preloaded_resources().set(key, entry);
+ };
// The fetch stays alive via ResourceLoader's GC::Root callbacks for the duration of the
// network request, so we don't need to retain the FetchController.
- (void)Fetch::Fetching::fetch(realm, request, algorithms);
+ (void)Fetch::Fetching::fetch(realm, request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input)));
}
Utf16String utf16_string_from_preload_scanner(u8 const* pointer, size_t length)
diff --git a/Libraries/LibWeb/HTML/PreloadEntry.cpp b/Libraries/LibWeb/HTML/PreloadEntry.cpp
index 9dfa68114d6..2b001d80165 100644
--- a/Libraries/LibWeb/HTML/PreloadEntry.cpp
+++ b/Libraries/LibWeb/HTML/PreloadEntry.cpp
@@ -130,4 +130,9 @@ bool consume_a_preloaded_resource(
return true;
}
+void discard_speculative_preloads(DOM::Document& document)
+{
+ document.map_of_preloaded_resources().remove_all_matching([](auto const&, auto const& entry) { return entry->is_speculative; });
+}
+
}
diff --git a/Libraries/LibWeb/HTML/PreloadEntry.h b/Libraries/LibWeb/HTML/PreloadEntry.h
index 18b44450b1e..d7e6a15d91c 100644
--- a/Libraries/LibWeb/HTML/PreloadEntry.h
+++ b/Libraries/LibWeb/HTML/PreloadEntry.h
@@ -74,6 +74,9 @@ public:
// sync XHR send(), whose event loop is paused while it's blocked) re-targets that fetch thru this, so it
// delivers its response without the event loop as well; see consume_a_preloaded_resource().
GC::Ptr<Fetch::Infrastructure::FetchController> controller;
+
+ // AD-HOC: Whether this entry offers a speculative fetch's response to the normal parser's fetch.
+ bool is_speculative { false };
};
// https://html.spec.whatwg.org/multipage/links.html#consume-a-preloaded-resource
@@ -87,6 +90,9 @@ bool consume_a_preloaded_resource(
GC::Ref<GC::Function<void(GC::Ref<Fetch::Infrastructure::Response>)>> on_response_available,
Fetch::Infrastructure::TaskDestination const& consumer_task_destination);
+// AD-HOC: Speculative fetches' responses that the normal parser didn't use must not be handed to a later fetch.
+void discard_speculative_preloads(DOM::Document&);
+
}
namespace AK {