File: no_state_prefetch_contents.h

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 (314 lines) | stat: -rw-r--r-- 11,257 bytes parent folder | download | duplicates (6)
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
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_NO_STATE_PREFETCH_BROWSER_NO_STATE_PREFETCH_CONTENTS_H_
#define COMPONENTS_NO_STATE_PREFETCH_BROWSER_NO_STATE_PREFETCH_CONTENTS_H_

#include <stdint.h>

#include <memory>
#include <optional>
#include <string>
#include <utility>
#include <vector>

#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_contents_delegate.h"
#include "components/no_state_prefetch/common/no_state_prefetch_canceler.mojom.h"
#include "components/no_state_prefetch/common/no_state_prefetch_final_status.h"
#include "components/no_state_prefetch/common/no_state_prefetch_origin.h"
#include "content/public/browser/web_contents_observer.h"
#include "content/public/common/referrer.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "ui/gfx/geometry/rect.h"
#include "url/origin.h"

namespace base {
class ProcessMetrics;
}

namespace content {
class BrowserContext;
class RenderViewHost;
class SessionStorageNamespace;
class WebContents;
class PreloadingAttempt;
}  // namespace content

namespace memory_instrumentation {
class GlobalMemoryDump;
}

namespace prerender {

class NoStatePrefetchManager;

class NoStatePrefetchContents
    : public content::WebContentsObserver,
      public prerender::mojom::NoStatePrefetchCanceler {
 public:
  // NoStatePrefetchContents::Create uses the currently registered Factory to
  // create the NoStatePrefetchContents. Factory is intended for testing.
  class Factory {
   public:
    Factory() = default;

    Factory(const Factory&) = delete;
    Factory& operator=(const Factory&) = delete;

    virtual ~Factory() = default;

    // Ownership is not transferred through this interface as
    // no_state_prefetch_manager and browser_context are stored as weak
    // pointers.
    virtual NoStatePrefetchContents* CreateNoStatePrefetchContents(
        std::unique_ptr<NoStatePrefetchContentsDelegate> delegate,
        NoStatePrefetchManager* no_state_prefetch_manager,
        content::BrowserContext* browser_context,
        const GURL& url,
        const content::Referrer& referrer,
        const std::optional<url::Origin>& initiator_origin,
        Origin origin) = 0;
  };

  class Observer {
   public:
    // Signals that the prefetch has started running.
    virtual void OnPrefetchStart(NoStatePrefetchContents* contents) {}

    // Signals that the prefetch has had its load event.
    virtual void OnPrefetchStopLoading(NoStatePrefetchContents* contents) {}

    // Signals that the prefetch has stopped running.
    // A NoStatePrefetchContents with an unset final status will always call
    // OnPrefetchStop before being destroyed.
    virtual void OnPrefetchStop(NoStatePrefetchContents* contents) {}

   protected:
    Observer() = default;
    virtual ~Observer() = 0;
  };

  NoStatePrefetchContents(const NoStatePrefetchContents&) = delete;
  NoStatePrefetchContents& operator=(const NoStatePrefetchContents&) = delete;

  ~NoStatePrefetchContents() override;

  // All observers of a NoStatePrefetchContents are removed after the
  // OnPrefetchStop event is sent, so there is no need to call RemoveObserver()
  // in the normal use case.
  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  bool Init();

  static Factory* CreateFactory();

  // Starts rendering the contents in the prerendered state.
  // |bounds| indicates the rectangle that the prerendered page should be in.
  // |session_storage_namespace| indicates the namespace that the prerendered
  // page should be part of. |preloading_attempt| allows to log metrics for this
  // NoStatePrefetch attempt.
  virtual void StartPrerendering(
      const gfx::Rect& bounds,
      content::SessionStorageNamespace* session_storage_namespace,
      base::WeakPtr<content::PreloadingAttempt> preloading_attempt);

  // Verifies that the prerendering is not using too many resources, and kills
  // it if not.
  void DestroyWhenUsingTooManyResources();

  content::RenderFrameHost* GetPrimaryMainFrame();

  NoStatePrefetchManager* no_state_prefetch_manager() {
    return no_state_prefetch_manager_;
  }

  const GURL& prefetch_url() const { return prefetch_url_; }
  bool has_finished_loading() const { return has_finished_loading_; }
  bool prefetching_has_started() const { return prefetching_has_started_; }

  FinalStatus final_status() const { return final_status_; }

  Origin origin() const { return origin_; }

  base::TimeTicks load_start_time() const { return load_start_time_; }

  // Indicates whether this prerendered page can be used for the provided
  // |url| and |session_storage_namespace|.
  bool Matches(
      const GURL& url,
      content::SessionStorageNamespace* session_storage_namespace) const;

  // content::WebContentsObserver implementation.
  void RenderFrameCreated(content::RenderFrameHost* render_frame_host) override;
  void DidStopLoading() override;
  void DidStartNavigation(
      content::NavigationHandle* navigation_handle) override;
  void DidRedirectNavigation(
      content::NavigationHandle* navigation_handle) override;
  void DidFinishLoad(content::RenderFrameHost* render_frame_host,
                     const GURL& validated_url) override;
  void DidFinishNavigation(
      content::NavigationHandle* navigation_handle) override;

  void PrimaryMainFrameRenderProcessGone(
      base::TerminationStatus status) override;

  // Checks that a URL may be prerendered, for one of the many redirections. If
  // the URL can not be prerendered - for example, it's an ftp URL - |this| will
  // be destroyed and false is returned. Otherwise, true is returned.
  virtual bool CheckURL(const GURL& url);

  // Adds an alias URL. If the URL can not be prerendered, |this| will be
  // destroyed and false is returned.
  bool AddAliasURL(const GURL& url);

  // The WebContents for NoStatePrefetch (may be NULL).
  content::WebContents* no_state_prefetch_contents() const {
    return no_state_prefetch_contents_.get();
  }

  // Sets the final status, calls OnDestroy and adds |this| to the
  // NoStatePrefetchManager's pending deletes list.
  void Destroy(FinalStatus reason);

  std::optional<base::Value::Dict> GetAsDict() const;

  // This function is not currently called in production since prerendered
  // contents are never used (only prefetch is supported), but it may be used in
  // the future: https://crbug.com/1126305
  void MarkAsUsedForTesting();

  bool prefetching_has_been_cancelled() const {
    return prefetching_has_been_cancelled_;
  }

  void AddNoStatePrefetchCancelerReceiver(
      mojo::PendingReceiver<prerender::mojom::NoStatePrefetchCanceler>
          receiver);

 protected:
  NoStatePrefetchContents(
      std::unique_ptr<NoStatePrefetchContentsDelegate> delegate,
      NoStatePrefetchManager* no_state_prefetch_manager,
      content::BrowserContext* browser_context,
      const GURL& url,
      const content::Referrer& referrer,
      const std::optional<url::Origin>& initiator_origin,
      Origin origin);

  // Set the final status for how the NoStatePrefetchContents was used. This
  // should only be called once, and should be called before the prerender
  // contents are destroyed.
  void SetFinalStatus(FinalStatus final_status);

  // These call out to methods on our Observers, using our observer_list_. Note
  // that NotifyPrefetchStop() also clears the observer list.
  void NotifyPrefetchStart();
  void NotifyPrefetchStopLoading();
  void NotifyPrefetchStop();

  std::unique_ptr<content::WebContents> CreateWebContents(
      content::SessionStorageNamespace* session_storage_namespace);

  bool prefetching_has_started_ = false;

  // Time at which we started to load the URL.  This is used to compute
  // the time elapsed from initiating a prerender until the time the
  // (potentially only partially) prerendered page is shown to the user.
  base::TimeTicks load_start_time_;

  // The WebContents for NoStatePrefetch; may be null.
  std::unique_ptr<content::WebContents> no_state_prefetch_contents_;

  // The session storage namespace id for use in matching. We must save it
  // rather than get it from the RenderViewHost since in the control group
  // we won't have a RenderViewHost.
  std::string session_storage_namespace_id_;

 private:
  class WebContentsDelegateImpl;

  // Needs to be able to call the constructor.
  friend class NoStatePrefetchContentsFactoryImpl;

  // Returns the ProcessMetrics for the render process, if it exists.
  void DidGetMemoryUsage(
      bool success,
      std::unique_ptr<memory_instrumentation::GlobalMemoryDump> dump);

  // Sets PreloadingFailureReason based on status corresponding to the
  // |attempt_|.
  void SetPreloadingFailureReason(FinalStatus status);

  // prerender::mojom::NoStatePrefetchCanceler:
  void CancelNoStatePrefetchForUnsupportedScheme() override;
  void CancelNoStatePrefetchAfterSubresourcesDiscovered() override;

  mojo::ReceiverSet<prerender::mojom::NoStatePrefetchCanceler>
      no_state_prefetch_canceler_receiver_set_;

  base::ObserverList<Observer>::UncheckedAndDanglingUntriaged observer_list_;

  // The prefetch manager owning this object.
  raw_ptr<NoStatePrefetchManager> no_state_prefetch_manager_;

  // The delegate that content embedders use to override this class's logic.
  std::unique_ptr<NoStatePrefetchContentsDelegate> delegate_;

  // The URL being prefetched.
  const GURL prefetch_url_;

  // Store the PreloadingAttempt for this NoStatePrefetch attempt. We store
  // WeakPtr as it is possible that the PreloadingAttempt is deleted before the
  // NoStatePrefetch is deleted.
  base::WeakPtr<content::PreloadingAttempt> attempt_ = nullptr;

  // The referrer.
  const content::Referrer referrer_;

  // The origin of the page requesting the prerender. Empty when the prerender
  // is browser initiated.
  const std::optional<url::Origin> initiator_origin_;

  // The browser context being used
  raw_ptr<content::BrowserContext> browser_context_;

  // A vector of URLs that this prerendered page matches against.
  // This array can contain more than element as a result of redirects,
  // such as HTTP redirects or javascript redirects.
  std::vector<GURL> alias_urls_;

  // True when the main frame has finished loading.
  bool has_finished_loading_ = false;

  FinalStatus final_status_;

  // Tracks whether or not prefetching has been cancelled by calling Destroy.
  // Used solely to prevent double deletion.
  bool prefetching_has_been_cancelled_ = false;

  // Pid of the render process associated with the RenderViewHost for this
  // object.
  base::ProcessId process_pid_;

  std::unique_ptr<WebContentsDelegateImpl> web_contents_delegate_;

  // Origin for this prerender.
  const Origin origin_;

  // The bounds of the WebView from the launching page.
  gfx::Rect bounds_;

  base::WeakPtrFactory<NoStatePrefetchContents> weak_factory_{this};
};

}  // namespace prerender

#endif  // COMPONENTS_NO_STATE_PREFETCH_BROWSER_NO_STATE_PREFETCH_CONTENTS_H_