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; |
174 } | 178 } |
175 | 179 |
176 } // namespace | 180 } // namespace |
177 | 181 |
178 PrecacheFetcher::Fetcher::Fetcher( | 182 PrecacheFetcher::Fetcher::Fetcher( |
179 net::URLRequestContextGetter* request_context, | 183 net::URLRequestContextGetter* request_context, |
180 const GURL& url, | 184 const GURL& url, |
| 185 const std::string& referrer, |
181 const base::Callback<void(const Fetcher&)>& callback, | 186 const base::Callback<void(const Fetcher&)>& callback, |
182 bool is_resource_request, | 187 bool is_resource_request, |
183 size_t max_bytes) | 188 size_t max_bytes) |
184 : request_context_(request_context), | 189 : request_context_(request_context), |
185 url_(url), | 190 url_(url), |
| 191 referrer_(referrer), |
186 callback_(callback), | 192 callback_(callback), |
187 is_resource_request_(is_resource_request), | 193 is_resource_request_(is_resource_request), |
188 max_bytes_(max_bytes), | 194 max_bytes_(max_bytes), |
189 response_bytes_(0), | 195 response_bytes_(0), |
190 network_response_bytes_(0) { | 196 network_response_bytes_(0), |
| 197 was_cached_(false) { |
| 198 DCHECK(url.is_valid()); |
191 if (is_resource_request_) | 199 if (is_resource_request_) |
192 LoadFromCache(); | 200 LoadFromCache(); |
193 else | 201 else |
194 LoadFromNetwork(); | 202 LoadFromNetwork(); |
195 } | 203 } |
196 | 204 |
197 PrecacheFetcher::Fetcher::~Fetcher() {} | 205 PrecacheFetcher::Fetcher::~Fetcher() {} |
198 | 206 |
199 void PrecacheFetcher::Fetcher::LoadFromCache() { | 207 void PrecacheFetcher::Fetcher::LoadFromCache() { |
200 fetch_stage_ = FetchStage::CACHE; | 208 fetch_stage_ = FetchStage::CACHE; |
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
233 const net::URLFetcher* source, | 241 const net::URLFetcher* source, |
234 int64_t current, | 242 int64_t current, |
235 int64_t total) { | 243 int64_t total) { |
236 // If going over the per-resource download cap. | 244 // If going over the per-resource download cap. |
237 if (fetch_stage_ == FetchStage::NETWORK && | 245 if (fetch_stage_ == FetchStage::NETWORK && |
238 // |current| is guaranteed to be non-negative, so this cast is safe. | 246 // |current| is guaranteed to be non-negative, so this cast is safe. |
239 static_cast<size_t>(std::max(current, total)) > max_bytes_) { | 247 static_cast<size_t>(std::max(current, total)) > max_bytes_) { |
240 VLOG(1) << "Cancelling " << url_ << ": (" << current << "/" << total | 248 VLOG(1) << "Cancelling " << url_ << ": (" << current << "/" << total |
241 << ") is over " << max_bytes_; | 249 << ") is over " << max_bytes_; |
242 | 250 |
243 // Cancel the download. | |
244 network_url_fetcher_.reset(); | |
245 | |
246 // Call the completion callback, to attempt the next download, or to trigger | 251 // Call the completion callback, to attempt the next download, or to trigger |
247 // cleanup in precache_delegate_->OnDone(). | 252 // cleanup in precache_delegate_->OnDone(). |
248 response_bytes_ = network_response_bytes_ = current; | 253 response_bytes_ = network_response_bytes_ = current; |
| 254 was_cached_ = source->WasCached(); |
249 | 255 |
| 256 // Cancel the download. |
| 257 network_url_fetcher_.reset(); |
250 callback_.Run(*this); | 258 callback_.Run(*this); |
251 } | 259 } |
252 } | 260 } |
253 | 261 |
254 void PrecacheFetcher::Fetcher::OnURLFetchComplete( | 262 void PrecacheFetcher::Fetcher::OnURLFetchComplete( |
255 const net::URLFetcher* source) { | 263 const net::URLFetcher* source) { |
256 CHECK(source); | 264 CHECK(source); |
257 if (fetch_stage_ == FetchStage::CACHE && | 265 if (fetch_stage_ == FetchStage::CACHE && |
258 (source->GetStatus().error() == net::ERR_CACHE_MISS || | 266 (source->GetStatus().error() == net::ERR_CACHE_MISS || |
259 (source->GetResponseHeaders() && | 267 (source->GetResponseHeaders() && |
260 source->GetResponseHeaders()->HasValidators()))) { | 268 source->GetResponseHeaders()->HasValidators()))) { |
261 // If the resource was not found in the cache, request it from the | 269 // If the resource was not found in the cache, request it from the |
262 // network. | 270 // network. |
263 // | 271 // |
264 // If the resource was found in the cache, but contains validators, | 272 // If the resource was found in the cache, but contains validators, |
265 // request a refresh. The presence of validators increases the chance that | 273 // 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 | 274 // we get a 304 response rather than a full one, thus allowing us to |
267 // refresh the cache with minimal network load. | 275 // refresh the cache with minimal network load. |
268 LoadFromNetwork(); | 276 LoadFromNetwork(); |
269 return; | 277 return; |
270 } | 278 } |
271 | 279 |
272 // If any of: | 280 // If any of: |
273 // - The request was for a config or manifest. | 281 // - The request was for a config or manifest. |
274 // - The resource was a cache hit without validators. | 282 // - The resource was a cache hit without validators. |
275 // - The response came from the network. | 283 // - The response came from the network. |
276 // Then Fetcher is done with this URL and can return control to the caller. | 284 // Then Fetcher is done with this URL and can return control to the caller. |
277 response_bytes_ = source->GetReceivedResponseContentLength(); | 285 response_bytes_ = source->GetReceivedResponseContentLength(); |
278 network_response_bytes_ = source->GetTotalReceivedBytes(); | 286 network_response_bytes_ = source->GetTotalReceivedBytes(); |
| 287 was_cached_ = source->WasCached(); |
279 callback_.Run(*this); | 288 callback_.Run(*this); |
280 } | 289 } |
281 | 290 |
282 // static | 291 // static |
283 void PrecacheFetcher::RecordCompletionStatistics( | 292 void PrecacheFetcher::RecordCompletionStatistics( |
284 const PrecacheUnfinishedWork& unfinished_work, | 293 const PrecacheUnfinishedWork& unfinished_work, |
285 size_t remaining_manifest_urls_to_fetch, | 294 size_t remaining_manifest_urls_to_fetch, |
286 size_t remaining_resource_urls_to_fetch) { | 295 size_t remaining_resource_urls_to_fetch) { |
287 // These may be unset in tests. | 296 // These may be unset in tests. |
288 if (!unfinished_work.has_start_time()) | 297 if (!unfinished_work.has_start_time()) |
(...skipping 24 matching lines...) Expand all Loading... |
313 percent_completed); | 322 percent_completed); |
314 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total", | 323 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Total", |
315 unfinished_work.total_bytes(), | 324 unfinished_work.total_bytes(), |
316 1, kMaxResponseBytes, 100); | 325 1, kMaxResponseBytes, 100); |
317 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network", | 326 UMA_HISTOGRAM_CUSTOM_COUNTS("Precache.Fetch.ResponseBytes.Network", |
318 unfinished_work.network_bytes(), | 327 unfinished_work.network_bytes(), |
319 1, kMaxResponseBytes, | 328 1, kMaxResponseBytes, |
320 100); | 329 100); |
321 } | 330 } |
322 | 331 |
| 332 // static |
| 333 std::string PrecacheFetcher::GetResourceURLBase64HashForTesting( |
| 334 const std::vector<GURL>& urls) { |
| 335 return GetResourceURLBase64Hash(urls); |
| 336 } |
| 337 |
323 PrecacheFetcher::PrecacheFetcher( | 338 PrecacheFetcher::PrecacheFetcher( |
324 net::URLRequestContextGetter* request_context, | 339 net::URLRequestContextGetter* request_context, |
325 const GURL& config_url, | 340 const GURL& config_url, |
326 const std::string& manifest_url_prefix, | 341 const std::string& manifest_url_prefix, |
327 std::unique_ptr<PrecacheUnfinishedWork> unfinished_work, | 342 std::unique_ptr<PrecacheUnfinishedWork> unfinished_work, |
328 uint32_t experiment_id, | 343 uint32_t experiment_id, |
| 344 const base::WeakPtr<PrecacheDatabase>& precache_database, |
| 345 const scoped_refptr<base::SingleThreadTaskRunner>& db_task_runner, |
329 PrecacheFetcher::PrecacheDelegate* precache_delegate) | 346 PrecacheFetcher::PrecacheDelegate* precache_delegate) |
330 : request_context_(request_context), | 347 : request_context_(request_context), |
331 config_url_(config_url), | 348 config_url_(config_url), |
332 manifest_url_prefix_(manifest_url_prefix), | 349 manifest_url_prefix_(manifest_url_prefix), |
| 350 precache_database_(precache_database), |
| 351 db_task_runner_(std::move(db_task_runner)), |
333 precache_delegate_(precache_delegate), | 352 precache_delegate_(precache_delegate), |
334 pool_(kMaxParallelFetches), | 353 pool_(kMaxParallelFetches), |
335 experiment_id_(experiment_id) { | 354 experiment_id_(experiment_id) { |
336 DCHECK(request_context_.get()); // Request context must be non-NULL. | 355 DCHECK(request_context_.get()); // Request context must be non-NULL. |
337 DCHECK(precache_delegate_); // Precache delegate must be non-NULL. | 356 DCHECK(precache_delegate_); // Precache delegate must be non-NULL. |
338 | 357 |
339 DCHECK_NE(GURL(), GetDefaultConfigURL()) | 358 DCHECK_NE(GURL(), GetDefaultConfigURL()) |
340 << "Could not determine the precache config settings URL."; | 359 << "Could not determine the precache config settings URL."; |
341 DCHECK_NE(std::string(), GetDefaultManifestURLPrefix()) | 360 DCHECK_NE(std::string(), GetDefaultManifestURLPrefix()) |
342 << "Could not determine the default precache manifest URL prefix."; | 361 << "Could not determine the default precache manifest URL prefix."; |
343 DCHECK(unfinished_work); | 362 DCHECK(unfinished_work); |
344 | 363 |
345 // Copy manifests and resources to member variables as a convenience. | 364 // Copy resources to member variable as a convenience. |
346 // TODO(bengr): Consider accessing these directly from the proto. | 365 // TODO(rajendrant): Consider accessing these directly from the proto, by |
347 for (const auto& manifest : unfinished_work->manifest()) { | 366 // 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()) { | 367 for (const auto& resource : unfinished_work->resource()) { |
352 if (resource.has_url()) | 368 if (resource.has_url() && resource.has_top_host_name()) { |
353 resource_urls_to_fetch_.push_back(GURL(resource.url())); | 369 resources_to_fetch_.emplace_back(GURL(resource.url()), |
| 370 resource.top_host_name()); |
| 371 } |
354 } | 372 } |
355 unfinished_work_ = std::move(unfinished_work); | 373 unfinished_work_ = std::move(unfinished_work); |
356 } | 374 } |
357 | 375 |
358 PrecacheFetcher::~PrecacheFetcher() { | 376 PrecacheFetcher::~PrecacheFetcher() { |
359 } | 377 } |
360 | 378 |
361 std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { | 379 std::unique_ptr<PrecacheUnfinishedWork> PrecacheFetcher::CancelPrecaching() { |
362 // This could get called multiple times, and it should be handled gracefully. | 380 // This could get called multiple times, and it should be handled gracefully. |
363 if (!unfinished_work_) | 381 if (!unfinished_work_) |
364 return nullptr; | 382 return nullptr; |
365 | 383 |
366 unfinished_work_->clear_manifest(); | |
367 unfinished_work_->clear_resource(); | 384 unfinished_work_->clear_resource(); |
368 for (const auto& manifest : manifest_urls_to_fetch_) | 385 if (top_hosts_to_fetch_) { |
369 unfinished_work_->add_manifest()->set_url(manifest.spec()); | 386 unfinished_work_->clear_top_host(); |
370 for (const auto& resource : resource_urls_to_fetch_) | 387 for (const auto& top_host : *top_hosts_to_fetch_) { |
371 unfinished_work_->add_resource()->set_url(resource.spec()); | 388 unfinished_work_->add_top_host()->set_hostname(top_host.hostname); |
| 389 } |
| 390 } |
| 391 for (const auto& resource : resources_to_fetch_) { |
| 392 auto new_resource = unfinished_work_->add_resource(); |
| 393 new_resource->set_url(resource.first.spec()); |
| 394 new_resource->set_top_host_name(resource.second); |
| 395 } |
372 for (const auto& it : pool_.elements()) { | 396 for (const auto& it : pool_.elements()) { |
373 const Fetcher* fetcher = it.first; | 397 const Fetcher* fetcher = it.first; |
374 if (fetcher->is_resource_request()) | 398 GURL config_url = |
375 unfinished_work_->add_resource()->set_url(fetcher->url().spec()); | 399 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; |
376 else if (fetcher->url() != config_url_) | 400 if (fetcher->is_resource_request()) { |
377 unfinished_work_->add_manifest()->set_url(fetcher->url().spec()); | 401 auto resource = unfinished_work_->add_resource(); |
| 402 resource->set_url(fetcher->url().spec()); |
| 403 resource->set_top_host_name(fetcher->referrer()); |
| 404 } else if (fetcher->url() != config_url) { |
| 405 unfinished_work_->add_top_host()->set_hostname(fetcher->referrer()); |
| 406 } |
378 } | 407 } |
379 manifest_urls_to_fetch_.clear(); | 408 top_hosts_to_fetch_.reset(); |
380 resource_urls_to_fetch_.clear(); | 409 resources_to_fetch_.clear(); |
381 pool_.DeleteAll(); | 410 pool_.DeleteAll(); |
382 return std::move(unfinished_work_); | 411 return std::move(unfinished_work_); |
383 } | 412 } |
384 | 413 |
385 void PrecacheFetcher::Start() { | 414 void PrecacheFetcher::Start() { |
386 if (unfinished_work_->has_config_settings()) { | 415 if (unfinished_work_->has_config_settings()) { |
387 DCHECK(unfinished_work_->has_start_time()); | 416 DCHECK(unfinished_work_->has_start_time()); |
388 DetermineManifests(); | 417 DetermineManifests(); |
389 return; | 418 return; |
390 } | 419 } |
391 | 420 |
392 GURL config_url = | 421 GURL config_url = |
393 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; | 422 config_url_.is_empty() ? GetDefaultConfigURL() : config_url_; |
394 | 423 |
395 DCHECK(config_url.is_valid()) << "Config URL not valid: " | 424 DCHECK(config_url.is_valid()) << "Config URL not valid: " |
396 << config_url.possibly_invalid_spec(); | 425 << config_url.possibly_invalid_spec(); |
397 | 426 |
398 // Fetch the precache configuration settings from the server. | 427 // Fetch the precache configuration settings from the server. |
399 DCHECK(pool_.IsEmpty()) << "All parallel requests should be available"; | 428 DCHECK(pool_.IsEmpty()) << "All parallel requests should be available"; |
400 VLOG(3) << "Fetching " << config_url; | 429 VLOG(3) << "Fetching " << config_url; |
401 pool_.Add(base::WrapUnique(new Fetcher( | 430 pool_.Add(base::WrapUnique(new Fetcher( |
402 request_context_.get(), config_url, | 431 request_context_.get(), config_url, std::string(), |
403 base::Bind(&PrecacheFetcher::OnConfigFetchComplete, | 432 base::Bind(&PrecacheFetcher::OnConfigFetchComplete, AsWeakPtr()), |
404 base::Unretained(this)), | |
405 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); | 433 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); |
406 } | 434 } |
407 | 435 |
408 void PrecacheFetcher::StartNextResourceFetch() { | 436 void PrecacheFetcher::StartNextResourceFetch() { |
409 DCHECK(unfinished_work_->has_config_settings()); | 437 DCHECK(unfinished_work_->has_config_settings()); |
410 while (!resource_urls_to_fetch_.empty() && pool_.IsAvailable()) { | 438 while (!resources_to_fetch_.empty() && pool_.IsAvailable()) { |
| 439 const auto& resource = resources_to_fetch_.front(); |
411 const size_t max_bytes = | 440 const size_t max_bytes = |
412 std::min(unfinished_work_->config_settings().max_bytes_per_resource(), | 441 std::min(unfinished_work_->config_settings().max_bytes_per_resource(), |
413 unfinished_work_->config_settings().max_bytes_total() - | 442 unfinished_work_->config_settings().max_bytes_total() - |
414 unfinished_work_->total_bytes()); | 443 unfinished_work_->total_bytes()); |
415 VLOG(3) << "Fetching " << resource_urls_to_fetch_.front(); | 444 VLOG(3) << "Fetching " << resource.first << " " << resource.second; |
416 pool_.Add(base::WrapUnique( | 445 pool_.Add(base::WrapUnique(new Fetcher( |
417 new Fetcher(request_context_.get(), resource_urls_to_fetch_.front(), | 446 request_context_.get(), resource.first, resource.second, |
418 base::Bind(&PrecacheFetcher::OnResourceFetchComplete, | 447 base::Bind(&PrecacheFetcher::OnResourceFetchComplete, AsWeakPtr()), |
419 base::Unretained(this)), | 448 true /* is_resource_request */, max_bytes))); |
420 true /* is_resource_request */, max_bytes))); | |
421 | 449 |
422 resource_urls_to_fetch_.pop_front(); | 450 resources_to_fetch_.pop_front(); |
423 } | 451 } |
424 } | 452 } |
425 | 453 |
426 void PrecacheFetcher::StartNextManifestFetch() { | 454 void PrecacheFetcher::StartNextManifestFetch() { |
427 if (manifest_urls_to_fetch_.empty() || !pool_.IsAvailable()) | 455 if (!top_hosts_to_fetch_ || top_hosts_to_fetch_->empty() || |
| 456 !pool_.IsAvailable()) |
428 return; | 457 return; |
429 | 458 |
430 // We only fetch one manifest at a time to keep the size of | 459 // We only fetch one manifest at a time to keep the size of |
431 // resource_urls_to_fetch_ as small as possible. | 460 // resources_to_fetch_ as small as possible. |
432 VLOG(3) << "Fetching " << manifest_urls_to_fetch_.front(); | 461 VLOG(3) << "Fetching " << top_hosts_to_fetch_->front().manifest_url; |
433 pool_.Add(base::WrapUnique(new Fetcher( | 462 pool_.Add(base::WrapUnique(new Fetcher( |
434 request_context_.get(), manifest_urls_to_fetch_.front(), | 463 request_context_.get(), top_hosts_to_fetch_->front().manifest_url, |
435 base::Bind(&PrecacheFetcher::OnManifestFetchComplete, | 464 top_hosts_to_fetch_->front().hostname, |
436 base::Unretained(this)), | 465 base::Bind(&PrecacheFetcher::OnManifestFetchComplete, AsWeakPtr()), |
437 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); | 466 false /* is_resource_request */, std::numeric_limits<int32_t>::max()))); |
438 | 467 top_hosts_to_fetch_->pop_front(); |
439 manifest_urls_to_fetch_.pop_front(); | |
440 } | 468 } |
441 | 469 |
442 void PrecacheFetcher::NotifyDone( | 470 void PrecacheFetcher::NotifyDone( |
443 size_t remaining_manifest_urls_to_fetch, | 471 size_t remaining_manifest_urls_to_fetch, |
444 size_t remaining_resource_urls_to_fetch) { | 472 size_t remaining_resource_urls_to_fetch) { |
445 RecordCompletionStatistics(*unfinished_work_, | 473 RecordCompletionStatistics(*unfinished_work_, |
446 remaining_manifest_urls_to_fetch, | 474 remaining_manifest_urls_to_fetch, |
447 remaining_resource_urls_to_fetch); | 475 remaining_resource_urls_to_fetch); |
448 precache_delegate_->OnDone(); | 476 precache_delegate_->OnDone(); |
449 } | 477 } |
450 | 478 |
451 void PrecacheFetcher::StartNextFetch() { | 479 void PrecacheFetcher::StartNextFetch() { |
452 DCHECK(unfinished_work_->has_config_settings()); | 480 DCHECK(unfinished_work_->has_config_settings()); |
453 // If over the precache total size cap, then stop prefetching. | 481 // If over the precache total size cap, then stop prefetching. |
454 if (unfinished_work_->total_bytes() > | 482 if (unfinished_work_->total_bytes() > |
455 unfinished_work_->config_settings().max_bytes_total()) { | 483 unfinished_work_->config_settings().max_bytes_total()) { |
456 size_t pending_manifests_in_pool = 0; | 484 size_t pending_manifests_in_pool = 0; |
457 size_t pending_resources_in_pool = 0; | 485 size_t pending_resources_in_pool = 0; |
458 for (const auto& element_pair : pool_.elements()) { | 486 for (const auto& element_pair : pool_.elements()) { |
459 const Fetcher* fetcher = element_pair.first; | 487 const Fetcher* fetcher = element_pair.first; |
460 if (fetcher->is_resource_request()) | 488 if (fetcher->is_resource_request()) |
461 pending_resources_in_pool++; | 489 pending_resources_in_pool++; |
462 else if (fetcher->url() != config_url_) | 490 else if (fetcher->url() != config_url_) |
463 pending_manifests_in_pool++; | 491 pending_manifests_in_pool++; |
464 } | 492 } |
465 pool_.DeleteAll(); | 493 pool_.DeleteAll(); |
466 NotifyDone(manifest_urls_to_fetch_.size() + pending_manifests_in_pool, | 494 size_t pending_top_hosts = |
467 resource_urls_to_fetch_.size() + pending_resources_in_pool); | 495 top_hosts_to_fetch_ ? top_hosts_to_fetch_->size() : 0; |
| 496 NotifyDone(pending_top_hosts + pending_manifests_in_pool, |
| 497 resources_to_fetch_.size() + pending_resources_in_pool); |
468 return; | 498 return; |
469 } | 499 } |
470 | 500 |
471 StartNextResourceFetch(); | 501 StartNextResourceFetch(); |
472 StartNextManifestFetch(); | 502 StartNextManifestFetch(); |
473 if (pool_.IsEmpty()) { | 503 if ((!top_hosts_to_fetch_ || top_hosts_to_fetch_->empty()) && |
| 504 resources_to_fetch_.empty() && pool_.IsEmpty()) { |
474 // There are no more URLs to fetch, so end the precache cycle. | 505 // There are no more URLs to fetch, so end the precache cycle. |
475 NotifyDone(0, 0); | 506 NotifyDone(0, 0); |
476 // OnDone may have deleted this PrecacheFetcher, so don't do anything after | 507 // OnDone may have deleted this PrecacheFetcher, so don't do anything after |
477 // it is called. | 508 // it is called. |
478 } | 509 } |
479 } | 510 } |
480 | 511 |
481 void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) { | 512 void PrecacheFetcher::OnConfigFetchComplete(const Fetcher& source) { |
482 UpdateStats(source.response_bytes(), source.network_response_bytes()); | 513 UpdateStats(source.response_bytes(), source.network_response_bytes()); |
483 if (source.network_url_fetcher() == nullptr) { | 514 if (source.network_url_fetcher() == nullptr) { |
484 pool_.DeleteAll(); // Cancel any other ongoing request. | 515 pool_.DeleteAll(); // Cancel any other ongoing request. |
485 } else { | 516 } else { |
486 // Attempt to parse the config proto. On failure, continue on with the | 517 // Attempt to parse the config proto. On failure, continue on with the |
487 // default configuration. | 518 // default configuration. |
488 ParseProtoFromFetchResponse( | 519 ParseProtoFromFetchResponse( |
489 *source.network_url_fetcher(), | 520 *source.network_url_fetcher(), |
490 unfinished_work_->mutable_config_settings()); | 521 unfinished_work_->mutable_config_settings()); |
491 pool_.Delete(source); | 522 pool_.Delete(source); |
492 DetermineManifests(); | 523 DetermineManifests(); |
493 } | 524 } |
494 } | 525 } |
495 | 526 |
496 void PrecacheFetcher::DetermineManifests() { | 527 void PrecacheFetcher::DetermineManifests() { |
497 DCHECK(unfinished_work_->has_config_settings()); | 528 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 | 529 |
| 530 std::deque<std::string> top_hosts_to_fetch; |
| 531 std::unique_ptr<std::deque<ManifestHostInfo>> top_hosts_info( |
| 532 new std::deque<ManifestHostInfo>); |
| 533 |
| 534 // Attempt to fetch manifests for starting hosts up to the maximum top sites |
| 535 // count. If a manifest does not exist for a particular starting host, then |
| 536 // the fetch will fail, and that starting host will be ignored. Starting |
| 537 // hosts are not added if this is a continuation from a previous precache |
| 538 // session. |
| 539 if (resources_to_fetch_.empty()) { |
504 // Keep track of manifest URLs that are being fetched, in order to elide | 540 // Keep track of manifest URLs that are being fetched, in order to elide |
505 // duplicates. | 541 // duplicates. |
506 base::hash_set<std::string> seen_manifest_urls; | 542 std::set<base::StringPiece> seen_top_hosts; |
| 543 int64_t rank = 0; |
| 544 for (const auto& host : unfinished_work_->top_host()) { |
| 545 ++rank; |
| 546 if (rank > unfinished_work_->config_settings().top_sites_count()) |
| 547 break; |
| 548 if (seen_top_hosts.insert(host.hostname()).second) |
| 549 top_hosts_to_fetch.push_back(host.hostname()); |
| 550 } |
507 | 551 |
508 // Attempt to fetch manifests for starting hosts up to the maximum top sites | 552 for (const std::string& host : |
509 // count. If a manifest does not exist for a particular starting host, then | 553 unfinished_work_->config_settings().forced_site()) { |
510 // the fetch will fail, and that starting host will be ignored. Starting | 554 if (seen_top_hosts.insert(host).second) |
511 // hosts are not added if this is a continuation from a previous precache | 555 top_hosts_to_fetch.push_back(host); |
512 // session. | 556 } |
513 if (manifest_urls_to_fetch_.empty() && | 557 } |
514 resource_urls_to_fetch_.empty()) { | 558 // We only fetch one manifest at a time to keep the size of |
515 int64_t rank = 0; | 559 // resources_to_fetch_ as small as possible. |
516 for (const auto& host : unfinished_work_->top_host()) { | 560 auto retrieve_manifest_callback = |
517 ++rank; | 561 base::Bind(&PrecacheFetcher::RetrieveManifestInfo, AsWeakPtr(), |
518 if (rank > unfinished_work_->config_settings().top_sites_count()) | 562 std::move(top_hosts_to_fetch), top_hosts_info.get()); |
519 break; | 563 db_task_runner_->PostTaskAndReply( |
520 AppendManifestURLIfValidAndNew(prefix, host.hostname(), | 564 FROM_HERE, retrieve_manifest_callback, |
521 &seen_manifest_urls, | 565 base::Bind(&PrecacheFetcher::OnManifestInfoRetrieved, |
522 &manifest_urls_to_fetch_); | 566 base::Unretained(this), base::Passed(&top_hosts_info))); |
523 } | 567 } |
524 | 568 |
525 for (const std::string& host | 569 void PrecacheFetcher::RetrieveManifestInfo( |
526 : unfinished_work_->config_settings().forced_site()) { | 570 std::deque<std::string> hosts_to_fetch, |
527 AppendManifestURLIfValidAndNew(prefix, host, &seen_manifest_urls, | 571 std::deque<ManifestHostInfo>* hosts_info) { |
528 &manifest_urls_to_fetch_); | 572 for (const auto& host : hosts_to_fetch) { |
529 } | 573 auto referrer_host_info = precache_database_->GetReferrerHost(host); |
| 574 if (referrer_host_info.id != PrecacheReferrerHostEntry::kInvalidId) { |
| 575 std::vector<GURL> used_urls, unused_urls; |
| 576 precache_database_->GetURLListForReferrerHost(referrer_host_info.id, |
| 577 &used_urls, &unused_urls); |
| 578 hosts_info->push_back(ManifestHostInfo( |
| 579 referrer_host_info.id, host, GetResourceURLBase64Hash(used_urls), |
| 580 GetResourceURLBase64Hash(unused_urls))); |
| 581 } else { |
| 582 hosts_info->push_back( |
| 583 ManifestHostInfo(PrecacheReferrerHostEntry::kInvalidId, host, |
| 584 std::string(), std::string())); |
530 } | 585 } |
531 unfinished_work_->set_num_manifest_urls(manifest_urls_to_fetch_.size()); | 586 } |
532 StartNextFetch(); | |
533 } | 587 } |
534 | 588 |
| 589 void PrecacheFetcher::OnManifestInfoRetrieved( |
| 590 std::unique_ptr<std::deque<ManifestHostInfo>> manifests_info) { |
| 591 DCHECK(manifests_info); |
| 592 const std::string prefix = manifest_url_prefix_.empty() |
| 593 ? GetDefaultManifestURLPrefix() |
| 594 : manifest_url_prefix_; |
| 595 top_hosts_to_fetch_.reset(new std::deque<ManifestHostInfo>()); |
| 596 for (auto& manifest : *manifests_info) { |
| 597 GURL manifest_url( |
| 598 prefix + |
| 599 net::EscapeQueryParamValue( |
| 600 net::EscapeQueryParamValue(manifest.hostname, false), false)); |
| 601 if (manifest_url.is_valid() && |
| 602 manifest.manifest_id != PrecacheReferrerHostEntry::kInvalidId) { |
| 603 manifest_url = net::AppendOrReplaceQueryParameter( |
| 604 manifest_url, "manifest", std::to_string(manifest.manifest_id)); |
| 605 manifest_url = net::AppendOrReplaceQueryParameter( |
| 606 manifest_url, "used_resources", manifest.used_url_hash); |
| 607 manifest_url = net::AppendOrReplaceQueryParameter( |
| 608 manifest_url, "unused_resources", manifest.unused_url_hash); |
| 609 DCHECK(manifest_url.is_valid()); |
| 610 } |
| 611 manifest.manifest_url = manifest_url; |
| 612 if (manifest_url.is_valid()) |
| 613 top_hosts_to_fetch_->push_back(std::move(manifest)); |
| 614 } |
| 615 unfinished_work_->set_num_manifest_urls(top_hosts_to_fetch_->size()); |
| 616 StartNextFetch(); |
| 617 } |
| 618 |
| 619 ManifestHostInfo::ManifestHostInfo(int64_t manifest_id, |
| 620 const std::string& hostname, |
| 621 const std::string& used_url_hash, |
| 622 const std::string& unused_url_hash) |
| 623 : manifest_id(manifest_id), |
| 624 hostname(hostname), |
| 625 used_url_hash(used_url_hash), |
| 626 unused_url_hash(unused_url_hash) {} |
| 627 |
| 628 ManifestHostInfo::~ManifestHostInfo() {} |
| 629 |
| 630 ManifestHostInfo::ManifestHostInfo(ManifestHostInfo&&) = default; |
| 631 |
| 632 ManifestHostInfo& ManifestHostInfo::operator=(ManifestHostInfo&&) = default; |
| 633 |
535 void PrecacheFetcher::OnManifestFetchComplete(const Fetcher& source) { | 634 void PrecacheFetcher::OnManifestFetchComplete(const Fetcher& source) { |
536 DCHECK(unfinished_work_->has_config_settings()); | 635 DCHECK(unfinished_work_->has_config_settings()); |
537 UpdateStats(source.response_bytes(), source.network_response_bytes()); | 636 UpdateStats(source.response_bytes(), source.network_response_bytes()); |
538 if (source.network_url_fetcher() == nullptr) { | 637 if (source.network_url_fetcher() == nullptr) { |
539 pool_.DeleteAll(); // Cancel any other ongoing request. | 638 pool_.DeleteAll(); // Cancel any other ongoing request. |
540 } else { | 639 } else { |
541 PrecacheManifest manifest; | 640 PrecacheManifest manifest; |
542 | 641 |
543 if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) { | 642 if (ParseProtoFromFetchResponse(*source.network_url_fetcher(), &manifest)) { |
544 const int32_t len = | 643 const int32_t len = |
545 std::min(manifest.resource_size(), | 644 std::min(manifest.resource_size(), |
546 unfinished_work_->config_settings().top_resources_count()); | 645 unfinished_work_->config_settings().top_resources_count()); |
547 const uint64_t resource_bitset = | 646 const uint64_t resource_bitset = |
548 GetResourceBitset(manifest, experiment_id_); | 647 GetResourceBitset(manifest, experiment_id_); |
549 for (int i = 0; i < len; ++i) { | 648 for (int i = 0; i < len; ++i) { |
550 if (((0x1ULL << i) & resource_bitset) && | 649 if (((0x1ULL << i) & resource_bitset) && |
551 manifest.resource(i).has_url()) { | 650 manifest.resource(i).has_url()) { |
552 GURL url(manifest.resource(i).url()); | 651 GURL url(manifest.resource(i).url()); |
553 if (url.is_valid()) | 652 if (url.is_valid()) { |
554 resource_urls_to_fetch_.push_back(url); | 653 resources_to_fetch_.emplace_back(url, source.referrer()); |
| 654 } |
555 } | 655 } |
556 } | 656 } |
| 657 db_task_runner_->PostTask( |
| 658 FROM_HERE, |
| 659 base::Bind(&PrecacheDatabase::UpdatePrecacheReferrerHost, |
| 660 precache_database_, source.referrer(), |
| 661 manifest.id().id(), base::Time::Now())); |
557 } | 662 } |
558 } | 663 } |
559 | 664 |
560 pool_.Delete(source); | 665 pool_.Delete(source); |
561 StartNextFetch(); | 666 StartNextFetch(); |
562 } | 667 } |
563 | 668 |
564 void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) { | 669 void PrecacheFetcher::OnResourceFetchComplete(const Fetcher& source) { |
565 UpdateStats(source.response_bytes(), source.network_response_bytes()); | 670 UpdateStats(source.response_bytes(), source.network_response_bytes()); |
| 671 |
| 672 db_task_runner_->PostTask( |
| 673 FROM_HERE, |
| 674 base::Bind(&PrecacheDatabase::RecordURLPrefetch, precache_database_, |
| 675 source.url(), source.referrer(), base::Time::Now(), |
| 676 source.was_cached(), source.response_bytes())); |
| 677 |
566 pool_.Delete(source); | 678 pool_.Delete(source); |
| 679 |
567 // The resource has already been put in the cache during the fetch process, so | 680 // The resource has already been put in the cache during the fetch process, so |
568 // nothing more needs to be done for the resource. | 681 // nothing more needs to be done for the resource. |
569 StartNextFetch(); | 682 StartNextFetch(); |
570 } | 683 } |
571 | 684 |
572 void PrecacheFetcher::UpdateStats(int64_t response_bytes, | 685 void PrecacheFetcher::UpdateStats(int64_t response_bytes, |
573 int64_t network_response_bytes) { | 686 int64_t network_response_bytes) { |
574 unfinished_work_->set_total_bytes( | 687 unfinished_work_->set_total_bytes( |
575 unfinished_work_->total_bytes() + response_bytes); | 688 unfinished_work_->total_bytes() + response_bytes); |
576 unfinished_work_->set_network_bytes( | 689 unfinished_work_->set_network_bytes( |
577 unfinished_work_->network_bytes() + network_response_bytes); | 690 unfinished_work_->network_bytes() + network_response_bytes); |
578 } | 691 } |
579 | 692 |
580 } // namespace precache | 693 } // namespace precache |
OLD | NEW |