Commit 7bf12bbe authored by Mugdha Lakhani's avatar Mugdha Lakhani Committed by Commit Bot

[Prerender] Remove unused files.

PrerenderManager was componentized here:
https://chromium-review.googlesource.com/c/chromium/src/+/2332194

but two files in chrome/bowser got left behind due to a rebase. This
simply deletes these files that aren't being used anymore.

Bug: 1096088
Change-Id: I7488220900c3bdda89b9bbcf4758c24ef9625ee1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2339554
Auto-Submit: Mugdha Lakhani <nator@chromium.org>
Reviewed-by: default avatarRyan Sturm <ryansturm@chromium.org>
Commit-Queue: Mugdha Lakhani <nator@chromium.org>
Cr-Commit-Position: refs/heads/master@{#795424}
parent 56afcd7b
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/prerender/browser/prerender_contents.h"
#include <stddef.h>
#include <functional>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/post_task.h"
#include "build/build_config.h"
#include "chrome/browser/prerender/prerender_contents_delegate.h"
#include "components/prerender/browser/prerender_manager.h"
#include "components/prerender/common/prerender_final_status.h"
#include "components/prerender/common/prerender_util.h"
#include "components/prerender/common/render_frame_prerender_messages.mojom.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host.h"
#include "content/public/browser/session_storage_namespace.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/frame_navigate_params.h"
#include "net/http/http_response_headers.h"
#include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h"
#include "services/service_manager/public/cpp/binder_registry.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "ui/base/page_transition_types.h"
#include "ui/gfx/geometry/size.h"
using content::BrowserThread;
using content::OpenURLParams;
using content::RenderViewHost;
using content::SessionStorageNamespace;
using content::WebContents;
namespace prerender {
class PrerenderContentsFactoryImpl : public PrerenderContents::Factory {
public:
PrerenderContents* CreatePrerenderContents(
std::unique_ptr<PrerenderContentsDelegate> delegate,
PrerenderManager* prerender_manager,
content::BrowserContext* browser_context,
const GURL& url,
const content::Referrer& referrer,
const base::Optional<url::Origin>& initiator_origin,
Origin origin) override {
return new PrerenderContents(std::move(delegate), prerender_manager,
browser_context, url, referrer,
initiator_origin, origin);
}
};
// WebContentsDelegateImpl -----------------------------------------------------
class PrerenderContents::WebContentsDelegateImpl
: public content::WebContentsDelegate {
public:
explicit WebContentsDelegateImpl(PrerenderContents* prerender_contents)
: prerender_contents_(prerender_contents) {}
// content::WebContentsDelegate implementation:
WebContents* OpenURLFromTab(WebContents* source,
const OpenURLParams& params) override {
// |OpenURLFromTab| is typically called when a frame performs a navigation
// that requires the browser to perform the transition instead of WebKit.
// Examples include client redirects to hosted app URLs.
// TODO(cbentzel): Consider supporting this for CURRENT_TAB dispositions, if
// it is a common case during prerenders.
prerender_contents_->Destroy(FINAL_STATUS_OPEN_URL);
return NULL;
}
bool ShouldTransferNavigation(bool is_main_frame_navigation) override {
// Cancel the prerender if the navigation attempts to transfer to a
// different process. Examples include server redirects to privileged pages
// or cross-site subframe navigations in --site-per-process.
prerender_contents_->Destroy(FINAL_STATUS_OPEN_URL);
return false;
}
void CanDownload(const GURL& url,
const std::string& request_method,
base::OnceCallback<void(bool)> callback) override {
prerender_contents_->Destroy(FINAL_STATUS_DOWNLOAD);
// Cancel the download.
std::move(callback).Run(false);
}
bool OnGoToEntryOffset(int offset) override {
// This isn't allowed because the history merge operation
// does not work if there are renderer issued challenges.
// TODO(cbentzel): Cancel in this case? May not need to do
// since render-issued offset navigations are not guaranteed,
// but indicates that the page cares about the history.
return false;
}
gfx::Size GetSizeForNewRenderView(WebContents* web_contents) override {
// Have to set the size of the RenderView on initialization to be sure it is
// set before the RenderView is hidden on all platforms (esp. Android).
return prerender_contents_->bounds_.size();
}
private:
PrerenderContents* prerender_contents_;
};
PrerenderContents::Observer::~Observer() {}
PrerenderContents::PrerenderContents(
std::unique_ptr<PrerenderContentsDelegate> delegate,
PrerenderManager* prerender_manager,
content::BrowserContext* browser_context,
const GURL& url,
const content::Referrer& referrer,
const base::Optional<url::Origin>& initiator_origin,
Origin origin)
: prerender_mode_(prerender::mojom::PrerenderMode::kNoPrerender),
prerendering_has_started_(false),
prerender_manager_(prerender_manager),
delegate_(std::move(delegate)),
prerender_url_(url),
referrer_(referrer),
initiator_origin_(initiator_origin),
browser_context_(browser_context),
has_finished_loading_(false),
final_status_(FINAL_STATUS_UNKNOWN),
prerendering_has_been_cancelled_(false),
process_pid_(base::kNullProcessId),
child_id_(-1),
route_id_(-1),
origin_(origin),
network_bytes_(0) {
switch (origin) {
case ORIGIN_OMNIBOX:
case ORIGIN_EXTERNAL_REQUEST:
case ORIGIN_EXTERNAL_REQUEST_FORCED_PRERENDER:
case ORIGIN_NAVIGATION_PREDICTOR:
case ORIGIN_ISOLATED_PRERENDER:
DCHECK(!initiator_origin_.has_value());
break;
case ORIGIN_GWS_PRERENDER:
case ORIGIN_LINK_REL_PRERENDER_SAMEDOMAIN:
case ORIGIN_LINK_REL_PRERENDER_CROSSDOMAIN:
case ORIGIN_LINK_REL_NEXT:
DCHECK(initiator_origin_.has_value());
break;
case ORIGIN_NONE:
case ORIGIN_MAX:
NOTREACHED();
}
DCHECK(prerender_manager);
}
bool PrerenderContents::Init() {
return AddAliasURL(prerender_url_);
}
void PrerenderContents::SetPrerenderMode(prerender::mojom::PrerenderMode mode) {
DCHECK(!prerendering_has_started_);
prerender_mode_ = mode;
}
// static
PrerenderContents::Factory* PrerenderContents::CreateFactory() {
return new PrerenderContentsFactoryImpl();
}
void PrerenderContents::StartPrerendering(
const gfx::Rect& bounds,
SessionStorageNamespace* session_storage_namespace) {
DCHECK(browser_context_);
DCHECK(!bounds.IsEmpty());
DCHECK(!prerendering_has_started_);
DCHECK(!prerender_contents_);
DCHECK_EQ(1U, alias_urls_.size());
session_storage_namespace_id_ = session_storage_namespace->id();
bounds_ = bounds;
DCHECK(load_start_time_.is_null());
load_start_time_ = base::TimeTicks::Now();
prerendering_has_started_ = true;
prerender_contents_ = CreateWebContents(session_storage_namespace);
content::WebContentsObserver::Observe(prerender_contents_.get());
delegate_->OnPrerenderContentsCreated(prerender_contents_.get());
web_contents_delegate_.reset(new WebContentsDelegateImpl(this));
prerender_contents_.get()->SetDelegate(web_contents_delegate_.get());
// Set the size of the prerender WebContents.
prerender_contents_.get()->Resize(bounds_);
// TODO(davidben): This logic assumes each prerender has at most one
// route. https://crbug.com/440544
child_id_ = GetRenderViewHost()->GetProcess()->GetID();
route_id_ = GetRenderViewHost()->GetRoutingID();
// TODO(davidben): This logic assumes each prerender has at most one
// process. https://crbug.com/440544
prerender_manager()->AddPrerenderProcessHost(
GetRenderViewHost()->GetProcess());
NotifyPrerenderStart();
// Register to inform new RenderViews that we're prerendering.
notification_registrar_.Add(
this, content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
content::Source<WebContents>(prerender_contents_.get()));
content::NavigationController::LoadURLParams load_url_params(prerender_url_);
load_url_params.referrer = referrer_;
load_url_params.initiator_origin = initiator_origin_;
load_url_params.transition_type = ui::PAGE_TRANSITION_LINK;
if (origin_ == ORIGIN_OMNIBOX) {
load_url_params.transition_type = ui::PageTransitionFromInt(
ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR);
} else if (origin_ == ORIGIN_NAVIGATION_PREDICTOR) {
load_url_params.transition_type =
ui::PageTransitionFromInt(ui::PAGE_TRANSITION_GENERATED);
}
prerender_contents_.get()->GetController().LoadURLWithParams(load_url_params);
}
bool PrerenderContents::GetChildId(int* child_id) const {
CHECK(child_id);
DCHECK_GE(child_id_, -1);
*child_id = child_id_;
return child_id_ != -1;
}
bool PrerenderContents::GetRouteId(int* route_id) const {
CHECK(route_id);
DCHECK_GE(route_id_, -1);
*route_id = route_id_;
return route_id_ != -1;
}
void PrerenderContents::SetFinalStatus(FinalStatus final_status) {
DCHECK_GE(final_status, FINAL_STATUS_USED);
DCHECK_LT(final_status, FINAL_STATUS_MAX);
DCHECK_EQ(FINAL_STATUS_UNKNOWN, final_status_);
final_status_ = final_status;
}
PrerenderContents::~PrerenderContents() {
DCHECK_NE(FINAL_STATUS_UNKNOWN, final_status());
DCHECK(prerendering_has_been_cancelled() ||
final_status() == FINAL_STATUS_USED);
DCHECK_NE(ORIGIN_MAX, origin());
prerender_manager_->RecordFinalStatus(origin(), final_status());
prerender_manager_->RecordNetworkBytesConsumed(origin(), network_bytes_);
if (!prerender_contents_)
return;
// If we still have a WebContents, clean up anything we need to and then
// destroy it.
std::unique_ptr<WebContents> contents = ReleasePrerenderContents();
}
void PrerenderContents::AddObserver(Observer* observer) {
DCHECK_EQ(FINAL_STATUS_UNKNOWN, final_status_);
observer_list_.AddObserver(observer);
}
void PrerenderContents::RemoveObserver(Observer* observer) {
observer_list_.RemoveObserver(observer);
}
void PrerenderContents::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
switch (type) {
case content::NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED: {
if (prerender_contents_.get()) {
DCHECK_EQ(content::Source<WebContents>(source).ptr(),
prerender_contents_.get());
content::Details<RenderViewHost> new_render_view_host(details);
OnRenderViewHostCreated(new_render_view_host.ptr());
// Make sure the size of the RenderViewHost has been passed to the new
// RenderView. Otherwise, the size may not be sent until the
// RenderViewReady event makes it from the render process to the UI
// thread of the browser process. When the RenderView receives its
// size, is also sets itself to be visible, which would then break the
// visibility API.
new_render_view_host->GetWidget()->SynchronizeVisualProperties();
prerender_contents_->WasHidden();
}
break;
}
default:
NOTREACHED() << "Unexpected notification sent.";
break;
}
}
void PrerenderContents::OnRenderViewHostCreated(
RenderViewHost* new_render_view_host) {}
std::unique_ptr<WebContents> PrerenderContents::CreateWebContents(
SessionStorageNamespace* session_storage_namespace) {
// TODO(ajwong): Remove the temporary map once prerendering is aware of
// multiple session storage namespaces per tab.
content::SessionStorageNamespaceMap session_storage_namespace_map;
session_storage_namespace_map[std::string()] = session_storage_namespace;
return WebContents::CreateWithSessionStorage(
WebContents::CreateParams(browser_context_),
session_storage_namespace_map);
}
void PrerenderContents::NotifyPrerenderStart() {
DCHECK_EQ(FINAL_STATUS_UNKNOWN, final_status_);
for (Observer& observer : observer_list_)
observer.OnPrerenderStart(this);
}
void PrerenderContents::NotifyPrerenderStopLoading() {
for (Observer& observer : observer_list_)
observer.OnPrerenderStopLoading(this);
}
void PrerenderContents::NotifyPrerenderDomContentLoaded() {
for (Observer& observer : observer_list_)
observer.OnPrerenderDomContentLoaded(this);
}
void PrerenderContents::NotifyPrerenderStop() {
DCHECK_NE(FINAL_STATUS_UNKNOWN, final_status_);
for (Observer& observer : observer_list_)
observer.OnPrerenderStop(this);
observer_list_.Clear();
}
bool PrerenderContents::CheckURL(const GURL& url) {
if (!url.SchemeIsHTTPOrHTTPS()) {
Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME);
return false;
}
if (prerender_manager_->HasRecentlyBeenNavigatedTo(origin(), url)) {
Destroy(FINAL_STATUS_RECENTLY_VISITED);
return false;
}
return true;
}
bool PrerenderContents::AddAliasURL(const GURL& url) {
if (!CheckURL(url))
return false;
alias_urls_.push_back(url);
return true;
}
bool PrerenderContents::Matches(
const GURL& url,
SessionStorageNamespace* session_storage_namespace) const {
// TODO(davidben): Remove any consumers that pass in a NULL
// session_storage_namespace and only test with matches.
if (session_storage_namespace &&
session_storage_namespace_id_ != session_storage_namespace->id()) {
return false;
}
return base::Contains(alias_urls_, url);
}
void PrerenderContents::RenderProcessGone(base::TerminationStatus status) {
if (status == base::TERMINATION_STATUS_STILL_RUNNING) {
// The renderer process is being killed because of the browser/test
// shutdown, before the termination notification is received.
Destroy(FINAL_STATUS_APP_TERMINATING);
}
Destroy(FINAL_STATUS_RENDERER_CRASHED);
}
void PrerenderContents::RenderFrameCreated(
content::RenderFrameHost* render_frame_host) {
// When a new RenderFrame is created for a prerendering WebContents, tell the
// new RenderFrame it's being used for prerendering before any navigations
// occur. Note that this is always triggered before the first navigation, so
// there's no need to send the message just after the WebContents is created.
mojo::AssociatedRemote<prerender::mojom::PrerenderMessages>
prerender_render_frame;
render_frame_host->GetRemoteAssociatedInterfaces()->GetInterface(
&prerender_render_frame);
prerender_render_frame->SetIsPrerendering(
prerender_mode_, PrerenderHistograms::GetHistogramPrefix(origin_));
}
void PrerenderContents::DidStopLoading() {
NotifyPrerenderStopLoading();
}
void PrerenderContents::DOMContentLoaded(
content::RenderFrameHost* render_frame_host) {
if (!render_frame_host->GetParent())
NotifyPrerenderDomContentLoaded();
}
void PrerenderContents::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame() ||
navigation_handle->IsSameDocument()) {
return;
}
if (!CheckURL(navigation_handle->GetURL()))
return;
// Usually, this event fires if the user clicks or enters a new URL.
// Neither of these can happen in the case of an invisible prerender.
// So the cause is: Some JavaScript caused a new URL to be loaded. In that
// case, the spinner would start again in the browser, so we must reset
// has_finished_loading_ so that the spinner won't be stopped.
has_finished_loading_ = false;
}
void PrerenderContents::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame())
return;
// If it's a redirect on the top-level resource, the name needs to be
// remembered for future matching, and if it redirects to an https resource,
// it needs to be canceled. If a subresource is redirected, nothing changes.
CheckURL(navigation_handle->GetURL());
}
void PrerenderContents::DidFinishLoad(
content::RenderFrameHost* render_frame_host,
const GURL& validated_url) {
if (!render_frame_host->GetParent())
has_finished_loading_ = true;
}
void PrerenderContents::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInMainFrame() ||
!navigation_handle->HasCommitted() || navigation_handle->IsErrorPage()) {
return;
}
if (navigation_handle->GetResponseHeaders() &&
navigation_handle->GetResponseHeaders()->response_code() >= 400) {
// Maintain same behavior as old navigation API when the URL is unreachable
// and leads to an error page. While there will be a subsequent navigation
// that has navigation_handle->IsErrorPage(), it'll be too late to wait for
// it as the renderer side will consider this prerender complete. This
// object would therefore have been destructed already and so instead look
// for the error response code now.
// Also maintain same final status code that previous navigation API
// returned, which was reached because the URL for the error page was
// kUnreachableWebDataURL and that was interpreted as unsupported scheme.
Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME);
return;
}
// Add each redirect as an alias. |navigation_handle->GetURL()| is included in
// |navigation_handle->GetRedirectChain()|.
//
// TODO(davidben): We do not correctly patch up history for renderer-initated
// navigations which add history entries. http://crbug.com/305660.
for (const auto& redirect : navigation_handle->GetRedirectChain()) {
if (!AddAliasURL(redirect))
return;
}
}
void PrerenderContents::Destroy(FinalStatus final_status) {
DCHECK_NE(final_status, FINAL_STATUS_USED);
if (prerendering_has_been_cancelled_)
return;
SetFinalStatus(final_status);
prerendering_has_been_cancelled_ = true;
prerender_manager_->AddToHistory(this);
prerender_manager_->SetPrefetchFinalStatusForUrl(prerender_url_,
final_status);
prerender_manager_->MoveEntryToPendingDelete(this, final_status);
if (prerendering_has_started())
NotifyPrerenderStop();
}
void PrerenderContents::DestroyWhenUsingTooManyResources() {
if (process_pid_ == base::kNullProcessId) {
RenderViewHost* rvh = GetRenderViewHost();
if (!rvh)
return;
content::RenderProcessHost* rph = rvh->GetProcess();
if (!rph)
return;
base::ProcessHandle handle = rph->GetProcess().Handle();
if (handle == base::kNullProcessHandle)
return;
process_pid_ = rph->GetProcess().Pid();
}
if (process_pid_ == base::kNullProcessId)
return;
// Using AdaptCallbackForRepeating allows for an easier transition to
// OnceCallbacks for https://crbug.com/714018.
memory_instrumentation::MemoryInstrumentation::GetInstance()
->RequestPrivateMemoryFootprint(
process_pid_, base::AdaptCallbackForRepeating(base::BindOnce(
&PrerenderContents::DidGetMemoryUsage,
weak_factory_.GetWeakPtr())));
}
void PrerenderContents::DidGetMemoryUsage(
bool success,
std::unique_ptr<memory_instrumentation::GlobalMemoryDump> global_dump) {
if (!success)
return;
for (const memory_instrumentation::GlobalMemoryDump::ProcessDump& dump :
global_dump->process_dumps()) {
if (dump.pid() != process_pid_)
continue;
// If |final_status_| == |FINAL_STATUS_USED|, then destruction will be
// handled by the entity that set final_status_.
if (dump.os_dump().private_footprint_kb * 1024 >
prerender_manager_->config().max_bytes &&
final_status_ != FINAL_STATUS_USED) {
Destroy(FINAL_STATUS_MEMORY_LIMIT_EXCEEDED);
}
return;
}
}
std::unique_ptr<WebContents> PrerenderContents::ReleasePrerenderContents() {
prerender_contents_->SetDelegate(nullptr);
content::WebContentsObserver::Observe(nullptr);
delegate_->ReleasePrerenderContents(prerender_contents_.get());
return std::move(prerender_contents_);
}
RenderViewHost* PrerenderContents::GetRenderViewHost() {
return prerender_contents_ ? prerender_contents_->GetRenderViewHost()
: nullptr;
}
std::unique_ptr<base::DictionaryValue> PrerenderContents::GetAsValue() const {
if (!prerender_contents_)
return nullptr;
auto dict_value = std::make_unique<base::DictionaryValue>();
dict_value->SetString("url", prerender_url_.spec());
base::TimeTicks current_time = base::TimeTicks::Now();
base::TimeDelta duration = current_time - load_start_time_;
dict_value->SetInteger("duration", duration.InSeconds());
dict_value->SetBoolean(
"is_loaded", prerender_contents_ && !prerender_contents_->IsLoading());
return dict_value;
}
void PrerenderContents::PrepareForUse() {
SetFinalStatus(FINAL_STATUS_USED);
if (prerender_contents_.get()) {
auto frames = prerender_contents_->GetAllFrames();
for (auto* frame : frames) {
mojo::AssociatedRemote<prerender::mojom::PrerenderMessages>
prerender_render_frame;
frame->GetRemoteAssociatedInterfaces()->GetInterface(
&prerender_render_frame);
prerender_render_frame->SetIsPrerendering(
prerender::mojom::PrerenderMode::kNoPrerender, std::string());
}
}
NotifyPrerenderStop();
}
void PrerenderContents::CancelPrerenderForUnsupportedScheme() {
Destroy(FINAL_STATUS_UNSUPPORTED_SCHEME);
}
void PrerenderContents::CancelPrerenderForNoStatePrefetch() {
Destroy(FINAL_STATUS_NOSTATE_PREFETCH_FINISHED);
}
void PrerenderContents::AddPrerenderCancelerReceiver(
mojo::PendingReceiver<prerender::mojom::PrerenderCanceler> receiver) {
prerender_canceler_receiver_set_.Add(this, std::move(receiver));
}
void PrerenderContents::AddNetworkBytes(int64_t bytes) {
network_bytes_ += bytes;
for (Observer& observer : observer_list_)
observer.OnPrerenderNetworkBytesChanged(this);
}
} // namespace prerender
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/prerender/browser/prerender_manager.h"
#include <stddef.h>
#include <algorithm>
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/check_op.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/notreached.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/system/sys_info.h"
#include "base/test/simple_test_tick_clock.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "base/values.h"
#include "chrome/browser/net/prediction_options.h"
#include "chrome/browser/predictors/loading_predictor.h"
#include "chrome/browser/predictors/loading_predictor_factory.h"
#include "chrome/browser/prerender/prerender_manager_delegate.h"
#include "chrome/browser/prerender/prerender_tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/prerender/browser/prerender_contents.h"
#include "components/prerender/browser/prerender_field_trial.h"
#include "components/prerender/browser/prerender_handle.h"
#include "components/prerender/browser/prerender_histograms.h"
#include "components/prerender/browser/prerender_history.h"
#include "components/prerender/browser/prerender_util.h"
#include "components/prerender/common/prerender_final_status.h"
#include "components/prerender/common/prerender_types.mojom.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/session_storage_namespace.h"
#include "content/public/browser/site_instance.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/common/url_constants.h"
#include "extensions/common/constants.h"
#include "net/http/http_cache.h"
#include "net/http/http_request_headers.h"
#include "third_party/blink/public/common/prerender/prerender_rel_type.h"
#include "ui/gfx/geometry/rect.h"
using chrome_browser_net::NetworkPredictionStatus;
using content::BrowserThread;
using content::RenderViewHost;
using content::SessionStorageNamespace;
using content::WebContents;
namespace prerender {
namespace {
// Time interval at which periodic cleanups are performed.
constexpr base::TimeDelta kPeriodicCleanupInterval =
base::TimeDelta::FromMilliseconds(1000);
// Time interval after which OnCloseWebContentsDeleter will schedule a
// WebContents for deletion.
constexpr base::TimeDelta kDeleteWithExtremePrejudice =
base::TimeDelta::FromSeconds(3);
// Length of prerender history, for display in chrome://net-internals
constexpr int kHistoryLength = 100;
} // namespace
class PrerenderManager::OnCloseWebContentsDeleter
: public content::WebContentsDelegate,
public base::SupportsWeakPtr<
PrerenderManager::OnCloseWebContentsDeleter> {
public:
OnCloseWebContentsDeleter(PrerenderManager* manager,
std::unique_ptr<WebContents> tab)
: manager_(manager), tab_(std::move(tab)) {
tab_->SetDelegate(this);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::BindOnce(
&OnCloseWebContentsDeleter::ScheduleWebContentsForDeletion,
AsWeakPtr(), /*timeout=*/true),
kDeleteWithExtremePrejudice);
}
void CloseContents(WebContents* source) override {
DCHECK_EQ(tab_.get(), source);
ScheduleWebContentsForDeletion(/*timeout=*/false);
}
private:
void ScheduleWebContentsForDeletion(bool timeout) {
UMA_HISTOGRAM_BOOLEAN("Prerender.TabContentsDeleterTimeout", timeout);
tab_->SetDelegate(nullptr);
manager_->ScheduleDeleteOldWebContents(std::move(tab_), this);
// |this| is deleted at this point.
}
PrerenderManager* const manager_;
std::unique_ptr<WebContents> tab_;
DISALLOW_COPY_AND_ASSIGN(OnCloseWebContentsDeleter);
};
PrerenderManagerObserver::~PrerenderManagerObserver() = default;
// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
PRERENDER_MODE_NOSTATE_PREFETCH;
struct PrerenderManager::NavigationRecord {
NavigationRecord(const GURL& url, base::TimeTicks time, Origin origin)
: url(url), time(time), origin(origin) {}
GURL url;
base::TimeTicks time;
Origin origin;
FinalStatus final_status = FINAL_STATUS_UNKNOWN;
};
PrerenderManager::PrerenderManager(
Profile* profile,
std::unique_ptr<PrerenderManagerDelegate> delegate)
: profile_(profile),
delegate_(std::move(delegate)),
prerender_contents_factory_(PrerenderContents::CreateFactory()),
prerender_history_(std::make_unique<PrerenderHistory>(kHistoryLength)),
histograms_(std::make_unique<PrerenderHistograms>()),
tick_clock_(base::DefaultTickClock::GetInstance()) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
last_prerender_start_time_ =
GetCurrentTimeTicks() -
base::TimeDelta::FromMilliseconds(kMinTimeBetweenPrerendersMs);
}
PrerenderManager::~PrerenderManager() {
// The earlier call to KeyedService::Shutdown() should have
// emptied these vectors already.
DCHECK(active_prerenders_.empty());
DCHECK(to_delete_prerenders_.empty());
for (auto* host : prerender_process_hosts_) {
host->RemoveObserver(this);
}
}
void PrerenderManager::Shutdown() {
DestroyAllContents(FINAL_STATUS_PROFILE_DESTROYED);
on_close_web_contents_deleters_.clear();
profile_ = nullptr;
DCHECK(active_prerenders_.empty());
}
std::unique_ptr<PrerenderHandle>
PrerenderManager::AddPrerenderFromLinkRelPrerender(
int process_id,
int route_id,
const GURL& url,
const uint32_t rel_types,
const content::Referrer& referrer,
const url::Origin& initiator_origin,
const gfx::Size& size) {
Origin origin = rel_types & blink::kPrerenderRelTypePrerender
? ORIGIN_LINK_REL_PRERENDER_CROSSDOMAIN
: ORIGIN_LINK_REL_NEXT;
SessionStorageNamespace* session_storage_namespace = nullptr;
// Unit tests pass in a process_id == -1.
if (process_id != -1) {
RenderViewHost* source_render_view_host =
RenderViewHost::FromID(process_id, route_id);
if (!source_render_view_host)
return nullptr;
WebContents* source_web_contents =
WebContents::FromRenderViewHost(source_render_view_host);
if (!source_web_contents)
return nullptr;
if (origin == ORIGIN_LINK_REL_PRERENDER_CROSSDOMAIN &&
source_web_contents->GetURL().host_piece() == url.host_piece()) {
origin = ORIGIN_LINK_REL_PRERENDER_SAMEDOMAIN;
}
// TODO(ajwong): This does not correctly handle storage for isolated apps.
session_storage_namespace = source_web_contents->GetController()
.GetDefaultSessionStorageNamespace();
}
return AddPrerenderWithPreconnectFallback(origin, url, referrer,
initiator_origin, gfx::Rect(size),
session_storage_namespace);
}
std::unique_ptr<PrerenderHandle> PrerenderManager::AddPrerenderFromOmnibox(
const GURL& url,
SessionStorageNamespace* session_storage_namespace,
const gfx::Size& size) {
return AddPrerenderWithPreconnectFallback(
ORIGIN_OMNIBOX, url, content::Referrer(), base::nullopt, gfx::Rect(size),
session_storage_namespace);
}
std::unique_ptr<PrerenderHandle>
PrerenderManager::AddPrerenderFromNavigationPredictor(
const GURL& url,
SessionStorageNamespace* session_storage_namespace,
const gfx::Size& size) {
DCHECK(IsNoStatePrefetchEnabled());
return AddPrerenderWithPreconnectFallback(
ORIGIN_NAVIGATION_PREDICTOR, url, content::Referrer(), base::nullopt,
gfx::Rect(size), session_storage_namespace);
}
std::unique_ptr<PrerenderHandle> PrerenderManager::AddIsolatedPrerender(
const GURL& url,
SessionStorageNamespace* session_storage_namespace,
const gfx::Size& size) {
DCHECK(IsNoStatePrefetchEnabled());
// The preconnect fallback won't happen.
return AddPrerenderWithPreconnectFallback(
ORIGIN_ISOLATED_PRERENDER, url, content::Referrer(), base::nullopt,
gfx::Rect(size), session_storage_namespace);
}
std::unique_ptr<PrerenderHandle>
PrerenderManager::AddPrerenderFromExternalRequest(
const GURL& url,
const content::Referrer& referrer,
SessionStorageNamespace* session_storage_namespace,
const gfx::Rect& bounds) {
return AddPrerenderWithPreconnectFallback(ORIGIN_EXTERNAL_REQUEST, url,
referrer, base::nullopt, bounds,
session_storage_namespace);
}
std::unique_ptr<PrerenderHandle>
PrerenderManager::AddForcedPrerenderFromExternalRequest(
const GURL& url,
const content::Referrer& referrer,
SessionStorageNamespace* session_storage_namespace,
const gfx::Rect& bounds) {
return AddPrerenderWithPreconnectFallback(
ORIGIN_EXTERNAL_REQUEST_FORCED_PRERENDER, url, referrer, base::nullopt,
bounds, session_storage_namespace);
}
void PrerenderManager::CancelAllPrerenders() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
while (!active_prerenders_.empty()) {
PrerenderContents* prerender_contents =
active_prerenders_.front()->contents();
prerender_contents->Destroy(FINAL_STATUS_CANCELLED);
}
}
void PrerenderManager::MoveEntryToPendingDelete(PrerenderContents* entry,
FinalStatus final_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(entry);
auto it = FindIteratorForPrerenderContents(entry);
DCHECK(it != active_prerenders_.end());
to_delete_prerenders_.push_back(std::move(*it));
active_prerenders_.erase(it);
// Destroy the old WebContents relatively promptly to reduce resource usage.
PostCleanupTask();
}
bool PrerenderManager::IsWebContentsPrerendering(
const WebContents* web_contents,
Origin* origin) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
PrerenderContents* prerender_contents = GetPrerenderContents(web_contents);
if (!prerender_contents)
return false;
if (origin)
*origin = prerender_contents->origin();
return true;
}
bool PrerenderManager::HasPrerenderedUrl(
GURL url,
content::WebContents* web_contents) const {
content::SessionStorageNamespace* session_storage_namespace =
web_contents->GetController().GetDefaultSessionStorageNamespace();
for (const auto& prerender_data : active_prerenders_) {
PrerenderContents* prerender_contents = prerender_data->contents();
if (prerender_contents->Matches(url, session_storage_namespace))
return true;
}
return false;
}
bool PrerenderManager::HasPrerenderedAndFinishedLoadingUrl(
GURL url,
content::WebContents* web_contents) const {
content::SessionStorageNamespace* session_storage_namespace =
web_contents->GetController().GetDefaultSessionStorageNamespace();
for (const auto& prerender_data : active_prerenders_) {
PrerenderContents* prerender_contents = prerender_data->contents();
if (prerender_contents->Matches(url, session_storage_namespace) &&
prerender_contents->has_finished_loading()) {
return true;
}
}
return false;
}
PrerenderContents* PrerenderManager::GetPrerenderContents(
const content::WebContents* web_contents) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (const auto& prerender : active_prerenders_) {
WebContents* prerender_web_contents =
prerender->contents()->prerender_contents();
if (prerender_web_contents == web_contents) {
return prerender->contents();
}
}
// Also check the pending-deletion list. If the prerender is in pending
// delete, anyone with a handle on the WebContents needs to know.
for (const auto& prerender : to_delete_prerenders_) {
WebContents* prerender_web_contents =
prerender->contents()->prerender_contents();
if (prerender_web_contents == web_contents) {
return prerender->contents();
}
}
return nullptr;
}
PrerenderContents* PrerenderManager::GetPrerenderContentsForRoute(
int child_id,
int route_id) const {
WebContents* web_contents = nullptr;
RenderViewHost* render_view_host = RenderViewHost::FromID(child_id, route_id);
web_contents = WebContents::FromRenderViewHost(render_view_host);
return web_contents ? GetPrerenderContents(web_contents) : nullptr;
}
PrerenderContents* PrerenderManager::GetPrerenderContentsForProcess(
int render_process_id) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& prerender_data : active_prerenders_) {
PrerenderContents* prerender_contents = prerender_data->contents();
if (prerender_contents->GetRenderViewHost()->GetProcess()->GetID() ==
render_process_id) {
return prerender_contents;
}
}
return nullptr;
}
std::vector<WebContents*>
PrerenderManager::GetAllNoStatePrefetchingContentsForTesting() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::vector<WebContents*> result;
for (const auto& prerender : active_prerenders_) {
WebContents* contents = prerender->contents()->prerender_contents();
if (contents && prerender->contents()->prerender_mode() ==
prerender::mojom::PrerenderMode::kPrefetchOnly) {
result.push_back(contents);
}
}
return result;
}
bool PrerenderManager::HasRecentlyBeenNavigatedTo(Origin origin,
const GURL& url) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
CleanUpOldNavigations(&navigations_, base::TimeDelta::FromMilliseconds(
kNavigationRecordWindowMs));
for (auto it = navigations_.rbegin(); it != navigations_.rend(); ++it) {
if (it->url == url)
return true;
}
return false;
}
std::unique_ptr<base::DictionaryValue> PrerenderManager::CopyAsValue() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto dict_value = std::make_unique<base::DictionaryValue>();
dict_value->Set("history", prerender_history_->CopyEntriesAsValue());
dict_value->Set("active", GetActivePrerendersAsValue());
dict_value->SetBoolean(
"enabled", GetPredictionStatus() == NetworkPredictionStatus::ENABLED);
std::string disabled_note;
if (GetPredictionStatus() == NetworkPredictionStatus::DISABLED_ALWAYS)
disabled_note = "Disabled by user setting";
if (GetPredictionStatus() == NetworkPredictionStatus::DISABLED_DUE_TO_NETWORK)
disabled_note = "Disabled on cellular connection by default";
dict_value->SetString("disabled_note", disabled_note);
// If prerender is disabled via a flag this method is not even called.
std::string enabled_note;
dict_value->SetString("enabled_note", enabled_note);
return dict_value;
}
void PrerenderManager::ClearData(int clear_flags) {
DCHECK_GE(clear_flags, 0);
DCHECK_LT(clear_flags, CLEAR_MAX);
if (clear_flags & CLEAR_PRERENDER_CONTENTS)
DestroyAllContents(FINAL_STATUS_CACHE_OR_HISTORY_CLEARED);
// This has to be second, since destroying prerenders can add to the history.
if (clear_flags & CLEAR_PRERENDER_HISTORY)
prerender_history_->Clear();
}
void PrerenderManager::RecordFinalStatus(Origin origin,
FinalStatus final_status) const {
histograms_->RecordFinalStatus(origin, final_status);
}
void PrerenderManager::RecordNavigation(const GURL& url) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
navigations_.emplace_back(url, GetCurrentTimeTicks(), ORIGIN_NONE);
CleanUpOldNavigations(&navigations_, base::TimeDelta::FromMilliseconds(
kNavigationRecordWindowMs));
}
struct PrerenderManager::PrerenderData::OrderByExpiryTime {
bool operator()(const std::unique_ptr<PrerenderData>& a,
const std::unique_ptr<PrerenderData>& b) const {
return a->expiry_time() < b->expiry_time();
}
};
PrerenderManager::PrerenderData::PrerenderData(
PrerenderManager* manager,
std::unique_ptr<PrerenderContents> contents,
base::TimeTicks expiry_time)
: manager_(manager),
contents_(std::move(contents)),
expiry_time_(expiry_time) {
DCHECK(contents_);
}
PrerenderManager::PrerenderData::~PrerenderData() = default;
void PrerenderManager::PrerenderData::OnHandleCreated(PrerenderHandle* handle) {
DCHECK(contents_);
++handle_count_;
contents_->AddObserver(handle);
}
void PrerenderManager::PrerenderData::OnHandleNavigatedAway(
PrerenderHandle* handle) {
DCHECK_LT(0, handle_count_);
DCHECK(contents_);
if (abandon_time_.is_null())
abandon_time_ = base::TimeTicks::Now();
// We intentionally don't decrement the handle count here, so that the
// prerender won't be canceled until it times out.
manager_->SourceNavigatedAway(this);
}
void PrerenderManager::PrerenderData::OnHandleCanceled(
PrerenderHandle* handle) {
DCHECK_LT(0, handle_count_);
DCHECK(contents_);
if (--handle_count_ == 0) {
// This will eventually remove this object from |active_prerenders_|.
contents_->Destroy(FINAL_STATUS_CANCELLED);
}
}
std::unique_ptr<PrerenderContents>
PrerenderManager::PrerenderData::ReleaseContents() {
return std::move(contents_);
}
void PrerenderManager::SourceNavigatedAway(PrerenderData* prerender_data) {
// The expiry time of our prerender data will likely change because of
// this navigation. This requires a re-sort of |active_prerenders_|.
for (auto it = active_prerenders_.begin(); it != active_prerenders_.end();
++it) {
PrerenderData* data = it->get();
if (data == prerender_data) {
data->set_expiry_time(std::min(data->expiry_time(),
GetExpiryTimeForNavigatedAwayPrerender()));
SortActivePrerenders();
return;
}
}
}
bool PrerenderManager::IsLowEndDevice() const {
return base::SysInfo::IsLowEndDevice();
}
void PrerenderManager::MaybePreconnect(Origin origin,
const GURL& url_arg) const {
delegate_->MaybePreconnect(url_arg);
}
std::unique_ptr<PrerenderHandle>
PrerenderManager::AddPrerenderWithPreconnectFallback(
Origin origin,
const GURL& url_arg,
const content::Referrer& referrer,
const base::Optional<url::Origin>& initiator_origin,
const gfx::Rect& bounds,
SessionStorageNamespace* session_storage_namespace) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Disallow prerendering on low end devices.
if (IsLowEndDevice()) {
SkipPrerenderContentsAndMaybePreconnect(url_arg, origin,
FINAL_STATUS_LOW_END_DEVICE);
return nullptr;
}
if ((origin == ORIGIN_LINK_REL_PRERENDER_CROSSDOMAIN ||
origin == ORIGIN_LINK_REL_PRERENDER_SAMEDOMAIN) &&
IsGoogleOriginURL(referrer.url)) {
origin = ORIGIN_GWS_PRERENDER;
}
GURL url = url_arg;
if (delegate_->GetCookieSettings()->ShouldBlockThirdPartyCookies()) {
SkipPrerenderContentsAndMaybePreconnect(
url, origin, FINAL_STATUS_BLOCK_THIRD_PARTY_COOKIES);
return nullptr;
}
NetworkPredictionStatus prerendering_status =
GetPredictionStatusForOrigin(origin);
if (prerendering_status != NetworkPredictionStatus::ENABLED) {
FinalStatus final_status =
prerendering_status == NetworkPredictionStatus::DISABLED_DUE_TO_NETWORK
? FINAL_STATUS_CELLULAR_NETWORK
: FINAL_STATUS_PRERENDERING_DISABLED;
SkipPrerenderContentsAndMaybePreconnect(url, origin, final_status);
return nullptr;
}
if (PrerenderData* preexisting_prerender_data =
FindPrerenderData(url, session_storage_namespace)) {
SkipPrerenderContentsAndMaybePreconnect(url, origin,
FINAL_STATUS_DUPLICATE);
return base::WrapUnique(new PrerenderHandle(preexisting_prerender_data));
}
if (IsNoStatePrefetchEnabled()) {
base::TimeDelta prefetch_age;
GetPrefetchInformation(url, &prefetch_age, nullptr /* final_status*/,
nullptr /* origin */);
if (!prefetch_age.is_zero() &&
prefetch_age <
base::TimeDelta::FromMinutes(net::HttpCache::kPrefetchReuseMins)) {
SkipPrerenderContentsAndMaybePreconnect(url, origin,
FINAL_STATUS_DUPLICATE);
return nullptr;
}
}
// Do not prerender if there are too many render processes, and we would
// have to use an existing one. We do not want prerendering to happen in
// a shared process, so that we can always reliably lower the CPU
// priority for prerendering.
// In single-process mode, ShouldTryToUseExistingProcessHost() always returns
// true, so that case needs to be explicitly checked for.
// TODO(tburkard): Figure out how to cancel prerendering in the opposite
// case, when a new tab is added to a process used for prerendering.
// TODO(ppi): Check whether there are usually enough render processes
// available on Android. If not, kill an existing renderers so that we can
// create a new one.
if (content::RenderProcessHost::ShouldTryToUseExistingProcessHost(profile_,
url) &&
!content::RenderProcessHost::run_renderer_in_process()) {
SkipPrerenderContentsAndMaybePreconnect(url, origin,
FINAL_STATUS_TOO_MANY_PROCESSES);
return nullptr;
}
// Check if enough time has passed since the last prerender.
if (!DoesRateLimitAllowPrerender(origin)) {
// Cancel the prerender. We could add it to the pending prerender list but
// this doesn't make sense as the next prerender request will be triggered
// by a navigation and is unlikely to be the same site.
SkipPrerenderContentsAndMaybePreconnect(url, origin,
FINAL_STATUS_RATE_LIMIT_EXCEEDED);
return nullptr;
}
// Record the URL in the prefetch list, even when in full prerender mode, to
// enable metrics comparisons.
prefetches_.emplace_back(url, GetCurrentTimeTicks(), origin);
if (GetMode() == PRERENDER_MODE_SIMPLE_LOAD_EXPERIMENT) {
// Exit after adding the url to prefetches_, so that no prefetching occurs
// but the page is still tracked as "would have been prefetched".
return nullptr;
}
// If this is GWS and we are in the holdback, skip the prefetch. Record the
// status as holdback, so we can analyze via UKM.
if (origin == ORIGIN_GWS_PRERENDER &&
base::FeatureList::IsEnabled(kGWSPrefetchHoldback)) {
// Set the holdback status on the prefetch entry.
SetPrefetchFinalStatusForUrl(url, FINAL_STATUS_GWS_HOLDBACK);
SkipPrerenderContentsAndMaybePreconnect(url, origin,
FINAL_STATUS_GWS_HOLDBACK);
return nullptr;
}
// If this is Navigation predictor and we are in the holdback, skip the
// prefetch. Record the status as holdback, so we can analyze via UKM.
if (origin == ORIGIN_NAVIGATION_PREDICTOR &&
base::FeatureList::IsEnabled(kNavigationPredictorPrefetchHoldback)) {
// Set the holdback status on the prefetch entry.
SetPrefetchFinalStatusForUrl(url,
FINAL_STATUS_NAVIGATION_PREDICTOR_HOLDBACK);
SkipPrerenderContentsAndMaybePreconnect(
url, origin, FINAL_STATUS_NAVIGATION_PREDICTOR_HOLDBACK);
return nullptr;
}
std::unique_ptr<PrerenderContents> prerender_contents =
CreatePrerenderContents(url, referrer, initiator_origin, origin);
DCHECK(prerender_contents);
PrerenderContents* prerender_contents_ptr = prerender_contents.get();
if (IsNoStatePrefetchEnabled()) {
prerender_contents_ptr->SetPrerenderMode(
prerender::mojom::PrerenderMode::kPrefetchOnly);
}
active_prerenders_.push_back(
std::make_unique<PrerenderData>(this, std::move(prerender_contents),
GetExpiryTimeForNewPrerender(origin)));
if (!prerender_contents_ptr->Init()) {
DCHECK(active_prerenders_.end() ==
FindIteratorForPrerenderContents(prerender_contents_ptr));
return nullptr;
}
DCHECK(!prerender_contents_ptr->prerendering_has_started());
std::unique_ptr<PrerenderHandle> prerender_handle =
base::WrapUnique(new PrerenderHandle(active_prerenders_.back().get()));
SortActivePrerenders();
last_prerender_start_time_ = GetCurrentTimeTicks();
gfx::Rect contents_bounds =
bounds.IsEmpty() ? config_.default_tab_bounds : bounds;
prerender_contents_ptr->StartPrerendering(contents_bounds,
session_storage_namespace);
DCHECK(prerender_contents_ptr->prerendering_has_started());
StartSchedulingPeriodicCleanups();
return prerender_handle;
}
void PrerenderManager::StartSchedulingPeriodicCleanups() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (repeating_timer_.IsRunning())
return;
repeating_timer_.Start(FROM_HERE, kPeriodicCleanupInterval, this,
&PrerenderManager::PeriodicCleanup);
}
void PrerenderManager::StopSchedulingPeriodicCleanups() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
repeating_timer_.Stop();
}
void PrerenderManager::PeriodicCleanup() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::ElapsedTimer resource_timer;
// Grab a copy of the current PrerenderContents pointers, so that we
// will not interfere with potential deletions of the list.
std::vector<PrerenderContents*> prerender_contents;
prerender_contents.reserve(active_prerenders_.size());
for (auto& prerender : active_prerenders_)
prerender_contents.push_back(prerender->contents());
// And now check for prerenders using too much memory.
for (auto* contents : prerender_contents)
contents->DestroyWhenUsingTooManyResources();
base::ElapsedTimer cleanup_timer;
// Perform deferred cleanup work.
DeleteOldWebContents();
DeleteOldEntries();
if (active_prerenders_.empty())
StopSchedulingPeriodicCleanups();
DeleteToDeletePrerenders();
CleanUpOldNavigations(&prefetches_, base::TimeDelta::FromMinutes(30));
}
void PrerenderManager::PostCleanupTask() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&PrerenderManager::PeriodicCleanup,
weak_factory_.GetWeakPtr()));
}
base::TimeTicks PrerenderManager::GetExpiryTimeForNewPrerender(
Origin origin) const {
return GetCurrentTimeTicks() + config_.time_to_live;
}
base::TimeTicks PrerenderManager::GetExpiryTimeForNavigatedAwayPrerender()
const {
return GetCurrentTimeTicks() + config_.abandon_time_to_live;
}
void PrerenderManager::DeleteOldEntries() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
while (!active_prerenders_.empty()) {
auto& prerender_data = active_prerenders_.front();
DCHECK(prerender_data);
DCHECK(prerender_data->contents());
if (prerender_data->expiry_time() > GetCurrentTimeTicks())
return;
prerender_data->contents()->Destroy(FINAL_STATUS_TIMED_OUT);
}
}
void PrerenderManager::DeleteToDeletePrerenders() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Delete the items one by one (after removing from the vector) as deleting
// the WebContents may trigger a call to GetPrerenderContents(), which
// iterates over |to_delete_prerenders_|.
while (!to_delete_prerenders_.empty()) {
std::unique_ptr<PrerenderData> prerender_data =
std::move(to_delete_prerenders_.back());
to_delete_prerenders_.pop_back();
}
}
base::Time PrerenderManager::GetCurrentTime() const {
return base::Time::Now();
}
base::TimeTicks PrerenderManager::GetCurrentTimeTicks() const {
return tick_clock_->NowTicks();
}
void PrerenderManager::SetTickClockForTesting(
const base::TickClock* tick_clock) {
tick_clock_ = tick_clock;
}
void PrerenderManager::AddObserver(
std::unique_ptr<PrerenderManagerObserver> observer) {
observers_.push_back(std::move(observer));
}
std::unique_ptr<PrerenderContents> PrerenderManager::CreatePrerenderContents(
const GURL& url,
const content::Referrer& referrer,
const base::Optional<url::Origin>& initiator_origin,
Origin origin) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return base::WrapUnique(prerender_contents_factory_->CreatePrerenderContents(
delegate_->GetPrerenderContentsDelegate(), this, profile_, url, referrer,
initiator_origin, origin));
}
void PrerenderManager::SortActivePrerenders() {
std::sort(active_prerenders_.begin(), active_prerenders_.end(),
PrerenderData::OrderByExpiryTime());
}
PrerenderManager::PrerenderData* PrerenderManager::FindPrerenderData(
const GURL& url,
SessionStorageNamespace* session_storage_namespace) {
for (const auto& prerender : active_prerenders_) {
PrerenderContents* contents = prerender->contents();
if (contents->Matches(url, session_storage_namespace))
return prerender.get();
}
return nullptr;
}
PrerenderManager::PrerenderDataVector::iterator
PrerenderManager::FindIteratorForPrerenderContents(
PrerenderContents* prerender_contents) {
for (auto it = active_prerenders_.begin(); it != active_prerenders_.end();
++it) {
if ((*it)->contents() == prerender_contents)
return it;
}
return active_prerenders_.end();
}
bool PrerenderManager::DoesRateLimitAllowPrerender(Origin origin) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Allow navigation predictor to manage its own rate limit.
if (origin == ORIGIN_NAVIGATION_PREDICTOR)
return true;
base::TimeDelta elapsed_time =
GetCurrentTimeTicks() - last_prerender_start_time_;
if (!config_.rate_limit_enabled)
return true;
return elapsed_time >=
base::TimeDelta::FromMilliseconds(kMinTimeBetweenPrerendersMs);
}
void PrerenderManager::DeleteOldWebContents() {
old_web_contents_list_.clear();
}
bool PrerenderManager::GetPrefetchInformation(const GURL& url,
base::TimeDelta* prefetch_age,
FinalStatus* final_status,
Origin* origin) {
CleanUpOldNavigations(&prefetches_, base::TimeDelta::FromMinutes(30));
if (prefetch_age)
*prefetch_age = base::TimeDelta();
if (final_status)
*final_status = FINAL_STATUS_MAX;
if (origin)
*origin = ORIGIN_NONE;
for (auto it = prefetches_.crbegin(); it != prefetches_.crend(); ++it) {
if (it->url == url) {
if (prefetch_age)
*prefetch_age = GetCurrentTimeTicks() - it->time;
if (final_status)
*final_status = it->final_status;
if (origin)
*origin = it->origin;
return true;
}
}
return false;
}
void PrerenderManager::SetPrefetchFinalStatusForUrl(const GURL& url,
FinalStatus final_status) {
for (auto it = prefetches_.rbegin(); it != prefetches_.rend(); ++it) {
if (it->url == url) {
it->final_status = final_status;
break;
}
}
}
bool PrerenderManager::HasRecentlyPrefetchedUrlForTesting(const GURL& url) {
return std::any_of(prefetches_.cbegin(), prefetches_.cend(),
[url](const NavigationRecord& r) {
return r.url == url &&
r.final_status ==
FINAL_STATUS_NOSTATE_PREFETCH_FINISHED;
});
}
void PrerenderManager::OnPrefetchUsed(const GURL& url) {
// Loading a prefetched URL resets the revalidation bypass. Remove all
// matching urls from the prefetch list for more accurate metrics.
base::EraseIf(prefetches_,
[url](const NavigationRecord& r) { return r.url == url; });
}
void PrerenderManager::CleanUpOldNavigations(
std::vector<NavigationRecord>* navigations,
base::TimeDelta max_age) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Cutoff. Navigations before this cutoff can be discarded.
base::TimeTicks cutoff = GetCurrentTimeTicks() - max_age;
auto it = navigations->begin();
for (; it != navigations->end(); ++it) {
if (it->time > cutoff)
break;
}
navigations->erase(navigations->begin(), it);
}
void PrerenderManager::ScheduleDeleteOldWebContents(
std::unique_ptr<WebContents> tab,
OnCloseWebContentsDeleter* deleter) {
old_web_contents_list_.push_back(std::move(tab));
PostCleanupTask();
if (!deleter)
return;
for (auto it = on_close_web_contents_deleters_.begin();
it != on_close_web_contents_deleters_.end(); ++it) {
if (it->get() == deleter) {
on_close_web_contents_deleters_.erase(it);
return;
}
}
NOTREACHED();
}
void PrerenderManager::AddToHistory(PrerenderContents* contents) {
PrerenderHistory::Entry entry(contents->prerender_url(),
contents->final_status(), contents->origin(),
base::Time::Now());
prerender_history_->AddEntry(entry);
}
std::unique_ptr<base::ListValue> PrerenderManager::GetActivePrerendersAsValue()
const {
auto list_value = std::make_unique<base::ListValue>();
for (const auto& prerender : active_prerenders_) {
auto prerender_value = prerender->contents()->GetAsValue();
if (prerender_value)
list_value->Append(std::move(prerender_value));
}
return list_value;
}
void PrerenderManager::DestroyAllContents(FinalStatus final_status) {
DeleteOldWebContents();
while (!active_prerenders_.empty()) {
PrerenderContents* contents = active_prerenders_.front()->contents();
contents->Destroy(final_status);
}
DeleteToDeletePrerenders();
}
void PrerenderManager::SkipPrerenderContentsAndMaybePreconnect(
const GURL& url,
Origin origin,
FinalStatus final_status) const {
PrerenderHistory::Entry entry(url, final_status, origin, base::Time::Now());
prerender_history_->AddEntry(entry);
histograms_->RecordFinalStatus(origin, final_status);
if (origin == ORIGIN_ISOLATED_PRERENDER) {
// Isolated Prerenders should not preconnect since that can't be done in a
// fully isolated way.
return;
}
if (final_status == FINAL_STATUS_LOW_END_DEVICE ||
final_status == FINAL_STATUS_CELLULAR_NETWORK ||
final_status == FINAL_STATUS_DUPLICATE ||
final_status == FINAL_STATUS_TOO_MANY_PROCESSES) {
MaybePreconnect(origin, url);
}
static_assert(
FINAL_STATUS_MAX == FINAL_STATUS_NAVIGATION_PREDICTOR_HOLDBACK + 1,
"Consider whether a failed prerender should fallback to preconnect");
}
void PrerenderManager::RecordNetworkBytesConsumed(Origin origin,
int64_t prerender_bytes) {
if (!IsNoStatePrefetchEnabled())
return;
int64_t recent_profile_bytes =
profile_network_bytes_ - last_recorded_profile_network_bytes_;
last_recorded_profile_network_bytes_ = profile_network_bytes_;
DCHECK_GE(recent_profile_bytes, 0);
histograms_->RecordNetworkBytesConsumed(origin, prerender_bytes,
recent_profile_bytes);
}
NetworkPredictionStatus PrerenderManager::GetPredictionStatus() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return chrome_browser_net::CanPrefetchAndPrerenderUI(profile_->GetPrefs());
}
NetworkPredictionStatus PrerenderManager::GetPredictionStatusForOrigin(
Origin origin) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// <link rel=prerender> origins ignore the network state and the privacy
// settings. Web developers should be able prefetch with all possible privacy
// settings and with all possible network types. This would avoid web devs
// coming up with creative ways to prefetch in cases they are not allowed to
// do so.
if (origin == ORIGIN_LINK_REL_PRERENDER_SAMEDOMAIN ||
origin == ORIGIN_LINK_REL_PRERENDER_CROSSDOMAIN) {
return NetworkPredictionStatus::ENABLED;
}
// Prerendering forced for cellular networks still prevents navigation with
// the DISABLED_ALWAYS selected via privacy settings.
NetworkPredictionStatus prediction_status =
chrome_browser_net::CanPrefetchAndPrerenderUI(profile_->GetPrefs());
if (origin == ORIGIN_EXTERNAL_REQUEST_FORCED_PRERENDER &&
prediction_status == NetworkPredictionStatus::DISABLED_DUE_TO_NETWORK) {
return NetworkPredictionStatus::ENABLED;
}
return prediction_status;
}
void PrerenderManager::AddProfileNetworkBytesIfEnabled(int64_t bytes) {
DCHECK_GE(bytes, 0);
if (GetPredictionStatus() == NetworkPredictionStatus::ENABLED &&
IsNoStatePrefetchEnabled())
profile_network_bytes_ += bytes;
}
void PrerenderManager::AddPrerenderProcessHost(
content::RenderProcessHost* process_host) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
bool inserted = prerender_process_hosts_.insert(process_host).second;
DCHECK(inserted);
process_host->AddObserver(this);
}
bool PrerenderManager::MayReuseProcessHost(
content::RenderProcessHost* process_host) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Isolate prerender processes to make the resource monitoring check more
// accurate.
return !base::Contains(prerender_process_hosts_, process_host);
}
void PrerenderManager::RenderProcessHostDestroyed(
content::RenderProcessHost* host) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
size_t erased = prerender_process_hosts_.erase(host);
DCHECK_EQ(1u, erased);
}
base::WeakPtr<PrerenderManager> PrerenderManager::AsWeakPtr() {
return weak_factory_.GetWeakPtr();
}
void PrerenderManager::ClearPrefetchInformationForTesting() {
prefetches_.clear();
}
void PrerenderManager::SetPrerenderContentsFactoryForTest(
PrerenderContents::Factory* prerender_contents_factory) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
prerender_contents_factory_.reset(prerender_contents_factory);
}
} // namespace prerender
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment