Chromium Code Reviews| OLD | NEW |
|---|---|
| 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 <string> | |
| 10 #include <utility> | 9 #include <utility> |
| 11 #include <vector> | 10 #include <vector> |
| 12 | 11 |
| 12 #include "base/base64.h" | |
| 13 #include "base/bind.h" | 13 #include "base/bind.h" |
| 14 #include "base/bind_helpers.h" | 14 #include "base/bind_helpers.h" |
| 15 #include "base/callback.h" | 15 #include "base/callback.h" |
| 16 #include "base/command_line.h" | 16 #include "base/command_line.h" |
| 17 #include "base/compiler_specific.h" | 17 #include "base/compiler_specific.h" |
| 18 #include "base/containers/hash_tables.h" | 18 #include "base/containers/hash_tables.h" |
| 19 #include "base/location.h" | 19 #include "base/location.h" |
| 20 #include "base/logging.h" | 20 #include "base/logging.h" |
| 21 #include "base/memory/ptr_util.h" | 21 #include "base/memory/ptr_util.h" |
| 22 #include "base/memory/ref_counted.h" | 22 #include "base/memory/ref_counted.h" |
| 23 #include "base/metrics/histogram_macros.h" | 23 #include "base/metrics/histogram_macros.h" |
| 24 #include "base/sha1.h" | |
| 25 #include "base/strings/string_piece.h" | |
| 26 #include "base/task_runner_util.h" | |
| 27 #include "components/precache/core/precache_database.h" | |
| 24 #include "components/precache/core/precache_switches.h" | 28 #include "components/precache/core/precache_switches.h" |
| 25 #include "components/precache/core/proto/precache.pb.h" | 29 #include "components/precache/core/proto/precache.pb.h" |
| 26 #include "components/precache/core/proto/unfinished_work.pb.h" | 30 #include "components/precache/core/proto/unfinished_work.pb.h" |
| 27 #include "net/base/completion_callback.h" | 31 #include "net/base/completion_callback.h" |
| 28 #include "net/base/escape.h" | 32 #include "net/base/escape.h" |
| 29 #include "net/base/io_buffer.h" | 33 #include "net/base/io_buffer.h" |
| 30 #include "net/base/load_flags.h" | 34 #include "net/base/load_flags.h" |
| 31 #include "net/base/net_errors.h" | 35 #include "net/base/net_errors.h" |
| 36 #include "net/base/url_util.h" | |
| 32 #include "net/http/http_response_headers.h" | 37 #include "net/http/http_response_headers.h" |
| 33 #include "net/url_request/url_fetcher_response_writer.h" | 38 #include "net/url_request/url_fetcher_response_writer.h" |
| 34 #include "net/url_request/url_request_context_getter.h" | 39 #include "net/url_request/url_request_context_getter.h" |
| 35 #include "net/url_request/url_request_status.h" | 40 #include "net/url_request/url_request_status.h" |
| 36 | 41 |
| 37 namespace precache { | 42 namespace precache { |
| 38 | 43 |
| 39 // The following flags are for privacy reasons. For example, if a user clears | 44 // The following flags are for privacy reasons. For example, if a user clears |
| 40 // their cookies, but a tracking beacon is prefetched and the beacon specifies | 45 // their cookies, but a tracking beacon is prefetched and the beacon specifies |
| 41 // its source URL in a URL param, the beacon site would be able to rebuild a | 46 // its source URL in a URL param, the beacon site would be able to rebuild a |
| (...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 83 | 88 |
| 84 #if defined(PRECACHE_MANIFEST_URL_PREFIX) | 89 #if defined(PRECACHE_MANIFEST_URL_PREFIX) |
| 85 return PRECACHE_MANIFEST_URL_PREFIX; | 90 return PRECACHE_MANIFEST_URL_PREFIX; |
| 86 #else | 91 #else |
| 87 // The precache manifest URL prefix could not be determined, so return an | 92 // The precache manifest URL prefix could not be determined, so return an |
| 88 // empty string. | 93 // empty string. |
| 89 return std::string(); | 94 return std::string(); |
| 90 #endif | 95 #endif |
| 91 } | 96 } |
| 92 | 97 |
| 93 // Construct the URL of the precache manifest for the given name (either host or | |
| 94 // URL). The server is expecting a request for a URL consisting of the manifest | |
| 95 // URL prefix followed by the doubly escaped name. | |
| 96 std::string ConstructManifestURL(const std::string& prefix, | |
| 97 const std::string& name) { | |
| 98 return prefix + net::EscapeQueryParamValue( | |
| 99 net::EscapeQueryParamValue(name, false), false); | |
| 100 } | |
| 101 | |
| 102 // Attempts to parse a protobuf message from the response string of a | 98 // Attempts to parse a protobuf message from the response string of a |
| 103 // URLFetcher. If parsing is successful, the message parameter will contain the | 99 // URLFetcher. If parsing is successful, the message parameter will contain the |
| 104 // parsed protobuf and this function will return true. Otherwise, returns false. | 100 // parsed protobuf and this function will return true. Otherwise, returns false. |
| 105 bool ParseProtoFromFetchResponse(const net::URLFetcher& source, | 101 bool ParseProtoFromFetchResponse(const net::URLFetcher& source, |
| 106 ::google::protobuf::MessageLite* message) { | 102 ::google::protobuf::MessageLite* message) { |
| 107 std::string response_string; | 103 std::string response_string; |
| 108 | 104 |
| 109 if (!source.GetStatus().is_success()) { | 105 if (!source.GetStatus().is_success()) { |
| 110 DLOG(WARNING) << "Fetch failed: " << source.GetOriginalURL().spec(); | 106 DLOG(WARNING) << "Fetch failed: " << source.GetOriginalURL().spec(); |
| 111 return false; | 107 return false; |
| (...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 152 int num_bytes, | 148 int num_bytes, |
| 153 const net::CompletionCallback& callback) override { | 149 const net::CompletionCallback& callback) override { |
| 154 return num_bytes; | 150 return num_bytes; |
| 155 } | 151 } |
| 156 | 152 |
| 157 int Finish(const net::CompletionCallback& callback) override { | 153 int Finish(const net::CompletionCallback& callback) override { |
| 158 return net::OK; | 154 return net::OK; |
| 159 } | 155 } |
| 160 }; | 156 }; |
| 161 | 157 |
| 162 void AppendManifestURLIfValidAndNew( | 158 // Returns the base64 encoded resource URL hashes. The resource URLs are hashed |
| 163 const std::string& prefix, | 159 // individually, and 8 bytes of each hash is appended together, which is then |
| 164 const std::string& name, | 160 // encoded to base64. |
| 165 base::hash_set<std::string>* seen_manifest_urls, | 161 std::string GetResourceURLBase64Hash(const std::vector<GURL>& urls) { |
| 166 std::list<GURL>* unique_manifest_urls) { | 162 // Each resource hash uses 8 bytes, instead of the 20 bytes of sha1 hash, as a |
| 167 const std::string manifest_url = ConstructManifestURL(prefix, name); | 163 // tradeoff between sending more bytes and reducing hash collisions. |
| 168 bool first_seen = seen_manifest_urls->insert(manifest_url).second; | 164 const size_t kHashBytesSize = 8; |
| 169 if (first_seen) { | 165 std::string hashes; |
| 170 GURL url(manifest_url); | 166 hashes.reserve(urls.size() * kHashBytesSize); |
| 171 if (url.is_valid()) | 167 |
| 172 unique_manifest_urls->push_back(url); | 168 for (const auto& url : urls) { |
| 169 const std::string& url_spec = url.spec(); | |
| 170 unsigned char sha1_hash[base::kSHA1Length]; | |
| 171 base::SHA1HashBytes( | |
| 172 reinterpret_cast<const unsigned char*>(url_spec.c_str()), | |
| 173 url_spec.size(), sha1_hash); | |
| 174 hashes.append(reinterpret_cast<const char*>(sha1_hash), kHashBytesSize); | |
| 173 } | 175 } |
| 176 base::Base64Encode(hashes, &hashes); | |
| 177 return hashes; | |
| 178 } | |
| 179 | |
| 180 // Retrieves the manifest info on the DB thread. Manifest info for each of the | |
| 181 // hosts in |hosts_to_fetch|, is added to |hosts_info|. | |
| 182 std::deque<ManifestHostInfo> RetrieveManifestInfo( | |
| 183 const base::WeakPtr<PrecacheDatabase>& precache_database, | |
| 184 std::vector<std::string> hosts_to_fetch) { | |
| 185 std::deque<ManifestHostInfo> hosts_info; | |
| 186 if (!precache_database) | |
| 187 return std::move(hosts_info); | |
| 188 | |
| 189 for (const auto& host : hosts_to_fetch) { | |
| 190 auto referrer_host_info = precache_database->GetReferrerHost(host); | |
| 191 if (referrer_host_info.id != PrecacheReferrerHostEntry::kInvalidId) { | |
| 192 std::vector<GURL> used_urls, unused_urls; | |
| 193 precache_database->GetURLListForReferrerHost(referrer_host_info.id, | |
| 194 &used_urls, &unused_urls); | |
| 195 hosts_info.push_back(ManifestHostInfo( | |
| 196 referrer_host_info.id, host, GetResourceURLBase64Hash(used_urls), | |
| 197 GetResourceURLBase64Hash(unused_urls))); | |
| 198 } else { | |
| 199 hosts_info.push_back( | |
| 200 ManifestHostInfo(PrecacheReferrerHostEntry::kInvalidId, host, | |
| 201 std::string(), std::string())); | |
| 202 } | |
| 203 } | |
| 204 return std::move(hosts_info); | |
|
sclittle
2016/08/24 02:39:44
nit: remove the std::move here. You don't have to
| |
| 174 } | 205 } |
| 175 | 206 |
| 176 } // namespace | 207 } // namespace |
| 177 | 208 |
| 178 PrecacheFetcher::Fetcher::Fetcher( | 209 PrecacheFetcher::Fetcher::Fetcher( |
| 179 net::URLRequestContextGetter* request_context, | 210 net::URLRequestContextGetter* request_context, |
| 180 const GURL& url, | 211 const GURL& url, |
| 212 const std::string& referrer, | |
| 181 const base::Callback<void(const Fetcher&)>& callback, | 213 const base::Callback<void(const Fetcher&)>& callback, |
| 182 bool is_resource_request, | 214 bool is_resource_request, |
| 183 size_t max_bytes) | 215 size_t max_bytes) |
| 184 : request_context_(request_context), | 216 : request_context_(request_context), |
| 185 url_(url), | 217 url_(url), |
| 218 referrer_(referrer), | |
| 186 callback_(callback), | 219 callback_(callback), |
| 187 is_resource_request_(is_resource_request), | 220 is_resource_request_(is_resource_request), |
| 188 max_bytes_(max_bytes), | 221 max_bytes_(max_bytes), |
| 189 response_bytes_(0), | 222 response_bytes_(0), |
| 190 network_response_bytes_(0) { | 223 network_response_bytes_(0), |
| 224 was_cached_(false) { | |
| 225 DCHECK(url.is_valid()); | |
| 191 if (is_resource_request_) | 226 if (is_resource_request_) |
| 192 LoadFromCache(); | 227 LoadFromCache(); |
| 193 else | 228 else |
| 194 LoadFromNetwork(); | 229 LoadFromNetwork(); |
| 195 } | 230 } |
| 196 | 231 |
| 197 PrecacheFetcher::Fetcher::~Fetcher() {} | 232 PrecacheFetcher::Fetcher::~Fetcher() {} |
| 198 | 233 |
| 199 void PrecacheFetcher::Fetcher::LoadFromCache() { | 234 void PrecacheFetcher::Fetcher::LoadFromCache() { |
| 200 fetch_stage_ = FetchStage::CACHE; | 235 fetch_stage_ = FetchStage::CACHE; |
| (...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 233 const net::URLFetcher* source, | 268 const net::URLFetcher* source, |
| 234 int64_t current, | 269 int64_t current, |
| 235 int64_t total) { | 270 int64_t total) { |
| 236 // If going over the per-resource download cap. | 271 // If going over the per-resource download cap. |
| 237 if (fetch_stage_ == FetchStage::NETWORK && | 272 if (fetch_stage_ == FetchStage::NETWORK && |
| 238 // |current| is guaranteed to be non-negative, so this cast is safe. | 273 // |current| is guaranteed to be non-negative, so this cast is safe. |
| 239 static_cast<size_t>(std::max(current, total)) > max_bytes_) { | 274 static_cast<size_t>(std::max(current, total)) > max_bytes_) { |
| 240 VLOG(1) << "Cancelling " << url_ << ": (" << current << "/" << total | 275 VLOG(1) << "Cancelling " << url_ << ": (" << current << "/" << total |
| 241 << ") is over " << max_bytes_; | 276 << ") is over " << max_bytes_; |
| 242 | 277 |
| 243 // Cancel the download. | |
| 244 network_url_fetcher_.reset(); | |
| 245 | |
| 246 // Call the completion callback, to attempt the next download, or to trigger | 278 // Call the completion callback, to attempt the next download, or to trigger |
| 247 // cleanup in precache_delegate_->OnDone(). | 279 // cleanup in precache_delegate_->OnDone(). |
| 248 response_bytes_ = network_response_bytes_ = current; | 280 response_bytes_ = network_response_bytes_ = current; |
| 281 was_cached_ = source->WasCached(); | |
| 249 | 282 |
| 283 // Cancel the download. | |
| 284 network_url_fetcher_.reset(); | |
| 250 callback_.Run(*this); | 285 callback_.Run(*this); |
| 251 } | 286 } |
| 252 } | 287 } |
| 253 | 288 |
| 254 void PrecacheFetcher::Fetcher::OnURLFetchComplete( | 289 void PrecacheFetcher::Fetcher::OnURLFetchComplete( |
| 255 const net::URLFetcher* source) { | 290 const net::URLFetcher* source) { |
| 256 CHECK(source); | 291 CHECK(source); |
| 257 if (fetch_stage_ == FetchStage::CACHE && | 292 if (fetch_stage_ == FetchStage::CACHE && |
| 258 (source->GetStatus().error() == net::ERR_CACHE_MISS || | 293 (source->GetStatus().error() == net::ERR_CACHE_MISS || |
| 259 (source->GetResponseHeaders() && | 294 (source->GetResponseHeaders() && |
| 260 source->GetResponseHeaders()->HasValidators()))) { | 295 source->GetResponseHeaders()->HasValidators()))) { |
| 261 // If the resource was not found in the cache, request it from the | 296 // If the resource was not found in the cache, request it from the |
| 262 // network. | 297 // network. |
| 263 // | 298 // |
| 264 // If the resource was found in the cache, but contains validators, | 299 // If the resource was found in the cache, but contains validators, |
| 265 // request a refresh. The presence of validators increases the chance that | 300 // request a refresh. The presence of validators increases the chance that |
| 266 // we get a 304 response rather than a full one, thus allowing us to | 301 // we get a 304 response rather than a full one, thus allowing us to |
| 267 // refresh the cache with minimal network load. | 302 // refresh the cache with minimal network load. |
| 268 LoadFromNetwork(); | 303 LoadFromNetwork(); |
| 269 return; | 304 return; |
| 270 } | 305 } |
| 271 | 306 |
| 272 // If any of: | 307 // If any of: |
| 273 // - The request was for a config or manifest. | 308 // - The request was for a config or manifest. |
| 274 // - The resource was a cache hit without validators. | 309 // - The resource was a cache hit without validators. |
| 275 // - The response came from the network. | 310 // - The response came from the network. |
| 276 // Then Fetcher is done with this URL and can return control to the caller. | 311 // Then Fetcher is done with this URL and can return control to the caller. |
| 277 response_bytes_ = source->GetReceivedResponseContentLength(); | 312 response_bytes_ = source->GetReceivedResponseContentLength(); |
| 278 network_response_bytes_ = source->GetTotalReceivedBytes(); | 313 network_response_bytes_ = source->GetTotalReceivedBytes(); |
| 314 was_cached_ = source->WasCached(); | |
| 279 callback_.Run(*this); | 315 callback_.Run(*this); |
| 280 } | 316 } |
| 281 | 317 |
| 282 // static | 318 // static |
| 283 void PrecacheFetcher::RecordCompletionStatistics( | 319 void PrecacheFetcher::RecordCompletionStatistics( |
| 284 const PrecacheUnfinishedWork& unfinished_work, | 320 const PrecacheUnfinishedWork& unfinished_work, |
| 285 size_t remaining_manifest_urls_to_fetch, | 321 size_t remaining_manifest_urls_to_fetch, |
| 286 size_t remaining_resource_urls_to_fetch) { | 322 size_t remaining_resource_urls_to_fetch) { |
| 287 // These may be unset in tests. | 323 // These may be unset in tests. |
| 288 if (!unfinished_work.has_start_time()) | 324 if (!unfinished_work.has_start_time()) |
| (...skipping 24 matching lines...) Expand all Loading... | |
| 313 percent_completed); | 349 percent_completed); |
| 314 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total", | 350 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total", |
| 315 unfinished_work.total_bytes(), | 351 unfinished_work.total_bytes(), |
| 316 1, kMaxResponseBytes, 100); | 352 1, kMaxResponseBytes, 100); |
| 317 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network", | 353 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network", |
| 318 unfinished_work.network_bytes(), | 354 unfinished_work.network_bytes(), |
| 319 1, kMaxResponseBytes, | 355 1, kMaxResponseBytes, |
| 320 100); | 356 100); |
| 321 } | 357 } |
| 322 | 358 |
| 359 // static | |
| 360 std::string PrecacheFetcher::GetResourceURLBase64HashForTesting( | |
| 361 const std::vector<GURL>& urls) { | |
| 362 return GetResourceURLBase64Hash(urls); | |
| 363 } | |
| 364 | |
| 323 PrecacheFetcher::PrecacheFetcher( | 365 PrecacheFetcher::PrecacheFetcher( |
| 324 net::URLRequestContextGetter* request_context, | 366 net::URLRequestContextGetter* request_context, |
| 325 const GURL& config_url, | 367 const GURL& config_url, |
| 326 const std::string& manifest_url_prefix, | 368 const std::string& manifest_url_prefix, |
| 327 std::unique_ptr<PrecacheUnfinishedWork> unfinished_work, | 369 std::unique_ptr<PrecacheUnfinishedWork> unfinished_work, |
| 328 uint32_t experiment_id, | 370 uint32_t experiment_id, |
| 371 const base::WeakPtr<PrecacheDatabase>& precache_database, | |
| 372 const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner, | |
| 329 PrecacheFetcher::PrecacheDelegate* precache_delegate) | 373 PrecacheFetcher::PrecacheDelegate* precache_delegate) |
| 330 : request_context_(request_context), | 374 : request_context_(request_context), |
| 331 config_url_(config_url), | 375 config_url_(config_url), |
| 332 manifest_url_prefix_(manifest_url_prefix), | 376 manifest_url_prefix_(manifest_url_prefix), |
| 377 precache_database_(precache_database), | |
| 378 db_task_runner_(std::move(db_task_runner)), | |
| 333 precache_delegate_(precache_delegate), | 379 precache_delegate_(precache_delegate), |
| 334 pool_(kMaxParallelFetches), | 380 pool_(kMaxParallelFetches), |
| 335 experiment_id_(experiment_id) { | 381 experiment_id_(experiment_id) { |
| 336 DCHECK(request_context_.get()); // Request context must be non-NULL. | 382 DCHECK(request_context_.get()); // Request context must be non-NULL. |
| 337 DCHECK(precache_delegate_); // Precache delegate must be non-NULL. | 383 DCHECK(precache_delegate_); // Precache delegate must be non-NULL. |
| 338 | 384 |
| 339 DCHECK_NE(GURL(), GetDefaultConfigURL()) | 385 DCHECK_NE(GURL(), GetDefaultConfigURL()) |
| 340 << "Could not determine the precache config settings URL."; | 386 << "Could not determine the precache config settings URL."; |
| 341 DCHECK_NE(std::string(), GetDefaultManifestURLPrefix()) | 387 DCHECK_NE(std::string(), GetDefaultManifestURLPrefix()) |
| 342 << "Could not determine the default precache manifest URL prefix."; | 388 << "Could not determine the default precache manifest URL prefix."; |
| 343 DCHECK(unfinished_work); | 389 DCHECK(unfinished_work); |
| 344 | 390 |
| 345 // Copy manifests and resources to member variables as a convenience. | 391 // Copy resources to member variable as a convenience. |
| 346 // TODO(bengr): Consider accessing these directly from the proto. | 392 // TODO(rajendrant): Consider accessing these directly from the proto, by |
| 347 for (const auto& manifest : unfinished_work->manifest()) { | 393 // keeping track of the current resource index. |
| 348 if (manifest.has_url()) | |
| 349 manifest_urls_to_fetch_.push_back(GURL(manifest.url())); | |
| 350 } | |
| 351 for (const auto& resource : unfinished_work->resource()) { | 394 for (const auto& resource : unfinished_work->resource()) { |
| 352 if (resource.has_url()) | 395 if (resource.has_url() && resource.has_top_host_name()) { |
| 353 resource_urls_to_fetch_.push_back(GURL(resource.url())); | 396 resources_to_fetch_.emplace_back(GURL(resource.url()), |
| 397 resource.top_host_name()); | |
| 398 } | |
| 354 } | 399 } |
| 355 unfinished_work_ = std::move(unfinished_work); | 400 unfinished_work_ = std::move(unfinished_work); |
| 356 } | 401 } |
| 357 | 402 |
| 358 PrecacheFetcher::~PrecacheFetcher() { | 403 PrecacheFetcher::~PrecacheFetcher() { |
| 359 } | 404 } |
| 360 | 405 |
| 361 std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { | 406 std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { |
| 362 // This could get called multiple times, and it should be handled gracefully. | 407 // This could get called multiple times, and it should be handled gracefully. |
| 363 if (!unfinished_work_) | 408 if (!unfinished_work_) |
| 364 return nullptr; | 409 return nullptr; |
| 365 | 410 |
| 366 unfinished_work_->clear_manifest(); | |
| 367 unfinished_work_->clear_resource(); | 411 unfinished_work_->clear_resource(); |
| 368 for (const auto& manifest : manifest_urls_to_fetch_) | 412 if (top_hosts_to_fetch_.size()) { |
| 369 unfinished_work_->add_manifest()->set_url(manifest.spec()); | 413 // If config fetch is incomplete, |top_hosts_to_fetch_| will be empty and |
| 370 for (const auto& resource : resource_urls_to_fetch_) | 414 // top hosts should be left as is in |unfinished_work_|. |
| 371 unfinished_work_->add_resource()->set_url(resource.spec()); | 415 unfinished_work_->clear_top_host(); |
| 416 for (const auto& top_host : top_hosts_to_fetch_) { | |
| 417 unfinished_work_->add_top_host()->set_hostname(top_host.hostname); | |
| 418 } | |
| 419 } | |
| 420 for (const auto& resource : resources_to_fetch_) { | |
| 421 auto new_resource = unfinished_work_->add_resource(); | |
| 422 new_resource->set_url(resource.first.spec()); | |
| 423 new_resource->set_top_host_name(resource.second); | |
| 424 } | |
| 372 for (const auto& it : pool_.elements()) { | 425 for (const auto& it : pool_.elements()) { |
| 373 const Fetcher* fetcher = it.first; | 426 const Fetcher* fetcher = it.first; |
| 374 if (fetcher->is_resource_request()) | 427 GURL config_url = |
| 375 unfinished_work_->add_resource()->set_url(fetcher->url().spec()); | 428 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; |
| 376 else if (fetcher->url() != config_url_) | 429 if (fetcher->is_resource_request()) { |
| 377 unfinished_work_->add_manifest()->set_url(fetcher->url().spec()); | 430 auto resource = unfinished_work_->add_resource(); |
| 431 resource->set_url(fetcher->url().spec()); | |
| 432 resource->set_top_host_name(fetcher->referrer()); | |
| 433 } else if (fetcher->url() != config_url) { | |
| 434 unfinished_work_->add_top_host()->set_hostname(fetcher->referrer()); | |
| 435 } | |
| 378 } | 436 } |
| 379 manifest_urls_to_fetch_.clear(); | 437 top_hosts_to_fetch_.clear(); |
| 380 resource_urls_to_fetch_.clear(); | 438 resources_to_fetch_.clear(); |
| 381 pool_.DeleteAll(); | 439 pool_.DeleteAll(); |
| 382 return std::move(unfinished_work_); | 440 return std::move(unfinished_work_); |
| 383 } | 441 } |
| 384 | 442 |
| 385 void PrecacheFetcher::Start() { | 443 void PrecacheFetcher::Start() { |
| 386 if (unfinished_work_->has_config_settings()) { | 444 if (unfinished_work_->has_config_settings()) { |
| 387 DCHECK(unfinished_work_->has_start_time()); | 445 DCHECK(unfinished_work_->has_start_time()); |
| 388 DetermineManifests(); | 446 DetermineManifests(); |
| 389 return; | 447 return; |
| 390 } | 448 } |
| 391 | 449 |
| 392 GURL config_url = | 450 GURL config_url = |
| 393 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; | 451 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; |
| 394 | 452 |
| 395 DCHECK(config_url.is_valid()) << "Config URL not valid: " | 453 DCHECK(config_url.is_valid()) << "Config URL not valid: " |
| 396 << config_url.possibly_invalid_spec(); | 454 << config_url.possibly_invalid_spec(); |
| 397 | 455 |
| 398 // Fetch the precache configuration settings from the server. | 456 // Fetch the precache configuration settings from the server. |
| 399 DCHECK(pool_.IsEmpty()) << "All parallel requests should be available"; | 457 DCHECK(pool_.IsEmpty()) << "All parallel requests should be available"; |
| 400 VLOG(3) << "Fetching " << config_url; | 458 VLOG(3) << "Fetching " << config_url; |
| 401 pool_.Add(base::WrapUnique(new Fetcher( | 459 pool_.Add(base::WrapUnique(new Fetcher( |
| 402 request_context_.get(), config_url, | 460 request_context_.get(), config_url, std::string(), |
| 403 base::Bind(&PrecacheFetcher::OnConfigFetchComplete, | 461 base::Bind(&PrecacheFetcher::OnConfigFetchComplete, AsWeakPtr()), |
| 404 base::Unretained(this)), | |
| 405 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); | 462 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); |
| 406 } | 463 } |
| 407 | 464 |
| 408 void PrecacheFetcher::StartNextResourceFetch() { | 465 void PrecacheFetcher::StartNextResourceFetch() { |
| 409 DCHECK(unfinished_work_->has_config_settings()); | 466 DCHECK(unfinished_work_->has_config_settings()); |
| 410 while (!resource_urls_to_fetch_.empty() && pool_.IsAvailable()) { | 467 while (!resources_to_fetch_.empty() && pool_.IsAvailable()) { |
| 468 const auto& resource = resources_to_fetch_.front(); | |
| 411 const size_t max_bytes = | 469 const size_t max_bytes = |
| 412 std::min(unfinished_work_->config_settings().max_bytes_per_resource(), | 470 std::min(unfinished_work_->config_settings().max_bytes_per_resource(), |
| 413 unfinished_work_->config_settings().max_bytes_total() - | 471 unfinished_work_->config_settings().max_bytes_total() - |
| 414 unfinished_work_->total_bytes()); | 472 unfinished_work_->total_bytes()); |
| 415 VLOG(3) << "Fetching " << resource_urls_to_fetch_.front(); | 473 VLOG(3) << "Fetching " << resource.first << " " << resource.second; |
| 416 pool_.Add(base::WrapUnique( | 474 pool_.Add(base::WrapUnique(new Fetcher( |
| 417 new Fetcher(request_context_.get(), resource_urls_to_fetch_.front(), | 475 request_context_.get(), resource.first, resource.second, |
| 418 base::Bind(&PrecacheFetcher::OnResourceFetchComplete, | 476 base::Bind(&PrecacheFetcher::OnResourceFetchComplete, AsWeakPtr()), |
| 419 base::Unretained(this)), | 477 true /* is_resource_request */, max_bytes))); |
| 420 true /* is_resource_request */, max_bytes))); | |
| 421 | 478 |
| 422 resource_urls_to_fetch_.pop_front(); | 479 resources_to_fetch_.pop_front(); |
| 423 } | 480 } |
| 424 } | 481 } |
| 425 | 482 |
| 426 void PrecacheFetcher::StartNextManifestFetch() { | 483 void PrecacheFetcher::StartNextManifestFetch() { |
| 427 if (manifest_urls_to_fetch_.empty() || !pool_.IsAvailable()) | 484 if (top_hosts_to_fetch_.empty() || !pool_.IsAvailable()) |
| 428 return; | 485 return; |
| 429 | 486 |
| 430 // We only fetch one manifest at a time to keep the size of | 487 // We only fetch one manifest at a time to keep the size of |
| 431 // resource_urls_to_fetch_ as small as possible. | 488 // resources_to_fetch_ as small as possible. |
| 432 VLOG(3) << "Fetching " << manifest_urls_to_fetch_.front(); | 489 VLOG(3) << "Fetching " << top_hosts_to_fetch_.front().manifest_url; |
| 433 pool_.Add(base::WrapUnique(new Fetcher( | 490 pool_.Add(base::WrapUnique(new Fetcher( |
| 434 request_context_.get(), manifest_urls_to_fetch_.front(), | 491 request_context_.get(), top_hosts_to_fetch_.front().manifest_url, |
| 435 base::Bind(&PrecacheFetcher::OnManifestFetchComplete, | 492 top_hosts_to_fetch_.front().hostname, |
| 436 base::Unretained(this)), | 493 base::Bind(&PrecacheFetcher::OnManifestFetchComplete, AsWeakPtr()), |
| 437 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); | 494 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); |
| 438 | 495 top_hosts_to_fetch_.pop_front(); |
| 439 manifest_urls_to_fetch_.pop_front(); | |
| 440 } | 496 } |
| 441 | 497 |
| 442 void PrecacheFetcher::NotifyDone( | 498 void PrecacheFetcher::NotifyDone( |
| 443 size_t remaining_manifest_urls_to_fetch, | 499 size_t remaining_manifest_urls_to_fetch, |
| 444 size_t remaining_resource_urls_to_fetch) { | 500 size_t remaining_resource_urls_to_fetch) { |
| 445 RecordCompletionStatistics(*unfinished_work_, | 501 RecordCompletionStatistics(*unfinished_work_, |
| 446 remaining_manifest_urls_to_fetch, | 502 remaining_manifest_urls_to_fetch, |
| 447 remaining_resource_urls_to_fetch); | 503 remaining_resource_urls_to_fetch); |
| 448 precache_delegate_->OnDone(); | 504 precache_delegate_->OnDone(); |
| 449 } | 505 } |
| 450 | 506 |
| 451 void PrecacheFetcher::StartNextFetch() { | 507 void PrecacheFetcher::StartNextFetch() { |
| 452 DCHECK(unfinished_work_->has_config_settings()); | 508 DCHECK(unfinished_work_->has_config_settings()); |
| 453 // If over the precache total size cap, then stop prefetching. | 509 // If over the precache total size cap, then stop prefetching. |
| 454 if (unfinished_work_->total_bytes() > | 510 if (unfinished_work_->total_bytes() > |
| 455 unfinished_work_->config_settings().max_bytes_total()) { | 511 unfinished_work_->config_settings().max_bytes_total()) { |
| 456 size_t pending_manifests_in_pool = 0; | 512 size_t pending_manifests_in_pool = 0; |
| 457 size_t pending_resources_in_pool = 0; | 513 size_t pending_resources_in_pool = 0; |
| 458 for (const auto& element_pair : pool_.elements()) { | 514 for (const auto& element_pair : pool_.elements()) { |
| 459 const Fetcher* fetcher = element_pair.first; | 515 const Fetcher* fetcher = element_pair.first; |
| 460 if (fetcher->is_resource_request()) | 516 if (fetcher->is_resource_request()) |
| 461 pending_resources_in_pool++; | 517 pending_resources_in_pool++; |
| 462 else if (fetcher->url() != config_url_) | 518 else if (fetcher->url() != config_url_) |
| 463 pending_manifests_in_pool++; | 519 pending_manifests_in_pool++; |
| 464 } | 520 } |
| 465 pool_.DeleteAll(); | 521 pool_.DeleteAll(); |
| 466 NotifyDone(manifest_urls_to_fetch_.size() + pending_manifests_in_pool, | 522 NotifyDone(top_hosts_to_fetch_.size() + pending_manifests_in_pool, |
| 467 resource_urls_to_fetch_.size() + pending_resources_in_pool); | 523 resources_to_fetch_.size() + pending_resources_in_pool); |
| 468 return; | 524 return; |
| 469 } | 525 } |
| 470 | 526 |
| 471 StartNextResourceFetch(); | 527 StartNextResourceFetch(); |
| 472 StartNextManifestFetch(); | 528 StartNextManifestFetch(); |
| 473 if (pool_.IsEmpty()) { | 529 if (top_hosts_to_fetch_.empty() && resources_to_fetch_.empty() && |
| 530 pool_.IsEmpty()) { | |
| 474 // There are no more URLs to fetch, so end the precache cycle. | 531 // There are no more URLs to fetch, so end the precache cycle. |
| 475 NotifyDone(0, 0); | 532 NotifyDone(0, 0); |
| 476 // OnDone may have deleted this PrecacheFetcher, so don't do anything after | 533 // OnDone may have deleted this PrecacheFetcher, so don't do anything after |
| 477 // it is called. | 534 // it is called. |
| 478 } | 535 } |
| 479 } | 536 } |
| 480 | 537 |
| 481 void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) { | 538 void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) { |
| 482 UpdateStats(source.response_bytes(), source.network_response_bytes()); | 539 UpdateStats(source.response_bytes(), source.network_response_bytes()); |
| 483 if (source.network_url_fetcher() == nullptr) { | 540 if (source.network_url_fetcher() == nullptr) { |
| 484 pool_.DeleteAll(); // Cancel any other ongoing request. | 541 pool_.DeleteAll(); // Cancel any other ongoing request. |
| 485 } else { | 542 } else { |
| 486 // Attempt to parse the config proto. On failure, continue on with the | 543 // Attempt to parse the config proto. On failure, continue on with the |
| 487 // default configuration. | 544 // default configuration. |
| 488 ParseProtoFromFetchResponse( | 545 ParseProtoFromFetchResponse( |
| 489 *source.network_url_fetcher(), | 546 *source.network_url_fetcher(), |
| 490 unfinished_work_->mutable_config_settings()); | 547 unfinished_work_->mutable_config_settings()); |
| 491 pool_.Delete(source); | 548 pool_.Delete(source); |
| 492 DetermineManifests(); | 549 DetermineManifests(); |
| 493 } | 550 } |
| 494 } | 551 } |
| 495 | 552 |
| 496 void PrecacheFetcher::DetermineManifests() { | 553 void PrecacheFetcher::DetermineManifests() { |
| 497 DCHECK(unfinished_work_->has_config_settings()); | 554 DCHECK(unfinished_work_->has_config_settings()); |
| 498 std::string prefix = manifest_url_prefix_.empty() | |
| 499 ? GetDefaultManifestURLPrefix() | |
| 500 : manifest_url_prefix_; | |
| 501 DCHECK_NE(std::string(), prefix) | |
| 502 << "Could not determine the precache manifest URL prefix."; | |
| 503 | 555 |
| 504 // Keep track of manifest URLs that are being fetched, in order to elide | 556 std::vector<std::string> top_hosts_to_fetch; |
| 505 // duplicates. | 557 std::unique_ptr<std::deque<ManifestHostInfo>> top_hosts_info( |
| 506 base::hash_set<std::string> seen_manifest_urls; | 558 new std::deque<ManifestHostInfo>); |
| 559 // Keep track of manifest URLs that are being fetched, in order to elide | |
| 560 // duplicates. | |
| 561 std::set<base::StringPiece> seen_top_hosts; | |
| 562 int64_t rank = 0; | |
| 507 | 563 |
| 508 // Attempt to fetch manifests for starting hosts up to the maximum top sites | 564 for (const auto& host : unfinished_work_->top_host()) { |
| 509 // count. If a manifest does not exist for a particular starting host, then | 565 ++rank; |
| 510 // the fetch will fail, and that starting host will be ignored. Starting | 566 if (rank > unfinished_work_->config_settings().top_sites_count()) |
| 511 // hosts are not added if this is a continuation from a previous precache | 567 break; |
| 512 // session. | 568 if (seen_top_hosts.insert(host.hostname()).second) |
| 513 if (manifest_urls_to_fetch_.empty() && | 569 top_hosts_to_fetch.push_back(host.hostname()); |
| 514 resource_urls_to_fetch_.empty()) { | 570 } |
| 515 int64_t rank = 0; | |
| 516 for (const auto& host : unfinished_work_->top_host()) { | |
| 517 ++rank; | |
| 518 if (rank > unfinished_work_->config_settings().top_sites_count()) | |
| 519 break; | |
| 520 AppendManifestURLIfValidAndNew(prefix, host.hostname(), | |
| 521 &seen_manifest_urls, | |
| 522 &manifest_urls_to_fetch_); | |
| 523 } | |
| 524 | 571 |
| 525 for (const std::string& host | 572 // Attempt to fetch manifests for starting hosts up to the maximum top sites |
| 526 : unfinished_work_->config_settings().forced_site()) { | 573 // count. If a manifest does not exist for a particular starting host, then |
| 527 AppendManifestURLIfValidAndNew(prefix, host, &seen_manifest_urls, | 574 // the fetch will fail, and that starting host will be ignored. Starting |
| 528 &manifest_urls_to_fetch_); | 575 // hosts are not added if this is a continuation from a previous precache |
| 529 } | 576 // session. |
| 577 if (resources_to_fetch_.empty()) { | |
| 578 for (const std::string& host : | |
| 579 unfinished_work_->config_settings().forced_site()) { | |
| 580 if (seen_top_hosts.insert(host).second) | |
| 581 top_hosts_to_fetch.push_back(host); | |
| 530 } | 582 } |
| 531 unfinished_work_->set_num_manifest_urls(manifest_urls_to_fetch_.size()); | 583 } |
| 532 StartNextFetch(); | 584 // We only fetch one manifest at a time to keep the size of |
| 585 // resources_to_fetch_ as small as possible. | |
| 586 PostTaskAndReplyWithResult( | |
| 587 db_task_runner_.get(), FROM_HERE, | |
| 588 base::Bind(&RetrieveManifestInfo, precache_database_, | |
| 589 std::move(top_hosts_to_fetch)), | |
| 590 base::Bind(&PrecacheFetcher::OnManifestInfoRetrieved, AsWeakPtr())); | |
| 533 } | 591 } |
| 534 | 592 |
| 593 void PrecacheFetcher::OnManifestInfoRetrieved( | |
| 594 std::deque<ManifestHostInfo> manifests_info) { | |
| 595 const std::string prefix = manifest_url_prefix_.empty() | |
| 596 ? GetDefaultManifestURLPrefix() | |
| 597 : manifest_url_prefix_; | |
| 598 if (!GURL(prefix).is_valid()) { | |
| 599 // Don't attempt to fetch any manifests if the manifest URL prefix | |
| 600 // is invalid. | |
| 601 top_hosts_to_fetch_.clear(); | |
| 602 unfinished_work_->set_num_manifest_urls(manifests_info.size()); | |
| 603 NotifyDone(manifests_info.size(), resources_to_fetch_.size()); | |
| 604 return; | |
| 605 } | |
| 606 | |
| 607 top_hosts_to_fetch_ = std::move(manifests_info); | |
| 608 for (auto& manifest : top_hosts_to_fetch_) { | |
| 609 manifest.manifest_url = | |
| 610 GURL(prefix + | |
| 611 net::EscapeQueryParamValue( | |
| 612 net::EscapeQueryParamValue(manifest.hostname, false), false)); | |
| 613 if (manifest.manifest_id != PrecacheReferrerHostEntry::kInvalidId) { | |
| 614 manifest.manifest_url = net::AppendOrReplaceQueryParameter( | |
| 615 manifest.manifest_url, "manifest", | |
| 616 std::to_string(manifest.manifest_id)); | |
| 617 manifest.manifest_url = net::AppendOrReplaceQueryParameter( | |
| 618 manifest.manifest_url, "used_resources", manifest.used_url_hash); | |
| 619 manifest.manifest_url = net::AppendOrReplaceQueryParameter( | |
| 620 manifest.manifest_url, "unused_resources", manifest.unused_url_hash); | |
| 621 DCHECK(manifest.manifest_url.is_valid()); | |
| 622 } | |
| 623 } | |
| 624 unfinished_work_->set_num_manifest_urls(top_hosts_to_fetch_.size()); | |
| 625 StartNextFetch(); | |
| 626 } | |
| 627 | |
| 628 ManifestHostInfo::ManifestHostInfo(int64_t manifest_id, | |
| 629 const std::string& hostname, | |
| 630 const std::string& used_url_hash, | |
| 631 const std::string& unused_url_hash) | |
| 632 : manifest_id(manifest_id), | |
| 633 hostname(hostname), | |
| 634 used_url_hash(used_url_hash), | |
| 635 unused_url_hash(unused_url_hash) {} | |
| 636 | |
| 637 ManifestHostInfo::~ManifestHostInfo() {} | |
| 638 | |
| 639 ManifestHostInfo::ManifestHostInfo(ManifestHostInfo&&) = default; | |
| 640 | |
| 641 ManifestHostInfo& ManifestHostInfo::operator=(ManifestHostInfo&&) = default; | |
| 642 | |
| 535 void PrecacheFetcher::OnManifestFetchComplete(const Fetcher& source) { | 643 void PrecacheFetcher::OnManifestFetchComplete(const Fetcher& source) { |
| 536 DCHECK(unfinished_work_->has_config_settings()); | 644 DCHECK(unfinished_work_->has_config_settings()); |
| 537 UpdateStats(source.response_bytes(), source.network_response_bytes()); | 645 UpdateStats(source.response_bytes(), source.network_response_bytes()); |
| 538 if (source.network_url_fetcher() == nullptr) { | 646 if (source.network_url_fetcher() == nullptr) { |
| 539 pool_.DeleteAll(); // Cancel any other ongoing request. | 647 pool_.DeleteAll(); // Cancel any other ongoing request. |
| 540 } else { | 648 } else { |
| 541 PrecacheManifest manifest; | 649 PrecacheManifest manifest; |
| 542 | 650 |
| 543 if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) { | 651 if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) { |
| 544 const int32_t len = | 652 const int32_t len = |
| 545 std::min(manifest.resource_size(), | 653 std::min(manifest.resource_size(), |
| 546 unfinished_work_->config_settings().top_resources_count()); | 654 unfinished_work_->config_settings().top_resources_count()); |
| 547 const uint64_t resource_bitset = | 655 const uint64_t resource_bitset = |
| 548 GetResourceBitset(manifest, experiment_id_); | 656 GetResourceBitset(manifest, experiment_id_); |
| 549 for (int i = 0; i < len; ++i) { | 657 for (int i = 0; i < len; ++i) { |
| 550 if (((0x1ULL << i) & resource_bitset) && | 658 if (((0x1ULL << i) & resource_bitset) && |
| 551 manifest.resource(i).has_url()) { | 659 manifest.resource(i).has_url()) { |
| 552 GURL url(manifest.resource(i).url()); | 660 GURL url(manifest.resource(i).url()); |
| 553 if (url.is_valid()) | 661 if (url.is_valid()) { |
| 554 resource_urls_to_fetch_.push_back(url); | 662 resources_to_fetch_.emplace_back(url, source.referrer()); |
| 663 } | |
| 555 } | 664 } |
| 556 } | 665 } |
| 666 db_task_runner_->PostTask( | |
| 667 FROM_HERE, base::Bind(&PrecacheDatabase::UpdatePrecacheReferrerHost, | |
| 668 precache_database_, source.referrer(), | |
| 669 manifest.id().id(), base::Time::Now())); | |
| 557 } | 670 } |
| 558 } | 671 } |
| 559 | 672 |
| 560 pool_.Delete(source); | 673 pool_.Delete(source); |
| 561 StartNextFetch(); | 674 StartNextFetch(); |
| 562 } | 675 } |
| 563 | 676 |
| 564 void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) { | 677 void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) { |
| 565 UpdateStats(source.response_bytes(), source.network_response_bytes()); | 678 UpdateStats(source.response_bytes(), source.network_response_bytes()); |
| 679 | |
| 680 db_task_runner_->PostTask( | |
| 681 FROM_HERE, | |
| 682 base::Bind(&PrecacheDatabase::RecordURLPrefetch, precache_database_, | |
| 683 source.url(), source.referrer(), base::Time::Now(), | |
| 684 source.was_cached(), source.response_bytes())); | |
| 685 | |
| 566 pool_.Delete(source); | 686 pool_.Delete(source); |
| 687 | |
| 567 // The resource has already been put in the cache during the fetch process, so | 688 // The resource has already been put in the cache during the fetch process, so |
| 568 // nothing more needs to be done for the resource. | 689 // nothing more needs to be done for the resource. |
| 569 StartNextFetch(); | 690 StartNextFetch(); |
| 570 } | 691 } |
| 571 | 692 |
| 572 void PrecacheFetcher::UpdateStats(int64_t response_bytes, | 693 void PrecacheFetcher::UpdateStats(int64_t response_bytes, |
| 573 int64_t network_response_bytes) { | 694 int64_t network_response_bytes) { |
| 574 unfinished_work_->set_total_bytes( | 695 unfinished_work_->set_total_bytes( |
| 575 unfinished_work_->total_bytes() + response_bytes); | 696 unfinished_work_->total_bytes() + response_bytes); |
| 576 unfinished_work_->set_network_bytes( | 697 unfinished_work_->set_network_bytes( |
| 577 unfinished_work_->network_bytes() + network_response_bytes); | 698 unfinished_work_->network_bytes() + network_response_bytes); |
| 578 } | 699 } |
| 579 | 700 |
| 580 } // namespace precache | 701 } // namespace precache |
| OLD | NEW |