File: loading_data_collector.cc

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (381 lines) | stat: -rw-r--r-- 13,434 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright 2017 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/predictors/loading_data_collector.h"

#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <utility>

#include "chrome/browser/browser_features.h"
#include "chrome/browser/predictors/loading_stats_collector.h"
#include "chrome/browser/predictors/predictors_features.h"
#include "chrome/browser/predictors/resource_prefetch_predictor.h"
#include "chrome/browser/predictors/resource_prefetch_predictor_tables.h"
#include "components/history/core/browser/history_service.h"
#include "content/public/browser/browser_thread.h"
#include "net/base/mime_util.h"
#include "net/base/url_util.h"
#include "net/http/http_response_headers.h"
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/common/loader/resource_type_util.h"
#include "third_party/blink/public/common/mime_util/mime_util.h"
#include "third_party/blink/public/mojom/loader/resource_load_info.mojom.h"

using content::BrowserThread;

namespace predictors {

namespace {

bool g_allow_port_in_urls = true;

// Sorted by decreasing likelihood according to HTTP archive.
const char* const kFontMimeTypes[] = {"font/woff2",
                                      "application/x-font-woff",
                                      "application/font-woff",
                                      "application/font-woff2",
                                      "font/x-woff",
                                      "application/x-font-ttf",
                                      "font/woff",
                                      "font/ttf",
                                      "application/x-font-otf",
                                      "x-font/woff",
                                      "application/font-sfnt",
                                      "application/font-ttf"};

// Determines the request destination from the mime type, defaulting to the
// |fallback| if the destination could not be determined.
network::mojom::RequestDestination GetRequestDestinationFromMimeType(
    const std::string& mime_type,
    network::mojom::RequestDestination fallback) {
  if (mime_type.empty()) {
    return fallback;
  } else if (blink::IsSupportedImageMimeType(mime_type)) {
    return network::mojom::RequestDestination::kImage;
  } else if (blink::IsSupportedJavascriptMimeType(mime_type)) {
    return network::mojom::RequestDestination::kScript;
  } else if (net::MatchesMimeType("text/css", mime_type)) {
    return network::mojom::RequestDestination::kStyle;
  } else {
    bool found = std::ranges::any_of(
        kFontMimeTypes, [&mime_type](const std::string& mime) {
          return net::MatchesMimeType(mime, mime_type);
        });
    if (found)
      return network::mojom::RequestDestination::kFont;
  }
  return fallback;
}

// Determines the resource type from the declared one, falling back to MIME
// type detection when it is not explicit.
network::mojom::RequestDestination GetRequestDestination(
    network::mojom::RequestDestination destination,
    const std::string& mime_type) {
  // Restricts empty request destination (e.g. prefetch, prerender, fetch,
  // xhr etc) to a small set of mime types, because these destination types
  // don't communicate how the resources will be used.
  if (destination == network::mojom::RequestDestination::kEmpty) {
    return GetRequestDestinationFromMimeType(
        mime_type, network::mojom::RequestDestination::kEmpty);
  }
  return destination;
}

}  // namespace

OriginRequestSummary::OriginRequestSummary() = default;
OriginRequestSummary::OriginRequestSummary(const OriginRequestSummary& other) =
    default;
OriginRequestSummary::~OriginRequestSummary() = default;

PageRequestSummary::PageRequestSummary(ukm::SourceId ukm_source_id,
                                       const GURL& main_frame_url,
                                       base::TimeTicks navigation_started)
    : ukm_source_id(ukm_source_id),
      main_frame_url(main_frame_url),
      initial_url(main_frame_url),
      navigation_started(navigation_started) {}

PageRequestSummary::PageRequestSummary(const PageRequestSummary& other) =
    default;

void PageRequestSummary::UpdateOrAddResource(
    const blink::mojom::ResourceLoadInfo& resource_load_info) {
  auto should_record_resource_load =
      ShouldRecordResourceLoad(resource_load_info);
  switch (should_record_resource_load) {
    case ShouldRecordResourceLoadResult::kNo:
      return;
    case ShouldRecordResourceLoadResult::kLowPriority:
    case ShouldRecordResourceLoadResult::kYes:
      const bool is_low_priority = should_record_resource_load ==
                                   ShouldRecordResourceLoadResult::kLowPriority;
      for (const auto& redirect_info : resource_load_info.redirect_info_chain) {
        UpdateOrAddToOrigins(redirect_info->origin_of_new_url,
                             redirect_info->network_info, is_low_priority);
      }
      UpdateOrAddToOrigins(url::Origin::Create(resource_load_info.final_url),
                           resource_load_info.network_info, is_low_priority);
      const GURL final_url =
          net::SimplifyUrlForRequest(resource_load_info.final_url);
      if (is_low_priority) {
        low_priority_subresource_urls.insert(final_url);
        // Prevent history bloat on long running pathological Web sites
	if (low_priority_subresource_urls.size() >
              MAX_PREDICTOR_SUBRESOURCE_URL_HISTORY) {
          low_priority_subresource_urls.erase(
              low_priority_subresource_urls.begin());
        }
      } else {
        subresource_urls.insert(final_url);
        // Prevent history bloat on long running pathological Web sites
	if (subresource_urls.size() > MAX_PREDICTOR_SUBRESOURCE_URL_HISTORY) {
          subresource_urls.erase(subresource_urls.begin());
        }
      }
      return;
  }
}

void PageRequestSummary::AddPreconnectAttempt(const GURL& preconnect_url) {
  if (main_frame_load_complete) {
    return;
  }
  url::Origin preconnect_origin = url::Origin::Create(preconnect_url);
  if (preconnect_origin == url::Origin::Create(main_frame_url)) {
    // Do not count preconnect to main frame origin in number of origins
    // preconnected to.
    return;
  }
  preconnect_origins.insert(preconnect_origin);
}

void PageRequestSummary::AddPrefetchAttempt(const GURL& prefetch_url) {
  if (main_frame_load_complete) {
    return;
  }
  prefetch_urls.insert(prefetch_url);

  if (!first_prefetch_initiated)
    first_prefetch_initiated = base::TimeTicks::Now();
}

void PageRequestSummary::MainFrameLoadComplete() {
  main_frame_load_complete = true;
}

PageRequestSummary::ShouldRecordResourceLoadResult
PageRequestSummary::ShouldRecordResourceLoad(
    const blink::mojom::ResourceLoadInfo& resource_load_info) const {
  const GURL& url = resource_load_info.final_url;
  if (!url.is_valid() || !url.SchemeIsHTTPOrHTTPS()) {
    return kNo;
  }

  if (!g_allow_port_in_urls && url.has_port()) {
    return kNo;
  }

  if (!IsHandledResourceType(resource_load_info.request_destination,
                             resource_load_info.mime_type)) {
    return kNo;
  }

  if (resource_load_info.method != "GET") {
    return kNo;
  }

  if (main_frame_load_complete) {
    return kLowPriority;
  }

  // Guard behind feature: All delayable requests are considered low priority.
  if (base::FeatureList::IsEnabled(
          features::kLoadingOnlyLearnHighPriorityResources) &&
      resource_load_info.request_priority < net::MEDIUM) {
    return kLowPriority;
  }

  return kYes;
}

// static
bool PageRequestSummary::IsHandledResourceType(
    network::mojom::RequestDestination destination,
    const std::string& mime_type) {
  network::mojom::RequestDestination actual_destination =
      GetRequestDestination(destination, mime_type);
  return actual_destination == network::mojom::RequestDestination::kDocument ||
         actual_destination == network::mojom::RequestDestination::kStyle ||
         actual_destination == network::mojom::RequestDestination::kScript ||
         actual_destination == network::mojom::RequestDestination::kImage ||
         actual_destination == network::mojom::RequestDestination::kFont;
}

void PageRequestSummary::UpdateOrAddToOrigins(
    const url::Origin& origin,
    const blink::mojom::CommonNetworkInfoPtr& network_info,
    bool is_low_priority) {
  if (origin.opaque())
    return;

  if (is_low_priority) {
    low_priority_origins.insert(origin);
    return;
  }

  auto it = origins.find(origin);
  if (it == origins.end()) {
    OriginRequestSummary summary;
    summary.origin = origin;
    summary.first_occurrence = origins.size();
    it = origins.insert({origin, summary}).first;
  }

  it->second.always_access_network |= network_info->always_access_network;
  it->second.accessed_network |= network_info->network_accessed;
}

PageRequestSummary::~PageRequestSummary() = default;

// static
void LoadingDataCollector::SetAllowPortInUrlsForTesting(bool state) {
  g_allow_port_in_urls = state;
}

LoadingDataCollector::LoadingDataCollector(
    ResourcePrefetchPredictor* predictor,
    predictors::LoadingStatsCollector* stats_collector,
    const LoadingPredictorConfig& config)
    : predictor_(predictor),
      stats_collector_(stats_collector),
      config_(config) {}

LoadingDataCollector::~LoadingDataCollector() = default;

void LoadingDataCollector::RecordStartNavigation(
    NavigationId navigation_id,
    ukm::SourceId ukm_source_id,
    const GURL& main_frame_url,
    base::TimeTicks creation_time) {
  CleanupAbandonedNavigations();

  // New empty navigation entry.
  inflight_navigations_.emplace(
      navigation_id, std::make_unique<PageRequestSummary>(
                         ukm_source_id, main_frame_url, creation_time));
}

void LoadingDataCollector::RecordFinishNavigation(
    NavigationId navigation_id,
    const GURL& new_main_frame_url,
    bool is_error_page) {
  if (is_error_page) {
    inflight_navigations_.erase(navigation_id);
    return;
  }

  auto nav_it = inflight_navigations_.find(navigation_id);
  if (nav_it != inflight_navigations_.end()) {
    nav_it->second->main_frame_url = new_main_frame_url;
    nav_it->second->navigation_committed = base::TimeTicks::Now();
  }
}

void LoadingDataCollector::RecordResourceLoadComplete(
    NavigationId navigation_id,
    const blink::mojom::ResourceLoadInfo& resource_load_info) {
  auto nav_it = inflight_navigations_.find(navigation_id);
  if (nav_it == inflight_navigations_.end())
    return;

  auto& page_request_summary = *nav_it->second;
  page_request_summary.UpdateOrAddResource(resource_load_info);
}

void LoadingDataCollector::RecordPreconnectInitiated(
    NavigationId navigation_id,
    const GURL& preconnect_url) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  auto nav_it = inflight_navigations_.find(navigation_id);
  if (nav_it == inflight_navigations_.end())
    return;

  auto& page_request_summary = *nav_it->second;
  page_request_summary.AddPreconnectAttempt(preconnect_url);
}

void LoadingDataCollector::RecordPrefetchInitiated(NavigationId navigation_id,
                                                   const GURL& prefetch_url) {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);

  auto nav_it = inflight_navigations_.find(navigation_id);
  if (nav_it == inflight_navigations_.end())
    return;

  auto& page_request_summary = *nav_it->second;
  page_request_summary.AddPrefetchAttempt(prefetch_url);
}

void LoadingDataCollector::RecordMainFrameLoadComplete(
    NavigationId navigation_id) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  // Initialize |predictor_| no matter whether the |navigation_id| is present in
  // |inflight_navigations_|. This is the case for NTP and about:blank pages,
  // for example.
  if (predictor_)
    predictor_->StartInitialization();

  auto nav_it = inflight_navigations_.find(navigation_id);
  if (nav_it == inflight_navigations_.end())
    return;

  PageRequestSummary& summary = *nav_it->second;
  summary.MainFrameLoadComplete();

  if (predictor_)
    predictor_->RecordPageRequestSummary(summary);
}

void LoadingDataCollector::RecordPageDestroyed(
    NavigationId navigation_id,
    const std::optional<OptimizationGuidePrediction>&
        optimization_guide_prediction) {
  auto nav_it = inflight_navigations_.find(navigation_id);
  if (nav_it == inflight_navigations_.end()) {
    return;
  }

  std::unique_ptr<PageRequestSummary> summary = std::move(nav_it->second);
  CHECK(summary->navigation_committed.has_value());
  inflight_navigations_.erase(nav_it);
  if (stats_collector_) {
    stats_collector_->RecordPageRequestSummary(*summary,
                                               optimization_guide_prediction);
  }
}

void LoadingDataCollector::CleanupAbandonedNavigations() {
  static const base::TimeDelta max_navigation_age =
      base::Seconds(config_.max_navigation_lifetime_seconds);

  base::TimeTicks time_now = base::TimeTicks::Now();
  for (auto it = inflight_navigations_.begin();
       it != inflight_navigations_.end();) {
    if (time_now - it->second->navigation_started > max_navigation_age &&
        !it->second->navigation_committed) {
      it = inflight_navigations_.erase(it);
    } else {
      ++it;
    }
  }
}

}  // namespace predictors