File: page_stability_monitor.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 (266 lines) | stat: -rw-r--r-- 9,375 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
// 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/renderer/actor/page_stability_monitor.h"

#include "base/functional/callback.h"
#include "base/memory/scoped_refptr.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/state_transitions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/time/time.h"
#include "chrome/common/actor/actor_logging.h"
#include "chrome/common/chrome_features.h"
#include "chrome/renderer/actor/tool_base.h"
#include "content/public/renderer/render_frame.h"
#include "third_party/blink/public/web/web_document.h"
#include "third_party/blink/public/web/web_frame_widget.h"
#include "third_party/blink/public/web/web_local_frame.h"

namespace actor {

using ::blink::WebDocument;
using ::blink::WebFrameWidget;
using ::blink::WebLocalFrame;
using ::content::RenderFrame;
using ::content::RenderFrameObserver;

std::ostream& operator<<(std::ostream& o,
                         const PageStabilityMonitor::State& state) {
  return o << static_cast<int>(state);
}

namespace {

// This is a high-level timeout that starts when WaitForStable is called. If it
// isn't completed after this delay it will timeout. This is relatively long
// because it often includes waiting on network.
base::TimeDelta GetGlobalTimeoutDelay() {
  return features::kGlicActorPageStabilityTimeout.Get();
}

// Timeout used when waiting on local work. This can be shorter because it's
// used after network requests are completed.
base::TimeDelta GetMainThreadTimeoutDelay() {
  return features::kGlicActorPageStabilityLocalTimeout.Get();
}

}  // namespace

PageStabilityMonitor::PageStabilityMonitor(RenderFrame& frame)
    : RenderFrameObserver(&frame) {
  CHECK(render_frame());
  CHECK(render_frame()->GetWebFrame());
  starting_request_count_ =
      render_frame()->GetWebFrame()->GetDocument().ActiveResourceRequestCount();
}

PageStabilityMonitor::~PageStabilityMonitor() = default;

void PageStabilityMonitor::WaitForStable(const ToolBase& tool,
                                         int32_t task_id,
                                         Journal& journal,
                                         base::OnceClosure callback) {
  CHECK_EQ(state_, State::kInitial);
  CHECK(!is_stable_callback_);
  journal_entry_ =
      journal.CreatePendingAsyncEntry(task_id, "PageStability", "");

  minimum_end_time_ = base::TimeTicks::Now() + tool.MinimumObservationDelay();

  is_stable_callback_ = std::move(callback);

  SetTimeout(State::kTimeoutGlobal, GetGlobalTimeoutDelay());
  MoveToState(State::kStartMonitoring);
}

void PageStabilityMonitor::DidCommitProvisionalLoad(
    ui::PageTransition transition) {
  // If a same-RenderFrame navigation was committed a new document will be
  // loaded so finish observing the page. (loading is observed from the browser
  // process).
  MoveToState(State::kInvokeCallback);
}

void PageStabilityMonitor::DidFailProvisionalLoad() {
  if (state_ == State::kWaitForNavigation) {
    MoveToState(State::kInvokeCallback);
  }
}

void PageStabilityMonitor::OnDestruct() {
  // It's the responsibility of users of this class to ensure it doesn't outlive
  // the RenderFrame. Posted tasks use WeakPtr so render_frame() is guaranteed
  // to be valid.
}

void PageStabilityMonitor::MoveToState(State new_state) {
  if (state_ == State::kDone) {
    return;
  }

  DCheckStateTransition(state_, new_state);

  state_ = new_state;
  switch (state_) {
    case State::kInitial: {
      NOTREACHED();
    }
    case State::kStartMonitoring: {
      WebDocument document = render_frame()->GetWebFrame()->GetDocument();
      int after_request_count = document.ActiveResourceRequestCount();

      State next_state;
      if (render_frame()->IsRequestingNavigation()) {
        next_state = State::kWaitForNavigation;
      } else if (after_request_count > starting_request_count_) {
        next_state = State::kWaitForNetworkIdle;
      } else {
        next_state = State::kWaitForMainThreadIdle;
      }

      MoveToState(next_state);
      break;
    }
    case State::kWaitForNavigation: {
      // Do nothing - the state will change from DidCommit|FailProvisionalLoad
      break;
    }
    case State::kWaitForNetworkIdle: {
      network_idle_callback_.Reset(
          PostMoveToStateClosure(State::kWaitForMainThreadIdle));
      render_frame()->GetWebFrame()->RequestNetworkIdleCallback(
          network_idle_callback_.callback());
      break;
    }
    case State::kWaitForMainThreadIdle: {
      SetTimeout(State::kTimeoutMainThread, GetMainThreadTimeoutDelay());
      render_frame()
          ->GetTaskRunner(blink::TaskType::kIdleTask)
          ->PostTask(FROM_HERE,
                     PostMoveToStateClosure(State::kEnsureMinimumDelay));
      break;
    }
    case State::kEnsureMinimumDelay: {
      if (base::TimeTicks::Now() < minimum_end_time_) {
        base::TimeDelta time_remaining =
            minimum_end_time_ - base::TimeTicks::Now();
        PostMoveToStateClosure(State::kWaitForVisualStateRequest,
                               /*delay=*/time_remaining)
            .Run();
      } else {
        MoveToState(State::kWaitForVisualStateRequest);
      }
      break;
    }
    case State::kWaitForVisualStateRequest: {
      WebFrameWidget* widget = render_frame()->GetWebFrame()->FrameWidget();
      if (!widget->InsertVisualStateRequest(
              PostMoveToStateClosure(State::kInvokeCallback))) {
        journal_entry_->EndEntry(
            "Failed to wait for new frame presentation due to no "
            "compositor.");
        MoveToState(State::kInvokeCallback);
      }
      break;
    }
    case State::kTimeoutGlobal: {
      journal_entry_->EndEntry("Timed out waiting for page stability.");
      MoveToState(State::kInvokeCallback);
      break;
    }
    case State::kTimeoutMainThread: {
      journal_entry_->EndEntry(
          "Timed out waiting for page stability - main thread to "
          "produce a thread.");
      MoveToState(State::kInvokeCallback);
      break;
    }
    case State::kInvokeCallback: {
      // Ensure we release the network idle callback slot.
      network_idle_callback_.Cancel();
      // Call the callback on a separate task.
      base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE, std::move(is_stable_callback_));
      MoveToState(State::kDone);
      break;
    }
    case State::kDone: {
      CHECK(!is_stable_callback_);
      break;
    }
  }
}

base::OnceClosure PageStabilityMonitor::PostMoveToStateClosure(
    State new_state,
    base::TimeDelta delay) {
  base::OnceClosure task =
      base::BindOnce(&PageStabilityMonitor::MoveToState,
                     weak_ptr_factory_.GetWeakPtr(), new_state);
  return base::BindOnce(
      [](scoped_refptr<base::SequencedTaskRunner> task_runner,
         base::OnceClosure task, base::TimeDelta delay) {
        task_runner->PostDelayedTask(FROM_HERE, std::move(task), delay);
      },
      base::SequencedTaskRunner::GetCurrentDefault(), std::move(task), delay);
}

void PageStabilityMonitor::SetTimeout(State timeout_type,
                                      base::TimeDelta delay) {
  CHECK(timeout_type == State::kTimeoutGlobal ||
        timeout_type == State::kTimeoutMainThread);
  PostMoveToStateClosure(timeout_type, delay).Run();
}

void PageStabilityMonitor::DCheckStateTransition(State old_state,
                                                 State new_state) {
#if DCHECK_IS_ON()
  static const base::NoDestructor<base::StateTransitions<State>> transitions(
      base::StateTransitions<State>({
          // clang-format off
          {State::kInitial,
              {State::kStartMonitoring}},
          {State::kStartMonitoring, {
              State::kWaitForNavigation,
              State::kWaitForNetworkIdle,
              State::kWaitForMainThreadIdle}},
          {State::kWaitForNavigation, {
              State::kInvokeCallback,
              State::kTimeoutGlobal}},
          {State::kWaitForNetworkIdle, {
              State::kWaitForMainThreadIdle,
              State::kTimeoutGlobal}},
          {State::kWaitForMainThreadIdle, {
              State::kEnsureMinimumDelay,
              State::kTimeoutMainThread,
              State::kTimeoutGlobal}},
          {State::kEnsureMinimumDelay, {
              State::kWaitForVisualStateRequest,
              State::kTimeoutMainThread,
              State::kTimeoutGlobal}},
          {State::kWaitForVisualStateRequest, {
              State::kInvokeCallback,
              State::kTimeoutMainThread,
              State::kTimeoutGlobal}},
          {State::kTimeoutMainThread, {
              State::kInvokeCallback}},
          {State::kTimeoutGlobal, {
              State::kInvokeCallback}},
          {State::kInvokeCallback, {
              State::kDone}}

          // kDone can be entered after various tasks are posted but before
          // they've invoked (e.g. by a timeout). As such we don't restrict what
          // state moves can be attempted from kDone but instead we never
          // transition out of it in the state machine.

          // clang-format on
      }));
  DCHECK_STATE_TRANSITION(transitions, old_state, new_state);
#endif  // DCHECK_IS_ON()
}

}  // namespace actor