File: search_preload_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (202 lines) | stat: -rw-r--r-- 7,016 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/preloading/search_preload/search_preload_service.h"

#include "base/metrics/histogram_functions.h"
#include "chrome/browser/preloading/search_preload/search_preload_features.h"
#include "chrome/browser/preloading/search_preload/search_preload_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search_engines/template_url_service_factory.h"
#include "components/omnibox/browser/autocomplete_match.h"
#include "components/omnibox/browser/autocomplete_result.h"
#include "components/omnibox/browser/omnibox.mojom-shared.h"
#include "components/search_engines/template_url_service.h"
#include "content/public/browser/web_contents.h"
#include "services/network/public/mojom/no_vary_search.mojom.h"
#include "services/network/public/mojom/url_response_head.mojom.h"

namespace {

net::HttpNoVarySearchData ParseHttpNoVarySearchDataFromMojom(
    const network::mojom::NoVarySearchPtr& no_vary_search_ptr) {
  if (no_vary_search_ptr->search_variance->is_vary_params()) {
    return net::HttpNoVarySearchData::CreateFromVaryParams(
        no_vary_search_ptr->search_variance->get_vary_params(),
        no_vary_search_ptr->vary_on_key_order);
  }
  return net::HttpNoVarySearchData::CreateFromNoVaryParams(
      no_vary_search_ptr->search_variance->get_no_vary_params(),
      no_vary_search_ptr->vary_on_key_order);
}

}  // namespace

// static
SearchPreloadService* SearchPreloadService::GetForProfile(Profile* profile) {
  return SearchPreloadServiceFactory::GetForProfile(profile);
}

SearchPreloadService::SearchPreloadService(Profile* profile)
    : profile_(profile) {
  CHECK(features::IsDsePreload2Enabled());

  auto* template_url_service =
      TemplateURLServiceFactory::GetForProfile(profile_);
  CHECK(template_url_service);
  observer_.Observe(template_url_service);
}

SearchPreloadService::~SearchPreloadService() = default;

void SearchPreloadService::Shutdown() {
  ClearPreloads();
  observer_.Reset();
}

void SearchPreloadService::OnTemplateURLServiceChanged() {
  ClearPreloads();
}

void SearchPreloadService::ClearPreloads() {
  if (pipeline_manager_.has_value() && pipeline_manager_.value()) {
    pipeline_manager_.value()->ClearPreloads();
  }
  pipeline_manager_.reset();
}

void SearchPreloadService::OnPrefetchHeadReceived(
    const network::mojom::URLResponseHead& head) {
  auto no_vary_search_header =
      [&]() -> std::optional<net::HttpNoVarySearchData> {
    // No No-Vary-Search headers
    if (!(head.parsed_headers &&
          head.parsed_headers->no_vary_search_with_parse_error)) {
      return std::nullopt;
    }

    // Error
    if (head.parsed_headers->no_vary_search_with_parse_error
            ->is_parse_error()) {
      return std::nullopt;
    }

    // Success
    return ParseHttpNoVarySearchDataFromMojom(
        head.parsed_headers->no_vary_search_with_parse_error
            ->get_no_vary_search());
  }();

  {
    SearchPreloadServiceNoVarySearchDataCacheUpdate update;
    if (no_vary_search_data_cache_ == no_vary_search_header) {
      update = SearchPreloadServiceNoVarySearchDataCacheUpdate::kUnchanged;
    } else {
      const bool had_value = no_vary_search_data_cache_.has_value();
      const bool has_value = no_vary_search_header.has_value();
      if (had_value && has_value) {
        update = SearchPreloadServiceNoVarySearchDataCacheUpdate::kSomeToSome;
      } else if (!had_value && has_value) {
        update = SearchPreloadServiceNoVarySearchDataCacheUpdate::kNullToSome;
      } else if (had_value && !has_value) {
        update = SearchPreloadServiceNoVarySearchDataCacheUpdate::kSomeToNull;
      } else {
        NOTREACHED();
      }
    }
    base::UmaHistogramEnumeration(
        "Omnibox.DsePreload.Prefetch.NoVarySearchDataCacheUpdate", update);
  }

  // TODO(crbug.com/422074579): Persist it to profile.
  if (no_vary_search_data_cache_ != no_vary_search_header) {
    no_vary_search_data_cache_ = std::move(no_vary_search_header);
  }
}

void SearchPreloadService::OnOnSuggestPrefetchCompletedOrFailed(
    const network::URLLoaderCompletionStatus& completion_status,
    const std::optional<int>& response_code) {
  const bool is_2xx = response_code.has_value() &&
                      (200 <= response_code && response_code < 300);
  if (!is_2xx) {
    pause_triggering_until_ = base::TimeTicks::Now() +
                              features::kDsePreload2ErrorBackoffDuration.Get();
  }
}

SearchPreloadPipelineManager&
SearchPreloadService::GetOrCreatePipelineManagerWithLimit(
    content::WebContents& web_contents) {
  // Allow at most one WebContents to hold preloads.
  //
  // TODO(crbug.com/394213503): Reconsider the limitation.
  const bool is_occupied_with_given_web_contents =
      pipeline_manager_.has_value() && pipeline_manager_.value() &&
      &pipeline_manager_.value()->GetWebContents() == &web_contents;
  if (!is_occupied_with_given_web_contents) {
    ClearPreloads();
  }

  if (!pipeline_manager_.has_value()) {
    SearchPreloadPipelineManager::CreateForWebContents(&web_contents);
    auto* pipeline_manager =
        SearchPreloadPipelineManager::FromWebContents(&web_contents);
    CHECK(pipeline_manager);
    pipeline_manager_ = pipeline_manager->GetWeakPtr();
  }

  return *pipeline_manager_.value();
}

void SearchPreloadService::OnAutocompleteResultChanged(
    content::WebContents* web_contents,
    const AutocompleteResult& result) {
  if (!web_contents) {
    return;
  }

  if (base::TimeTicks::Now() < pause_triggering_until_) {
    return;
  }

  GetOrCreatePipelineManagerWithLimit(*web_contents)
      .OnAutocompleteResultChanged(*profile_, GetWeakPtr(), result,
                                   no_vary_search_data_cache_);
}

bool SearchPreloadService::OnNavigationLikely(
    size_t index,
    const AutocompleteMatch& match,
    omnibox::mojom::NavigationPredictor navigation_predictor,
    content::WebContents* web_contents) {
  if (!web_contents) {
    return false;
  }

  if (base::TimeTicks::Now() < pause_triggering_until_) {
    return false;
  }

  return GetOrCreatePipelineManagerWithLimit(*web_contents)
      .OnNavigationLikely(*profile_, GetWeakPtr(), match, navigation_predictor,
                          no_vary_search_data_cache_);
}

const std::optional<net::HttpNoVarySearchData>&
SearchPreloadService::GetNoVarySearchDataCacheForTesting() const {
  return no_vary_search_data_cache_;
}

void SearchPreloadService::SetNoVarySearchDataCacheForTesting(
    std::optional<net::HttpNoVarySearchData> no_vary_search_data) {
  no_vary_search_data_cache_ = std::move(no_vary_search_data);
}

bool SearchPreloadService::InvalidatePipelineForTesting(
    content::WebContents& web_contents,
    GURL canonical_url) {
  return GetOrCreatePipelineManagerWithLimit(web_contents)
      .InvalidatePipelineForTesting(canonical_url);  // IN-TEST
}