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

Side by Side Diff: net/http/http_cache_transaction.cc

Issue 455623003: stale-while-revalidate experimental implementation. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Remove --disable-stale-while-revalidate flag and strengthen must-revalidate. Created 6 years, 3 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 (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 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 "net/http/http_cache_transaction.h" 5 #include "net/http/http_cache_transaction.h"
6 6
7 #include "build/build_config.h" 7 #include "build/build_config.h"
8 8
9 #if defined(OS_POSIX) 9 #if defined(OS_POSIX)
10 #include <unistd.h> 10 #include <unistd.h>
11 #endif 11 #endif
12 12
13 #include <algorithm> 13 #include <algorithm>
14 #include <string> 14 #include <string>
15 15
16 #include "base/bind.h" 16 #include "base/bind.h"
17 #include "base/compiler_specific.h" 17 #include "base/compiler_specific.h"
18 #include "base/format_macros.h" 18 #include "base/format_macros.h"
19 #include "base/memory/ref_counted.h" 19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h"
20 #include "base/metrics/field_trial.h" 21 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram.h" 22 #include "base/metrics/histogram.h"
22 #include "base/metrics/sparse_histogram.h" 23 #include "base/metrics/sparse_histogram.h"
23 #include "base/rand_util.h" 24 #include "base/rand_util.h"
24 #include "base/strings/string_number_conversions.h" 25 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_piece.h" 26 #include "base/strings/string_piece.h"
26 #include "base/strings/string_util.h" 27 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h" 28 #include "base/strings/stringprintf.h"
28 #include "base/time/time.h" 29 #include "base/time/time.h"
30 #include "base/values.h"
29 #include "net/base/completion_callback.h" 31 #include "net/base/completion_callback.h"
30 #include "net/base/io_buffer.h" 32 #include "net/base/io_buffer.h"
31 #include "net/base/load_flags.h" 33 #include "net/base/load_flags.h"
32 #include "net/base/load_timing_info.h" 34 #include "net/base/load_timing_info.h"
33 #include "net/base/net_errors.h" 35 #include "net/base/net_errors.h"
34 #include "net/base/net_log.h" 36 #include "net/base/net_log.h"
35 #include "net/base/upload_data_stream.h" 37 #include "net/base/upload_data_stream.h"
36 #include "net/cert/cert_status_flags.h" 38 #include "net/cert/cert_status_flags.h"
37 #include "net/disk_cache/disk_cache.h" 39 #include "net/disk_cache/disk_cache.h"
38 #include "net/http/disk_based_cert_cache.h" 40 #include "net/http/disk_based_cert_cache.h"
(...skipping 192 matching lines...) Expand 10 before | Expand all | Expand 10 after
231 233
232 void RecordNoStoreHeaderHistogram(int load_flags, 234 void RecordNoStoreHeaderHistogram(int load_flags,
233 const net::HttpResponseInfo* response) { 235 const net::HttpResponseInfo* response) {
234 if (load_flags & net::LOAD_MAIN_FRAME) { 236 if (load_flags & net::LOAD_MAIN_FRAME) {
235 UMA_HISTOGRAM_BOOLEAN( 237 UMA_HISTOGRAM_BOOLEAN(
236 "Net.MainFrameNoStore", 238 "Net.MainFrameNoStore",
237 response->headers->HasHeaderValue("cache-control", "no-store")); 239 response->headers->HasHeaderValue("cache-control", "no-store"));
238 } 240 }
239 } 241 }
240 242
243 base::Value* NetLogAsyncRevalidationInfoCallback(
244 const net::NetLog::Source& source,
245 const net::HttpRequestInfo* request,
246 net::NetLog::LogLevel log_level) {
247 base::DictionaryValue* dict = new base::DictionaryValue();
248 source.AddToEventParameters(dict);
249
250 dict->SetString("url", request->url.possibly_invalid_spec());
251 dict->SetString("method", request->method);
252 return dict;
253 }
254
241 } // namespace 255 } // namespace
242 256
243 namespace net { 257 namespace net {
244 258
245 struct HeaderNameAndValue { 259 struct HeaderNameAndValue {
246 const char* name; 260 const char* name;
247 const char* value; 261 const char* value;
248 }; 262 };
249 263
250 // If the request includes one of these request headers, then avoid caching 264 // If the request includes one of these request headers, then avoid caching
(...skipping 1835 matching lines...) Expand 10 before | Expand all | Expand 10 after
2086 2100
2087 if (entry_->disk_entry->GetDataSize(kMetadataIndex)) 2101 if (entry_->disk_entry->GetDataSize(kMetadataIndex))
2088 next_state_ = STATE_CACHE_READ_METADATA; 2102 next_state_ = STATE_CACHE_READ_METADATA;
2089 2103
2090 return OK; 2104 return OK;
2091 } 2105 }
2092 2106
2093 int HttpCache::Transaction::BeginCacheValidation() { 2107 int HttpCache::Transaction::BeginCacheValidation() {
2094 DCHECK(mode_ == READ_WRITE); 2108 DCHECK(mode_ == READ_WRITE);
2095 2109
2096 bool skip_validation = !RequiresValidation(); 2110 ValidationType required_validation = RequiresValidation();
2111
2112 bool skip_validation = (required_validation == VALIDATION_NONE);
2113
2114 if (required_validation == VALIDATION_ASYNCHRONOUS &&
2115 !(request_->method == "GET" && (truncated_ || partial_)) && cache_ &&
2116 cache_->use_stale_while_revalidate()) {
2117 TriggerAsyncValidation();
2118 skip_validation = true;
2119 }
2097 2120
2098 if (request_->method == "HEAD" && 2121 if (request_->method == "HEAD" &&
2099 (truncated_ || response_.headers->response_code() == 206)) { 2122 (truncated_ || response_.headers->response_code() == 206)) {
2100 DCHECK(!partial_); 2123 DCHECK(!partial_);
2101 if (skip_validation) 2124 if (skip_validation)
2102 return SetupEntryForRead(); 2125 return SetupEntryForRead();
2103 2126
2104 // Bail out! 2127 // Bail out!
2105 next_state_ = STATE_SEND_REQUEST; 2128 next_state_ = STATE_SEND_REQUEST;
2106 mode_ = NONE; 2129 mode_ = NONE;
2107 return OK; 2130 return OK;
2108 } 2131 }
2109 2132
2110 if (truncated_) { 2133 if (truncated_) {
2111 // Truncated entries can cause partial gets, so we shouldn't record this 2134 // Truncated entries can cause partial gets, so we shouldn't record this
2112 // load in histograms. 2135 // load in histograms.
2113 UpdateTransactionPattern(PATTERN_NOT_COVERED); 2136 UpdateTransactionPattern(PATTERN_NOT_COVERED);
2114 skip_validation = !partial_->initial_validation(); 2137 skip_validation = !partial_->initial_validation();
2115 } 2138 }
2116 2139
2117 if (partial_.get() && (is_sparse_ || truncated_) && 2140 if (partial_.get() && (is_sparse_ || truncated_) &&
2118 (!partial_->IsCurrentRangeCached() || invalid_range_)) { 2141 (!partial_->IsCurrentRangeCached() || invalid_range_)) {
2119 // Force revalidation for sparse or truncated entries. Note that we don't 2142 // Force revalidation for sparse or truncated entries. Note that we don't
2120 // want to ignore the regular validation logic just because a byte range was 2143 // want to ignore the regular validation logic just because a byte range was
2121 // part of the request. 2144 // part of the request.
2122 skip_validation = false; 2145 skip_validation = false;
2123 } 2146 }
2124 2147
2125 if (skip_validation) { 2148 if (skip_validation) {
2149 // TODO(ricea): Is this pattern okay for asynchronous revalidations?
2126 UpdateTransactionPattern(PATTERN_ENTRY_USED); 2150 UpdateTransactionPattern(PATTERN_ENTRY_USED);
2127 RecordOfflineStatus(effective_load_flags_, OFFLINE_STATUS_FRESH_CACHE); 2151 RecordOfflineStatus(effective_load_flags_, OFFLINE_STATUS_FRESH_CACHE);
2128 return SetupEntryForRead(); 2152 return SetupEntryForRead();
2129 } else { 2153 } else {
2130 // Make the network request conditional, to see if we may reuse our cached 2154 // Make the network request conditional, to see if we may reuse our cached
2131 // response. If we cannot do so, then we just resort to a normal fetch. 2155 // response. If we cannot do so, then we just resort to a normal fetch.
2132 // Our mode remains READ_WRITE for a conditional request. Even if the 2156 // Our mode remains READ_WRITE for a conditional request. Even if the
2133 // conditionalization fails, we don't switch to WRITE mode until we 2157 // conditionalization fails, we don't switch to WRITE mode until we
2134 // know we won't be falling back to using the cache entry in the 2158 // know we won't be falling back to using the cache entry in the
2135 // LOAD_FROM_CACHE_IF_OFFLINE case. 2159 // LOAD_FROM_CACHE_IF_OFFLINE case.
(...skipping 119 matching lines...) Expand 10 before | Expand all | Expand 10 after
2255 DCHECK(network_trans_.get()); 2279 DCHECK(network_trans_.get());
2256 DCHECK_EQ(STATE_NONE, next_state_); 2280 DCHECK_EQ(STATE_NONE, next_state_);
2257 2281
2258 next_state_ = STATE_SEND_REQUEST_COMPLETE; 2282 next_state_ = STATE_SEND_REQUEST_COMPLETE;
2259 int rv = network_trans_->RestartWithAuth(credentials, io_callback_); 2283 int rv = network_trans_->RestartWithAuth(credentials, io_callback_);
2260 if (rv != ERR_IO_PENDING) 2284 if (rv != ERR_IO_PENDING)
2261 return DoLoop(rv); 2285 return DoLoop(rv);
2262 return rv; 2286 return rv;
2263 } 2287 }
2264 2288
2265 bool HttpCache::Transaction::RequiresValidation() { 2289 ValidationType HttpCache::Transaction::RequiresValidation() {
2266 // TODO(darin): need to do more work here: 2290 // TODO(darin): need to do more work here:
2267 // - make sure we have a matching request method 2291 // - make sure we have a matching request method
2268 // - watch out for cached responses that depend on authentication 2292 // - watch out for cached responses that depend on authentication
2269 2293
2270 // In playback mode, nothing requires validation. 2294 // In playback mode, nothing requires validation.
2271 if (cache_->mode() == net::HttpCache::PLAYBACK) 2295 if (cache_->mode() == net::HttpCache::PLAYBACK)
2272 return false; 2296 return VALIDATION_NONE;
2273 2297
2274 if (response_.vary_data.is_valid() && 2298 if (response_.vary_data.is_valid() &&
2275 !response_.vary_data.MatchesRequest(*request_, 2299 !response_.vary_data.MatchesRequest(*request_,
2276 *response_.headers.get())) { 2300 *response_.headers.get())) {
2277 vary_mismatch_ = true; 2301 vary_mismatch_ = true;
2278 return true; 2302 return VALIDATION_SYNCHRONOUS;
2279 } 2303 }
2280 2304
2281 if (effective_load_flags_ & LOAD_PREFERRING_CACHE) 2305 if (effective_load_flags_ & LOAD_PREFERRING_CACHE)
2282 return false; 2306 return VALIDATION_NONE;
2283 2307
2284 if (effective_load_flags_ & LOAD_VALIDATE_CACHE) 2308 if (effective_load_flags_ & (LOAD_VALIDATE_CACHE | LOAD_ASYNC_REVALIDATION))
2285 return true; 2309 return VALIDATION_SYNCHRONOUS;
2286 2310
2287 if (request_->method == "PUT" || request_->method == "DELETE") 2311 if (request_->method == "PUT" || request_->method == "DELETE")
2288 return true; 2312 return VALIDATION_SYNCHRONOUS;
2289 2313
2290 if (response_.headers->RequiresValidation( 2314 ValidationType validation_required_by_headers =
2291 response_.request_time, response_.response_time, Time::Now())) { 2315 response_.headers->RequiresValidation(
2292 return true; 2316 response_.request_time, response_.response_time, Time::Now());
2317
2318 if (validation_required_by_headers == VALIDATION_ASYNCHRONOUS) {
2319 // Asynchronous revalidation is only supported for GET and HEAD methods.
2320 if (request_->method != "GET" && request_->method != "HEAD")
2321 return VALIDATION_SYNCHRONOUS;
2293 } 2322 }
2294 2323
2295 return false; 2324 return validation_required_by_headers;
2296 } 2325 }
2297 2326
2298 bool HttpCache::Transaction::ConditionalizeRequest() { 2327 bool HttpCache::Transaction::ConditionalizeRequest() {
2299 DCHECK(response_.headers.get()); 2328 DCHECK(response_.headers.get());
2300 2329
2301 if (request_->method == "PUT" || request_->method == "DELETE") 2330 if (request_->method == "PUT" || request_->method == "DELETE")
2302 return false; 2331 return false;
2303 2332
2304 // This only makes sense for cached 200 or 206 responses. 2333 // This only makes sense for cached 200 or 206 responses.
2305 if (response_.headers->response_code() != 200 && 2334 if (response_.headers->response_code() != 200 &&
(...skipping 27 matching lines...) Expand all
2333 request_ = custom_request_.get(); 2362 request_ = custom_request_.get();
2334 } 2363 }
2335 DCHECK(custom_request_.get()); 2364 DCHECK(custom_request_.get());
2336 2365
2337 bool use_if_range = partial_.get() && !partial_->IsCurrentRangeCached() && 2366 bool use_if_range = partial_.get() && !partial_->IsCurrentRangeCached() &&
2338 !invalid_range_; 2367 !invalid_range_;
2339 2368
2340 if (!use_if_range) { 2369 if (!use_if_range) {
2341 // stale-while-revalidate is not useful when we only have a partial response 2370 // stale-while-revalidate is not useful when we only have a partial response
2342 // cached, so don't set the header in that case. 2371 // cached, so don't set the header in that case.
2343 TimeDelta stale_while_revalidate; 2372 HttpResponseHeaders::FreshnessLifetimes lifetime =
2344 if (response_.headers->GetStaleWhileRevalidateValue( 2373 response_.headers->GetFreshnessLifetimes(response_.response_time);
2345 &stale_while_revalidate) && 2374 if (lifetime.stale > TimeDelta()) {
2346 stale_while_revalidate > TimeDelta()) {
2347 TimeDelta max_age =
2348 response_.headers->GetFreshnessLifetime(response_.response_time);
2349 TimeDelta current_age = response_.headers->GetCurrentAge( 2375 TimeDelta current_age = response_.headers->GetCurrentAge(
2350 response_.request_time, response_.response_time, Time::Now()); 2376 response_.request_time, response_.response_time, Time::Now());
2351 2377
2352 custom_request_->extra_headers.SetHeader( 2378 custom_request_->extra_headers.SetHeader(
2353 kFreshnessHeader, 2379 kFreshnessHeader,
2354 base::StringPrintf("max-age=%" PRId64 2380 base::StringPrintf("max-age=%" PRId64
2355 ",stale-while-revalidate=%" PRId64 ",age=%" PRId64, 2381 ",stale-while-revalidate=%" PRId64 ",age=%" PRId64,
2356 max_age.InSeconds(), 2382 lifetime.fresh.InSeconds(),
2357 stale_while_revalidate.InSeconds(), 2383 lifetime.stale.InSeconds(),
2358 current_age.InSeconds())); 2384 current_age.InSeconds()));
2359 } 2385 }
2360 } 2386 }
2361 2387
2362 if (!etag_value.empty()) { 2388 if (!etag_value.empty()) {
2363 if (use_if_range) { 2389 if (use_if_range) {
2364 // We don't want to switch to WRITE mode if we don't have this block of a 2390 // We don't want to switch to WRITE mode if we don't have this block of a
2365 // byte-range request because we may have other parts cached. 2391 // byte-range request because we may have other parts cached.
2366 custom_request_->extra_headers.SetHeader( 2392 custom_request_->extra_headers.SetHeader(
2367 HttpRequestHeaders::kIfRange, etag_value); 2393 HttpRequestHeaders::kIfRange, etag_value);
(...skipping 148 matching lines...) Expand 10 before | Expand all | Expand 10 after
2516 } 2542 }
2517 2543
2518 void HttpCache::Transaction::FixHeadersForHead() { 2544 void HttpCache::Transaction::FixHeadersForHead() {
2519 if (response_.headers->response_code() == 206) { 2545 if (response_.headers->response_code() == 206) {
2520 response_.headers->RemoveHeader("Content-Length"); 2546 response_.headers->RemoveHeader("Content-Length");
2521 response_.headers->RemoveHeader("Content-Range"); 2547 response_.headers->RemoveHeader("Content-Range");
2522 response_.headers->ReplaceStatusLine("HTTP/1.1 200 OK"); 2548 response_.headers->ReplaceStatusLine("HTTP/1.1 200 OK");
2523 } 2549 }
2524 } 2550 }
2525 2551
2552 void HttpCache::Transaction::TriggerAsyncValidation() {
2553 DCHECK(!request_->upload_data_stream);
2554 BoundNetLog async_revalidation_net_log(
2555 BoundNetLog::Make(net_log_.net_log(), NetLog::SOURCE_ASYNC_REVALIDATION));
2556 net_log_.AddEvent(
2557 NetLog::TYPE_HTTP_CACHE_VALIDATE_RESOURCE_ASYNC,
2558 async_revalidation_net_log.source().ToEventParametersCallback());
2559 async_revalidation_net_log.BeginEvent(
2560 NetLog::TYPE_ASYNC_REVALIDATION,
2561 base::Bind(
2562 &NetLogAsyncRevalidationInfoCallback, net_log_.source(), request_));
2563 base::MessageLoop::current()->PostTask(
2564 FROM_HERE,
2565 base::Bind(&HttpCache::PerformAsyncValidation,
2566 cache_, // cache_ is a weak pointer.
2567 *request_,
2568 async_revalidation_net_log));
2569 }
2570
2526 void HttpCache::Transaction::FailRangeRequest() { 2571 void HttpCache::Transaction::FailRangeRequest() {
2527 response_ = *new_response_; 2572 response_ = *new_response_;
2528 partial_->FixResponseHeaders(response_.headers.get(), false); 2573 partial_->FixResponseHeaders(response_.headers.get(), false);
2529 } 2574 }
2530 2575
2531 int HttpCache::Transaction::SetupEntryForRead() { 2576 int HttpCache::Transaction::SetupEntryForRead() {
2532 if (network_trans_) 2577 if (network_trans_)
2533 ResetNetworkTransaction(); 2578 ResetNetworkTransaction();
2534 if (partial_.get()) { 2579 if (partial_.get()) {
2535 if (truncated_ || is_sparse_ || !invalid_range_) { 2580 if (truncated_ || is_sparse_ || !invalid_range_) {
(...skipping 326 matching lines...) Expand 10 before | Expand all | Expand 10 after
2862 default: 2907 default:
2863 NOTREACHED(); 2908 NOTREACHED();
2864 } 2909 }
2865 } 2910 }
2866 2911
2867 void HttpCache::Transaction::OnIOComplete(int result) { 2912 void HttpCache::Transaction::OnIOComplete(int result) {
2868 DoLoop(result); 2913 DoLoop(result);
2869 } 2914 }
2870 2915
2871 } // namespace net 2916 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698