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
|
// 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 "content/renderer/renderer_navigation_metrics_manager.h"
#include "base/check.h"
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
#include "base/task/thread_pool.h"
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_id_helper.h"
#include "content/renderer/render_thread_impl.h"
namespace content {
namespace {
// If a navigation hasn't completed within this timeout, its timeline data will
// be cleaned up. See also cleanup comments in GetOrCreateTimeline() below.
constexpr base::TimeDelta kLazyCleanupTimeout = base::Seconds(300);
// Kill switch for `RendererNavigationMetricsManager`'s generation of renderer
// trace events and metrics, in case they cause any unexpected overhead or other
// issues. See https://crbug.com/415821826.
BASE_FEATURE(kEnableRendererNavigationTimeline,
"EnableRendererNavigationTimeline",
base::FEATURE_ENABLED_BY_DEFAULT);
} // namespace
RendererNavigationMetricsManager& RendererNavigationMetricsManager::Instance() {
static base::NoDestructor<RendererNavigationMetricsManager> manager;
return *manager.get();
}
RendererNavigationMetricsManager::RendererNavigationMetricsManager() = default;
RendererNavigationMetricsManager::~RendererNavigationMetricsManager() = default;
RendererNavigationMetricsManager::Timeline::Timeline() = default;
RendererNavigationMetricsManager::Timeline::~Timeline() = default;
RendererNavigationMetricsManager::Timeline&
RendererNavigationMetricsManager::GetOrCreateTimeline(
const base::UnguessableToken& navigation_metrics_token) {
auto it = timelines_.find(navigation_metrics_token);
if (it != timelines_.end()) {
return it->second;
}
// Create a new Timeline object for this navigation.
Timeline& timeline = timelines_[navigation_metrics_token];
// Post a task to clean up the new timeline after a timeout, if the
// corresponding navigation hasn't finished by then.
//
// Ideally, we would detect navigation cancellation and remove the timeline at
// that point. Unfortunately, this is not as easy as it seems:
// - IPCs for destroying previously created proxies, views, and provisional
// frames would all have to identify which navigation they pertained to, if
// any, which would add a lot of complexity.
// - detecting NavigationClient interface disconnection seems promising, but
// unfortunately doesn't work for cross-process browser-initiated
// navigations where the commit NavigationClient isn't set up until
// ready-to-commit time, after proxy/view creation.
//
// As a longer-term solution, it might be possible to set up the commit
// NavigationClient earlier and the corresponding `Timeline` directly on it.
// However, this will also be tricky, since the current NavigationClient
// lifetime also impacts web compatibility, by defining when a
// renderer-initiated navigation may be canceled by JavaScript - see comments
// on `RenderFrameImpl::navigation_client_impl_`.
timeline.lazy_cleanup_timer_.Start(
FROM_HERE, kLazyCleanupTimeout,
base::BindOnce(
[](const base::UnguessableToken& token) {
RendererNavigationMetricsManager::Instance().timelines_.erase(
token);
},
navigation_metrics_token));
// Remember that this process has started at least one navigation.
timeline.is_first_navigation_in_this_process = !has_first_navigation_started_;
has_first_navigation_started_ = true;
return timeline;
}
void RendererNavigationMetricsManager::AddCreateViewEvent(
const std::optional<base::UnguessableToken>& navigation_metrics_token,
const base::TimeTicks& start_time,
const base::TimeDelta& elapsed_time) {
if (!base::FeatureList::IsEnabled(kEnableRendererNavigationTimeline)) {
return;
}
// Don't record any metrics if this event was not for a navigation.
if (!navigation_metrics_token) {
return;
}
auto& timeline = GetOrCreateTimeline(*navigation_metrics_token);
timeline.create_view_events.emplace_back(start_time,
start_time + elapsed_time);
}
void RendererNavigationMetricsManager::AddCreateRemoteChildrenEvent(
const std::optional<base::UnguessableToken>& navigation_metrics_token,
const base::TimeTicks& start_time,
const base::TimeDelta& elapsed_time) {
if (!base::FeatureList::IsEnabled(kEnableRendererNavigationTimeline)) {
return;
}
// Don't record any metrics if this event was not for a navigation.
if (!navigation_metrics_token) {
return;
}
auto& timeline = GetOrCreateTimeline(*navigation_metrics_token);
timeline.create_remote_children_events.emplace_back(
start_time, start_time + elapsed_time);
}
void RendererNavigationMetricsManager::AddCreateFrameEvent(
const std::optional<base::UnguessableToken>& navigation_metrics_token,
const base::TimeTicks& start_time,
const base::TimeDelta& elapsed_time) {
if (!base::FeatureList::IsEnabled(kEnableRendererNavigationTimeline)) {
return;
}
// Don't record any metrics if this event was not for a navigation.
if (!navigation_metrics_token) {
return;
}
auto& timeline = GetOrCreateTimeline(*navigation_metrics_token);
// Typically, there's one CreateFrame call per navigation, corresponding to
// the provisional frame that will eventually commit the navigation. However,
// it's possible that a navigation will pick a different RenderFrame at
// response time, which could end up being created in the same renderer
// process. In this case, for now, capture the start/end times of the latest
// CreateFrame call (which is more relevant for navigation latency), by
// overwriting the start/end times if they already exist. In the future,
// these calls could potentially be tracked as separate events.
timeline.create_frame_event.emplace(start_time, start_time + elapsed_time);
}
void RendererNavigationMetricsManager::MarkCommitStart(
const base::UnguessableToken& navigation_metrics_token) {
if (!base::FeatureList::IsEnabled(kEnableRendererNavigationTimeline)) {
return;
}
GetOrCreateTimeline(navigation_metrics_token).commit_start =
base::TimeTicks().Now();
}
void RendererNavigationMetricsManager::RecordTraceEventsAndMetrics(
const RendererNavigationMetricsManager::Timeline& timeline,
const GURL& url) {
CHECK(!timeline.navigation_start.is_null())
<< "Navigation start time not found for " << url;
RenderThreadImpl* render_thread = RenderThreadImpl::current();
// The `render_thread` may be null in tests.
if (!render_thread) {
return;
}
// Record these trace events in a global "Navigations" track, so that it can
// be found under "Global Track Events". This complements events logged
// from the browser process into the same track.
constexpr uint64_t kGlobalInstantTrackId = 0;
static perfetto::NamedTrack track(
"Navigation: Timelines (Renderer)",
base::trace_event::GetNextGlobalTraceId(),
perfetto::Track::Global(kGlobalInstantTrackId));
// Define a helper to log both a trace event slice and a corresponding metric
// for one stage of a navigation.
//
// Note: A similar helper exists to log browser-side navigation timeline
// events in RecordNavigationTraceEventsAndMetrics(). When adding new code
// here, consider whether the browser-side helper also needs to be updated.
// It might be desirable to merge the two helpers in the future.
auto log_trace_event_and_uma =
[&](perfetto::StaticString name, const base::TimeTicks& begin_time,
const base::TimeTicks& end_time,
const std::optional<std::string>& histogram_name = std::nullopt,
const std::optional<std::string>& url = std::nullopt) {
if (begin_time.is_null() || end_time.is_null()) {
return;
}
TRACE_EVENT_BEGIN(
"navigation", name, track, begin_time,
[&](perfetto::EventContext& ctx) {
if (!url.has_value()) {
return;
}
perfetto::protos::pbzero::PageLoad* page_load =
ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>()
->set_page_load();
page_load->set_url(*url);
});
TRACE_EVENT_END("navigation", track, end_time);
// When provided, `histogram_name` is used to avoid including variable
// or sensitive data in the reported metric name. For example, `name`
// may include the navigation URL when measuring the start-to-finish
// time, but we only want to use that for trace events and omit the
// URL in metric names for UMA.
base::UmaHistogramTimes(
base::StrCat({"Navigation.Renderer.Timeline.",
histogram_name.value_or(std::string(name.value)),
".Duration"}),
end_time - begin_time);
};
// Actual navigation events are logged below in contiguous (or nested)
// intervals.
// TODO(crbug.com/405437928): Overlapping navigations may incorrectly appear
// to be nested, using the wrong end times.
log_trace_event_and_uma("Renderer Navigation", timeline.navigation_start,
timeline.commit_end,
/*histogram_name=*/"Total");
// Emit a trace event with url in the name for convenience. Do this in a
// separate trace event from the one above, since events with dynamic strings
// are filtered out in some traces, and the event above would still be useful
// in that case.
// TODO(crbug.com/415720503): Remove once Perfetto navigation plugins surfaces
// urls.
std::string top_level_trace_event_name = "URL: " + url.spec();
TRACE_EVENT_BEGIN("navigation",
perfetto::DynamicString(top_level_trace_event_name), track,
timeline.navigation_start);
TRACE_EVENT_END("navigation", track, timeline.commit_end);
// It's possible that the process was still starting when the navigation
// started. In that case, record an event which measures the time for the
// process to finish starting up and become ready for processing IPCs, and
// treat that point as the starting point for the next event.
base::TimeTicks process_ready_time = render_thread->run_loop_start_time();
if (timeline.navigation_start < process_ready_time) {
log_trace_event_and_uma("WaitingForProcessReady", timeline.navigation_start,
process_ready_time);
} else if (timeline.is_first_navigation_in_this_process) {
// If this was the first navigation in this renderer process, and the
// process was ready before the navigation started, record a zero-sized
// event for WaitingForProcessReady. This allows measuring how much of a
// problem process startup costs are for navigations in a freshly created
// process.
log_trace_event_and_uma("WaitingForProcessReady", timeline.navigation_start,
timeline.navigation_start);
}
// Create an event for each CreateView IPC. There could be multiple if there
// are multiple pages on the navigating frame's opener chain. There could also
// be no CreateView IPCs at all, for example if a subframe navigates
// same-origin.
for (const auto& event : timeline.create_view_events) {
log_trace_event_and_uma("CreateView", event.start, event.end);
}
// Create an event for each CreateRemoteChildren IPC, which creates all
// subframe proxies for a particular page/frame tree. There could be multiple
// of these IPCs per navigation if there are multiple pages on the navigating
// frame's opener chain. Note that main frame proxies are created as part of
// CreateView, and while there is also a CreateRemoteChild IPC to create
// an individual proxy, it is not currently used in the navigation flow, so it
// is not traced here.
for (const auto& event : timeline.create_remote_children_events) {
log_trace_event_and_uma("CreateChildProxies", event.start, event.end);
}
// Create an event for processing the CreateFrame IPC. Note that CreateFrame
// may not happen if the navigation is staying in a previous RenderFrame, e.g.
// for browser-initiated same-document navigations, navigations out of the
// initial empty document, or same-site navigations when RenderDocument is
// turned off.
if (timeline.create_frame_event) {
log_trace_event_and_uma("CreateFrame", timeline.create_frame_event->start,
timeline.create_frame_event->end);
}
log_trace_event_and_uma("CommitToDidCommit", timeline.commit_start,
timeline.commit_end);
}
void RendererNavigationMetricsManager::ProcessNavigationCommit(
const base::UnguessableToken& navigation_metrics_token,
const GURL& url,
const base::TimeTicks& navigation_start_time) {
if (!base::FeatureList::IsEnabled(kEnableRendererNavigationTimeline)) {
return;
}
auto it = timelines_.find(navigation_metrics_token);
// The timeline may not exist for synchronous about:blank commits or
// renderer-initiated same-document navigations. For now, do not record
// anything for these cases.
if (it == timelines_.end()) {
return;
}
auto& timeline = it->second;
timeline.navigation_start = navigation_start_time;
timeline.commit_end = base::TimeTicks().Now();
RecordTraceEventsAndMetrics(timeline, url);
// Remove the timeline from the map and cancel the cleanup timer.
timeline.lazy_cleanup_timer_.Stop();
timelines_.erase(it);
}
} // namespace content
|