Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(464)

Side by Side Diff: components/precache/core/precache_fetcher.cc

Issue 2403193002: Precache: Optionally rank resources-to-precache globally. (Closed)
Patch Set: Rebase. Created 4 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2013 The Chromium Authors. All rights reserved. 1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "components/precache/core/precache_fetcher.h" 5 #include "components/precache/core/precache_fetcher.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <limits> 8 #include <limits>
9 #include <set>
9 #include <utility> 10 #include <utility>
10 #include <vector> 11 #include <vector>
11 12
12 #include "base/base64.h" 13 #include "base/base64.h"
13 #include "base/bind.h" 14 #include "base/bind.h"
14 #include "base/bind_helpers.h" 15 #include "base/bind_helpers.h"
15 #include "base/callback.h" 16 #include "base/callback.h"
16 #include "base/command_line.h" 17 #include "base/command_line.h"
17 #include "base/compiler_specific.h" 18 #include "base/compiler_specific.h"
18 #include "base/containers/hash_tables.h" 19 #include "base/containers/hash_tables.h"
(...skipping 27 matching lines...) Expand all
46 // The following flags are for privacy reasons. For example, if a user clears 47 // The following flags are for privacy reasons. For example, if a user clears
47 // their cookies, but a tracking beacon is prefetched and the beacon specifies 48 // their cookies, but a tracking beacon is prefetched and the beacon specifies
48 // its source URL in a URL param, the beacon site would be able to rebuild a 49 // its source URL in a URL param, the beacon site would be able to rebuild a
49 // profile of the user. All three flags should occur together, or not at all, 50 // profile of the user. All three flags should occur together, or not at all,
50 // per 51 // per
51 // https://groups.google.com/a/chromium.org/d/topic/net-dev/vvcodRV6SdM/discussi on. 52 // https://groups.google.com/a/chromium.org/d/topic/net-dev/vvcodRV6SdM/discussi on.
52 const int kNoTracking = 53 const int kNoTracking =
53 net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | 54 net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
54 net::LOAD_DO_NOT_SEND_AUTH_DATA; 55 net::LOAD_DO_NOT_SEND_AUTH_DATA;
55 56
57 // The maximum number of URLFetcher requests that can be in flight in parallel.
58 // Note that OnManifestFetchComplete and OnResourceFetchComplete perform
59 // remove_if operations which are O(kMaxParallelFetches). Those should be
60 // optimized before increasing this value significantly.
61 const int kMaxParallelFetches = 10;
62
56 namespace { 63 namespace {
57 64
58 // The maximum number of URLFetcher requests that can be on flight in parallel.
59 const int kMaxParallelFetches = 10;
60
61 // The maximum for the Precache.Fetch.ResponseBytes.* histograms. We set this to 65 // The maximum for the Precache.Fetch.ResponseBytes.* histograms. We set this to
62 // a number we expect to be in the 99th percentile for the histogram, give or 66 // a number we expect to be in the 99th percentile for the histogram, give or
63 // take. 67 // take.
64 const int kMaxResponseBytes = 500 * 1024 * 1024; 68 const int kMaxResponseBytes = 500 * 1024 * 1024;
65 69
66 GURL GetDefaultConfigURL() { 70 GURL GetDefaultConfigURL() {
67 const base::CommandLine& command_line = 71 const base::CommandLine& command_line =
68 *base::CommandLine::ForCurrentProcess(); 72 *base::CommandLine::ForCurrentProcess();
69 if (command_line.HasSwitch(switches::kPrecacheConfigSettingsURL)) { 73 if (command_line.HasSwitch(switches::kPrecacheConfigSettingsURL)) {
70 return GURL( 74 return GURL(
(...skipping 105 matching lines...) Expand 10 before | Expand all | Expand 10 after
176 hashes.append(reinterpret_cast<const char*>(sha1_hash), kHashBytesSize); 180 hashes.append(reinterpret_cast<const char*>(sha1_hash), kHashBytesSize);
177 } 181 }
178 base::Base64Encode(hashes, &hashes); 182 base::Base64Encode(hashes, &hashes);
179 return hashes; 183 return hashes;
180 } 184 }
181 185
182 // Retrieves the manifest info on the DB thread. Manifest info for each of the 186 // Retrieves the manifest info on the DB thread. Manifest info for each of the
183 // hosts in |hosts_to_fetch|, is added to |hosts_info|. 187 // hosts in |hosts_to_fetch|, is added to |hosts_info|.
184 std::deque<ManifestHostInfo> RetrieveManifestInfo( 188 std::deque<ManifestHostInfo> RetrieveManifestInfo(
185 const base::WeakPtr<PrecacheDatabase>& precache_database, 189 const base::WeakPtr<PrecacheDatabase>& precache_database,
186 std::vector<std::string> hosts_to_fetch) { 190 std::vector<std::pair<std::string, int64_t>> hosts_to_fetch) {
187 std::deque<ManifestHostInfo> hosts_info; 191 std::deque<ManifestHostInfo> hosts_info;
188 if (!precache_database) 192 if (!precache_database)
189 return hosts_info; 193 return hosts_info;
190 194
191 for (const auto& host : hosts_to_fetch) { 195 for (const auto& host : hosts_to_fetch) {
192 auto referrer_host_info = precache_database->GetReferrerHost(host); 196 auto referrer_host_info = precache_database->GetReferrerHost(host.first);
193 if (referrer_host_info.id != PrecacheReferrerHostEntry::kInvalidId) { 197 if (referrer_host_info.id != PrecacheReferrerHostEntry::kInvalidId) {
194 std::vector<GURL> used_urls, unused_urls; 198 std::vector<GURL> used_urls, unused_urls;
195 precache_database->GetURLListForReferrerHost(referrer_host_info.id, 199 precache_database->GetURLListForReferrerHost(referrer_host_info.id,
196 &used_urls, &unused_urls); 200 &used_urls, &unused_urls);
197 hosts_info.push_back( 201 hosts_info.push_back(
198 ManifestHostInfo(referrer_host_info.manifest_id, host, 202 ManifestHostInfo(referrer_host_info.manifest_id, host.first,
199 GetResourceURLBase64Hash(used_urls), 203 host.second, GetResourceURLBase64Hash(used_urls),
200 GetResourceURLBase64Hash(unused_urls))); 204 GetResourceURLBase64Hash(unused_urls)));
201 } else { 205 } else {
202 hosts_info.push_back( 206 hosts_info.push_back(
203 ManifestHostInfo(PrecacheReferrerHostEntry::kInvalidId, host, 207 ManifestHostInfo(PrecacheReferrerHostEntry::kInvalidId, host.first,
204 std::string(), std::string())); 208 host.second, std::string(), std::string()));
205 } 209 }
206 } 210 }
207 return hosts_info; 211 return hosts_info;
208 } 212 }
209 213
210 PrecacheQuota RetrieveQuotaInfo( 214 PrecacheQuota RetrieveQuotaInfo(
211 const base::WeakPtr<PrecacheDatabase>& precache_database) { 215 const base::WeakPtr<PrecacheDatabase>& precache_database) {
212 PrecacheQuota quota; 216 PrecacheQuota quota;
213 if (precache_database) { 217 if (precache_database) {
214 quota = precache_database->GetQuota(); 218 quota = precache_database->GetQuota();
215 } 219 }
216 return quota; 220 return quota;
217 } 221 }
218 222
219 // Returns true if the |quota| time has expired. 223 // Returns true if the |quota| time has expired.
220 bool IsQuotaTimeExpired(const PrecacheQuota& quota, 224 bool IsQuotaTimeExpired(const PrecacheQuota& quota,
221 const base::Time& time_now) { 225 const base::Time& time_now) {
222 // Quota expires one day after the start time. 226 // Quota expires one day after the start time.
223 base::Time start_time = base::Time::FromInternalValue(quota.start_time()); 227 base::Time start_time = base::Time::FromInternalValue(quota.start_time());
224 return start_time > time_now || 228 return start_time > time_now ||
225 start_time + base::TimeDelta::FromDays(1) < time_now; 229 start_time + base::TimeDelta::FromDays(1) < time_now;
226 } 230 }
227 231
232 double ResourceWeight(const PrecacheResource& resource, int64_t host_visits) {
233 return resource.weight_ratio() * host_visits;
234 }
235
228 } // namespace 236 } // namespace
229 237
230 PrecacheFetcher::Fetcher::Fetcher( 238 PrecacheFetcher::Fetcher::Fetcher(
231 net::URLRequestContextGetter* request_context, 239 net::URLRequestContextGetter* request_context,
232 const GURL& url, 240 const GURL& url,
233 const std::string& referrer, 241 const std::string& referrer,
234 const base::Callback<void(const Fetcher&)>& callback, 242 const base::Callback<void(const Fetcher&)>& callback,
235 bool is_resource_request, 243 bool is_resource_request,
236 size_t max_bytes) 244 size_t max_bytes)
237 : request_context_(request_context), 245 : request_context_(request_context),
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
294 void PrecacheFetcher::Fetcher::OnURLFetchDownloadProgress( 302 void PrecacheFetcher::Fetcher::OnURLFetchDownloadProgress(
295 const net::URLFetcher* source, 303 const net::URLFetcher* source,
296 int64_t current, 304 int64_t current,
297 int64_t total, 305 int64_t total,
298 int64_t current_network_bytes) { 306 int64_t current_network_bytes) {
299 // If network bytes going over the per-resource download cap. 307 // If network bytes going over the per-resource download cap.
300 if (fetch_stage_ == FetchStage::NETWORK && 308 if (fetch_stage_ == FetchStage::NETWORK &&
301 // |current_network_bytes| is guaranteed to be non-negative, so this cast 309 // |current_network_bytes| is guaranteed to be non-negative, so this cast
302 // is safe. 310 // is safe.
303 static_cast<size_t>(current_network_bytes) > max_bytes_) { 311 static_cast<size_t>(current_network_bytes) > max_bytes_) {
304 VLOG(1) << "Cancelling " << url_ << ": (" << current << "/" << total
305 << ") is over " << max_bytes_;
306
307 // Call the completion callback, to attempt the next download, or to trigger 312 // Call the completion callback, to attempt the next download, or to trigger
308 // cleanup in precache_delegate_->OnDone(). 313 // cleanup in precache_delegate_->OnDone().
309 response_bytes_ = current; 314 response_bytes_ = current;
310 network_response_bytes_ = current_network_bytes; 315 network_response_bytes_ = current_network_bytes;
311 was_cached_ = source->WasCached(); 316 was_cached_ = source->WasCached();
312 317
313 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.NetworkWasted", 318 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.NetworkWasted",
314 network_response_bytes_, 1, 319 network_response_bytes_, 1,
315 1024 * 1024 /* 1 MB */, 100); 320 1024 * 1024 /* 1 MB */, 100);
316 // Cancel the download. 321 // Cancel the download.
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
356 // These may be unset in tests. 361 // These may be unset in tests.
357 if (!unfinished_work.has_start_time()) 362 if (!unfinished_work.has_start_time())
358 return; 363 return;
359 base::TimeDelta time_to_fetch = 364 base::TimeDelta time_to_fetch =
360 base::Time::Now() - 365 base::Time::Now() -
361 base::Time::FromInternalValue(unfinished_work.start_time()); 366 base::Time::FromInternalValue(unfinished_work.start_time());
362 UMA_HISTOGRAM_CUSTOM_TIMES("Precache.Fetch.TimeToComplete", time_to_fetch, 367 UMA_HISTOGRAM_CUSTOM_TIMES("Precache.Fetch.TimeToComplete", time_to_fetch,
363 base::TimeDelta::FromSeconds(1), 368 base::TimeDelta::FromSeconds(1),
364 base::TimeDelta::FromHours(4), 50); 369 base::TimeDelta::FromHours(4), 50);
365 370
366 // Number of manifests for which we have downloaded all resources. 371 int num_total_resources = unfinished_work.num_resource_urls();
367 int manifests_completed = 372 int percent_completed =
368 unfinished_work.num_manifest_urls() - remaining_manifest_urls_to_fetch; 373 num_total_resources == 0
369 374 ? 101 // Overflow bucket.
370 // If there are resource URLs left to fetch, the last manifest is not yet 375 : (100 * (static_cast<double>(num_total_resources -
371 // completed. 376 remaining_resource_urls_to_fetch) /
372 if (remaining_resource_urls_to_fetch > 0) 377 num_total_resources));
373 --manifests_completed;
374
375 DCHECK_GE(manifests_completed, 0);
376 int percent_completed = unfinished_work.num_manifest_urls() == 0
377 ? 0
378 : (static_cast<double>(manifests_completed) /
379 unfinished_work.num_manifest_urls() * 100);
380 378
381 UMA_HISTOGRAM_PERCENTAGE("Precache.Fetch.PercentCompleted", 379 UMA_HISTOGRAM_PERCENTAGE("Precache.Fetch.PercentCompleted",
382 percent_completed); 380 percent_completed);
383 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total", 381 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total",
384 unfinished_work.total_bytes(), 382 unfinished_work.total_bytes(), 1,
385 1, kMaxResponseBytes, 100); 383 kMaxResponseBytes, 100);
386 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network", 384 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network",
387 unfinished_work.network_bytes(), 385 unfinished_work.network_bytes(), 1,
388 1, kMaxResponseBytes, 386 kMaxResponseBytes, 100);
389 100);
390 } 387 }
391 388
392 // static 389 // static
393 std::string PrecacheFetcher::GetResourceURLBase64HashForTesting( 390 std::string PrecacheFetcher::GetResourceURLBase64HashForTesting(
394 const std::vector<GURL>& urls) { 391 const std::vector<GURL>& urls) {
395 return GetResourceURLBase64Hash(urls); 392 return GetResourceURLBase64Hash(urls);
396 } 393 }
397 394
398 PrecacheFetcher::PrecacheFetcher( 395 PrecacheFetcher::PrecacheFetcher(
399 net::URLRequestContextGetter* request_context, 396 net::URLRequestContextGetter* request_context,
(...skipping 19 matching lines...) Expand all
419 << "Could not determine the precache config settings URL."; 416 << "Could not determine the precache config settings URL.";
420 DCHECK_NE(std::string(), GetDefaultManifestURLPrefix()) 417 DCHECK_NE(std::string(), GetDefaultManifestURLPrefix())
421 << "Could not determine the default precache manifest URL prefix."; 418 << "Could not determine the default precache manifest URL prefix.";
422 DCHECK(unfinished_work); 419 DCHECK(unfinished_work);
423 420
424 // Copy resources to member variable as a convenience. 421 // Copy resources to member variable as a convenience.
425 // TODO(rajendrant): Consider accessing these directly from the proto, by 422 // TODO(rajendrant): Consider accessing these directly from the proto, by
426 // keeping track of the current resource index. 423 // keeping track of the current resource index.
427 for (const auto& resource : unfinished_work->resource()) { 424 for (const auto& resource : unfinished_work->resource()) {
428 if (resource.has_url() && resource.has_top_host_name()) { 425 if (resource.has_url() && resource.has_top_host_name()) {
426 // Weight doesn't matter, as the resources have already been sorted by
427 // this point.
429 resources_to_fetch_.emplace_back(GURL(resource.url()), 428 resources_to_fetch_.emplace_back(GURL(resource.url()),
430 resource.top_host_name()); 429 resource.top_host_name(), 0);
431 } 430 }
432 } 431 }
433 unfinished_work_ = std::move(unfinished_work); 432 unfinished_work_ = std::move(unfinished_work);
434 } 433 }
435 434
436 PrecacheFetcher::~PrecacheFetcher() { 435 PrecacheFetcher::~PrecacheFetcher() {
437 } 436 }
438 437
439 std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { 438 std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() {
440 // This could get called multiple times, and it should be handled gracefully. 439 // This could get called multiple times, and it should be handled gracefully.
441 if (!unfinished_work_) 440 if (!unfinished_work_)
442 return nullptr; 441 return nullptr;
443 442
444 unfinished_work_->clear_resource(); 443 unfinished_work_->clear_resource();
445 if (unfinished_work_->has_config_settings()) { 444 if (unfinished_work_->has_config_settings()) {
446 // If config fetch is incomplete, |top_hosts_to_fetch_| will be empty and 445 // If config fetch is incomplete, |top_hosts_to_fetch_| will be empty and
447 // top hosts should be left as is in |unfinished_work_|. 446 // top hosts should be left as is in |unfinished_work_|.
448 unfinished_work_->clear_top_host(); 447 unfinished_work_->clear_top_host();
449 for (const auto& top_host : top_hosts_to_fetch_) { 448 for (const auto& top_host : top_hosts_fetching_)
450 unfinished_work_->add_top_host()->set_hostname(top_host.hostname); 449 unfinished_work_->add_top_host()->set_hostname(top_host.hostname);
451 } 450 for (const auto& top_host : top_hosts_to_fetch_)
451 unfinished_work_->add_top_host()->set_hostname(top_host.hostname);
452 }
453 for (const auto& resource : resources_fetching_) {
454 auto new_resource = unfinished_work_->add_resource();
455 new_resource->set_url(resource.url.spec());
456 new_resource->set_top_host_name(resource.referrer);
452 } 457 }
453 for (const auto& resource : resources_to_fetch_) { 458 for (const auto& resource : resources_to_fetch_) {
454 auto new_resource = unfinished_work_->add_resource(); 459 auto new_resource = unfinished_work_->add_resource();
455 new_resource->set_url(resource.first.spec()); 460 new_resource->set_url(resource.url.spec());
456 new_resource->set_top_host_name(resource.second); 461 new_resource->set_top_host_name(resource.referrer);
457 } 462 }
458 for (const auto& it : pool_.elements()) { 463 top_hosts_fetching_.clear();
459 const Fetcher* fetcher = it.first;
460 GURL config_url =
461 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_;
462 if (fetcher->is_resource_request()) {
463 auto resource = unfinished_work_->add_resource();
464 resource->set_url(fetcher->url().spec());
465 resource->set_top_host_name(fetcher->referrer());
466 } else if (fetcher->url() != config_url) {
467 unfinished_work_->add_top_host()->set_hostname(fetcher->referrer());
468 }
469 }
470 top_hosts_to_fetch_.clear(); 464 top_hosts_to_fetch_.clear();
465 resources_fetching_.clear();
471 resources_to_fetch_.clear(); 466 resources_to_fetch_.clear();
472 pool_.DeleteAll(); 467 pool_.DeleteAll();
473 return std::move(unfinished_work_); 468 return std::move(unfinished_work_);
474 } 469 }
475 470
476 void PrecacheFetcher::Start() { 471 void PrecacheFetcher::Start() {
477 if (unfinished_work_->has_config_settings()) { 472 if (unfinished_work_->has_config_settings()) {
478 DCHECK(unfinished_work_->has_start_time()); 473 DCHECK(unfinished_work_->has_start_time());
479 DetermineManifests(); 474 DetermineManifests();
480 return; 475 return;
481 } 476 }
482 477
483 GURL config_url = 478 GURL config_url =
484 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; 479 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_;
485 480
486 DCHECK(config_url.is_valid()) << "Config URL not valid: " 481 DCHECK(config_url.is_valid()) << "Config URL not valid: "
487 << config_url.possibly_invalid_spec(); 482 << config_url.possibly_invalid_spec();
488 483
489 // Fetch the precache configuration settings from the server. 484 // Fetch the precache configuration settings from the server.
490 DCHECK(pool_.IsEmpty()) << "All parallel requests should be available"; 485 DCHECK(pool_.IsEmpty()) << "All parallel requests should be available";
491 VLOG(3) << "Fetching " << config_url;
492 pool_.Add(base::MakeUnique<Fetcher>( 486 pool_.Add(base::MakeUnique<Fetcher>(
493 request_context_.get(), config_url, std::string(), 487 request_context_.get(), config_url, std::string(),
494 base::Bind(&PrecacheFetcher::OnConfigFetchComplete, AsWeakPtr()), 488 base::Bind(&PrecacheFetcher::OnConfigFetchComplete, AsWeakPtr()),
495 false /* is_resource_request */, std::numeric_limits<int32_t>::max())); 489 false /* is_resource_request */, std::numeric_limits<int32_t>::max()));
496 } 490 }
497 491
498 void PrecacheFetcher::StartNextResourceFetch() { 492 void PrecacheFetcher::StartNextResourceFetch() {
499 DCHECK(unfinished_work_->has_config_settings()); 493 DCHECK(unfinished_work_->has_config_settings());
500 while (!resources_to_fetch_.empty() && pool_.IsAvailable()) { 494 while (!resources_to_fetch_.empty() && pool_.IsAvailable()) {
501 const auto& resource = resources_to_fetch_.front(); 495 ResourceInfo& resource = resources_to_fetch_.front();
502 const size_t max_bytes = std::min( 496 const size_t max_bytes = std::min(
503 quota_.remaining(), 497 quota_.remaining(),
504 std::min(unfinished_work_->config_settings().max_bytes_per_resource(), 498 std::min(unfinished_work_->config_settings().max_bytes_per_resource(),
505 unfinished_work_->config_settings().max_bytes_total() - 499 unfinished_work_->config_settings().max_bytes_total() -
506 unfinished_work_->total_bytes())); 500 unfinished_work_->total_bytes()));
507 VLOG(3) << "Fetching " << resource.first << " " << resource.second;
508 pool_.Add(base::MakeUnique<Fetcher>( 501 pool_.Add(base::MakeUnique<Fetcher>(
509 request_context_.get(), resource.first, resource.second, 502 request_context_.get(), resource.url, resource.referrer,
510 base::Bind(&PrecacheFetcher::OnResourceFetchComplete, AsWeakPtr()), 503 base::Bind(&PrecacheFetcher::OnResourceFetchComplete, AsWeakPtr()),
511 true /* is_resource_request */, max_bytes)); 504 true /* is_resource_request */, max_bytes));
512 505
506 resources_fetching_.push_back(std::move(resource));
513 resources_to_fetch_.pop_front(); 507 resources_to_fetch_.pop_front();
514 } 508 }
515 } 509 }
516 510
517 void PrecacheFetcher::StartNextManifestFetch() { 511 void PrecacheFetcher::StartNextManifestFetches() {
518 if (top_hosts_to_fetch_.empty() || !pool_.IsAvailable()) 512 // We fetch as many manifests at a time as possible, as we need all resource
519 return; 513 // URLs in memory in order to rank them.
520 514 while (!top_hosts_to_fetch_.empty() && pool_.IsAvailable()) {
521 // We only fetch one manifest at a time to keep the size of 515 ManifestHostInfo& top_host = top_hosts_to_fetch_.front();
522 // resources_to_fetch_ as small as possible. 516 pool_.Add(base::MakeUnique<Fetcher>(
523 VLOG(3) << "Fetching " << top_hosts_to_fetch_.front().manifest_url; 517 request_context_.get(), top_host.manifest_url, top_host.hostname,
524 pool_.Add(base::MakeUnique<Fetcher>( 518 base::Bind(&PrecacheFetcher::OnManifestFetchComplete, AsWeakPtr(),
525 request_context_.get(), top_hosts_to_fetch_.front().manifest_url, 519 top_host.visits),
526 top_hosts_to_fetch_.front().hostname, 520 false /* is_resource_request */, std::numeric_limits<int32_t>::max()));
527 base::Bind(&PrecacheFetcher::OnManifestFetchComplete, AsWeakPtr()), 521 top_hosts_fetching_.push_back(std::move(top_host));
528 false /* is_resource_request */, std::numeric_limits<int32_t>::max())); 522 top_hosts_to_fetch_.pop_front();
529 top_hosts_to_fetch_.pop_front(); 523 }
530 } 524 }
531 525
532 void PrecacheFetcher::NotifyDone( 526 void PrecacheFetcher::NotifyDone(
533 size_t remaining_manifest_urls_to_fetch, 527 size_t remaining_manifest_urls_to_fetch,
534 size_t remaining_resource_urls_to_fetch) { 528 size_t remaining_resource_urls_to_fetch) {
535 RecordCompletionStatistics(*unfinished_work_, 529 RecordCompletionStatistics(*unfinished_work_,
536 remaining_manifest_urls_to_fetch, 530 remaining_manifest_urls_to_fetch,
537 remaining_resource_urls_to_fetch); 531 remaining_resource_urls_to_fetch);
538 precache_delegate_->OnDone(); 532 precache_delegate_->OnDone();
539 } 533 }
540 534
541 void PrecacheFetcher::StartNextFetch() { 535 void PrecacheFetcher::StartNextFetch() {
542 DCHECK(unfinished_work_->has_config_settings()); 536 DCHECK(unfinished_work_->has_config_settings());
543 537
544 // If over the precache total size cap or daily quota, then stop prefetching. 538 // If over the precache total size cap or daily quota, then stop prefetching.
545 if ((unfinished_work_->total_bytes() > 539 if ((unfinished_work_->total_bytes() >
546 unfinished_work_->config_settings().max_bytes_total()) || 540 unfinished_work_->config_settings().max_bytes_total()) ||
547 quota_.remaining() == 0) { 541 quota_.remaining() == 0) {
548 size_t pending_manifests_in_pool = 0;
549 size_t pending_resources_in_pool = 0;
550 for (const auto& element_pair : pool_.elements()) {
551 const Fetcher* fetcher = element_pair.first;
552 if (fetcher->is_resource_request())
553 pending_resources_in_pool++;
554 else if (fetcher->url() != config_url_)
555 pending_manifests_in_pool++;
556 }
557 pool_.DeleteAll(); 542 pool_.DeleteAll();
558 NotifyDone(top_hosts_to_fetch_.size() + pending_manifests_in_pool, 543 NotifyDone(top_hosts_to_fetch_.size() + top_hosts_fetching_.size(),
559 resources_to_fetch_.size() + pending_resources_in_pool); 544 resources_to_fetch_.size() + resources_fetching_.size());
560 return; 545 return;
561 } 546 }
562 547
563 StartNextResourceFetch(); 548 StartNextResourceFetch();
564 StartNextManifestFetch(); 549 StartNextManifestFetches();
565 if (top_hosts_to_fetch_.empty() && resources_to_fetch_.empty() && 550 if (top_hosts_to_fetch_.empty() && resources_to_fetch_.empty() &&
566 pool_.IsEmpty()) { 551 pool_.IsEmpty()) {
567 // There are no more URLs to fetch, so end the precache cycle. 552 // There are no more URLs to fetch, so end the precache cycle.
568 NotifyDone(0, 0); 553 NotifyDone(0, 0);
569 // OnDone may have deleted this PrecacheFetcher, so don't do anything after 554 // OnDone may have deleted this PrecacheFetcher, so don't do anything after
570 // it is called. 555 // it is called.
571 } 556 }
572 } 557 }
573 558
574 void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) { 559 void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) {
575 UpdateStats(source.response_bytes(), source.network_response_bytes()); 560 UpdateStats(source.response_bytes(), source.network_response_bytes());
576 if (source.network_url_fetcher() == nullptr) { 561 if (source.network_url_fetcher() == nullptr) {
577 pool_.DeleteAll(); // Cancel any other ongoing request. 562 pool_.DeleteAll(); // Cancel any other ongoing request.
578 } else { 563 } else {
579 // Attempt to parse the config proto. On failure, continue on with the 564 // Attempt to parse the config proto. On failure, continue on with the
580 // default configuration. 565 // default configuration.
581 ParseProtoFromFetchResponse( 566 ParseProtoFromFetchResponse(
582 *source.network_url_fetcher(), 567 *source.network_url_fetcher(),
583 unfinished_work_->mutable_config_settings()); 568 unfinished_work_->mutable_config_settings());
584 pool_.Delete(source); 569 pool_.Delete(source);
585 DetermineManifests(); 570 DetermineManifests();
586 } 571 }
587 } 572 }
588 573
589 void PrecacheFetcher::DetermineManifests() { 574 void PrecacheFetcher::DetermineManifests() {
590 DCHECK(unfinished_work_->has_config_settings()); 575 DCHECK(unfinished_work_->has_config_settings());
591 576
592 std::vector<std::string> top_hosts_to_fetch; 577 std::vector<std::pair<std::string, int64_t>> top_hosts_to_fetch;
593 std::unique_ptr<std::deque<ManifestHostInfo>> top_hosts_info(
594 new std::deque<ManifestHostInfo>);
595 // Keep track of manifest URLs that are being fetched, in order to elide 578 // Keep track of manifest URLs that are being fetched, in order to elide
596 // duplicates. 579 // duplicates.
597 std::set<base::StringPiece> seen_top_hosts; 580 std::set<base::StringPiece> seen_top_hosts;
598 int64_t rank = 0; 581 int64_t rank = 0;
599 582
600 for (const auto& host : unfinished_work_->top_host()) { 583 for (const auto& host : unfinished_work_->top_host()) {
601 ++rank; 584 ++rank;
602 if (rank > unfinished_work_->config_settings().top_sites_count()) 585 if (rank > unfinished_work_->config_settings().top_sites_count())
603 break; 586 break;
604 if (seen_top_hosts.insert(host.hostname()).second) 587 if (seen_top_hosts.insert(host.hostname()).second)
605 top_hosts_to_fetch.push_back(host.hostname()); 588 top_hosts_to_fetch.emplace_back(host.hostname(), host.visits());
606 } 589 }
607 590
608 // Attempt to fetch manifests for starting hosts up to the maximum top sites 591 // Attempt to fetch manifests for starting hosts up to the maximum top sites
609 // count. If a manifest does not exist for a particular starting host, then 592 // count. If a manifest does not exist for a particular starting host, then
610 // the fetch will fail, and that starting host will be ignored. Starting 593 // the fetch will fail, and that starting host will be ignored. Starting
611 // hosts are not added if this is a continuation from a previous precache 594 // hosts are not added if this is a continuation from a previous precache
612 // session. 595 // session.
613 if (resources_to_fetch_.empty()) { 596 if (resources_to_fetch_.empty()) {
614 for (const std::string& host : 597 for (const std::string& host :
615 unfinished_work_->config_settings().forced_site()) { 598 unfinished_work_->config_settings().forced_site()) {
599 // We add a forced site with visits == 0, which means its resources will
600 // be downloaded last. TODO(twifkak): Consider removing support for
601 // forced_site.
616 if (seen_top_hosts.insert(host).second) 602 if (seen_top_hosts.insert(host).second)
617 top_hosts_to_fetch.push_back(host); 603 top_hosts_to_fetch.emplace_back(host, 0);
618 } 604 }
619 } 605 }
620 // We only fetch one manifest at a time to keep the size of 606 // We retrieve manifest usage and quota info from the local database before
621 // resources_to_fetch_ as small as possible. 607 // fetching the manifests.
622 PostTaskAndReplyWithResult( 608 PostTaskAndReplyWithResult(
623 db_task_runner_.get(), FROM_HERE, 609 db_task_runner_.get(), FROM_HERE,
624 base::Bind(&RetrieveManifestInfo, precache_database_, 610 base::Bind(&RetrieveManifestInfo, precache_database_,
625 std::move(top_hosts_to_fetch)), 611 std::move(top_hosts_to_fetch)),
626 base::Bind(&PrecacheFetcher::OnManifestInfoRetrieved, AsWeakPtr())); 612 base::Bind(&PrecacheFetcher::OnManifestInfoRetrieved, AsWeakPtr()));
627 } 613 }
628 614
629 void PrecacheFetcher::OnManifestInfoRetrieved( 615 void PrecacheFetcher::OnManifestInfoRetrieved(
630 std::deque<ManifestHostInfo> manifests_info) { 616 std::deque<ManifestHostInfo> manifests_info) {
631 const std::string prefix = manifest_url_prefix_.empty() 617 const std::string prefix = manifest_url_prefix_.empty()
632 ? GetDefaultManifestURLPrefix() 618 ? GetDefaultManifestURLPrefix()
633 : manifest_url_prefix_; 619 : manifest_url_prefix_;
634 if (!GURL(prefix).is_valid()) { 620 if (!GURL(prefix).is_valid()) {
635 // Don't attempt to fetch any manifests if the manifest URL prefix 621 // Don't attempt to fetch any manifests if the manifest URL prefix
636 // is invalid. 622 // is invalid.
637 top_hosts_to_fetch_.clear(); 623 top_hosts_to_fetch_.clear();
638 unfinished_work_->set_num_manifest_urls(manifests_info.size()); 624 unfinished_work_->set_num_manifest_urls(manifests_info.size());
639 NotifyDone(manifests_info.size(), resources_to_fetch_.size()); 625 NotifyDone(manifests_info.size(), resources_to_rank_.size());
640 return; 626 return;
641 } 627 }
642 628
643 top_hosts_to_fetch_ = std::move(manifests_info); 629 top_hosts_to_fetch_ = std::move(manifests_info);
644 for (auto& manifest : top_hosts_to_fetch_) { 630 for (auto& manifest : top_hosts_to_fetch_) {
645 manifest.manifest_url = 631 manifest.manifest_url =
646 GURL(prefix + 632 GURL(prefix +
647 net::EscapeQueryParamValue( 633 net::EscapeQueryParamValue(
648 net::EscapeQueryParamValue(manifest.hostname, false), false)); 634 net::EscapeQueryParamValue(manifest.hostname, false), false));
649 if (manifest.manifest_id != PrecacheReferrerHostEntry::kInvalidId) { 635 if (manifest.manifest_id != PrecacheReferrerHostEntry::kInvalidId) {
(...skipping 26 matching lines...) Expand all
676 unfinished_work_->config_settings().daily_quota_total()); 662 unfinished_work_->config_settings().daily_quota_total());
677 db_task_runner_->PostTask( 663 db_task_runner_->PostTask(
678 FROM_HERE, 664 FROM_HERE,
679 base::Bind(&PrecacheDatabase::SaveQuota, precache_database_, quota_)); 665 base::Bind(&PrecacheDatabase::SaveQuota, precache_database_, quota_));
680 } 666 }
681 StartNextFetch(); 667 StartNextFetch();
682 } 668 }
683 669
684 ManifestHostInfo::ManifestHostInfo(int64_t manifest_id, 670 ManifestHostInfo::ManifestHostInfo(int64_t manifest_id,
685 const std::string& hostname, 671 const std::string& hostname,
672 int64_t visits,
686 const std::string& used_url_hash, 673 const std::string& used_url_hash,
687 const std::string& unused_url_hash) 674 const std::string& unused_url_hash)
688 : manifest_id(manifest_id), 675 : manifest_id(manifest_id),
689 hostname(hostname), 676 hostname(hostname),
677 visits(visits),
690 used_url_hash(used_url_hash), 678 used_url_hash(used_url_hash),
691 unused_url_hash(unused_url_hash) {} 679 unused_url_hash(unused_url_hash) {}
692 680
693 ManifestHostInfo::~ManifestHostInfo() {} 681 ManifestHostInfo::~ManifestHostInfo() {}
694 682
695 ManifestHostInfo::ManifestHostInfo(ManifestHostInfo&&) = default; 683 ManifestHostInfo::ManifestHostInfo(ManifestHostInfo&&) = default;
696 684
697 ManifestHostInfo& ManifestHostInfo::operator=(ManifestHostInfo&&) = default; 685 ManifestHostInfo& ManifestHostInfo::operator=(ManifestHostInfo&&) = default;
698 686
699 void PrecacheFetcher::OnManifestFetchComplete(const Fetcher& source) { 687 ResourceInfo::ResourceInfo(const GURL& url,
688 const std::string& referrer,
689 double weight)
690 : url(url), referrer(referrer), weight(weight) {}
691
692 ResourceInfo::~ResourceInfo() {}
693
694 ResourceInfo::ResourceInfo(ResourceInfo&&) = default;
695
696 ResourceInfo& ResourceInfo::operator=(ResourceInfo&&) = default;
697
698 void PrecacheFetcher::OnManifestFetchComplete(int64_t host_visits,
699 const Fetcher& source) {
700 DCHECK(unfinished_work_->has_config_settings()); 700 DCHECK(unfinished_work_->has_config_settings());
701 UpdateStats(source.response_bytes(), source.network_response_bytes()); 701 UpdateStats(source.response_bytes(), source.network_response_bytes());
702 if (source.network_url_fetcher() == nullptr) { 702 if (source.network_url_fetcher() == nullptr) {
703 pool_.DeleteAll(); // Cancel any other ongoing request. 703 pool_.DeleteAll(); // Cancel any other ongoing request.
704 } else { 704 } else {
705 PrecacheManifest manifest; 705 PrecacheManifest manifest;
706 706
707 if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) { 707 if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) {
708 const int32_t len = 708 const int32_t len =
709 std::min(manifest.resource_size(), 709 std::min(manifest.resource_size(),
710 unfinished_work_->config_settings().top_resources_count()); 710 unfinished_work_->config_settings().top_resources_count());
711 const uint64_t resource_bitset = 711 const uint64_t resource_bitset =
712 GetResourceBitset(manifest, experiment_id_); 712 GetResourceBitset(manifest, experiment_id_);
713 for (int i = 0; i < len; ++i) { 713 for (int i = 0; i < len; ++i) {
714 if (((0x1ULL << i) & resource_bitset) && 714 if (((0x1ULL << i) & resource_bitset) &&
715 manifest.resource(i).has_url()) { 715 manifest.resource(i).has_url()) {
716 GURL url(manifest.resource(i).url()); 716 GURL url(manifest.resource(i).url());
717 if (url.is_valid()) { 717 if (url.is_valid()) {
718 resources_to_fetch_.emplace_back(url, source.referrer()); 718 double weight = ResourceWeight(manifest.resource(i), host_visits);
719 if (weight >= unfinished_work_->config_settings().min_weight())
720 resources_to_rank_.emplace_back(url, source.referrer(), weight);
719 } 721 }
720 } 722 }
721 } 723 }
722 db_task_runner_->PostTask( 724 db_task_runner_->PostTask(
723 FROM_HERE, base::Bind(&PrecacheDatabase::UpdatePrecacheReferrerHost, 725 FROM_HERE, base::Bind(&PrecacheDatabase::UpdatePrecacheReferrerHost,
724 precache_database_, source.referrer(), 726 precache_database_, source.referrer(),
725 manifest.id().id(), base::Time::Now())); 727 manifest.id().id(), base::Time::Now()));
726 } 728 }
727 } 729 }
728 730
731 top_hosts_fetching_.remove_if([&source](const ManifestHostInfo& top_host) {
732 return top_host.manifest_url == source.url();
733 });
734
729 pool_.Delete(source); 735 pool_.Delete(source);
736
737 if (top_hosts_to_fetch_.empty() && top_hosts_fetching_.empty())
738 QueueResourcesForFetch();
739
730 StartNextFetch(); 740 StartNextFetch();
731 } 741 }
732 742
743 void PrecacheFetcher::QueueResourcesForFetch() {
744 // Done fetching manifests. Now move resources_to_rank_ into
745 // resources_to_fetch_, so that StartNextFetch will begin fetching resources.
746 resources_to_fetch_ = std::move(resources_to_rank_);
747
748 if (unfinished_work_->config_settings().global_ranking()) {
749 // Sort resources_to_fetch_ by descending weight.
750 std::stable_sort(resources_to_fetch_.begin(), resources_to_fetch_.end(),
751 [](const ResourceInfo& first, const ResourceInfo& second) {
752 return first.weight > second.weight;
753 });
754 }
755
756 // Truncate to size |total_resources_count|.
757 const size_t num_resources = std::min(
758 resources_to_fetch_.size(),
759 static_cast<size_t>(
760 unfinished_work_->config_settings().total_resources_count()));
761 resources_to_fetch_.erase(resources_to_fetch_.begin() + num_resources,
762 resources_to_fetch_.end());
763
764 // Save denominator for PercentCompleted UMA.
765 unfinished_work_->set_num_resource_urls(resources_to_fetch_.size());
766 }
767
733 void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) { 768 void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) {
734 UpdateStats(source.response_bytes(), source.network_response_bytes()); 769 UpdateStats(source.response_bytes(), source.network_response_bytes());
735 770
736 db_task_runner_->PostTask( 771 db_task_runner_->PostTask(
737 FROM_HERE, 772 FROM_HERE,
738 base::Bind(&PrecacheDatabase::RecordURLPrefetch, precache_database_, 773 base::Bind(&PrecacheDatabase::RecordURLPrefetch, precache_database_,
739 source.url(), source.referrer(), base::Time::Now(), 774 source.url(), source.referrer(), base::Time::Now(),
740 source.was_cached(), source.response_bytes())); 775 source.was_cached(), source.response_bytes()));
741 776
777 resources_fetching_.remove_if([&source](const ResourceInfo& resource) {
778 return resource.url == source.url();
779 });
780
742 pool_.Delete(source); 781 pool_.Delete(source);
743 782
744 // The resource has already been put in the cache during the fetch process, so 783 // The resource has already been put in the cache during the fetch process, so
745 // nothing more needs to be done for the resource. 784 // nothing more needs to be done for the resource.
746 StartNextFetch(); 785 StartNextFetch();
747 } 786 }
748 787
749 void PrecacheFetcher::UpdateStats(int64_t response_bytes, 788 void PrecacheFetcher::UpdateStats(int64_t response_bytes,
750 int64_t network_response_bytes) { 789 int64_t network_response_bytes) {
751 DCHECK_LE(0, response_bytes); 790 DCHECK_LE(0, response_bytes);
(...skipping 12 matching lines...) Expand all
764 remaining = 0; 803 remaining = 0;
765 quota_.set_remaining( 804 quota_.set_remaining(
766 used_bytes > quota_.remaining() ? 0U : quota_.remaining() - used_bytes); 805 used_bytes > quota_.remaining() ? 0U : quota_.remaining() - used_bytes);
767 db_task_runner_->PostTask( 806 db_task_runner_->PostTask(
768 FROM_HERE, 807 FROM_HERE,
769 base::Bind(&PrecacheDatabase::SaveQuota, precache_database_, quota_)); 808 base::Bind(&PrecacheDatabase::SaveQuota, precache_database_, quota_));
770 } 809 }
771 } 810 }
772 811
773 } // namespace precache 812 } // namespace precache
OLDNEW
« no previous file with comments | « components/precache/core/precache_fetcher.h ('k') | components/precache/core/precache_fetcher_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698