blob: 1bf234b3c7bc88387b45aba3bf78fd682581d883 [file]
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/preloading/prefetch/prefetch_document_manager.h"
#include <string>
#include "base/strings/string_number_conversions.h"
#include "content/browser/preloading/prefetch/prefetch_container.h"
#include "content/browser/preloading/prefetch/prefetch_features.h"
#include "content/browser/preloading/prefetch/prefetch_request.h"
#include "content/browser/preloading/prefetch/prefetch_test_util_internal.h"
#include "content/browser/preloading/preloading.h"
#include "content/browser/preloading/speculation_rules/speculation_rules_tags.h"
#include "content/browser/preloading/speculation_rules/speculation_rules_util.h"
#include "content/public/test/navigation_simulator.h"
#include "content/test/test_render_frame_host.h"
#include "services/network/public/mojom/no_vary_search.mojom.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/mojom/loader/referrer.mojom.h"
#include "third_party/blink/public/mojom/speculation_rules/speculation_rules.mojom.h"
namespace content {
namespace {
using testing::FieldsAre;
using testing::IsEmpty;
using testing::IsNull;
using testing::UnorderedElementsAreArray;
class PrefetchDocumentManagerTest : public PrefetchingMetricsTestBase {
public:
void SetUp() override {
PrefetchingMetricsTestBase::SetUp();
NavigateAndCommit(GetSameOriginUrl("/"));
prefetch_service_ =
std::make_unique<TestPrefetchService>(browser_context());
PrefetchDocumentManager::SetPrefetchServiceForTesting(
prefetch_service_.get());
}
void TearDown() override {
// The PrefetchService we created for the test contains a
// PrefetchOriginProber, which holds a raw pointer to the BrowserContext.
// When tearing down, it's important to free our PrefetchService
// before freeing the BrowserContext, to avoid any chance of a use after
// free.
PrefetchDocumentManager::SetPrefetchServiceForTesting(nullptr);
prefetch_service_.reset();
PrefetchingMetricsTestBase::TearDown();
}
GURL GetSameOriginUrl(const std::string& path) {
return GURL("https://example.com" + path);
}
GURL GetSameSiteCrossOriginUrl(const std::string& path) {
return GURL("https://other.example.com" + path);
}
GURL GetCrossOriginUrl(const std::string& path) {
return GURL("https://other.com" + path);
}
void NavigateMainframeRendererTo(const GURL& url) {
std::unique_ptr<NavigationSimulator> simulator =
NavigationSimulator::CreateRendererInitiated(url, main_rfh());
simulator->SetTransition(ui::PAGE_TRANSITION_LINK);
simulator->Start();
}
const std::vector<base::WeakPtr<PrefetchContainer>>& GetPrefetches() {
return prefetch_service_->prefetches_;
}
// Used to make sure that No-Vary-Search parsing error/warning message is sent
// to DevTools console.
std::string TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError parse_error) {
// Used to create responses.
const net::IsolationInfo info;
// Process the candidates with the |PrefetchDocumentManager| for the current
// document.
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
// Create list of SpeculationCandidatePtrs.
std::vector<blink::mojom::SpeculationCandidatePtr> candidates;
// Create candidate for private cross-origin prefetch. This candidate should
// be prefetched by |PrefetchDocumentManager|.
auto candidate1 = blink::mojom::SpeculationCandidate::New();
candidate1->tags = {std::nullopt};
const auto test_url = GetCrossOriginUrl("/candidate1.html?a=2&b=3");
candidate1->action = blink::mojom::SpeculationAction::kPrefetch;
candidate1->requires_anonymous_client_ip_when_cross_origin = false;
candidate1->url = test_url;
candidate1->referrer = blink::mojom::Referrer::New();
candidates.push_back(std::move(candidate1));
prefetch_document_manager->ProcessCandidates(candidates);
// Now call TakePrefetchedResponse
network::mojom::URLResponseHeadPtr head =
SuccessfulPrefetchResponseHeadForTesting();
head->parsed_headers = network::mojom::ParsedHeaders::New();
head->parsed_headers->no_vary_search_with_parse_error =
network::mojom::NoVarySearchWithParseError::NewParseError(parse_error);
MakeServableStreamingURLLoaderForTest(GetPrefetches()[0].get(),
std::move(head), "empty");
auto& test_rfh = static_cast<TestRenderFrameHost&>(*main_rfh());
return test_rfh.GetConsoleMessages()[0];
}
private:
std::unique_ptr<TestPrefetchService> prefetch_service_;
};
TEST_F(PrefetchDocumentManagerTest, PopulateNoVarySearchHint) {
// Process the candidates with the |PrefetchDocumentManager| for the current
// document.
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
// Create list of SpeculationCandidatePtrs.
std::vector<blink::mojom::SpeculationCandidatePtr> candidates;
// Create candidate for private cross-origin prefetch. This candidate should
// be prefetched by |PrefetchDocumentManager|.
auto candidate1 = blink::mojom::SpeculationCandidate::New();
candidate1->tags = {std::nullopt};
const auto test_url1 = GetCrossOriginUrl("/candidate1.html?a=2&b=3");
candidate1->action = blink::mojom::SpeculationAction::kPrefetch;
candidate1->requires_anonymous_client_ip_when_cross_origin = false;
candidate1->url = test_url1;
candidate1->referrer = blink::mojom::Referrer::New();
candidate1->no_vary_search_hint = network::mojom::NoVarySearch::New();
candidate1->no_vary_search_hint->vary_on_key_order = false;
candidate1->no_vary_search_hint->search_variance =
network::mojom::SearchParamsVariance::NewNoVaryParams({"a"});
auto candidate2 = blink::mojom::SpeculationCandidate::New();
candidate2->tags = {std::nullopt};
const auto test_url2 = GetCrossOriginUrl("/candidate2.html?a=2&b=3");
candidate2->action = blink::mojom::SpeculationAction::kPrefetch;
candidate2->requires_anonymous_client_ip_when_cross_origin = false;
candidate2->url = test_url2;
candidate2->referrer = blink::mojom::Referrer::New();
candidate2->no_vary_search_hint = network::mojom::NoVarySearch::New();
candidate2->no_vary_search_hint->vary_on_key_order = true;
candidate2->no_vary_search_hint->search_variance =
network::mojom::SearchParamsVariance::NewVaryParams({"a"});
auto candidate3 = blink::mojom::SpeculationCandidate::New();
candidate3->tags = {std::nullopt};
const auto test_url3 = GetCrossOriginUrl("/candidate3.html?a=2&b=3");
candidate3->action = blink::mojom::SpeculationAction::kPrefetch;
candidate3->requires_anonymous_client_ip_when_cross_origin = false;
candidate3->url = test_url3;
candidate3->referrer = blink::mojom::Referrer::New();
candidates.push_back(std::move(candidate1));
candidates.push_back(std::move(candidate2));
candidates.push_back(std::move(candidate3));
prefetch_document_manager->ProcessCandidates(candidates);
ASSERT_EQ(GetPrefetches().size(), 3u);
{
auto& prefetch = GetPrefetches()[0];
ASSERT_TRUE(prefetch);
ASSERT_TRUE(prefetch->GetNoVarySearchHint().has_value());
EXPECT_FALSE(prefetch->GetNoVarySearchHint()->vary_on_key_order());
EXPECT_THAT(prefetch->GetNoVarySearchHint()->GetAffectedParams(),
UnorderedElementsAreArray({"a"}));
}
{
auto& prefetch = GetPrefetches()[1];
ASSERT_TRUE(prefetch);
ASSERT_TRUE(prefetch->GetNoVarySearchHint().has_value());
EXPECT_TRUE(prefetch->GetNoVarySearchHint()->vary_on_key_order());
EXPECT_THAT(prefetch->GetNoVarySearchHint()->GetAffectedParams(),
UnorderedElementsAreArray({"a"}));
}
{
auto& prefetch = GetPrefetches()[2];
ASSERT_TRUE(prefetch);
EXPECT_FALSE(prefetch->GetNoVarySearchHint().has_value());
}
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithDefaultValue) {
EXPECT_THAT(TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kDefaultValue),
testing::HasSubstr("is equivalent to the default behavior"));
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithNotDictionary) {
EXPECT_THAT(TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kNotDictionary),
testing::HasSubstr("is not a dictionary"));
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithUnknownDictionaryKey) {
EXPECT_THAT(
TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kUnknownDictionaryKey),
testing::HasSubstr("contains unknown dictionary keys"));
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithNonBooleanKeyOrder) {
EXPECT_THAT(
TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kNonBooleanKeyOrder),
testing::HasSubstr(
"contains a \"key-order\" dictionary value that is not a boolean"));
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithParamsNotStringList) {
EXPECT_THAT(TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kParamsNotStringList),
testing::HasSubstr(
"contains a \"params\" dictionary value that is not a list"));
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithExceptNotStringList) {
EXPECT_THAT(
TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kExceptNotStringList),
testing::HasSubstr(
"contains an \"except\" dictionary value that is not a list"));
}
TEST_F(PrefetchDocumentManagerTest,
ProcessNoVarySearchResponseWithExceptWithoutTrueParams) {
EXPECT_THAT(
TriggerNoVarySearchParseErrorAndGetConsoleMessage(
network::mojom::NoVarySearchParseError::kExceptWithoutTrueParams),
testing::HasSubstr(
"contains an \"except\" dictionary key, without the \"params\""));
}
TEST_F(PrefetchDocumentManagerTest, ProcessSpeculationCandidates) {
// Create list of SpeculationCandidatePtrs.
std::vector<blink::mojom::SpeculationCandidatePtr> candidates;
auto referrer = blink::mojom::Referrer::New();
referrer->url = GetSameOriginUrl("/referrer");
// Create candidate for private cross-origin prefetch. This candidate should
// be prefetched by |PrefetchDocumentManager|.
auto candidate1 = blink::mojom::SpeculationCandidate::New();
candidate1->tags = {std::nullopt};
candidate1->action = blink::mojom::SpeculationAction::kPrefetch;
candidate1->requires_anonymous_client_ip_when_cross_origin = true;
candidate1->url = GetCrossOriginUrl("/candidate1.html");
candidate1->referrer = referrer->Clone();
candidate1->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate1));
// Create candidate for non-private cross-origin prefetch. This candidate
// should be prefetched by |PrefetchDocumentManager|.
auto candidate2 = blink::mojom::SpeculationCandidate::New();
candidate2->tags = {std::nullopt};
candidate2->action = blink::mojom::SpeculationAction::kPrefetch;
candidate2->requires_anonymous_client_ip_when_cross_origin = false;
candidate2->url = GetCrossOriginUrl("/candidate2.html");
candidate2->referrer = referrer->Clone();
candidate2->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate2));
// Create candidate for non-private cross-origin prefetch. This candidate
// should be prefetched by |PrefetchDocumentManager|.
auto candidate3 = blink::mojom::SpeculationCandidate::New();
candidate3->tags = {std::nullopt};
candidate3->action = blink::mojom::SpeculationAction::kPrefetch;
candidate3->requires_anonymous_client_ip_when_cross_origin = false;
candidate3->url = GetSameOriginUrl("/candidate3.html");
candidate3->referrer = referrer->Clone();
candidate3->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate3));
// Create candidate for prerender. This candidate should not be prefetched by
// |PrefetchDocumentManager|.
auto candidate4 = blink::mojom::SpeculationCandidate::New();
candidate4->tags = {std::nullopt};
candidate4->action = blink::mojom::SpeculationAction::kPrerender;
candidate4->requires_anonymous_client_ip_when_cross_origin = false;
candidate4->url = GetCrossOriginUrl("/candidate4.html");
candidate4->referrer = referrer->Clone();
candidate4->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate4));
// Create candidate for private cross-origin prefetch with default eagerness.
// This candidate should be prefetched by |PrefetchDocumentManager|.
auto candidate5 = blink::mojom::SpeculationCandidate::New();
candidate5->tags = {std::nullopt};
candidate5->action = blink::mojom::SpeculationAction::kPrefetch;
candidate5->requires_anonymous_client_ip_when_cross_origin = true;
candidate5->url = GetCrossOriginUrl("/candidate5.html");
candidate5->referrer = referrer->Clone();
candidate5->eagerness = blink::mojom::SpeculationEagerness::kConservative;
candidates.push_back(std::move(candidate5));
// Create candidate for same-site prefetch. This candidate should
// be prefetched by |PrefetchDocumentManager|.
auto candidate6 = blink::mojom::SpeculationCandidate::New();
candidate6->tags = {std::nullopt};
candidate6->action = blink::mojom::SpeculationAction::kPrefetch;
candidate6->requires_anonymous_client_ip_when_cross_origin = false;
candidate6->url = GetSameSiteCrossOriginUrl("/candidate6.html");
candidate6->referrer = referrer->Clone();
candidate6->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate6));
// Create candidate for same-origin prefetch that requires a proxy if
// redirected to a cross-origin URL. This candidate should be prefetched by
// |PrefetchDocumentManager|.
auto candidate7 = blink::mojom::SpeculationCandidate::New();
candidate7->tags = {std::nullopt};
candidate7->action = blink::mojom::SpeculationAction::kPrefetch;
candidate7->requires_anonymous_client_ip_when_cross_origin = true;
candidate7->url = GetSameOriginUrl("/candidate7.html");
candidate7->referrer = referrer->Clone();
candidate7->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate7));
// Process the candidates with the |PrefetchDocumentManager| for the current
// document.
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
prefetch_document_manager->ProcessCandidates(candidates);
// Check that the candidates that should be prefetched were sent to
// |PrefetchService|.
const auto& prefetch_urls = GetPrefetches();
ASSERT_EQ(prefetch_urls.size(), 6U);
EXPECT_EQ(prefetch_urls[0]->GetURL(), GetCrossOriginUrl("/candidate1.html"));
EXPECT_EQ(prefetch_urls[0]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/true,
blink::mojom::SpeculationEagerness::kImmediate));
EXPECT_EQ(prefetch_urls[1]->GetURL(), GetCrossOriginUrl("/candidate2.html"));
EXPECT_EQ(prefetch_urls[1]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kImmediate));
EXPECT_EQ(prefetch_urls[2]->GetURL(), GetSameOriginUrl("/candidate3.html"));
EXPECT_EQ(prefetch_urls[2]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kImmediate));
EXPECT_EQ(prefetch_urls[3]->GetURL(), GetCrossOriginUrl("/candidate5.html"));
EXPECT_EQ(prefetch_urls[3]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/true,
blink::mojom::SpeculationEagerness::kConservative));
EXPECT_EQ(prefetch_urls[4]->GetURL(),
GetSameSiteCrossOriginUrl("/candidate6.html"));
EXPECT_EQ(prefetch_urls[4]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kImmediate));
EXPECT_EQ(prefetch_urls[5]->GetURL(), GetSameOriginUrl("/candidate7.html"));
EXPECT_EQ(prefetch_urls[5]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/true,
blink::mojom::SpeculationEagerness::kImmediate));
// Check that the only remaining entries in candidates are those that
// shouldn't be prefetched by |PrefetchService|.
ASSERT_EQ(candidates.size(), 1U);
EXPECT_EQ(candidates[0]->url, GetCrossOriginUrl("/candidate4.html"));
// Check IsPrefetchAttemptFailedOrDiscarded method
// URLs that were not processed
EXPECT_TRUE(prefetch_document_manager->IsPrefetchAttemptFailedOrDiscarded(
GetSameOriginUrl("/random_page.html")));
// Prefetches with no status yet
EXPECT_FALSE(prefetch_urls[0]->HasPrefetchStatus());
EXPECT_FALSE(prefetch_document_manager->IsPrefetchAttemptFailedOrDiscarded(
GetCrossOriginUrl("/candidate1.html")));
// Prefetches with status
prefetch_urls[0]->SetPrefetchStatus(PrefetchStatus::kPrefetchSuccessful);
EXPECT_FALSE(prefetch_document_manager->IsPrefetchAttemptFailedOrDiscarded(
GetCrossOriginUrl("/candidate1.html")));
prefetch_urls[1]->SetPrefetchStatus(
PrefetchStatus::kPrefetchIneligibleSchemeIsNotHttps);
EXPECT_TRUE(prefetch_document_manager->IsPrefetchAttemptFailedOrDiscarded(
GetCrossOriginUrl("/candidate2.html")));
prefetch_urls[2]->SetPrefetchStatus(PrefetchStatus::kPrefetchFailedNetError);
EXPECT_TRUE(prefetch_document_manager->IsPrefetchAttemptFailedOrDiscarded(
GetCrossOriginUrl("/candidate3.html")));
}
// Link speculationrules prefetch is not started in fenced frame.
// `CanPrefetchNow()` check blocks speculationrules prefetch from fenced frames.
TEST_F(PrefetchDocumentManagerTest, FencedFrameDoesNotStartPrefetch) {
// Create list of SpeculationCandidatePtrs.
std::vector<blink::mojom::SpeculationCandidatePtr> candidates;
auto referrer = blink::mojom::Referrer::New();
referrer->url = GetSameOriginUrl("/referrer");
const GURL cross_origin_url = GetCrossOriginUrl("/candidate.html");
// Create candidate for private cross-origin prefetch. This candidate should
// be added to the queue of |PrefetchDocumentManager|. However, it will not be
// prefetched because it is from a fenced frame.
auto candidate = blink::mojom::SpeculationCandidate::New();
candidate->tags = {std::nullopt};
candidate->action = blink::mojom::SpeculationAction::kPrefetch;
candidate->requires_anonymous_client_ip_when_cross_origin = true;
candidate->url = cross_origin_url;
candidate->referrer = referrer->Clone();
candidate->eagerness = blink::mojom::SpeculationEagerness::kImmediate;
candidates.push_back(std::move(candidate));
// Process the candidate with the |PrefetchDocumentManager| for the current
// document.
TestRenderFrameHost* fenced_frame_rfh =
static_cast<TestRenderFrameHost&>(*main_rfh()).AppendFencedFrame();
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(fenced_frame_rfh);
prefetch_document_manager->ProcessCandidates(candidates);
// Check that the candidate was sent to |PrefetchService|.
const auto& prefetch_urls = GetPrefetches();
ASSERT_EQ(prefetch_urls.size(), 1U);
EXPECT_EQ(prefetch_urls[0]->GetURL(), cross_origin_url);
EXPECT_EQ(prefetch_urls[0]->request().prefetch_type(),
PrefetchType(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/true,
blink::mojom::SpeculationEagerness::kImmediate));
// `CanPrefetchNow()` blocks the speculationrules prefetch from fenced frame.
EXPECT_THAT(prefetch_document_manager->CanPrefetchNow(prefetch_urls[0].get()),
FieldsAre(false, IsNull()));
}
TEST_F(PrefetchDocumentManagerTest, CanPrefetchNowLimits_Default) {
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
// Create 2 completed non-immediate prefetches to reach the default limit.
for (int i = 0; i < 2; ++i) {
auto candidate = blink::mojom::SpeculationCandidate::New();
candidate->tags = {std::nullopt};
candidate->action = blink::mojom::SpeculationAction::kPrefetch;
candidate->url =
GetCrossOriginUrl("/candidate" + base::NumberToString(i) + ".html");
candidate->referrer = blink::mojom::Referrer::New();
candidate->eagerness = blink::mojom::SpeculationEagerness::kModerate;
std::vector<blink::mojom::SpeculationCandidatePtr> candidates;
candidates.push_back(std::move(candidate));
prefetch_document_manager->ProcessCandidates(candidates);
auto& prefetch = GetPrefetches().back();
MakeServableStreamingURLLoaderForTest(
prefetch.get(), SuccessfulPrefetchResponseHeadForTesting(),
"test body");
}
ASSERT_EQ(GetPrefetches().size(), 2u);
// Now we are at the default limit (2).
// A new regular candidate should trigger eviction.
{
auto candidate = blink::mojom::SpeculationCandidate::New();
candidate->tags = {std::nullopt};
candidate->action = blink::mojom::SpeculationAction::kPrefetch;
candidate->url = GetCrossOriginUrl("/candidate_new.html");
candidate->referrer = blink::mojom::Referrer::New();
candidate->eagerness = blink::mojom::SpeculationEagerness::kModerate;
std::vector<blink::mojom::SpeculationCandidatePtr> candidates;
candidates.push_back(std::move(candidate));
prefetch_document_manager->ProcessCandidates(candidates);
auto& prefetch = GetPrefetches().back();
auto [can_prefetch, to_evict] =
prefetch_document_manager->CanPrefetchNow(prefetch.get());
EXPECT_TRUE(can_prefetch);
EXPECT_EQ(to_evict.get(), GetPrefetches()[0].get());
}
}
TEST_F(PrefetchDocumentManagerTest, CanPrefetchNowLimits_EagerEviction) {
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
// Enable the feature and set limit to 4 for viewport heuristics.
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeatureWithParameters(
::features::kPrefetchEagerLimit,
{{"max_number_of_eager_prefetches_per_page", "4"}});
// Add 4 completed Moderate prefetches to reach 4.
for (int i = 0; i < 4; ++i) {
const GURL url_mod =
GetCrossOriginUrl("/candidate_mod" + base::NumberToString(i) + ".html");
PrefetchType prefetch_type_mod(
PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kModerate);
prefetch_document_manager->PrefetchUrl(
url_mod, prefetch_type_mod,
preloading_predictor::kModerateViewportHeuristic,
blink::mojom::Referrer(), SpeculationRulesTags(), nullptr,
PreloadPipelineInfo::Create(PreloadingType::kPrefetch));
auto& prefetch = GetPrefetches().back();
MakeServableStreamingURLLoaderForTest(
prefetch.get(), SuccessfulPrefetchResponseHeadForTesting(),
"test body");
}
ASSERT_EQ(GetPrefetches().size(), 4u);
// Create an Eager candidate.
const GURL url_eager = GetCrossOriginUrl("/candidate_eager.html");
PrefetchType prefetch_type_eager(PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kEager);
// Determine the correct enacting predictor based on platform behavior.
const bool is_eager_immediate = IsImmediateSpeculationEagerness(
blink::mojom::SpeculationEagerness::kEager);
const PreloadingPredictor enacting_predictor =
is_eager_immediate ? content_preloading_predictor::kSpeculationRules
: preloading_predictor::kModerateViewportHeuristic;
prefetch_document_manager->PrefetchUrl(
url_eager, prefetch_type_eager, enacting_predictor,
blink::mojom::Referrer(), SpeculationRulesTags(), nullptr,
PreloadPipelineInfo::Create(PreloadingType::kPrefetch));
auto& prefetch_eager = GetPrefetches().back();
auto [can_prefetch, to_evict] =
prefetch_document_manager->CanPrefetchNow(prefetch_eager.get());
EXPECT_TRUE(can_prefetch);
if (is_eager_immediate) {
// If eager is immediate, it uses the immediate limit (50) and does not
// trigger eviction of non-immediate prefetches.
EXPECT_FALSE(to_evict);
} else {
// If eager is not immediate, it is subject to the eager limit (4) and
// should trigger eviction.
EXPECT_EQ(to_evict.get(), GetPrefetches()[0].get());
}
}
TEST_F(PrefetchDocumentManagerTest, CanPrefetchNowLimits_ModerateEviction) {
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
// Enable the feature and set limit to 4 for viewport heuristics.
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeatureWithParameters(
::features::kPrefetchModerateLimit,
{{"max_number_of_moderate_prefetches_per_page", "4"}});
// Add 4 completed Moderate prefetches to reach 4.
for (int i = 0; i < 4; ++i) {
const GURL url_mod =
GetCrossOriginUrl("/candidate_mod" + base::NumberToString(i) + ".html");
PrefetchType prefetch_type_mod(
PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kModerate);
prefetch_document_manager->PrefetchUrl(
url_mod, prefetch_type_mod,
preloading_predictor::kModerateViewportHeuristic,
blink::mojom::Referrer(), SpeculationRulesTags(), nullptr,
PreloadPipelineInfo::Create(PreloadingType::kPrefetch));
auto& prefetch = GetPrefetches().back();
MakeServableStreamingURLLoaderForTest(
prefetch.get(), SuccessfulPrefetchResponseHeadForTesting(),
"test body");
}
ASSERT_EQ(GetPrefetches().size(), 4u);
// Create a Moderate candidate.
const GURL url_mod_new = GetCrossOriginUrl("/candidate_mod_new.html");
PrefetchType prefetch_type_mod_new(
PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kModerate);
prefetch_document_manager->PrefetchUrl(
url_mod_new, prefetch_type_mod_new,
preloading_predictor::kModerateViewportHeuristic,
blink::mojom::Referrer(), SpeculationRulesTags(), nullptr,
PreloadPipelineInfo::Create(PreloadingType::kPrefetch));
auto& prefetch_mod_new = GetPrefetches().back();
// We are at limit (4). Moderate candidate should trigger eviction.
auto [can_prefetch, to_evict] =
prefetch_document_manager->CanPrefetchNow(prefetch_mod_new.get());
EXPECT_TRUE(can_prefetch);
EXPECT_EQ(to_evict.get(), GetPrefetches()[0].get());
}
TEST_F(PrefetchDocumentManagerTest, CanPrefetchNowLimits_ConservativeEviction) {
auto* prefetch_document_manager =
PrefetchDocumentManager::GetOrCreateForCurrentDocument(main_rfh());
// Enable the feature and set limit to 4 for viewport heuristics.
base::test::ScopedFeatureList feature_list;
feature_list.InitAndEnableFeatureWithParameters(
::features::kPrefetchModerateLimit,
{{"max_number_of_moderate_prefetches_per_page", "4"}});
std::vector<base::WeakPtr<PrefetchContainer>> my_prefetches;
// Add 4 completed Moderate prefetches to reach 4.
for (int i = 0; i < 4; ++i) {
const GURL url_mod =
GetCrossOriginUrl("/candidate_mod" + base::NumberToString(i) + ".html");
PrefetchType prefetch_type_mod(
PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kModerate);
prefetch_document_manager->PrefetchUrl(
url_mod, prefetch_type_mod,
preloading_predictor::kModerateViewportHeuristic,
blink::mojom::Referrer(), SpeculationRulesTags(), nullptr,
PreloadPipelineInfo::Create(PreloadingType::kPrefetch));
my_prefetches.push_back(GetPrefetches().back());
MakeServableStreamingURLLoaderForTest(
my_prefetches.back().get(), SuccessfulPrefetchResponseHeadForTesting(),
"test body");
}
ASSERT_EQ(GetPrefetches().size(), 4u);
// Create a Conservative candidate.
const GURL url_cons = GetCrossOriginUrl("/candidate_cons.html");
PrefetchType prefetch_type_cons(
PreloadingTriggerType::kSpeculationRule,
/*use_prefetch_proxy=*/false,
blink::mojom::SpeculationEagerness::kConservative);
prefetch_document_manager->PrefetchUrl(
url_cons, prefetch_type_cons,
preloading_predictor::kModerateViewportHeuristic,
blink::mojom::Referrer(), SpeculationRulesTags(), nullptr,
PreloadPipelineInfo::Create(PreloadingType::kPrefetch));
auto& prefetch_cons = GetPrefetches().back();
// Limit for Conservative is 2. We have 4 completed non-immediate prefetches.
// CanPrefetchNow should return true and suggest oldest for eviction.
auto [can_prefetch_cons, to_evict_cons] =
prefetch_document_manager->CanPrefetchNow(prefetch_cons.get());
EXPECT_TRUE(can_prefetch_cons);
EXPECT_EQ(to_evict_cons.get(), my_prefetches[0].get());
// Set a dummy callback to avoid crash in OnWillBeDestroyed.
prefetch_document_manager->SetPrefetchDestructionCallback(
base::BindRepeating([](const GURL&) {}));
// Simulate eviction of the first one!
prefetch_document_manager->OnWillBeDestroyed(*my_prefetches[0]);
// Call CanPrefetchNow again! Count is now 3. Limit is still 2.
auto [can_prefetch_cons2, to_evict_cons2] =
prefetch_document_manager->CanPrefetchNow(prefetch_cons.get());
EXPECT_TRUE(can_prefetch_cons2);
EXPECT_EQ(to_evict_cons2.get(), my_prefetches[1].get());
// Simulate eviction of the second one!
prefetch_document_manager->OnWillBeDestroyed(*my_prefetches[1]);
// Call CanPrefetchNow again! Count is now 2. Limit is still 2.
auto [can_prefetch_cons3, to_evict_cons3] =
prefetch_document_manager->CanPrefetchNow(prefetch_cons.get());
EXPECT_TRUE(can_prefetch_cons3);
EXPECT_EQ(to_evict_cons3.get(), my_prefetches[2].get());
// Simulate eviction of the third one!
prefetch_document_manager->OnWillBeDestroyed(*my_prefetches[2]);
// Call CanPrefetchNow again! Count is now 1. Limit is still 2.
// Now count is less than limit, so no eviction needed!
auto [can_prefetch_cons4, to_evict_cons4] =
prefetch_document_manager->CanPrefetchNow(prefetch_cons.get());
EXPECT_TRUE(can_prefetch_cons4);
EXPECT_FALSE(to_evict_cons4);
}
} // namespace
} // namespace content