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
3 // found in the LICENSE file.
5 #include "net/http/http_cache_transaction.h"
7 #include "build/build_config.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/format_macros.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/metrics/sparse_histogram.h"
24 #include "base/profiler/scoped_tracker.h"
25 #include "base/rand_util.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/stringprintf.h"
30 #include "base/time/time.h"
31 #include "base/values.h"
32 #include "net/base/completion_callback.h"
33 #include "net/base/io_buffer.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/load_timing_info.h"
36 #include "net/base/net_errors.h"
37 #include "net/base/net_log.h"
38 #include "net/base/upload_data_stream.h"
39 #include "net/cert/cert_status_flags.h"
40 #include "net/disk_cache/disk_cache.h"
41 #include "net/http/disk_based_cert_cache.h"
42 #include "net/http/http_network_session.h"
43 #include "net/http/http_request_info.h"
44 #include "net/http/http_response_headers.h"
45 #include "net/http/http_transaction.h"
46 #include "net/http/http_util.h"
47 #include "net/http/partial_data.h"
48 #include "net/ssl/ssl_cert_request_info.h"
49 #include "net/ssl/ssl_config_service.h"
52 using base::TimeDelta
;
53 using base::TimeTicks
;
57 // TODO(ricea): Move this to HttpResponseHeaders once it is standardised.
58 static const char kFreshnessHeader
[] = "Resource-Freshness";
60 // Stores data relevant to the statistics of writing and reading entire
61 // certificate chains using DiskBasedCertCache. |num_pending_ops| is the number
62 // of certificates in the chain that have pending operations in the
63 // DiskBasedCertCache. |start_time| is the time that the read and write
64 // commands began being issued to the DiskBasedCertCache.
65 // TODO(brandonsalmon): Remove this when it is no longer necessary to
67 class SharedChainData
: public base::RefCounted
<SharedChainData
> {
69 SharedChainData(int num_ops
, TimeTicks start
)
70 : num_pending_ops(num_ops
), start_time(start
) {}
76 friend class base::RefCounted
<SharedChainData
>;
78 DISALLOW_COPY_AND_ASSIGN(SharedChainData
);
81 // Used to obtain a cache entry key for an OSCertHandle.
82 // TODO(brandonsalmon): Remove this when cache keys are stored
83 // and no longer have to be recomputed to retrieve the OSCertHandle
85 std::string
GetCacheKeyForCert(net::X509Certificate::OSCertHandle cert_handle
) {
86 net::SHA1HashValue fingerprint
=
87 net::X509Certificate::CalculateFingerprint(cert_handle
);
90 base::HexEncode(fingerprint
.data
, arraysize(fingerprint
.data
));
93 // |dist_from_root| indicates the position of the read certificate in the
94 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
95 // whether or not the read certificate was the leaf of the chain.
96 // |shared_chain_data| contains data shared by each certificate in
98 void OnCertReadIOComplete(
101 const scoped_refptr
<SharedChainData
>& shared_chain_data
,
102 net::X509Certificate::OSCertHandle cert_handle
) {
103 // If |num_pending_ops| is one, this was the last pending read operation
104 // for this chain of certificates. The total time used to read the chain
105 // can be calculated by subtracting the starting time from Now().
106 shared_chain_data
->num_pending_ops
--;
107 if (!shared_chain_data
->num_pending_ops
) {
108 const TimeDelta read_chain_wait
=
109 TimeTicks::Now() - shared_chain_data
->start_time
;
110 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainReadTime",
112 base::TimeDelta::FromMilliseconds(1),
113 base::TimeDelta::FromMinutes(10),
117 bool success
= (cert_handle
!= NULL
);
119 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoReadSuccessLeaf", success
);
122 UMA_HISTOGRAM_CUSTOM_COUNTS(
123 "DiskBasedCertCache.CertIoReadSuccess", dist_from_root
, 0, 10, 7);
125 UMA_HISTOGRAM_CUSTOM_COUNTS(
126 "DiskBasedCertCache.CertIoReadFailure", dist_from_root
, 0, 10, 7);
129 // |dist_from_root| indicates the position of the written certificate in the
130 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
131 // whether or not the written certificate was the leaf of the chain.
132 // |shared_chain_data| contains data shared by each certificate in
134 void OnCertWriteIOComplete(
137 const scoped_refptr
<SharedChainData
>& shared_chain_data
,
138 const std::string
& key
) {
139 // If |num_pending_ops| is one, this was the last pending write operation
140 // for this chain of certificates. The total time used to write the chain
141 // can be calculated by subtracting the starting time from Now().
142 shared_chain_data
->num_pending_ops
--;
143 if (!shared_chain_data
->num_pending_ops
) {
144 const TimeDelta write_chain_wait
=
145 TimeTicks::Now() - shared_chain_data
->start_time
;
146 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainWriteTime",
148 base::TimeDelta::FromMilliseconds(1),
149 base::TimeDelta::FromMinutes(10),
153 bool success
= !key
.empty();
155 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoWriteSuccessLeaf", success
);
158 UMA_HISTOGRAM_CUSTOM_COUNTS(
159 "DiskBasedCertCache.CertIoWriteSuccess", dist_from_root
, 0, 10, 7);
161 UMA_HISTOGRAM_CUSTOM_COUNTS(
162 "DiskBasedCertCache.CertIoWriteFailure", dist_from_root
, 0, 10, 7);
165 // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
166 // a "non-error response" is one with a 2xx (Successful) or 3xx
167 // (Redirection) status code.
168 bool NonErrorResponse(int status_code
) {
169 int status_code_range
= status_code
/ 100;
170 return status_code_range
== 2 || status_code_range
== 3;
173 // Error codes that will be considered indicative of a page being offline/
174 // unreachable for LOAD_FROM_CACHE_IF_OFFLINE.
175 bool IsOfflineError(int error
) {
176 return (error
== net::ERR_NAME_NOT_RESOLVED
||
177 error
== net::ERR_INTERNET_DISCONNECTED
||
178 error
== net::ERR_ADDRESS_UNREACHABLE
||
179 error
== net::ERR_CONNECTION_TIMED_OUT
);
182 // Enum for UMA, indicating the status (with regard to offline mode) of
183 // a particular request.
184 enum RequestOfflineStatus
{
185 // A cache transaction hit in cache (data was present and not stale)
187 OFFLINE_STATUS_FRESH_CACHE
,
189 // A network request was required for a cache entry, and it succeeded.
190 OFFLINE_STATUS_NETWORK_SUCCEEDED
,
192 // A network request was required for a cache entry, and it failed with
193 // a non-offline error.
194 OFFLINE_STATUS_NETWORK_FAILED
,
196 // A network request was required for a cache entry, it failed with an
197 // offline error, and we could serve stale data if
198 // LOAD_FROM_CACHE_IF_OFFLINE was set.
199 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE
,
201 // A network request was required for a cache entry, it failed with
202 // an offline error, and there was no servable data in cache (even
204 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE
,
206 OFFLINE_STATUS_MAX_ENTRIES
209 void RecordOfflineStatus(int load_flags
, RequestOfflineStatus status
) {
210 // Restrict to main frame to keep statistics close to
211 // "would have shown them something useful if offline mode was enabled".
212 if (load_flags
& net::LOAD_MAIN_FRAME
) {
213 UMA_HISTOGRAM_ENUMERATION("HttpCache.OfflineStatus", status
,
214 OFFLINE_STATUS_MAX_ENTRIES
);
218 void RecordNoStoreHeaderHistogram(int load_flags
,
219 const net::HttpResponseInfo
* response
) {
220 if (load_flags
& net::LOAD_MAIN_FRAME
) {
221 UMA_HISTOGRAM_BOOLEAN(
222 "Net.MainFrameNoStore",
223 response
->headers
->HasHeaderValue("cache-control", "no-store"));
227 base::Value
* NetLogAsyncRevalidationInfoCallback(
228 const net::NetLog::Source
& source
,
229 const net::HttpRequestInfo
* request
,
230 net::NetLog::LogLevel log_level
) {
231 base::DictionaryValue
* dict
= new base::DictionaryValue();
232 source
.AddToEventParameters(dict
);
234 dict
->SetString("url", request
->url
.possibly_invalid_spec());
235 dict
->SetString("method", request
->method
);
239 enum ExternallyConditionalizedType
{
240 EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION
,
241 EXTERNALLY_CONDITIONALIZED_CACHE_USABLE
,
242 EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS
,
243 EXTERNALLY_CONDITIONALIZED_MAX
250 struct HeaderNameAndValue
{
255 // If the request includes one of these request headers, then avoid caching
256 // to avoid getting confused.
257 static const HeaderNameAndValue kPassThroughHeaders
[] = {
258 { "if-unmodified-since", NULL
}, // causes unexpected 412s
259 { "if-match", NULL
}, // causes unexpected 412s
260 { "if-range", NULL
},
264 struct ValidationHeaderInfo
{
265 const char* request_header_name
;
266 const char* related_response_header_name
;
269 static const ValidationHeaderInfo kValidationHeaders
[] = {
270 { "if-modified-since", "last-modified" },
271 { "if-none-match", "etag" },
274 // If the request includes one of these request headers, then avoid reusing
275 // our cached copy if any.
276 static const HeaderNameAndValue kForceFetchHeaders
[] = {
277 { "cache-control", "no-cache" },
278 { "pragma", "no-cache" },
282 // If the request includes one of these request headers, then force our
283 // cached copy (if any) to be revalidated before reusing it.
284 static const HeaderNameAndValue kForceValidateHeaders
[] = {
285 { "cache-control", "max-age=0" },
289 static bool HeaderMatches(const HttpRequestHeaders
& headers
,
290 const HeaderNameAndValue
* search
) {
291 for (; search
->name
; ++search
) {
292 std::string header_value
;
293 if (!headers
.GetHeader(search
->name
, &header_value
))
299 HttpUtil::ValuesIterator
v(header_value
.begin(), header_value
.end(), ',');
300 while (v
.GetNext()) {
301 if (LowerCaseEqualsASCII(v
.value_begin(), v
.value_end(), search
->value
))
308 //-----------------------------------------------------------------------------
310 HttpCache::Transaction::Transaction(
311 RequestPriority priority
,
313 : next_state_(STATE_NONE
),
316 cache_(cache
->GetWeakPtr()),
321 target_state_(STATE_NONE
),
323 invalid_range_(false),
326 range_requested_(false),
327 handling_206_(false),
328 cache_pending_(false),
329 done_reading_(false),
330 vary_mismatch_(false),
331 couldnt_conditionalize_request_(false),
332 bypass_lock_for_test_(false),
335 effective_load_flags_(0),
337 transaction_pattern_(PATTERN_UNDEFINED
),
338 total_received_bytes_(0),
339 websocket_handshake_stream_base_create_helper_(NULL
),
340 weak_factory_(this) {
341 COMPILE_ASSERT(HttpCache::Transaction::kNumValidationHeaders
==
342 arraysize(kValidationHeaders
),
343 Invalid_number_of_validation_headers
);
345 io_callback_
= base::Bind(&Transaction::OnIOComplete
,
346 weak_factory_
.GetWeakPtr());
349 HttpCache::Transaction::~Transaction() {
350 // We may have to issue another IO, but we should never invoke the callback_
356 bool cancel_request
= reading_
&& response_
.headers
.get();
357 if (cancel_request
) {
359 entry_
->disk_entry
->CancelSparseIO();
361 cancel_request
&= (response_
.headers
->response_code() == 200);
365 cache_
->DoneWithEntry(entry_
, this, cancel_request
);
366 } else if (cache_pending_
) {
367 cache_
->RemovePendingTransaction(this);
372 int HttpCache::Transaction::WriteMetadata(IOBuffer
* buf
, int buf_len
,
373 const CompletionCallback
& callback
) {
375 DCHECK_GT(buf_len
, 0);
376 DCHECK(!callback
.is_null());
377 if (!cache_
.get() || !entry_
)
378 return ERR_UNEXPECTED
;
380 // We don't need to track this operation for anything.
381 // It could be possible to check if there is something already written and
382 // avoid writing again (it should be the same, right?), but let's allow the
383 // caller to "update" the contents with something new.
384 return entry_
->disk_entry
->WriteData(kMetadataIndex
, 0, buf
, buf_len
,
388 bool HttpCache::Transaction::AddTruncatedFlag() {
389 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
391 // Don't set the flag for sparse entries.
392 if (partial_
.get() && !truncated_
)
395 if (!CanResume(true))
398 // We may have received the whole resource already.
403 target_state_
= STATE_NONE
;
404 next_state_
= STATE_CACHE_WRITE_TRUNCATED_RESPONSE
;
409 LoadState
HttpCache::Transaction::GetWriterLoadState() const {
410 if (network_trans_
.get())
411 return network_trans_
->GetLoadState();
412 if (entry_
|| !request_
)
413 return LOAD_STATE_IDLE
;
414 return LOAD_STATE_WAITING_FOR_CACHE
;
417 const BoundNetLog
& HttpCache::Transaction::net_log() const {
421 int HttpCache::Transaction::Start(const HttpRequestInfo
* request
,
422 const CompletionCallback
& callback
,
423 const BoundNetLog
& net_log
) {
425 DCHECK(!callback
.is_null());
427 // Ensure that we only have one asynchronous call at a time.
428 DCHECK(callback_
.is_null());
430 DCHECK(!network_trans_
.get());
434 return ERR_UNEXPECTED
;
436 SetRequest(net_log
, request
);
438 // We have to wait until the backend is initialized so we start the SM.
439 next_state_
= STATE_GET_BACKEND
;
442 // Setting this here allows us to check for the existence of a callback_ to
443 // determine if we are still inside Start.
444 if (rv
== ERR_IO_PENDING
)
445 callback_
= callback
;
450 int HttpCache::Transaction::RestartIgnoringLastError(
451 const CompletionCallback
& callback
) {
452 DCHECK(!callback
.is_null());
454 // Ensure that we only have one asynchronous call at a time.
455 DCHECK(callback_
.is_null());
458 return ERR_UNEXPECTED
;
460 int rv
= RestartNetworkRequest();
462 if (rv
== ERR_IO_PENDING
)
463 callback_
= callback
;
468 int HttpCache::Transaction::RestartWithCertificate(
469 X509Certificate
* client_cert
,
470 const CompletionCallback
& callback
) {
471 DCHECK(!callback
.is_null());
473 // Ensure that we only have one asynchronous call at a time.
474 DCHECK(callback_
.is_null());
477 return ERR_UNEXPECTED
;
479 int rv
= RestartNetworkRequestWithCertificate(client_cert
);
481 if (rv
== ERR_IO_PENDING
)
482 callback_
= callback
;
487 int HttpCache::Transaction::RestartWithAuth(
488 const AuthCredentials
& credentials
,
489 const CompletionCallback
& callback
) {
490 DCHECK(auth_response_
.headers
.get());
491 DCHECK(!callback
.is_null());
493 // Ensure that we only have one asynchronous call at a time.
494 DCHECK(callback_
.is_null());
497 return ERR_UNEXPECTED
;
499 // Clear the intermediate response since we are going to start over.
500 auth_response_
= HttpResponseInfo();
502 int rv
= RestartNetworkRequestWithAuth(credentials
);
504 if (rv
== ERR_IO_PENDING
)
505 callback_
= callback
;
510 bool HttpCache::Transaction::IsReadyToRestartForAuth() {
511 if (!network_trans_
.get())
513 return network_trans_
->IsReadyToRestartForAuth();
516 int HttpCache::Transaction::Read(IOBuffer
* buf
, int buf_len
,
517 const CompletionCallback
& callback
) {
519 DCHECK_GT(buf_len
, 0);
520 DCHECK(!callback
.is_null());
522 DCHECK(callback_
.is_null());
525 return ERR_UNEXPECTED
;
527 // If we have an intermediate auth response at this point, then it means the
528 // user wishes to read the network response (the error page). If there is a
529 // previous response in the cache then we should leave it intact.
530 if (auth_response_
.headers
.get() && mode_
!= NONE
) {
531 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
532 DCHECK(mode_
& WRITE
);
533 DoneWritingToEntry(mode_
== READ_WRITE
);
542 DCHECK(partial_
.get());
543 if (!network_trans_
.get()) {
544 // We are just reading from the cache, but we may be writing later.
545 rv
= ReadFromEntry(buf
, buf_len
);
550 DCHECK(network_trans_
.get());
551 rv
= ReadFromNetwork(buf
, buf_len
);
554 rv
= ReadFromEntry(buf
, buf_len
);
561 if (rv
== ERR_IO_PENDING
) {
562 DCHECK(callback_
.is_null());
563 callback_
= callback
;
568 void HttpCache::Transaction::StopCaching() {
569 // We really don't know where we are now. Hopefully there is no operation in
570 // progress, but nothing really prevents this method to be called after we
571 // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
572 // point because we need the state machine for that (and even if we are really
573 // free, that would be an asynchronous operation). In other words, keep the
574 // entry how it is (it will be marked as truncated at destruction), and let
575 // the next piece of code that executes know that we are now reading directly
577 // TODO(mmenke): This doesn't release the lock on the cache entry, so a
578 // future request for the resource will be blocked on this one.
580 if (cache_
.get() && entry_
&& (mode_
& WRITE
) && network_trans_
.get() &&
581 !is_sparse_
&& !range_requested_
) {
586 bool HttpCache::Transaction::GetFullRequestHeaders(
587 HttpRequestHeaders
* headers
) const {
589 return network_trans_
->GetFullRequestHeaders(headers
);
591 // TODO(ttuttle): Read headers from cache.
595 int64
HttpCache::Transaction::GetTotalReceivedBytes() const {
596 int64 total_received_bytes
= total_received_bytes_
;
598 total_received_bytes
+= network_trans_
->GetTotalReceivedBytes();
599 return total_received_bytes
;
602 void HttpCache::Transaction::DoneReading() {
603 if (cache_
.get() && entry_
) {
604 DCHECK_NE(mode_
, UPDATE
);
606 DoneWritingToEntry(true);
607 } else if (mode_
& READ
) {
608 // It is necessary to check mode_ & READ because it is possible
609 // for mode_ to be NONE and entry_ non-NULL with a write entry
610 // if StopCaching was called.
611 cache_
->DoneReadingFromEntry(entry_
, this);
617 const HttpResponseInfo
* HttpCache::Transaction::GetResponseInfo() const {
618 // Null headers means we encountered an error or haven't a response yet
619 if (auth_response_
.headers
.get())
620 return &auth_response_
;
621 return (response_
.headers
.get() || response_
.ssl_info
.cert
.get() ||
622 response_
.cert_request_info
.get())
627 LoadState
HttpCache::Transaction::GetLoadState() const {
628 LoadState state
= GetWriterLoadState();
629 if (state
!= LOAD_STATE_WAITING_FOR_CACHE
)
633 return cache_
->GetLoadStateForPendingTransaction(this);
635 return LOAD_STATE_IDLE
;
638 UploadProgress
HttpCache::Transaction::GetUploadProgress() const {
639 if (network_trans_
.get())
640 return network_trans_
->GetUploadProgress();
641 return final_upload_progress_
;
644 void HttpCache::Transaction::SetQuicServerInfo(
645 QuicServerInfo
* quic_server_info
) {}
647 bool HttpCache::Transaction::GetLoadTimingInfo(
648 LoadTimingInfo
* load_timing_info
) const {
650 return network_trans_
->GetLoadTimingInfo(load_timing_info
);
652 if (old_network_trans_load_timing_
) {
653 *load_timing_info
= *old_network_trans_load_timing_
;
657 if (first_cache_access_since_
.is_null())
660 // If the cache entry was opened, return that time.
661 load_timing_info
->send_start
= first_cache_access_since_
;
662 // This time doesn't make much sense when reading from the cache, so just use
663 // the same time as send_start.
664 load_timing_info
->send_end
= first_cache_access_since_
;
668 void HttpCache::Transaction::SetPriority(RequestPriority priority
) {
669 priority_
= priority
;
671 network_trans_
->SetPriority(priority_
);
674 void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
675 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
676 websocket_handshake_stream_base_create_helper_
= create_helper
;
678 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(create_helper
);
681 void HttpCache::Transaction::SetBeforeNetworkStartCallback(
682 const BeforeNetworkStartCallback
& callback
) {
683 DCHECK(!network_trans_
);
684 before_network_start_callback_
= callback
;
687 void HttpCache::Transaction::SetBeforeProxyHeadersSentCallback(
688 const BeforeProxyHeadersSentCallback
& callback
) {
689 DCHECK(!network_trans_
);
690 before_proxy_headers_sent_callback_
= callback
;
693 int HttpCache::Transaction::ResumeNetworkStart() {
695 return network_trans_
->ResumeNetworkStart();
696 return ERR_UNEXPECTED
;
699 //-----------------------------------------------------------------------------
701 void HttpCache::Transaction::DoCallback(int rv
) {
702 DCHECK(rv
!= ERR_IO_PENDING
);
703 DCHECK(!callback_
.is_null());
705 read_buf_
= NULL
; // Release the buffer before invoking the callback.
707 // Since Run may result in Read being called, clear callback_ up front.
708 CompletionCallback c
= callback_
;
713 int HttpCache::Transaction::HandleResult(int rv
) {
714 DCHECK(rv
!= ERR_IO_PENDING
);
715 if (!callback_
.is_null())
721 // A few common patterns: (Foo* means Foo -> FooComplete)
723 // 1. Not-cached entry:
725 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
726 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
727 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
728 // PartialHeadersReceived
731 // NetworkRead* -> CacheWriteData*
733 // 2. Cached entry, no validation:
735 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
736 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
737 // SetupEntryForRead()
742 // 3. Cached entry, validation (304):
744 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
745 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
746 // SendRequest* -> SuccessfulSendRequest -> UpdateCachedResponse ->
747 // CacheWriteResponse* -> UpdateCachedResponseComplete ->
748 // OverwriteCachedResponse -> PartialHeadersReceived
753 // 4. Cached entry, validation and replace (200):
755 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
756 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
757 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
758 // CacheWriteResponse* -> DoTruncateCachedData* -> TruncateCachedMetadata* ->
759 // PartialHeadersReceived
762 // NetworkRead* -> CacheWriteData*
764 // 5. Sparse entry, partially cached, byte range request:
766 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
767 // -> BeginPartialCacheValidation() -> CacheQueryData* ->
768 // ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation ->
769 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
770 // SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteResponse* ->
771 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
772 // PartialHeadersReceived
775 // NetworkRead* -> CacheWriteData*
778 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
779 // CompletePartialCacheValidation -> CacheReadData* ->
782 // CacheReadData* -> StartPartialCacheValidation ->
783 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
784 // SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
785 // -> PartialHeadersReceived -> NetworkRead* -> CacheWriteData*
787 // 6. HEAD. Not-cached entry:
788 // Pass through. Don't save a HEAD by itself.
790 // GetBackend* -> InitEntry -> OpenEntry* -> SendRequest*
792 // 7. HEAD. Cached entry, no validation:
794 // The same flow as for a GET request (example #2)
797 // CacheReadData (returns 0)
799 // 8. HEAD. Cached entry, validation (304):
800 // The request updates the stored headers.
801 // Start(): Same as for a GET request (example #3)
804 // CacheReadData (returns 0)
806 // 9. HEAD. Cached entry, validation and replace (200):
807 // Pass through. The request dooms the old entry, as a HEAD won't be stored by
810 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
811 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
812 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse
814 // 10. HEAD. Sparse entry, partially cached:
815 // Serve the request from the cache, as long as it doesn't require
816 // revalidation. Ignore missing ranges when deciding to revalidate. If the
817 // entry requires revalidation, ignore the whole request and go to full pass
818 // through (the result of the HEAD request will NOT update the entry).
820 // Start(): Basically the same as example 7, as we never create a partial_
821 // object for this request.
823 int HttpCache::Transaction::DoLoop(int result
) {
824 DCHECK(next_state_
!= STATE_NONE
);
828 State state
= next_state_
;
829 next_state_
= STATE_NONE
;
831 case STATE_GET_BACKEND
:
835 case STATE_GET_BACKEND_COMPLETE
:
836 rv
= DoGetBackendComplete(rv
);
838 case STATE_SEND_REQUEST
:
840 rv
= DoSendRequest();
842 case STATE_SEND_REQUEST_COMPLETE
:
843 rv
= DoSendRequestComplete(rv
);
845 case STATE_SUCCESSFUL_SEND_REQUEST
:
847 rv
= DoSuccessfulSendRequest();
849 case STATE_NETWORK_READ
:
851 rv
= DoNetworkRead();
853 case STATE_NETWORK_READ_COMPLETE
:
854 rv
= DoNetworkReadComplete(rv
);
856 case STATE_INIT_ENTRY
:
860 case STATE_OPEN_ENTRY
:
864 case STATE_OPEN_ENTRY_COMPLETE
:
865 rv
= DoOpenEntryComplete(rv
);
867 case STATE_CREATE_ENTRY
:
869 rv
= DoCreateEntry();
871 case STATE_CREATE_ENTRY_COMPLETE
:
872 rv
= DoCreateEntryComplete(rv
);
874 case STATE_DOOM_ENTRY
:
878 case STATE_DOOM_ENTRY_COMPLETE
:
879 rv
= DoDoomEntryComplete(rv
);
881 case STATE_ADD_TO_ENTRY
:
885 case STATE_ADD_TO_ENTRY_COMPLETE
:
886 rv
= DoAddToEntryComplete(rv
);
888 case STATE_START_PARTIAL_CACHE_VALIDATION
:
890 rv
= DoStartPartialCacheValidation();
892 case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
:
893 rv
= DoCompletePartialCacheValidation(rv
);
895 case STATE_UPDATE_CACHED_RESPONSE
:
897 rv
= DoUpdateCachedResponse();
899 case STATE_UPDATE_CACHED_RESPONSE_COMPLETE
:
900 rv
= DoUpdateCachedResponseComplete(rv
);
902 case STATE_OVERWRITE_CACHED_RESPONSE
:
904 rv
= DoOverwriteCachedResponse();
906 case STATE_TRUNCATE_CACHED_DATA
:
908 rv
= DoTruncateCachedData();
910 case STATE_TRUNCATE_CACHED_DATA_COMPLETE
:
911 rv
= DoTruncateCachedDataComplete(rv
);
913 case STATE_TRUNCATE_CACHED_METADATA
:
915 rv
= DoTruncateCachedMetadata();
917 case STATE_TRUNCATE_CACHED_METADATA_COMPLETE
:
918 rv
= DoTruncateCachedMetadataComplete(rv
);
920 case STATE_PARTIAL_HEADERS_RECEIVED
:
922 rv
= DoPartialHeadersReceived();
924 case STATE_CACHE_READ_RESPONSE
:
926 rv
= DoCacheReadResponse();
928 case STATE_CACHE_READ_RESPONSE_COMPLETE
:
929 rv
= DoCacheReadResponseComplete(rv
);
931 case STATE_CACHE_WRITE_RESPONSE
:
933 rv
= DoCacheWriteResponse();
935 case STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
937 rv
= DoCacheWriteTruncatedResponse();
939 case STATE_CACHE_WRITE_RESPONSE_COMPLETE
:
940 rv
= DoCacheWriteResponseComplete(rv
);
942 case STATE_CACHE_READ_METADATA
:
944 rv
= DoCacheReadMetadata();
946 case STATE_CACHE_READ_METADATA_COMPLETE
:
947 rv
= DoCacheReadMetadataComplete(rv
);
949 case STATE_CACHE_QUERY_DATA
:
951 rv
= DoCacheQueryData();
953 case STATE_CACHE_QUERY_DATA_COMPLETE
:
954 rv
= DoCacheQueryDataComplete(rv
);
956 case STATE_CACHE_READ_DATA
:
958 rv
= DoCacheReadData();
960 case STATE_CACHE_READ_DATA_COMPLETE
:
961 rv
= DoCacheReadDataComplete(rv
);
963 case STATE_CACHE_WRITE_DATA
:
964 rv
= DoCacheWriteData(rv
);
966 case STATE_CACHE_WRITE_DATA_COMPLETE
:
967 rv
= DoCacheWriteDataComplete(rv
);
970 NOTREACHED() << "bad state";
974 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
976 if (rv
!= ERR_IO_PENDING
)
982 int HttpCache::Transaction::DoGetBackend() {
983 cache_pending_
= true;
984 next_state_
= STATE_GET_BACKEND_COMPLETE
;
985 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
);
986 return cache_
->GetBackendForTransaction(this);
989 int HttpCache::Transaction::DoGetBackendComplete(int result
) {
990 DCHECK(result
== OK
|| result
== ERR_FAILED
);
991 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
,
993 cache_pending_
= false;
995 if (!ShouldPassThrough()) {
996 cache_key_
= cache_
->GenerateCacheKey(request_
);
998 // Requested cache access mode.
999 if (effective_load_flags_
& LOAD_ONLY_FROM_CACHE
) {
1001 } else if (effective_load_flags_
& LOAD_BYPASS_CACHE
) {
1007 // Downgrade to UPDATE if the request has been externally conditionalized.
1008 if (external_validation_
.initialized
) {
1009 if (mode_
& WRITE
) {
1010 // Strip off the READ_DATA bit (and maybe add back a READ_META bit
1011 // in case READ was off).
1019 // Use PUT and DELETE only to invalidate existing stored entries.
1020 if ((request_
->method
== "PUT" || request_
->method
== "DELETE") &&
1021 mode_
!= READ_WRITE
&& mode_
!= WRITE
) {
1025 // Note that if mode_ == UPDATE (which is tied to external_validation_), the
1026 // transaction behaves the same for GET and HEAD requests at this point: if it
1027 // was not modified, the entry is updated and a response is not returned from
1028 // the cache. If we receive 200, it doesn't matter if there was a validation
1030 if (request_
->method
== "HEAD" && mode_
== WRITE
)
1033 // If must use cache, then we must fail. This can happen for back/forward
1034 // navigations to a page generated via a form post.
1035 if (!(mode_
& READ
) && effective_load_flags_
& LOAD_ONLY_FROM_CACHE
)
1036 return ERR_CACHE_MISS
;
1038 if (mode_
== NONE
) {
1039 if (partial_
.get()) {
1040 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1043 next_state_
= STATE_SEND_REQUEST
;
1045 next_state_
= STATE_INIT_ENTRY
;
1048 // This is only set if we have something to do with the response.
1049 range_requested_
= (partial_
.get() != NULL
);
1054 int HttpCache::Transaction::DoSendRequest() {
1055 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1056 DCHECK(!network_trans_
.get());
1058 send_request_since_
= TimeTicks::Now();
1060 // Create a network transaction.
1061 int rv
= cache_
->network_layer_
->CreateTransaction(priority_
,
1065 network_trans_
->SetBeforeNetworkStartCallback(before_network_start_callback_
);
1066 network_trans_
->SetBeforeProxyHeadersSentCallback(
1067 before_proxy_headers_sent_callback_
);
1069 // Old load timing information, if any, is now obsolete.
1070 old_network_trans_load_timing_
.reset();
1072 if (websocket_handshake_stream_base_create_helper_
)
1073 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(
1074 websocket_handshake_stream_base_create_helper_
);
1076 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1077 rv
= network_trans_
->Start(request_
, io_callback_
, net_log_
);
1081 int HttpCache::Transaction::DoSendRequestComplete(int result
) {
1083 return ERR_UNEXPECTED
;
1085 // If requested, and we have a readable cache entry, and we have
1086 // an error indicating that we're offline as opposed to in contact
1087 // with a bad server, read from cache anyway.
1088 if (IsOfflineError(result
)) {
1089 if (mode_
== READ_WRITE
&& entry_
&& !partial_
) {
1090 RecordOfflineStatus(effective_load_flags_
,
1091 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE
);
1092 if (effective_load_flags_
& LOAD_FROM_CACHE_IF_OFFLINE
) {
1093 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1094 response_
.server_data_unavailable
= true;
1095 return SetupEntryForRead();
1098 RecordOfflineStatus(effective_load_flags_
,
1099 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE
);
1102 RecordOfflineStatus(effective_load_flags_
,
1103 (result
== OK
? OFFLINE_STATUS_NETWORK_SUCCEEDED
:
1104 OFFLINE_STATUS_NETWORK_FAILED
));
1107 // If we tried to conditionalize the request and failed, we know
1108 // we won't be reading from the cache after this point.
1109 if (couldnt_conditionalize_request_
)
1113 next_state_
= STATE_SUCCESSFUL_SEND_REQUEST
;
1117 // Do not record requests that have network errors or restarts.
1118 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1119 if (IsCertificateError(result
)) {
1120 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
1121 // If we get a certificate error, then there is a certificate in ssl_info,
1122 // so GetResponseInfo() should never return NULL here.
1124 response_
.ssl_info
= response
->ssl_info
;
1125 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
1126 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
1128 response_
.cert_request_info
= response
->cert_request_info
;
1129 } else if (response_
.was_cached
) {
1130 DoneWritingToEntry(true);
1135 // We received the response headers and there is no error.
1136 int HttpCache::Transaction::DoSuccessfulSendRequest() {
1137 DCHECK(!new_response_
);
1138 const HttpResponseInfo
* new_response
= network_trans_
->GetResponseInfo();
1139 bool authentication_failure
= false;
1141 if (new_response
->headers
->response_code() == 401 ||
1142 new_response
->headers
->response_code() == 407) {
1143 auth_response_
= *new_response
;
1147 // We initiated a second request the caller doesn't know about. We should be
1148 // able to authenticate this request because we should have authenticated
1149 // this URL moments ago.
1150 if (IsReadyToRestartForAuth()) {
1151 DCHECK(!response_
.auth_challenge
.get());
1152 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1153 // In theory we should check to see if there are new cookies, but there
1154 // is no way to do that from here.
1155 return network_trans_
->RestartWithAuth(AuthCredentials(), io_callback_
);
1158 // We have to perform cleanup at this point so that at least the next
1159 // request can succeed.
1160 authentication_failure
= true;
1162 DoomPartialEntry(false);
1167 new_response_
= new_response
;
1168 if (authentication_failure
||
1169 (!ValidatePartialResponse() && !auth_response_
.headers
.get())) {
1170 // Something went wrong with this request and we have to restart it.
1171 // If we have an authentication response, we are exposed to weird things
1172 // hapenning if the user cancels the authentication before we receive
1173 // the new response.
1174 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1175 response_
= HttpResponseInfo();
1176 ResetNetworkTransaction();
1177 new_response_
= NULL
;
1178 next_state_
= STATE_SEND_REQUEST
;
1182 if (handling_206_
&& mode_
== READ_WRITE
&& !truncated_
&& !is_sparse_
) {
1183 // We have stored the full entry, but it changed and the server is
1184 // sending a range. We have to delete the old entry.
1185 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1186 DoneWritingToEntry(false);
1189 if (mode_
== WRITE
&&
1190 transaction_pattern_
!= PATTERN_ENTRY_CANT_CONDITIONALIZE
) {
1191 UpdateTransactionPattern(PATTERN_ENTRY_NOT_CACHED
);
1194 // Invalidate any cached GET with a successful PUT or DELETE.
1195 if (mode_
== WRITE
&&
1196 (request_
->method
== "PUT" || request_
->method
== "DELETE")) {
1197 if (NonErrorResponse(new_response
->headers
->response_code())) {
1198 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1201 cache_
->DoneWritingToEntry(entry_
, true);
1206 // Invalidate any cached GET with a successful POST.
1207 if (!(effective_load_flags_
& LOAD_DISABLE_CACHE
) &&
1208 request_
->method
== "POST" &&
1209 NonErrorResponse(new_response
->headers
->response_code())) {
1210 cache_
->DoomMainEntryForUrl(request_
->url
);
1213 RecordNoStoreHeaderHistogram(request_
->load_flags
, new_response
);
1215 if (new_response_
->headers
->response_code() == 416 &&
1216 (request_
->method
== "GET" || request_
->method
== "POST")) {
1217 // If there is an active entry it may be destroyed with this transaction.
1218 response_
= *new_response_
;
1222 // Are we expecting a response to a conditional query?
1223 if (mode_
== READ_WRITE
|| mode_
== UPDATE
) {
1224 if (new_response
->headers
->response_code() == 304 || handling_206_
) {
1225 UpdateTransactionPattern(PATTERN_ENTRY_VALIDATED
);
1226 next_state_
= STATE_UPDATE_CACHED_RESPONSE
;
1229 UpdateTransactionPattern(PATTERN_ENTRY_UPDATED
);
1233 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1237 int HttpCache::Transaction::DoNetworkRead() {
1238 next_state_
= STATE_NETWORK_READ_COMPLETE
;
1239 return network_trans_
->Read(read_buf_
.get(), io_buf_len_
, io_callback_
);
1242 int HttpCache::Transaction::DoNetworkReadComplete(int result
) {
1243 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1246 return ERR_UNEXPECTED
;
1248 // If there is an error or we aren't saving the data, we are done; just wait
1249 // until the destructor runs to see if we can keep the data.
1250 if (mode_
== NONE
|| result
< 0)
1253 next_state_
= STATE_CACHE_WRITE_DATA
;
1257 int HttpCache::Transaction::DoInitEntry() {
1258 DCHECK(!new_entry_
);
1261 return ERR_UNEXPECTED
;
1263 if (mode_
== WRITE
) {
1264 next_state_
= STATE_DOOM_ENTRY
;
1268 next_state_
= STATE_OPEN_ENTRY
;
1272 int HttpCache::Transaction::DoOpenEntry() {
1273 DCHECK(!new_entry_
);
1274 next_state_
= STATE_OPEN_ENTRY_COMPLETE
;
1275 cache_pending_
= true;
1276 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
);
1277 first_cache_access_since_
= TimeTicks::Now();
1278 return cache_
->OpenEntry(cache_key_
, &new_entry_
, this);
1281 int HttpCache::Transaction::DoOpenEntryComplete(int result
) {
1282 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1283 // OK, otherwise the cache will end up with an active entry without any
1284 // transaction attached.
1285 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
, result
);
1286 cache_pending_
= false;
1288 next_state_
= STATE_ADD_TO_ENTRY
;
1292 if (result
== ERR_CACHE_RACE
) {
1293 next_state_
= STATE_INIT_ENTRY
;
1297 if (request_
->method
== "PUT" || request_
->method
== "DELETE" ||
1298 (request_
->method
== "HEAD" && mode_
== READ_WRITE
)) {
1299 DCHECK(mode_
== READ_WRITE
|| mode_
== WRITE
|| request_
->method
== "HEAD");
1301 next_state_
= STATE_SEND_REQUEST
;
1305 if (mode_
== READ_WRITE
) {
1307 next_state_
= STATE_CREATE_ENTRY
;
1310 if (mode_
== UPDATE
) {
1311 // There is no cache entry to update; proceed without caching.
1313 next_state_
= STATE_SEND_REQUEST
;
1316 if (cache_
->mode() == PLAYBACK
)
1317 DVLOG(1) << "Playback Cache Miss: " << request_
->url
;
1319 // The entry does not exist, and we are not permitted to create a new entry,
1321 return ERR_CACHE_MISS
;
1324 int HttpCache::Transaction::DoCreateEntry() {
1325 DCHECK(!new_entry_
);
1326 next_state_
= STATE_CREATE_ENTRY_COMPLETE
;
1327 cache_pending_
= true;
1328 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
);
1329 return cache_
->CreateEntry(cache_key_
, &new_entry_
, this);
1332 int HttpCache::Transaction::DoCreateEntryComplete(int result
) {
1333 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1334 // OK, otherwise the cache will end up with an active entry without any
1335 // transaction attached.
1336 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
,
1338 cache_pending_
= false;
1339 next_state_
= STATE_ADD_TO_ENTRY
;
1341 if (result
== ERR_CACHE_RACE
) {
1342 next_state_
= STATE_INIT_ENTRY
;
1347 // We have a race here: Maybe we failed to open the entry and decided to
1348 // create one, but by the time we called create, another transaction already
1349 // created the entry. If we want to eliminate this issue, we need an atomic
1350 // OpenOrCreate() method exposed by the disk cache.
1351 DLOG(WARNING
) << "Unable to create cache entry";
1354 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1355 next_state_
= STATE_SEND_REQUEST
;
1360 int HttpCache::Transaction::DoDoomEntry() {
1361 next_state_
= STATE_DOOM_ENTRY_COMPLETE
;
1362 cache_pending_
= true;
1363 if (first_cache_access_since_
.is_null())
1364 first_cache_access_since_
= TimeTicks::Now();
1365 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
);
1366 return cache_
->DoomEntry(cache_key_
, this);
1369 int HttpCache::Transaction::DoDoomEntryComplete(int result
) {
1370 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
, result
);
1371 next_state_
= STATE_CREATE_ENTRY
;
1372 cache_pending_
= false;
1373 if (result
== ERR_CACHE_RACE
)
1374 next_state_
= STATE_INIT_ENTRY
;
1378 int HttpCache::Transaction::DoAddToEntry() {
1380 cache_pending_
= true;
1381 next_state_
= STATE_ADD_TO_ENTRY_COMPLETE
;
1382 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
);
1383 DCHECK(entry_lock_waiting_since_
.is_null());
1384 entry_lock_waiting_since_
= TimeTicks::Now();
1385 int rv
= cache_
->AddTransactionToEntry(new_entry_
, this);
1386 if (rv
== ERR_IO_PENDING
) {
1387 if (bypass_lock_for_test_
) {
1388 OnAddToEntryTimeout(entry_lock_waiting_since_
);
1390 int timeout_milliseconds
= 20 * 1000;
1391 if (partial_
&& new_entry_
->writer
&&
1392 new_entry_
->writer
->range_requested_
) {
1393 // Quickly timeout and bypass the cache if we're a range request and
1394 // we're blocked by the reader/writer lock. Doing so eliminates a long
1395 // running issue, http://crbug.com/31014, where two of the same media
1396 // resources could not be played back simultaneously due to one locking
1397 // the cache entry until the entire video was downloaded.
1399 // Bypassing the cache is not ideal, as we are now ignoring the cache
1400 // entirely for all range requests to a resource beyond the first. This
1401 // is however a much more succinct solution than the alternatives, which
1402 // would require somewhat significant changes to the http caching logic.
1404 // Allow some timeout slack for the entry addition to complete in case
1405 // the writer lock is imminently released; we want to avoid skipping
1406 // the cache if at all possible. See http://crbug.com/408765
1407 timeout_milliseconds
= 25;
1409 base::MessageLoop::current()->PostDelayedTask(
1411 base::Bind(&HttpCache::Transaction::OnAddToEntryTimeout
,
1412 weak_factory_
.GetWeakPtr(), entry_lock_waiting_since_
),
1413 TimeDelta::FromMilliseconds(timeout_milliseconds
));
1419 int HttpCache::Transaction::DoAddToEntryComplete(int result
) {
1420 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
,
1422 const TimeDelta entry_lock_wait
=
1423 TimeTicks::Now() - entry_lock_waiting_since_
;
1424 UMA_HISTOGRAM_TIMES("HttpCache.EntryLockWait", entry_lock_wait
);
1426 entry_lock_waiting_since_
= TimeTicks();
1428 cache_pending_
= false;
1431 entry_
= new_entry_
;
1433 // If there is a failure, the cache should have taken care of new_entry_.
1436 if (result
== ERR_CACHE_RACE
) {
1437 next_state_
= STATE_INIT_ENTRY
;
1441 if (result
== ERR_CACHE_LOCK_TIMEOUT
) {
1442 // The cache is busy, bypass it for this transaction.
1444 next_state_
= STATE_SEND_REQUEST
;
1446 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1457 if (mode_
== WRITE
) {
1459 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1460 next_state_
= STATE_SEND_REQUEST
;
1462 // We have to read the headers from the cached entry.
1463 DCHECK(mode_
& READ_META
);
1464 next_state_
= STATE_CACHE_READ_RESPONSE
;
1469 // We may end up here multiple times for a given request.
1470 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1474 next_state_
= STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
;
1475 return partial_
->ShouldValidateCache(entry_
->disk_entry
, io_callback_
);
1478 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result
) {
1480 // This is the end of the request.
1481 if (mode_
& WRITE
) {
1482 DoneWritingToEntry(true);
1484 cache_
->DoneReadingFromEntry(entry_
, this);
1493 partial_
->PrepareCacheValidation(entry_
->disk_entry
,
1494 &custom_request_
->extra_headers
);
1496 if (reading_
&& partial_
->IsCurrentRangeCached()) {
1497 next_state_
= STATE_CACHE_READ_DATA
;
1501 return BeginCacheValidation();
1504 // We received 304 or 206 and we want to update the cached response headers.
1505 int HttpCache::Transaction::DoUpdateCachedResponse() {
1506 next_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1508 // Update cached response based on headers in new_response.
1509 // TODO(wtc): should we update cached certificate (response_.ssl_info), too?
1510 response_
.headers
->Update(*new_response_
->headers
.get());
1511 response_
.response_time
= new_response_
->response_time
;
1512 response_
.request_time
= new_response_
->request_time
;
1513 response_
.network_accessed
= new_response_
->network_accessed
;
1515 if (response_
.headers
->HasHeaderValue("cache-control", "no-store")) {
1516 if (!entry_
->doomed
) {
1517 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1521 // If we are already reading, we already updated the headers for this
1522 // request; doing it again will change Content-Length.
1524 target_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1525 next_state_
= STATE_CACHE_WRITE_RESPONSE
;
1532 int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result
) {
1533 if (mode_
== UPDATE
) {
1534 DCHECK(!handling_206_
);
1535 // We got a "not modified" response and already updated the corresponding
1536 // cache entry above.
1538 // By closing the cached entry now, we make sure that the 304 rather than
1539 // the cached 200 response, is what will be returned to the user.
1540 DoneWritingToEntry(true);
1541 } else if (entry_
&& !handling_206_
) {
1542 DCHECK_EQ(READ_WRITE
, mode_
);
1543 if (!partial_
.get() || partial_
->IsLastRange()) {
1544 cache_
->ConvertWriterToReader(entry_
);
1547 // We no longer need the network transaction, so destroy it.
1548 final_upload_progress_
= network_trans_
->GetUploadProgress();
1549 ResetNetworkTransaction();
1550 } else if (entry_
&& handling_206_
&& truncated_
&&
1551 partial_
->initial_validation()) {
1552 // We just finished the validation of a truncated entry, and the server
1553 // is willing to resume the operation. Now we go back and start serving
1554 // the first part to the user.
1555 ResetNetworkTransaction();
1556 new_response_
= NULL
;
1557 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
1558 partial_
->SetRangeToStartDownload();
1561 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1565 int HttpCache::Transaction::DoOverwriteCachedResponse() {
1567 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1571 // We change the value of Content-Length for partial content.
1572 if (handling_206_
&& partial_
.get())
1573 partial_
->FixContentLength(new_response_
->headers
.get());
1575 response_
= *new_response_
;
1577 if (request_
->method
== "HEAD") {
1578 // This response is replacing the cached one.
1579 DoneWritingToEntry(false);
1581 new_response_
= NULL
;
1585 target_state_
= STATE_TRUNCATE_CACHED_DATA
;
1586 next_state_
= truncated_
? STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
1587 STATE_CACHE_WRITE_RESPONSE
;
1591 int HttpCache::Transaction::DoTruncateCachedData() {
1592 next_state_
= STATE_TRUNCATE_CACHED_DATA_COMPLETE
;
1595 if (net_log_
.IsLogging())
1596 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1597 // Truncate the stream.
1598 return WriteToEntry(kResponseContentIndex
, 0, NULL
, 0, io_callback_
);
1601 int HttpCache::Transaction::DoTruncateCachedDataComplete(int result
) {
1603 if (net_log_
.IsLogging()) {
1604 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1609 next_state_
= STATE_TRUNCATE_CACHED_METADATA
;
1613 int HttpCache::Transaction::DoTruncateCachedMetadata() {
1614 next_state_
= STATE_TRUNCATE_CACHED_METADATA_COMPLETE
;
1618 if (net_log_
.IsLogging())
1619 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1620 return WriteToEntry(kMetadataIndex
, 0, NULL
, 0, io_callback_
);
1623 int HttpCache::Transaction::DoTruncateCachedMetadataComplete(int result
) {
1625 if (net_log_
.IsLogging()) {
1626 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1631 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1635 int HttpCache::Transaction::DoPartialHeadersReceived() {
1636 new_response_
= NULL
;
1637 if (entry_
&& !partial_
.get() &&
1638 entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
1639 next_state_
= STATE_CACHE_READ_METADATA
;
1641 if (!partial_
.get())
1645 if (network_trans_
.get()) {
1646 next_state_
= STATE_NETWORK_READ
;
1648 next_state_
= STATE_CACHE_READ_DATA
;
1650 } else if (mode_
!= NONE
) {
1651 // We are about to return the headers for a byte-range request to the user,
1652 // so let's fix them.
1653 partial_
->FixResponseHeaders(response_
.headers
.get(), true);
1658 int HttpCache::Transaction::DoCacheReadResponse() {
1660 next_state_
= STATE_CACHE_READ_RESPONSE_COMPLETE
;
1662 io_buf_len_
= entry_
->disk_entry
->GetDataSize(kResponseInfoIndex
);
1663 read_buf_
= new IOBuffer(io_buf_len_
);
1665 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1666 return entry_
->disk_entry
->ReadData(kResponseInfoIndex
, 0, read_buf_
.get(),
1667 io_buf_len_
, io_callback_
);
1670 int HttpCache::Transaction::DoCacheReadResponseComplete(int result
) {
1671 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1672 if (result
!= io_buf_len_
||
1673 !HttpCache::ParseResponseInfo(read_buf_
->data(), io_buf_len_
,
1674 &response_
, &truncated_
)) {
1675 return OnCacheReadError(result
, true);
1678 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
1679 if (cache_
->cert_cache() && response_
.ssl_info
.is_valid())
1682 // Some resources may have slipped in as truncated when they're not.
1683 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1684 if (response_
.headers
->GetContentLength() == current_size
)
1687 // We now have access to the cache entry.
1689 // o if we are a reader for the transaction, then we can start reading the
1692 // o if we can read or write, then we should check if the cache entry needs
1693 // to be validated and then issue a network request if needed or just read
1694 // from the cache if the cache entry is already valid.
1696 // o if we are set to UPDATE, then we are handling an externally
1697 // conditionalized request (if-modified-since / if-none-match). We check
1698 // if the request headers define a validation request.
1702 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
1703 result
= BeginCacheRead();
1706 result
= BeginPartialCacheValidation();
1709 result
= BeginExternallyConditionalizedRequest();
1714 result
= ERR_FAILED
;
1719 int HttpCache::Transaction::DoCacheWriteResponse() {
1721 if (net_log_
.IsLogging())
1722 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1724 return WriteResponseInfoToEntry(false);
1727 int HttpCache::Transaction::DoCacheWriteTruncatedResponse() {
1729 if (net_log_
.IsLogging())
1730 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1732 return WriteResponseInfoToEntry(true);
1735 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result
) {
1736 next_state_
= target_state_
;
1737 target_state_
= STATE_NONE
;
1740 if (net_log_
.IsLogging()) {
1741 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1745 // Balance the AddRef from WriteResponseInfoToEntry.
1746 if (result
!= io_buf_len_
) {
1747 DLOG(ERROR
) << "failed to write response info to cache";
1748 DoneWritingToEntry(false);
1753 int HttpCache::Transaction::DoCacheReadMetadata() {
1755 DCHECK(!response_
.metadata
.get());
1756 next_state_
= STATE_CACHE_READ_METADATA_COMPLETE
;
1758 response_
.metadata
=
1759 new IOBufferWithSize(entry_
->disk_entry
->GetDataSize(kMetadataIndex
));
1761 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1762 return entry_
->disk_entry
->ReadData(kMetadataIndex
, 0,
1763 response_
.metadata
.get(),
1764 response_
.metadata
->size(),
1768 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result
) {
1769 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1770 if (result
!= response_
.metadata
->size())
1771 return OnCacheReadError(result
, false);
1775 int HttpCache::Transaction::DoCacheQueryData() {
1776 next_state_
= STATE_CACHE_QUERY_DATA_COMPLETE
;
1777 return entry_
->disk_entry
->ReadyForSparseIO(io_callback_
);
1780 int HttpCache::Transaction::DoCacheQueryDataComplete(int result
) {
1781 if (result
== ERR_NOT_IMPLEMENTED
) {
1782 // Restart the request overwriting the cache entry.
1783 // TODO(pasko): remove this workaround as soon as the SimpleBackendImpl
1784 // supports Sparse IO.
1785 return DoRestartPartialRequest();
1787 DCHECK_EQ(OK
, result
);
1789 return ERR_UNEXPECTED
;
1791 return ValidateEntryHeadersAndContinue();
1794 int HttpCache::Transaction::DoCacheReadData() {
1796 next_state_
= STATE_CACHE_READ_DATA_COMPLETE
;
1798 if (net_log_
.IsLogging())
1799 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_DATA
);
1800 if (partial_
.get()) {
1801 return partial_
->CacheRead(entry_
->disk_entry
, read_buf_
.get(), io_buf_len_
,
1805 return entry_
->disk_entry
->ReadData(kResponseContentIndex
, read_offset_
,
1806 read_buf_
.get(), io_buf_len_
,
1810 int HttpCache::Transaction::DoCacheReadDataComplete(int result
) {
1811 if (net_log_
.IsLogging()) {
1812 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_DATA
,
1817 return ERR_UNEXPECTED
;
1819 if (partial_
.get()) {
1820 // Partial requests are confusing to report in histograms because they may
1821 // have multiple underlying requests.
1822 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1823 return DoPartialCacheReadCompleted(result
);
1827 read_offset_
+= result
;
1828 } else if (result
== 0) { // End of file.
1830 cache_
->DoneReadingFromEntry(entry_
, this);
1833 return OnCacheReadError(result
, false);
1838 int HttpCache::Transaction::DoCacheWriteData(int num_bytes
) {
1839 next_state_
= STATE_CACHE_WRITE_DATA_COMPLETE
;
1840 write_len_
= num_bytes
;
1842 if (net_log_
.IsLogging())
1843 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1846 return AppendResponseDataToEntry(read_buf_
.get(), num_bytes
, io_callback_
);
1849 int HttpCache::Transaction::DoCacheWriteDataComplete(int result
) {
1851 if (net_log_
.IsLogging()) {
1852 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1856 // Balance the AddRef from DoCacheWriteData.
1858 return ERR_UNEXPECTED
;
1860 if (result
!= write_len_
) {
1861 DLOG(ERROR
) << "failed to write response data to cache";
1862 DoneWritingToEntry(false);
1864 // We want to ignore errors writing to disk and just keep reading from
1866 result
= write_len_
;
1867 } else if (!done_reading_
&& entry_
) {
1868 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1869 int64 body_size
= response_
.headers
->GetContentLength();
1870 if (body_size
>= 0 && body_size
<= current_size
)
1871 done_reading_
= true;
1874 if (partial_
.get()) {
1875 // This may be the last request.
1876 if (!(result
== 0 && !truncated_
&&
1877 (partial_
->IsLastRange() || mode_
== WRITE
)))
1878 return DoPartialNetworkReadCompleted(result
);
1882 // End of file. This may be the result of a connection problem so see if we
1883 // have to keep the entry around to be flagged as truncated later on.
1884 if (done_reading_
|| !entry_
|| partial_
.get() ||
1885 response_
.headers
->GetContentLength() <= 0)
1886 DoneWritingToEntry(true);
1892 //-----------------------------------------------------------------------------
1894 void HttpCache::Transaction::ReadCertChain() {
1896 GetCacheKeyForCert(response_
.ssl_info
.cert
->os_cert_handle());
1897 const X509Certificate::OSCertHandles
& intermediates
=
1898 response_
.ssl_info
.cert
->GetIntermediateCertificates();
1899 int dist_from_root
= intermediates
.size();
1901 scoped_refptr
<SharedChainData
> shared_chain_data(
1902 new SharedChainData(intermediates
.size() + 1, TimeTicks::Now()));
1903 cache_
->cert_cache()->GetCertificate(key
,
1904 base::Bind(&OnCertReadIOComplete
,
1907 shared_chain_data
));
1909 for (X509Certificate::OSCertHandles::const_iterator it
=
1910 intermediates
.begin();
1911 it
!= intermediates
.end();
1914 key
= GetCacheKeyForCert(*it
);
1915 cache_
->cert_cache()->GetCertificate(key
,
1916 base::Bind(&OnCertReadIOComplete
,
1918 false /* is not leaf */,
1919 shared_chain_data
));
1921 DCHECK_EQ(0, dist_from_root
);
1924 void HttpCache::Transaction::WriteCertChain() {
1925 const X509Certificate::OSCertHandles
& intermediates
=
1926 response_
.ssl_info
.cert
->GetIntermediateCertificates();
1927 int dist_from_root
= intermediates
.size();
1929 scoped_refptr
<SharedChainData
> shared_chain_data(
1930 new SharedChainData(intermediates
.size() + 1, TimeTicks::Now()));
1931 cache_
->cert_cache()->SetCertificate(
1932 response_
.ssl_info
.cert
->os_cert_handle(),
1933 base::Bind(&OnCertWriteIOComplete
,
1936 shared_chain_data
));
1937 for (X509Certificate::OSCertHandles::const_iterator it
=
1938 intermediates
.begin();
1939 it
!= intermediates
.end();
1942 cache_
->cert_cache()->SetCertificate(*it
,
1943 base::Bind(&OnCertWriteIOComplete
,
1945 false /* is not leaf */,
1946 shared_chain_data
));
1948 DCHECK_EQ(0, dist_from_root
);
1951 void HttpCache::Transaction::SetRequest(const BoundNetLog
& net_log
,
1952 const HttpRequestInfo
* request
) {
1955 effective_load_flags_
= request_
->load_flags
;
1957 switch (cache_
->mode()) {
1961 // When in record mode, we want to NEVER load from the cache.
1962 // The reason for this is because we save the Set-Cookie headers
1963 // (intentionally). If we read from the cache, we replay them
1965 effective_load_flags_
|= LOAD_BYPASS_CACHE
;
1968 // When in playback mode, we want to load exclusively from the cache.
1969 effective_load_flags_
|= LOAD_ONLY_FROM_CACHE
;
1972 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1976 // Some headers imply load flags. The order here is significant.
1978 // LOAD_DISABLE_CACHE : no cache read or write
1979 // LOAD_BYPASS_CACHE : no cache read
1980 // LOAD_VALIDATE_CACHE : no cache read unless validation
1982 // The former modes trump latter modes, so if we find a matching header we
1983 // can stop iterating kSpecialHeaders.
1985 static const struct {
1986 const HeaderNameAndValue
* search
;
1988 } kSpecialHeaders
[] = {
1989 { kPassThroughHeaders
, LOAD_DISABLE_CACHE
},
1990 { kForceFetchHeaders
, LOAD_BYPASS_CACHE
},
1991 { kForceValidateHeaders
, LOAD_VALIDATE_CACHE
},
1994 bool range_found
= false;
1995 bool external_validation_error
= false;
1997 if (request_
->extra_headers
.HasHeader(HttpRequestHeaders::kRange
))
2000 for (size_t i
= 0; i
< arraysize(kSpecialHeaders
); ++i
) {
2001 if (HeaderMatches(request_
->extra_headers
, kSpecialHeaders
[i
].search
)) {
2002 effective_load_flags_
|= kSpecialHeaders
[i
].load_flag
;
2007 // Check for conditionalization headers which may correspond with a
2008 // cache validation request.
2009 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); ++i
) {
2010 const ValidationHeaderInfo
& info
= kValidationHeaders
[i
];
2011 std::string validation_value
;
2012 if (request_
->extra_headers
.GetHeader(
2013 info
.request_header_name
, &validation_value
)) {
2014 if (!external_validation_
.values
[i
].empty() ||
2015 validation_value
.empty()) {
2016 external_validation_error
= true;
2018 external_validation_
.values
[i
] = validation_value
;
2019 external_validation_
.initialized
= true;
2023 // We don't support ranges and validation headers.
2024 if (range_found
&& external_validation_
.initialized
) {
2025 LOG(WARNING
) << "Byte ranges AND validation headers found.";
2026 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2029 // If there is more than one validation header, we can't treat this request as
2030 // a cache validation, since we don't know for sure which header the server
2031 // will give us a response for (and they could be contradictory).
2032 if (external_validation_error
) {
2033 LOG(WARNING
) << "Multiple or malformed validation headers found.";
2034 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2037 if (range_found
&& !(effective_load_flags_
& LOAD_DISABLE_CACHE
)) {
2038 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2039 partial_
.reset(new PartialData
);
2040 if (request_
->method
== "GET" && partial_
->Init(request_
->extra_headers
)) {
2041 // We will be modifying the actual range requested to the server, so
2042 // let's remove the header here.
2043 custom_request_
.reset(new HttpRequestInfo(*request_
));
2044 custom_request_
->extra_headers
.RemoveHeader(HttpRequestHeaders::kRange
);
2045 request_
= custom_request_
.get();
2046 partial_
->SetHeaders(custom_request_
->extra_headers
);
2048 // The range is invalid or we cannot handle it properly.
2049 VLOG(1) << "Invalid byte range found.";
2050 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2051 partial_
.reset(NULL
);
2056 bool HttpCache::Transaction::ShouldPassThrough() {
2057 // We may have a null disk_cache if there is an error we cannot recover from,
2058 // like not enough disk space, or sharing violations.
2059 if (!cache_
->disk_cache_
.get())
2062 // When using the record/playback modes, we always use the cache
2063 // and we never pass through.
2064 if (cache_
->mode() == RECORD
|| cache_
->mode() == PLAYBACK
)
2067 if (effective_load_flags_
& LOAD_DISABLE_CACHE
)
2070 if (request_
->method
== "GET" || request_
->method
== "HEAD")
2073 if (request_
->method
== "POST" && request_
->upload_data_stream
&&
2074 request_
->upload_data_stream
->identifier()) {
2078 if (request_
->method
== "PUT" && request_
->upload_data_stream
)
2081 if (request_
->method
== "DELETE")
2087 int HttpCache::Transaction::BeginCacheRead() {
2088 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
2089 if (response_
.headers
->response_code() == 206 || partial_
.get()) {
2091 return ERR_CACHE_MISS
;
2094 if (request_
->method
== "HEAD")
2095 FixHeadersForHead();
2097 // We don't have the whole resource.
2099 return ERR_CACHE_MISS
;
2101 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2102 next_state_
= STATE_CACHE_READ_METADATA
;
2107 int HttpCache::Transaction::BeginCacheValidation() {
2108 DCHECK(mode_
== READ_WRITE
);
2110 ValidationType required_validation
= RequiresValidation();
2112 bool skip_validation
= (required_validation
== VALIDATION_NONE
);
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;
2121 if (request_
->method
== "HEAD" &&
2122 (truncated_
|| response_
.headers
->response_code() == 206)) {
2124 if (skip_validation
)
2125 return SetupEntryForRead();
2128 next_state_
= STATE_SEND_REQUEST
;
2134 // Truncated entries can cause partial gets, so we shouldn't record this
2135 // load in histograms.
2136 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2137 skip_validation
= !partial_
->initial_validation();
2140 if (partial_
.get() && (is_sparse_
|| truncated_
) &&
2141 (!partial_
->IsCurrentRangeCached() || invalid_range_
)) {
2142 // Force revalidation for sparse or truncated entries. Note that we don't
2143 // want to ignore the regular validation logic just because a byte range was
2144 // part of the request.
2145 skip_validation
= false;
2148 if (skip_validation
) {
2149 // TODO(ricea): Is this pattern okay for asynchronous revalidations?
2150 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
2151 RecordOfflineStatus(effective_load_flags_
, OFFLINE_STATUS_FRESH_CACHE
);
2152 return SetupEntryForRead();
2154 // Make the network request conditional, to see if we may reuse our cached
2155 // response. If we cannot do so, then we just resort to a normal fetch.
2156 // Our mode remains READ_WRITE for a conditional request. Even if the
2157 // conditionalization fails, we don't switch to WRITE mode until we
2158 // know we won't be falling back to using the cache entry in the
2159 // LOAD_FROM_CACHE_IF_OFFLINE case.
2160 if (!ConditionalizeRequest()) {
2161 couldnt_conditionalize_request_
= true;
2162 UpdateTransactionPattern(PATTERN_ENTRY_CANT_CONDITIONALIZE
);
2164 return DoRestartPartialRequest();
2166 DCHECK_NE(206, response_
.headers
->response_code());
2168 next_state_
= STATE_SEND_REQUEST
;
2173 int HttpCache::Transaction::BeginPartialCacheValidation() {
2174 DCHECK(mode_
== READ_WRITE
);
2176 if (response_
.headers
->response_code() != 206 && !partial_
.get() &&
2178 return BeginCacheValidation();
2181 // Partial requests should not be recorded in histograms.
2182 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2183 if (range_requested_
) {
2184 next_state_
= STATE_CACHE_QUERY_DATA
;
2188 // The request is not for a range, but we have stored just ranges.
2190 if (request_
->method
== "HEAD")
2191 return BeginCacheValidation();
2193 partial_
.reset(new PartialData());
2194 partial_
->SetHeaders(request_
->extra_headers
);
2195 if (!custom_request_
.get()) {
2196 custom_request_
.reset(new HttpRequestInfo(*request_
));
2197 request_
= custom_request_
.get();
2200 return ValidateEntryHeadersAndContinue();
2203 // This should only be called once per request.
2204 int HttpCache::Transaction::ValidateEntryHeadersAndContinue() {
2205 DCHECK(mode_
== READ_WRITE
);
2207 if (!partial_
->UpdateFromStoredHeaders(
2208 response_
.headers
.get(), entry_
->disk_entry
, truncated_
)) {
2209 return DoRestartPartialRequest();
2212 if (response_
.headers
->response_code() == 206)
2215 if (!partial_
->IsRequestedRangeOK()) {
2216 // The stored data is fine, but the request may be invalid.
2217 invalid_range_
= true;
2220 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2224 int HttpCache::Transaction::BeginExternallyConditionalizedRequest() {
2225 DCHECK_EQ(UPDATE
, mode_
);
2226 DCHECK(external_validation_
.initialized
);
2228 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); i
++) {
2229 if (external_validation_
.values
[i
].empty())
2231 // Retrieve either the cached response's "etag" or "last-modified" header.
2232 std::string validator
;
2233 response_
.headers
->EnumerateHeader(
2235 kValidationHeaders
[i
].related_response_header_name
,
2238 if (response_
.headers
->response_code() != 200 || truncated_
||
2239 validator
.empty() || validator
!= external_validation_
.values
[i
]) {
2240 // The externally conditionalized request is not a validation request
2241 // for our existing cache entry. Proceed with caching disabled.
2242 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2243 DoneWritingToEntry(true);
2247 // TODO(ricea): This calculation is expensive to perform just to collect
2248 // statistics. Either remove it or use the result, depending on the result of
2250 ExternallyConditionalizedType type
=
2251 EXTERNALLY_CONDITIONALIZED_CACHE_USABLE
;
2253 type
= EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS
;
2254 else if (RequiresValidation())
2255 type
= EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION
;
2257 // TODO(ricea): Add CACHE_USABLE_STALE once stale-while-revalidate CL landed.
2258 // TODO(ricea): Either remove this histogram or make it permanent by M40.
2259 UMA_HISTOGRAM_ENUMERATION("HttpCache.ExternallyConditionalized",
2261 EXTERNALLY_CONDITIONALIZED_MAX
);
2263 next_state_
= STATE_SEND_REQUEST
;
2267 int HttpCache::Transaction::RestartNetworkRequest() {
2268 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2269 DCHECK(network_trans_
.get());
2270 DCHECK_EQ(STATE_NONE
, next_state_
);
2272 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2273 int rv
= network_trans_
->RestartIgnoringLastError(io_callback_
);
2274 if (rv
!= ERR_IO_PENDING
)
2279 int HttpCache::Transaction::RestartNetworkRequestWithCertificate(
2280 X509Certificate
* client_cert
) {
2281 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2282 DCHECK(network_trans_
.get());
2283 DCHECK_EQ(STATE_NONE
, next_state_
);
2285 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2286 int rv
= network_trans_
->RestartWithCertificate(client_cert
, io_callback_
);
2287 if (rv
!= ERR_IO_PENDING
)
2292 int HttpCache::Transaction::RestartNetworkRequestWithAuth(
2293 const AuthCredentials
& credentials
) {
2294 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2295 DCHECK(network_trans_
.get());
2296 DCHECK_EQ(STATE_NONE
, next_state_
);
2298 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2299 int rv
= network_trans_
->RestartWithAuth(credentials
, io_callback_
);
2300 if (rv
!= ERR_IO_PENDING
)
2305 ValidationType
HttpCache::Transaction::RequiresValidation() {
2306 // TODO(darin): need to do more work here:
2307 // - make sure we have a matching request method
2308 // - watch out for cached responses that depend on authentication
2310 // In playback mode, nothing requires validation.
2311 if (cache_
->mode() == net::HttpCache::PLAYBACK
)
2312 return VALIDATION_NONE
;
2314 if (response_
.vary_data
.is_valid() &&
2315 !response_
.vary_data
.MatchesRequest(*request_
,
2316 *response_
.headers
.get())) {
2317 vary_mismatch_
= true;
2318 return VALIDATION_SYNCHRONOUS
;
2321 if (effective_load_flags_
& LOAD_PREFERRING_CACHE
)
2322 return VALIDATION_NONE
;
2324 if (effective_load_flags_
& (LOAD_VALIDATE_CACHE
| LOAD_ASYNC_REVALIDATION
))
2325 return VALIDATION_SYNCHRONOUS
;
2327 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2328 return VALIDATION_SYNCHRONOUS
;
2330 ValidationType validation_required_by_headers
=
2331 response_
.headers
->RequiresValidation(
2332 response_
.request_time
, response_
.response_time
, Time::Now());
2334 if (validation_required_by_headers
== VALIDATION_ASYNCHRONOUS
) {
2335 // Asynchronous revalidation is only supported for GET and HEAD methods.
2336 if (request_
->method
!= "GET" && request_
->method
!= "HEAD")
2337 return VALIDATION_SYNCHRONOUS
;
2340 return validation_required_by_headers
;
2343 bool HttpCache::Transaction::ConditionalizeRequest() {
2344 DCHECK(response_
.headers
.get());
2346 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2349 // This only makes sense for cached 200 or 206 responses.
2350 if (response_
.headers
->response_code() != 200 &&
2351 response_
.headers
->response_code() != 206) {
2355 if (response_
.headers
->response_code() == 206 &&
2356 !response_
.headers
->HasStrongValidators()) {
2360 // Just use the first available ETag and/or Last-Modified header value.
2361 // TODO(darin): Or should we use the last?
2363 std::string etag_value
;
2364 if (response_
.headers
->GetHttpVersion() >= HttpVersion(1, 1))
2365 response_
.headers
->EnumerateHeader(NULL
, "etag", &etag_value
);
2367 std::string last_modified_value
;
2368 if (!vary_mismatch_
) {
2369 response_
.headers
->EnumerateHeader(NULL
, "last-modified",
2370 &last_modified_value
);
2373 if (etag_value
.empty() && last_modified_value
.empty())
2376 if (!partial_
.get()) {
2377 // Need to customize the request, so this forces us to allocate :(
2378 custom_request_
.reset(new HttpRequestInfo(*request_
));
2379 request_
= custom_request_
.get();
2381 DCHECK(custom_request_
.get());
2383 bool use_if_range
= partial_
.get() && !partial_
->IsCurrentRangeCached() &&
2386 if (!use_if_range
) {
2387 // stale-while-revalidate is not useful when we only have a partial response
2388 // cached, so don't set the header in that case.
2389 HttpResponseHeaders::FreshnessLifetimes lifetimes
=
2390 response_
.headers
->GetFreshnessLifetimes(response_
.response_time
);
2391 if (lifetimes
.staleness
> TimeDelta()) {
2392 TimeDelta current_age
= response_
.headers
->GetCurrentAge(
2393 response_
.request_time
, response_
.response_time
, Time::Now());
2395 custom_request_
->extra_headers
.SetHeader(
2397 base::StringPrintf("max-age=%" PRId64
2398 ",stale-while-revalidate=%" PRId64
",age=%" PRId64
,
2399 lifetimes
.freshness
.InSeconds(),
2400 lifetimes
.staleness
.InSeconds(),
2401 current_age
.InSeconds()));
2405 if (!etag_value
.empty()) {
2407 // We don't want to switch to WRITE mode if we don't have this block of a
2408 // byte-range request because we may have other parts cached.
2409 custom_request_
->extra_headers
.SetHeader(
2410 HttpRequestHeaders::kIfRange
, etag_value
);
2412 custom_request_
->extra_headers
.SetHeader(
2413 HttpRequestHeaders::kIfNoneMatch
, etag_value
);
2415 // For byte-range requests, make sure that we use only one way to validate
2417 if (partial_
.get() && !partial_
->IsCurrentRangeCached())
2421 if (!last_modified_value
.empty()) {
2423 custom_request_
->extra_headers
.SetHeader(
2424 HttpRequestHeaders::kIfRange
, last_modified_value
);
2426 custom_request_
->extra_headers
.SetHeader(
2427 HttpRequestHeaders::kIfModifiedSince
, last_modified_value
);
2434 // We just received some headers from the server. We may have asked for a range,
2435 // in which case partial_ has an object. This could be the first network request
2436 // we make to fulfill the original request, or we may be already reading (from
2437 // the net and / or the cache). If we are not expecting a certain response, we
2438 // just bypass the cache for this request (but again, maybe we are reading), and
2439 // delete partial_ (so we are not able to "fix" the headers that we return to
2440 // the user). This results in either a weird response for the caller (we don't
2441 // expect it after all), or maybe a range that was not exactly what it was asked
2444 // If the server is simply telling us that the resource has changed, we delete
2445 // the cached entry and restart the request as the caller intended (by returning
2446 // false from this method). However, we may not be able to do that at any point,
2447 // for instance if we already returned the headers to the user.
2449 // WARNING: Whenever this code returns false, it has to make sure that the next
2450 // time it is called it will return true so that we don't keep retrying the
2452 bool HttpCache::Transaction::ValidatePartialResponse() {
2453 const HttpResponseHeaders
* headers
= new_response_
->headers
.get();
2454 int response_code
= headers
->response_code();
2455 bool partial_response
= (response_code
== 206);
2456 handling_206_
= false;
2458 if (!entry_
|| request_
->method
!= "GET")
2461 if (invalid_range_
) {
2462 // We gave up trying to match this request with the stored data. If the
2463 // server is ok with the request, delete the entry, otherwise just ignore
2466 if (partial_response
|| response_code
== 200) {
2467 DoomPartialEntry(true);
2470 if (response_code
== 304)
2472 IgnoreRangeRequest();
2477 if (!partial_
.get()) {
2478 // We are not expecting 206 but we may have one.
2479 if (partial_response
)
2480 IgnoreRangeRequest();
2485 // TODO(rvargas): Do we need to consider other results here?.
2486 bool failure
= response_code
== 200 || response_code
== 416;
2488 if (partial_
->IsCurrentRangeCached()) {
2489 // We asked for "If-None-Match: " so a 206 means a new object.
2490 if (partial_response
)
2493 if (response_code
== 304 && partial_
->ResponseHeadersOK(headers
))
2496 // We asked for "If-Range: " so a 206 means just another range.
2497 if (partial_response
&& partial_
->ResponseHeadersOK(headers
)) {
2498 handling_206_
= true;
2502 if (!reading_
&& !is_sparse_
&& !partial_response
) {
2503 // See if we can ignore the fact that we issued a byte range request.
2504 // If the server sends 200, just store it. If it sends an error, redirect
2505 // or something else, we may store the response as long as we didn't have
2506 // anything already stored.
2507 if (response_code
== 200 ||
2508 (!truncated_
&& response_code
!= 304 && response_code
!= 416)) {
2509 // The server is sending something else, and we can save it.
2510 DCHECK((truncated_
&& !partial_
->IsLastRange()) || range_requested_
);
2517 // 304 is not expected here, but we'll spare the entry (unless it was
2524 // We cannot truncate this entry, it has to be deleted.
2525 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2526 DoomPartialEntry(false);
2528 if (!reading_
&& !partial_
->IsLastRange()) {
2529 // We'll attempt to issue another network request, this time without us
2530 // messing up the headers.
2531 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
2536 LOG(WARNING
) << "Failed to revalidate partial entry";
2541 IgnoreRangeRequest();
2545 void HttpCache::Transaction::IgnoreRangeRequest() {
2546 // We have a problem. We may or may not be reading already (in which case we
2547 // returned the headers), but we'll just pretend that this request is not
2548 // using the cache and see what happens. Most likely this is the first
2549 // response from the server (it's not changing its mind midway, right?).
2550 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2552 DoneWritingToEntry(mode_
!= WRITE
);
2553 else if (mode_
& READ
&& entry_
)
2554 cache_
->DoneReadingFromEntry(entry_
, this);
2556 partial_
.reset(NULL
);
2561 void HttpCache::Transaction::FixHeadersForHead() {
2562 if (response_
.headers
->response_code() == 206) {
2563 response_
.headers
->RemoveHeader("Content-Length");
2564 response_
.headers
->RemoveHeader("Content-Range");
2565 response_
.headers
->ReplaceStatusLine("HTTP/1.1 200 OK");
2569 void HttpCache::Transaction::TriggerAsyncValidation() {
2570 DCHECK(!request_
->upload_data_stream
);
2571 BoundNetLog
async_revalidation_net_log(
2572 BoundNetLog::Make(net_log_
.net_log(), NetLog::SOURCE_ASYNC_REVALIDATION
));
2574 NetLog::TYPE_HTTP_CACHE_VALIDATE_RESOURCE_ASYNC
,
2575 async_revalidation_net_log
.source().ToEventParametersCallback());
2576 async_revalidation_net_log
.BeginEvent(
2577 NetLog::TYPE_ASYNC_REVALIDATION
,
2579 &NetLogAsyncRevalidationInfoCallback
, net_log_
.source(), request_
));
2580 base::MessageLoop::current()->PostTask(
2582 base::Bind(&HttpCache::PerformAsyncValidation
,
2583 cache_
, // cache_ is a weak pointer.
2585 async_revalidation_net_log
));
2588 void HttpCache::Transaction::FailRangeRequest() {
2589 response_
= *new_response_
;
2590 partial_
->FixResponseHeaders(response_
.headers
.get(), false);
2593 int HttpCache::Transaction::SetupEntryForRead() {
2595 ResetNetworkTransaction();
2596 if (partial_
.get()) {
2597 if (truncated_
|| is_sparse_
|| !invalid_range_
) {
2598 // We are going to return the saved response headers to the caller, so
2599 // we may need to adjust them first.
2600 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
2606 cache_
->ConvertWriterToReader(entry_
);
2609 if (request_
->method
== "HEAD")
2610 FixHeadersForHead();
2612 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2613 next_state_
= STATE_CACHE_READ_METADATA
;
2618 int HttpCache::Transaction::ReadFromNetwork(IOBuffer
* data
, int data_len
) {
2620 io_buf_len_
= data_len
;
2621 next_state_
= STATE_NETWORK_READ
;
2625 int HttpCache::Transaction::ReadFromEntry(IOBuffer
* data
, int data_len
) {
2626 if (request_
->method
== "HEAD")
2630 io_buf_len_
= data_len
;
2631 next_state_
= STATE_CACHE_READ_DATA
;
2635 int HttpCache::Transaction::WriteToEntry(int index
, int offset
,
2636 IOBuffer
* data
, int data_len
,
2637 const CompletionCallback
& callback
) {
2642 if (!partial_
.get() || !data_len
) {
2643 rv
= entry_
->disk_entry
->WriteData(index
, offset
, data
, data_len
, callback
,
2646 rv
= partial_
->CacheWrite(entry_
->disk_entry
, data
, data_len
, callback
);
2651 int HttpCache::Transaction::WriteResponseInfoToEntry(bool truncated
) {
2652 next_state_
= STATE_CACHE_WRITE_RESPONSE_COMPLETE
;
2656 // Do not cache no-store content (unless we are record mode). Do not cache
2657 // content with cert errors either. This is to prevent not reporting net
2658 // errors when loading a resource from the cache. When we load a page over
2659 // HTTPS with a cert error we show an SSL blocking page. If the user clicks
2660 // proceed we reload the resource ignoring the errors. The loaded resource
2661 // is then cached. If that resource is subsequently loaded from the cache,
2662 // no net error is reported (even though the cert status contains the actual
2663 // errors) and no SSL blocking page is shown. An alternative would be to
2664 // reverse-map the cert status to a net error and replay the net error.
2665 if ((cache_
->mode() != RECORD
&&
2666 response_
.headers
->HasHeaderValue("cache-control", "no-store")) ||
2667 net::IsCertStatusError(response_
.ssl_info
.cert_status
)) {
2668 DoneWritingToEntry(false);
2669 if (net_log_
.IsLogging())
2670 net_log_
.EndEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
2674 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
2675 if (cache_
->cert_cache() && response_
.ssl_info
.is_valid())
2678 // When writing headers, we normally only write the non-transient
2679 // headers; when in record mode, record everything.
2680 bool skip_transient_headers
= (cache_
->mode() != RECORD
);
2683 DCHECK_EQ(200, response_
.headers
->response_code());
2685 scoped_refptr
<PickledIOBuffer
> data(new PickledIOBuffer());
2686 response_
.Persist(data
->pickle(), skip_transient_headers
, truncated
);
2689 io_buf_len_
= data
->pickle()->size();
2690 return entry_
->disk_entry
->WriteData(kResponseInfoIndex
, 0, data
.get(),
2691 io_buf_len_
, io_callback_
, true);
2694 int HttpCache::Transaction::AppendResponseDataToEntry(
2695 IOBuffer
* data
, int data_len
, const CompletionCallback
& callback
) {
2696 if (!entry_
|| !data_len
)
2699 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
2700 return WriteToEntry(kResponseContentIndex
, current_size
, data
, data_len
,
2704 void HttpCache::Transaction::DoneWritingToEntry(bool success
) {
2710 cache_
->DoneWritingToEntry(entry_
, success
);
2712 mode_
= NONE
; // switch to 'pass through' mode
2715 int HttpCache::Transaction::OnCacheReadError(int result
, bool restart
) {
2716 DLOG(ERROR
) << "ReadData failed: " << result
;
2717 const int result_for_histogram
= std::max(0, -result
);
2719 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2720 result_for_histogram
);
2722 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorNonRestartable",
2723 result_for_histogram
);
2726 // Avoid using this entry in the future.
2728 cache_
->DoomActiveEntry(cache_key_
);
2732 DCHECK(!network_trans_
.get());
2733 cache_
->DoneWithEntry(entry_
, this, false);
2737 next_state_
= STATE_GET_BACKEND
;
2741 return ERR_CACHE_READ_FAILURE
;
2744 void HttpCache::Transaction::OnAddToEntryTimeout(base::TimeTicks start_time
) {
2745 if (entry_lock_waiting_since_
!= start_time
)
2748 DCHECK_EQ(next_state_
, STATE_ADD_TO_ENTRY_COMPLETE
);
2753 cache_
->RemovePendingTransaction(this);
2754 OnIOComplete(ERR_CACHE_LOCK_TIMEOUT
);
2757 void HttpCache::Transaction::DoomPartialEntry(bool delete_object
) {
2758 DVLOG(2) << "DoomPartialEntry";
2759 int rv
= cache_
->DoomEntry(cache_key_
, NULL
);
2761 cache_
->DoneWithEntry(entry_
, this, false);
2765 partial_
.reset(NULL
);
2768 int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result
) {
2769 partial_
->OnNetworkReadCompleted(result
);
2772 // We need to move on to the next range.
2773 ResetNetworkTransaction();
2774 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2779 int HttpCache::Transaction::DoPartialCacheReadCompleted(int result
) {
2780 partial_
->OnCacheReadCompleted(result
);
2782 if (result
== 0 && mode_
== READ_WRITE
) {
2783 // We need to move on to the next range.
2784 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2785 } else if (result
< 0) {
2786 return OnCacheReadError(result
, false);
2791 int HttpCache::Transaction::DoRestartPartialRequest() {
2792 // The stored data cannot be used. Get rid of it and restart this request.
2793 // We need to also reset the |truncated_| flag as a new entry is created.
2794 DoomPartialEntry(!range_requested_
);
2797 next_state_
= STATE_INIT_ENTRY
;
2801 void HttpCache::Transaction::ResetNetworkTransaction() {
2802 DCHECK(!old_network_trans_load_timing_
);
2803 DCHECK(network_trans_
);
2804 LoadTimingInfo load_timing
;
2805 if (network_trans_
->GetLoadTimingInfo(&load_timing
))
2806 old_network_trans_load_timing_
.reset(new LoadTimingInfo(load_timing
));
2807 total_received_bytes_
+= network_trans_
->GetTotalReceivedBytes();
2808 network_trans_
.reset();
2811 // Histogram data from the end of 2010 show the following distribution of
2812 // response headers:
2814 // Content-Length............... 87%
2815 // Date......................... 98%
2816 // Last-Modified................ 49%
2817 // Etag......................... 19%
2818 // Accept-Ranges: bytes......... 25%
2819 // Accept-Ranges: none.......... 0.4%
2820 // Strong Validator............. 50%
2821 // Strong Validator + ranges.... 24%
2822 // Strong Validator + CL........ 49%
2824 bool HttpCache::Transaction::CanResume(bool has_data
) {
2825 // Double check that there is something worth keeping.
2826 if (has_data
&& !entry_
->disk_entry
->GetDataSize(kResponseContentIndex
))
2829 if (request_
->method
!= "GET")
2832 // Note that if this is a 206, content-length was already fixed after calling
2833 // PartialData::ResponseHeadersOK().
2834 if (response_
.headers
->GetContentLength() <= 0 ||
2835 response_
.headers
->HasHeaderValue("Accept-Ranges", "none") ||
2836 !response_
.headers
->HasStrongValidators()) {
2843 void HttpCache::Transaction::UpdateTransactionPattern(
2844 TransactionPattern new_transaction_pattern
) {
2845 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2847 DCHECK(transaction_pattern_
== PATTERN_UNDEFINED
||
2848 new_transaction_pattern
== PATTERN_NOT_COVERED
);
2849 transaction_pattern_
= new_transaction_pattern
;
2852 void HttpCache::Transaction::RecordHistograms() {
2853 DCHECK_NE(PATTERN_UNDEFINED
, transaction_pattern_
);
2854 if (!cache_
.get() || !cache_
->GetCurrentBackend() ||
2855 cache_
->GetCurrentBackend()->GetCacheType() != DISK_CACHE
||
2856 cache_
->mode() != NORMAL
|| request_
->method
!= "GET") {
2859 UMA_HISTOGRAM_ENUMERATION(
2860 "HttpCache.Pattern", transaction_pattern_
, PATTERN_MAX
);
2861 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2863 DCHECK(!range_requested_
);
2864 DCHECK(!first_cache_access_since_
.is_null());
2866 TimeDelta total_time
= base::TimeTicks::Now() - first_cache_access_since_
;
2868 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time
);
2870 bool did_send_request
= !send_request_since_
.is_null();
2872 (did_send_request
&&
2873 (transaction_pattern_
== PATTERN_ENTRY_NOT_CACHED
||
2874 transaction_pattern_
== PATTERN_ENTRY_VALIDATED
||
2875 transaction_pattern_
== PATTERN_ENTRY_UPDATED
||
2876 transaction_pattern_
== PATTERN_ENTRY_CANT_CONDITIONALIZE
)) ||
2877 (!did_send_request
&& transaction_pattern_
== PATTERN_ENTRY_USED
));
2879 if (!did_send_request
) {
2880 DCHECK(transaction_pattern_
== PATTERN_ENTRY_USED
);
2881 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time
);
2885 TimeDelta before_send_time
= send_request_since_
- first_cache_access_since_
;
2886 int before_send_percent
=
2887 total_time
.ToInternalValue() == 0 ? 0
2888 : before_send_time
* 100 / total_time
;
2889 DCHECK_LE(0, before_send_percent
);
2890 DCHECK_GE(100, before_send_percent
);
2892 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time
);
2893 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time
);
2894 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend", before_send_percent
);
2896 // TODO(gavinp): Remove or minimize these histograms, particularly the ones
2897 // below this comment after we have received initial data.
2898 switch (transaction_pattern_
) {
2899 case PATTERN_ENTRY_CANT_CONDITIONALIZE
: {
2900 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize",
2902 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.CantConditionalize",
2903 before_send_percent
);
2906 case PATTERN_ENTRY_NOT_CACHED
: {
2907 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time
);
2908 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.NotCached",
2909 before_send_percent
);
2912 case PATTERN_ENTRY_VALIDATED
: {
2913 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time
);
2914 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Validated",
2915 before_send_percent
);
2918 case PATTERN_ENTRY_UPDATED
: {
2919 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time
);
2920 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Updated",
2921 before_send_percent
);
2929 void HttpCache::Transaction::OnIOComplete(int result
) {
2930 // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
2931 tracked_objects::ScopedTracker
tracking_profile(
2932 FROM_HERE_WITH_EXPLICIT_FUNCTION("422516 Transaction::OnIOComplete"));