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

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

Issue 2721933002: HttpCache::Transaction layer allowing parallel validation (Closed)
Patch Set: Feedback addressed Created 3 years, 8 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" // For OS_POSIX 7 #include "build/build_config.h" // For OS_POSIX
8 8
9 #if defined(OS_POSIX) 9 #if defined(OS_POSIX)
10 #include <unistd.h> 10 #include <unistd.h>
(...skipping 138 matching lines...) Expand 10 before | Expand all | Expand 10 after
149 149
150 HttpCache::Transaction::Transaction(RequestPriority priority, HttpCache* cache) 150 HttpCache::Transaction::Transaction(RequestPriority priority, HttpCache* cache)
151 : next_state_(STATE_NONE), 151 : next_state_(STATE_NONE),
152 request_(NULL), 152 request_(NULL),
153 priority_(priority), 153 priority_(priority),
154 cache_(cache->GetWeakPtr()), 154 cache_(cache->GetWeakPtr()),
155 entry_(NULL), 155 entry_(NULL),
156 new_entry_(NULL), 156 new_entry_(NULL),
157 new_response_(NULL), 157 new_response_(NULL),
158 mode_(NONE), 158 mode_(NONE),
159 original_mode_(NONE),
159 reading_(false), 160 reading_(false),
160 invalid_range_(false), 161 invalid_range_(false),
161 truncated_(false), 162 truncated_(false),
162 is_sparse_(false), 163 is_sparse_(false),
163 range_requested_(false), 164 range_requested_(false),
164 handling_206_(false), 165 handling_206_(false),
165 cache_pending_(false), 166 cache_pending_(false),
166 done_reading_(false), 167 done_reading_(false),
167 vary_mismatch_(false), 168 vary_mismatch_(false),
168 couldnt_conditionalize_request_(false), 169 couldnt_conditionalize_request_(false),
(...skipping 20 matching lines...) Expand all
189 } 190 }
190 191
191 HttpCache::Transaction::~Transaction() { 192 HttpCache::Transaction::~Transaction() {
192 TRACE_EVENT0("io", "HttpCacheTransaction::~Transaction"); 193 TRACE_EVENT0("io", "HttpCacheTransaction::~Transaction");
193 // We may have to issue another IO, but we should never invoke the callback_ 194 // We may have to issue another IO, but we should never invoke the callback_
194 // after this point. 195 // after this point.
195 callback_.Reset(); 196 callback_.Reset();
196 197
197 if (cache_) { 198 if (cache_) {
198 if (entry_) { 199 if (entry_) {
199 bool cancel_request = reading_ && response_.headers.get(); 200 bool writing_incomplete = cache_->IsTransactionWritingIncomplete(
200 if (cancel_request) { 201 entry_, this, request_->method);
201 if (partial_) { 202 if (writing_incomplete && partial_)
202 entry_->disk_entry->CancelSparseIO(); 203 entry_->disk_entry->CancelSparseIO();
203 } else {
204 cancel_request &= (response_.headers->response_code() == 200);
205 }
206 }
207 204
208 cache_->DoneWithEntry(entry_, this, cancel_request); 205 cache_->DoneWithEntry(entry_, this, writing_incomplete);
209 } else if (cache_pending_) { 206 } else if (cache_pending_) {
210 cache_->RemovePendingTransaction(this); 207 cache_->RemovePendingTransaction(this);
211 } 208 }
212 } 209 }
213 } 210 }
214 211
215 int HttpCache::Transaction::WriteMetadata(IOBuffer* buf, int buf_len, 212 int HttpCache::Transaction::WriteMetadata(IOBuffer* buf, int buf_len,
216 const CompletionCallback& callback) { 213 const CompletionCallback& callback) {
217 DCHECK(buf); 214 DCHECK(buf);
218 DCHECK_GT(buf_len, 0); 215 DCHECK_GT(buf_len, 0);
(...skipping 339 matching lines...) Expand 10 before | Expand all | Expand 10 after
558 ConnectionAttempts* out) const { 555 ConnectionAttempts* out) const {
559 ConnectionAttempts new_connection_attempts; 556 ConnectionAttempts new_connection_attempts;
560 if (network_trans_) 557 if (network_trans_)
561 network_trans_->GetConnectionAttempts(&new_connection_attempts); 558 network_trans_->GetConnectionAttempts(&new_connection_attempts);
562 559
563 out->swap(new_connection_attempts); 560 out->swap(new_connection_attempts);
564 out->insert(out->begin(), old_connection_attempts_.begin(), 561 out->insert(out->begin(), old_connection_attempts_.begin(),
565 old_connection_attempts_.end()); 562 old_connection_attempts_.end());
566 } 563 }
567 564
565 void HttpCache::Transaction::SetValidatingCannotProceed() {
566 DCHECK(!reading_);
567 next_state_ = STATE_HEADERS_PHASE_CANNOT_PROCEED;
568 entry_ = nullptr;
569 }
570
568 size_t HttpCache::Transaction::EstimateMemoryUsage() const { 571 size_t HttpCache::Transaction::EstimateMemoryUsage() const {
569 // TODO(xunjieli): Consider improving the coverage. crbug.com/669108. 572 // TODO(xunjieli): Consider improving the coverage. crbug.com/669108.
570 return 0; 573 return 0;
571 } 574 }
572 575
573 //----------------------------------------------------------------------------- 576 //-----------------------------------------------------------------------------
574 577
575 // A few common patterns: (Foo* means Foo -> FooComplete) 578 // A few common patterns: (Foo* means Foo -> FooComplete)
576 // 579 //
577 // 1. Not-cached entry: 580 // 1. Not-cached entry:
578 // Start(): 581 // Start():
579 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* -> 582 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
580 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse -> 583 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
581 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* -> 584 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
582 // PartialHeadersReceived 585 // PartialHeadersReceived -> FinishHeaders*
583 // 586 //
584 // Read(): 587 // Read():
585 // NetworkRead* -> CacheWriteData* 588 // NetworkRead* -> CacheWriteData*
586 // 589 //
587 // 2. Cached entry, no validation: 590 // 2. Cached entry, no validation:
588 // Start(): 591 // Start():
589 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse* 592 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
590 // -> CacheDispatchValidation -> BeginPartialCacheValidation() -> 593 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
591 // BeginCacheValidation() -> SetupEntryForRead() 594 // BeginCacheValidation() -> SetupEntryForRead() -> FinishHeaders*
592 // 595 //
593 // Read(): 596 // Read():
594 // CacheReadData* 597 // CacheReadData*
595 // 598 //
596 // 3. Cached entry, validation (304): 599 // 3. Cached entry, validation (304):
597 // Start(): 600 // Start():
598 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse* 601 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
599 // -> CacheDispatchValidation -> BeginPartialCacheValidation() -> 602 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
600 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest -> 603 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
601 // UpdateCachedResponse -> CacheWriteUpdatedResponse* -> 604 // UpdateCachedResponse -> CacheWriteUpdatedResponse* ->
602 // UpdateCachedResponseComplete -> OverwriteCachedResponse -> 605 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
603 // PartialHeadersReceived 606 // PartialHeadersReceived -> FinishHeaders*
604 // 607 //
605 // Read(): 608 // Read():
606 // CacheReadData* 609 // CacheReadData*
607 // 610 //
608 // 4. Cached entry, validation and replace (200): 611 // 4. Cached entry, validation and replace (200):
609 // Start(): 612 // Start():
610 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse* 613 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
611 // -> CacheDispatchValidation -> BeginPartialCacheValidation() -> 614 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
612 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest -> 615 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
613 // OverwriteCachedResponse -> CacheWriteResponse* -> DoTruncateCachedData* -> 616 // OverwriteCachedResponse -> CacheWriteResponse* -> DoTruncateCachedData* ->
614 // TruncateCachedMetadata* -> PartialHeadersReceived 617 // TruncateCachedMetadata* -> PartialHeadersReceived -> FinishHeaders*
615 // 618 //
616 // Read(): 619 // Read():
617 // NetworkRead* -> CacheWriteData* 620 // NetworkRead* -> CacheWriteData*
618 // 621 //
619 // 5. Sparse entry, partially cached, byte range request: 622 // 5. Sparse entry, partially cached, byte range request:
620 // Start(): 623 // Start():
621 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse* 624 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
622 // -> CacheDispatchValidation -> BeginPartialCacheValidation() -> 625 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
623 // CacheQueryData* -> ValidateEntryHeadersAndContinue() -> 626 // CacheQueryData* -> ValidateEntryHeadersAndContinue() ->
624 // StartPartialCacheValidation -> CompletePartialCacheValidation -> 627 // StartPartialCacheValidation -> CompletePartialCacheValidation ->
625 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest -> 628 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
626 // UpdateCachedResponse -> CacheWriteUpdatedResponse* -> 629 // UpdateCachedResponse -> CacheWriteUpdatedResponse* ->
627 // UpdateCachedResponseComplete -> OverwriteCachedResponse -> 630 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
628 // PartialHeadersReceived 631 // PartialHeadersReceived -> FinishHeaders*
629 // 632 //
630 // Read() 1: 633 // Read() 1:
631 // NetworkRead* -> CacheWriteData* 634 // NetworkRead* -> CacheWriteData*
632 // 635 //
633 // Read() 2: 636 // Read() 2:
634 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation -> 637 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
635 // CompletePartialCacheValidation -> CacheReadData* -> 638 // CompletePartialCacheValidation -> CacheReadData* ->
636 // 639 //
637 // Read() 3: 640 // Read() 3:
638 // CacheReadData* -> StartPartialCacheValidation -> 641 // CacheReadData* -> StartPartialCacheValidation ->
(...skipping 20 matching lines...) Expand all
659 // Read(): 662 // Read():
660 // CacheReadData (returns 0) 663 // CacheReadData (returns 0)
661 // 664 //
662 // 9. HEAD. Cached entry, validation and replace (200): 665 // 9. HEAD. Cached entry, validation and replace (200):
663 // Pass through. The request dooms the old entry, as a HEAD won't be stored by 666 // Pass through. The request dooms the old entry, as a HEAD won't be stored by
664 // itself. 667 // itself.
665 // Start(): 668 // Start():
666 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse* 669 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
667 // -> CacheDispatchValidation -> BeginPartialCacheValidation() -> 670 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
668 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest -> 671 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
669 // OverwriteCachedResponse 672 // OverwriteCachedResponse -> FinishHeaders*
670 // 673 //
671 // 10. HEAD. Sparse entry, partially cached: 674 // 10. HEAD. Sparse entry, partially cached:
672 // Serve the request from the cache, as long as it doesn't require 675 // Serve the request from the cache, as long as it doesn't require
673 // revalidation. Ignore missing ranges when deciding to revalidate. If the 676 // revalidation. Ignore missing ranges when deciding to revalidate. If the
674 // entry requires revalidation, ignore the whole request and go to full pass 677 // entry requires revalidation, ignore the whole request and go to full pass
675 // through (the result of the HEAD request will NOT update the entry). 678 // through (the result of the HEAD request will NOT update the entry).
676 // 679 //
677 // Start(): Basically the same as example 7, as we never create a partial_ 680 // Start(): Basically the same as example 7, as we never create a partial_
678 // object for this request. 681 // object for this request.
679 // 682 //
680 // 11. Prefetch, not-cached entry: 683 // 11. Prefetch, not-cached entry:
681 // The same as example 1. The "unused_since_prefetch" bit is stored as true in 684 // The same as example 1. The "unused_since_prefetch" bit is stored as true in
682 // UpdateCachedResponse. 685 // UpdateCachedResponse.
683 // 686 //
684 // 12. Prefetch, cached entry: 687 // 12. Prefetch, cached entry:
685 // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between 688 // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between
686 // CacheReadResponse* and CacheDispatchValidation if the unused_since_prefetch 689 // CacheReadResponse* and CacheDispatchValidation if the unused_since_prefetch
687 // bit is unset. 690 // bit is unset.
688 // 691 //
689 // 13. Cached entry less than 5 minutes old, unused_since_prefetch is true: 692 // 13. Cached entry less than 5 minutes old, unused_since_prefetch is true:
690 // Skip validation, similar to example 2. 693 // Skip validation, similar to example 2.
691 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse* 694 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
692 // -> CacheToggleUnusedSincePrefetch* -> CacheDispatchValidation -> 695 // -> CacheToggleUnusedSincePrefetch* -> CacheDispatchValidation ->
693 // BeginPartialCacheValidation() -> BeginCacheValidation() -> 696 // BeginPartialCacheValidation() -> BeginCacheValidation() ->
694 // SetupEntryForRead() 697 // SetupEntryForRead() -> FinishHeaders*
695 // 698 //
696 // Read(): 699 // Read():
697 // CacheReadData* 700 // CacheReadData*
698 // 701 //
699 // 14. Cached entry more than 5 minutes old, unused_since_prefetch is true: 702 // 14. Cached entry more than 5 minutes old, unused_since_prefetch is true:
700 // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between 703 // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between
701 // CacheReadResponse* and CacheDispatchValidation. 704 // CacheReadResponse* and CacheDispatchValidation.
702 int HttpCache::Transaction::DoLoop(int result) { 705 int HttpCache::Transaction::DoLoop(int result) {
703 DCHECK_NE(STATE_UNSET, next_state_); 706 DCHECK_NE(STATE_UNSET, next_state_);
704 DCHECK_NE(STATE_NONE, next_state_); 707 DCHECK_NE(STATE_NONE, next_state_);
705 DCHECK(!in_do_loop_); 708 DCHECK(!in_do_loop_);
706 709
707 int rv = result; 710 int rv = result;
711 State state = next_state_;
708 do { 712 do {
709 State state = next_state_; 713 state = next_state_;
710 next_state_ = STATE_UNSET; 714 next_state_ = STATE_UNSET;
711 base::AutoReset<bool> scoped_in_do_loop(&in_do_loop_, true); 715 base::AutoReset<bool> scoped_in_do_loop(&in_do_loop_, true);
712 716
713 switch (state) { 717 switch (state) {
714 case STATE_GET_BACKEND: 718 case STATE_GET_BACKEND:
715 DCHECK_EQ(OK, rv); 719 DCHECK_EQ(OK, rv);
716 rv = DoGetBackend(); 720 rv = DoGetBackend();
717 break; 721 break;
718 case STATE_GET_BACKEND_COMPLETE: 722 case STATE_GET_BACKEND_COMPLETE:
719 rv = DoGetBackendComplete(rv); 723 rv = DoGetBackendComplete(rv);
(...skipping 116 matching lines...) Expand 10 before | Expand all | Expand 10 after
836 DCHECK_EQ(OK, rv); 840 DCHECK_EQ(OK, rv);
837 rv = DoPartialHeadersReceived(); 841 rv = DoPartialHeadersReceived();
838 break; 842 break;
839 case STATE_CACHE_READ_METADATA: 843 case STATE_CACHE_READ_METADATA:
840 DCHECK_EQ(OK, rv); 844 DCHECK_EQ(OK, rv);
841 rv = DoCacheReadMetadata(); 845 rv = DoCacheReadMetadata();
842 break; 846 break;
843 case STATE_CACHE_READ_METADATA_COMPLETE: 847 case STATE_CACHE_READ_METADATA_COMPLETE:
844 rv = DoCacheReadMetadataComplete(rv); 848 rv = DoCacheReadMetadataComplete(rv);
845 break; 849 break;
850 case STATE_HEADERS_PHASE_CANNOT_PROCEED:
851 rv = DoHeadersPhaseCannotProceed();
852 break;
853 case STATE_FINISH_HEADERS:
854 rv = DoFinishHeaders(rv);
855 break;
856 case STATE_FINISH_HEADERS_COMPLETE:
857 rv = DoFinishHeadersComplete(rv);
858 break;
846 case STATE_NETWORK_READ: 859 case STATE_NETWORK_READ:
847 DCHECK_EQ(OK, rv); 860 DCHECK_EQ(OK, rv);
848 rv = DoNetworkRead(); 861 rv = DoNetworkRead();
849 break; 862 break;
850 case STATE_NETWORK_READ_COMPLETE: 863 case STATE_NETWORK_READ_COMPLETE:
851 rv = DoNetworkReadComplete(rv); 864 rv = DoNetworkReadComplete(rv);
852 break; 865 break;
853 case STATE_CACHE_READ_DATA: 866 case STATE_CACHE_READ_DATA:
854 DCHECK_EQ(OK, rv); 867 DCHECK_EQ(OK, rv);
855 rv = DoCacheReadData(); 868 rv = DoCacheReadData();
(...skipping 16 matching lines...) Expand all
872 break; 885 break;
873 default: 886 default:
874 NOTREACHED() << "bad state " << state; 887 NOTREACHED() << "bad state " << state;
875 rv = ERR_FAILED; 888 rv = ERR_FAILED;
876 break; 889 break;
877 } 890 }
878 DCHECK(next_state_ != STATE_UNSET) << "Previous state was " << state; 891 DCHECK(next_state_ != STATE_UNSET) << "Previous state was " << state;
879 892
880 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE); 893 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
881 894
895 // Assert Start() state machine's allowed last state in successful cases when
896 // caching is happening.
897 DCHECK(reading_ || rv != OK || !entry_ ||
898 state == STATE_FINISH_HEADERS_COMPLETE);
899
882 if (rv != ERR_IO_PENDING && !callback_.is_null()) { 900 if (rv != ERR_IO_PENDING && !callback_.is_null()) {
883 read_buf_ = NULL; // Release the buffer before invoking the callback. 901 read_buf_ = nullptr; // Release the buffer before invoking the callback.
884 base::ResetAndReturn(&callback_).Run(rv); 902 base::ResetAndReturn(&callback_).Run(rv);
885 } 903 }
886 904
887 return rv; 905 return rv;
888 } 906 }
889 907
890 int HttpCache::Transaction::DoGetBackend() { 908 int HttpCache::Transaction::DoGetBackend() {
891 cache_pending_ = true; 909 cache_pending_ = true;
892 TransitionToState(STATE_GET_BACKEND_COMPLETE); 910 TransitionToState(STATE_GET_BACKEND_COMPLETE);
893 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_GET_BACKEND); 911 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_GET_BACKEND);
894 return cache_->GetBackendForTransaction(this); 912 return cache_->GetBackendForTransaction(this);
895 } 913 }
896 914
897 int HttpCache::Transaction::DoGetBackendComplete(int result) { 915 int HttpCache::Transaction::DoGetBackendComplete(int result) {
898 DCHECK(result == OK || result == ERR_FAILED); 916 DCHECK(result == OK || result == ERR_FAILED);
899 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_GET_BACKEND, 917 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_GET_BACKEND,
900 result); 918 result);
901 cache_pending_ = false; 919 cache_pending_ = false;
902 920
903 if (!ShouldPassThrough()) { 921 if (!ShouldPassThrough()) {
904 cache_key_ = cache_->GenerateCacheKey(request_); 922 cache_key_ = cache_->GenerateCacheKey(request_);
905 923
906 // Requested cache access mode. 924 // Requested cache access mode.
907 if (effective_load_flags_ & LOAD_ONLY_FROM_CACHE) { 925 if (effective_load_flags_ & LOAD_ONLY_FROM_CACHE) {
908 if (effective_load_flags_ & LOAD_BYPASS_CACHE) { 926 if (effective_load_flags_ & LOAD_BYPASS_CACHE) {
909 // The client has asked for nonsense. 927 // The client has asked for nonsense.
910 TransitionToState(STATE_NONE); 928 TransitionToState(STATE_FINISH_HEADERS);
911 return ERR_CACHE_MISS; 929 return ERR_CACHE_MISS;
912 } 930 }
913 mode_ = READ; 931 mode_ = READ;
914 } else if (effective_load_flags_ & LOAD_BYPASS_CACHE) { 932 } else if (effective_load_flags_ & LOAD_BYPASS_CACHE) {
915 mode_ = WRITE; 933 mode_ = WRITE;
916 } else { 934 } else {
917 mode_ = READ_WRITE; 935 mode_ = READ_WRITE;
918 } 936 }
919 937
920 // Downgrade to UPDATE if the request has been externally conditionalized. 938 // Downgrade to UPDATE if the request has been externally conditionalized.
(...skipping 18 matching lines...) Expand all
939 // transaction behaves the same for GET and HEAD requests at this point: if it 957 // transaction behaves the same for GET and HEAD requests at this point: if it
940 // was not modified, the entry is updated and a response is not returned from 958 // was not modified, the entry is updated and a response is not returned from
941 // the cache. If we receive 200, it doesn't matter if there was a validation 959 // the cache. If we receive 200, it doesn't matter if there was a validation
942 // header or not. 960 // header or not.
943 if (request_->method == "HEAD" && mode_ == WRITE) 961 if (request_->method == "HEAD" && mode_ == WRITE)
944 mode_ = NONE; 962 mode_ = NONE;
945 963
946 // If must use cache, then we must fail. This can happen for back/forward 964 // If must use cache, then we must fail. This can happen for back/forward
947 // navigations to a page generated via a form post. 965 // navigations to a page generated via a form post.
948 if (!(mode_ & READ) && effective_load_flags_ & LOAD_ONLY_FROM_CACHE) { 966 if (!(mode_ & READ) && effective_load_flags_ & LOAD_ONLY_FROM_CACHE) {
949 TransitionToState(STATE_NONE); 967 TransitionToState(STATE_FINISH_HEADERS);
950 return ERR_CACHE_MISS; 968 return ERR_CACHE_MISS;
951 } 969 }
952 970
953 if (mode_ == NONE) { 971 if (mode_ == NONE) {
954 if (partial_) { 972 if (partial_) {
955 partial_->RestoreHeaders(&custom_request_->extra_headers); 973 partial_->RestoreHeaders(&custom_request_->extra_headers);
956 partial_.reset(); 974 partial_.reset();
957 } 975 }
958 TransitionToState(STATE_SEND_REQUEST); 976 TransitionToState(STATE_SEND_REQUEST);
959 } else { 977 } else {
960 TransitionToState(STATE_INIT_ENTRY); 978 TransitionToState(STATE_INIT_ENTRY);
961 } 979 }
962 980
963 // This is only set if we have something to do with the response. 981 // This is only set if we have something to do with the response.
964 range_requested_ = (partial_.get() != NULL); 982 range_requested_ = (partial_.get() != NULL);
965 983
984 // mode_ may change later, save the initial mode in case we need to restart
985 // this request.
986 original_mode_ = mode_;
966 return OK; 987 return OK;
967 } 988 }
968 989
969 int HttpCache::Transaction::DoInitEntry() { 990 int HttpCache::Transaction::DoInitEntry() {
970 TRACE_EVENT0("io", "HttpCacheTransaction::DoInitEntry"); 991 TRACE_EVENT0("io", "HttpCacheTransaction::DoInitEntry");
971 DCHECK(!new_entry_); 992 DCHECK(!new_entry_);
972 993
973 if (!cache_.get()) { 994 if (!cache_.get()) {
974 TransitionToState(STATE_NONE); 995 TransitionToState(STATE_FINISH_HEADERS);
975 return ERR_UNEXPECTED; 996 return ERR_UNEXPECTED;
976 } 997 }
977 998
978 if (mode_ == WRITE) { 999 if (mode_ == WRITE) {
979 TransitionToState(STATE_DOOM_ENTRY); 1000 TransitionToState(STATE_DOOM_ENTRY);
980 return OK; 1001 return OK;
981 } 1002 }
982 1003
983 TransitionToState(STATE_OPEN_ENTRY); 1004 TransitionToState(STATE_OPEN_ENTRY);
984 return OK; 1005 return OK;
(...skipping 16 matching lines...) Expand all
1001 // transaction attached. 1022 // transaction attached.
1002 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_OPEN_ENTRY, 1023 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_OPEN_ENTRY,
1003 result); 1024 result);
1004 cache_pending_ = false; 1025 cache_pending_ = false;
1005 if (result == OK) { 1026 if (result == OK) {
1006 TransitionToState(STATE_ADD_TO_ENTRY); 1027 TransitionToState(STATE_ADD_TO_ENTRY);
1007 return OK; 1028 return OK;
1008 } 1029 }
1009 1030
1010 if (result == ERR_CACHE_RACE) { 1031 if (result == ERR_CACHE_RACE) {
1011 TransitionToState(STATE_INIT_ENTRY); 1032 TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED);
1012 return OK; 1033 return OK;
1013 } 1034 }
1014 1035
1015 if (request_->method == "PUT" || request_->method == "DELETE" || 1036 if (request_->method == "PUT" || request_->method == "DELETE" ||
1016 (request_->method == "HEAD" && mode_ == READ_WRITE)) { 1037 (request_->method == "HEAD" && mode_ == READ_WRITE)) {
1017 DCHECK(mode_ == READ_WRITE || mode_ == WRITE || request_->method == "HEAD"); 1038 DCHECK(mode_ == READ_WRITE || mode_ == WRITE || request_->method == "HEAD");
1018 mode_ = NONE; 1039 mode_ = NONE;
1019 TransitionToState(STATE_SEND_REQUEST); 1040 TransitionToState(STATE_SEND_REQUEST);
1020 return OK; 1041 return OK;
1021 } 1042 }
1022 1043
1023 if (mode_ == READ_WRITE) { 1044 if (mode_ == READ_WRITE) {
1024 mode_ = WRITE; 1045 mode_ = WRITE;
1025 TransitionToState(STATE_CREATE_ENTRY); 1046 TransitionToState(STATE_CREATE_ENTRY);
1026 return OK; 1047 return OK;
1027 } 1048 }
1028 if (mode_ == UPDATE) { 1049 if (mode_ == UPDATE) {
1029 // There is no cache entry to update; proceed without caching. 1050 // There is no cache entry to update; proceed without caching.
1030 mode_ = NONE; 1051 mode_ = NONE;
1031 TransitionToState(STATE_SEND_REQUEST); 1052 TransitionToState(STATE_SEND_REQUEST);
1032 return OK; 1053 return OK;
1033 } 1054 }
1034 1055
1035 // The entry does not exist, and we are not permitted to create a new entry, 1056 // The entry does not exist, and we are not permitted to create a new entry,
1036 // so we must fail. 1057 // so we must fail.
1037 TransitionToState(STATE_NONE); 1058 TransitionToState(STATE_FINISH_HEADERS);
1038 return ERR_CACHE_MISS; 1059 return ERR_CACHE_MISS;
1039 } 1060 }
1040 1061
1041 int HttpCache::Transaction::DoDoomEntry() { 1062 int HttpCache::Transaction::DoDoomEntry() {
1042 TRACE_EVENT0("io", "HttpCacheTransaction::DoDoomEntry"); 1063 TRACE_EVENT0("io", "HttpCacheTransaction::DoDoomEntry");
1043 TransitionToState(STATE_DOOM_ENTRY_COMPLETE); 1064 TransitionToState(STATE_DOOM_ENTRY_COMPLETE);
1044 cache_pending_ = true; 1065 cache_pending_ = true;
1045 if (first_cache_access_since_.is_null()) 1066 if (first_cache_access_since_.is_null())
1046 first_cache_access_since_ = TimeTicks::Now(); 1067 first_cache_access_since_ = TimeTicks::Now();
1047 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_DOOM_ENTRY); 1068 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_DOOM_ENTRY);
1048 return cache_->DoomEntry(cache_key_, this); 1069 return cache_->DoomEntry(cache_key_, this);
1049 } 1070 }
1050 1071
1051 int HttpCache::Transaction::DoDoomEntryComplete(int result) { 1072 int HttpCache::Transaction::DoDoomEntryComplete(int result) {
1052 TRACE_EVENT0("io", "HttpCacheTransaction::DoDoomEntryComplete"); 1073 TRACE_EVENT0("io", "HttpCacheTransaction::DoDoomEntryComplete");
1053 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_DOOM_ENTRY, 1074 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_DOOM_ENTRY,
1054 result); 1075 result);
1055 cache_pending_ = false; 1076 cache_pending_ = false;
1056 TransitionToState(result == ERR_CACHE_RACE ? STATE_INIT_ENTRY 1077 TransitionToState(result == ERR_CACHE_RACE
1057 : STATE_CREATE_ENTRY); 1078 ? STATE_HEADERS_PHASE_CANNOT_PROCEED
1079 : STATE_CREATE_ENTRY);
1058 return OK; 1080 return OK;
1059 } 1081 }
1060 1082
1061 int HttpCache::Transaction::DoCreateEntry() { 1083 int HttpCache::Transaction::DoCreateEntry() {
1062 TRACE_EVENT0("io", "HttpCacheTransaction::DoCreateEntry"); 1084 TRACE_EVENT0("io", "HttpCacheTransaction::DoCreateEntry");
1063 DCHECK(!new_entry_); 1085 DCHECK(!new_entry_);
1064 TransitionToState(STATE_CREATE_ENTRY_COMPLETE); 1086 TransitionToState(STATE_CREATE_ENTRY_COMPLETE);
1065 cache_pending_ = true; 1087 cache_pending_ = true;
1066 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_CREATE_ENTRY); 1088 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_CREATE_ENTRY);
1067 return cache_->CreateEntry(cache_key_, &new_entry_, this); 1089 return cache_->CreateEntry(cache_key_, &new_entry_, this);
1068 } 1090 }
1069 1091
1070 int HttpCache::Transaction::DoCreateEntryComplete(int result) { 1092 int HttpCache::Transaction::DoCreateEntryComplete(int result) {
1071 TRACE_EVENT0("io", "HttpCacheTransaction::DoCreateEntryComplete"); 1093 TRACE_EVENT0("io", "HttpCacheTransaction::DoCreateEntryComplete");
1072 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is 1094 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1073 // OK, otherwise the cache will end up with an active entry without any 1095 // OK, otherwise the cache will end up with an active entry without any
1074 // transaction attached. 1096 // transaction attached.
1075 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_CREATE_ENTRY, 1097 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_CREATE_ENTRY,
1076 result); 1098 result);
1077 cache_pending_ = false; 1099 cache_pending_ = false;
1078 switch (result) { 1100 switch (result) {
1079 case OK: 1101 case OK:
1080 TransitionToState(STATE_ADD_TO_ENTRY); 1102 TransitionToState(STATE_ADD_TO_ENTRY);
1081 break; 1103 break;
1082 1104
1083 case ERR_CACHE_RACE: 1105 case ERR_CACHE_RACE:
1084 TransitionToState(STATE_INIT_ENTRY); 1106 TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED);
1085 break; 1107 break;
1086 1108
1087 default: 1109 default:
1088 // We have a race here: Maybe we failed to open the entry and decided to 1110 // We have a race here: Maybe we failed to open the entry and decided to
1089 // create one, but by the time we called create, another transaction 1111 // create one, but by the time we called create, another transaction
1090 // already created the entry. If we want to eliminate this issue, we 1112 // already created the entry. If we want to eliminate this issue, we
1091 // need an atomic OpenOrCreate() method exposed by the disk cache. 1113 // need an atomic OpenOrCreate() method exposed by the disk cache.
1092 DLOG(WARNING) << "Unable to create cache entry"; 1114 DLOG(WARNING) << "Unable to create cache entry";
1093 mode_ = NONE; 1115 mode_ = NONE;
1094 if (partial_) 1116 if (partial_)
(...skipping 60 matching lines...) Expand 10 before | Expand all | Expand 10 after
1155 DCHECK(new_entry_); 1177 DCHECK(new_entry_);
1156 cache_pending_ = false; 1178 cache_pending_ = false;
1157 1179
1158 if (result == OK) 1180 if (result == OK)
1159 entry_ = new_entry_; 1181 entry_ = new_entry_;
1160 1182
1161 // If there is a failure, the cache should have taken care of new_entry_. 1183 // If there is a failure, the cache should have taken care of new_entry_.
1162 new_entry_ = NULL; 1184 new_entry_ = NULL;
1163 1185
1164 if (result == ERR_CACHE_RACE) { 1186 if (result == ERR_CACHE_RACE) {
1165 TransitionToState(STATE_INIT_ENTRY); 1187 TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED);
1166 return OK; 1188 return OK;
1167 } 1189 }
1168 1190
1169 if (result == ERR_CACHE_LOCK_TIMEOUT) { 1191 if (result == ERR_CACHE_LOCK_TIMEOUT) {
1170 if (mode_ == READ) { 1192 if (mode_ == READ) {
1171 TransitionToState(STATE_NONE); 1193 TransitionToState(STATE_FINISH_HEADERS);
1172 return ERR_CACHE_MISS; 1194 return ERR_CACHE_MISS;
1173 } 1195 }
1174 1196
1175 // The cache is busy, bypass it for this transaction. 1197 // The cache is busy, bypass it for this transaction.
1176 mode_ = NONE; 1198 mode_ = NONE;
1177 TransitionToState(STATE_SEND_REQUEST); 1199 TransitionToState(STATE_SEND_REQUEST);
1178 if (partial_) { 1200 if (partial_) {
1179 partial_->RestoreHeaders(&custom_request_->extra_headers); 1201 partial_->RestoreHeaders(&custom_request_->extra_headers);
1180 partial_.reset(); 1202 partial_.reset();
1181 } 1203 }
1182 return OK; 1204 return OK;
1183 } 1205 }
1184 1206
1185 open_entry_last_used_ = entry_->disk_entry->GetLastUsed(); 1207 // Access timestamp for histograms only if entry is already written, to avoid
1208 // data race since cache thread can also access this. TODO(crbug.com/713354)
Randy Smith (Not in Mondays) 2017/04/25 21:11:32 Usual format is "TODO(<username> of person who can
asanka 2017/04/26 02:01:45 FYI: TODO(crbug.com/..) is now allowed in the styl
jkarlin 2017/04/26 17:11:01 This still needs to be addressed.
shivanisha 2017/04/26 17:48:38 done
1209 if (!cache_->IsWritingInProgress(entry_))
1210 open_entry_last_used_ = entry_->GetLastUsed(this);
1186 1211
1187 // TODO(jkarlin): We should either handle the case or DCHECK. 1212 // TODO(jkarlin): We should either handle the case or DCHECK.
1188 if (result != OK) { 1213 if (result != OK) {
1189 NOTREACHED(); 1214 NOTREACHED();
1190 TransitionToState(STATE_NONE); 1215 TransitionToState(STATE_FINISH_HEADERS);
1191 return result; 1216 return result;
1192 } 1217 }
1193 1218
1194 if (mode_ == WRITE) { 1219 if (mode_ == WRITE) {
1195 if (partial_) 1220 if (partial_)
1196 partial_->RestoreHeaders(&custom_request_->extra_headers); 1221 partial_->RestoreHeaders(&custom_request_->extra_headers);
1197 TransitionToState(STATE_SEND_REQUEST); 1222 TransitionToState(STATE_SEND_REQUEST);
1198 } else { 1223 } else {
1199 // We have to read the headers from the cached entry. 1224 // We have to read the headers from the cached entry.
1200 DCHECK(mode_ & READ_META); 1225 DCHECK(mode_ & READ_META);
1201 TransitionToState(STATE_CACHE_READ_RESPONSE); 1226 TransitionToState(STATE_CACHE_READ_RESPONSE);
1202 } 1227 }
1203 return OK; 1228 return OK;
1204 } 1229 }
1205 1230
1206 int HttpCache::Transaction::DoCacheReadResponse() { 1231 int HttpCache::Transaction::DoCacheReadResponse() {
1207 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadResponse"); 1232 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadResponse");
1208 DCHECK(entry_); 1233 DCHECK(entry_);
1209 TransitionToState(STATE_CACHE_READ_RESPONSE_COMPLETE); 1234 TransitionToState(STATE_CACHE_READ_RESPONSE_COMPLETE);
1210 1235
1211 io_buf_len_ = entry_->disk_entry->GetDataSize(kResponseInfoIndex); 1236 io_buf_len_ = entry_->GetDataSize(kResponseInfoIndex, this);
1212 read_buf_ = new IOBuffer(io_buf_len_); 1237 read_buf_ = new IOBuffer(io_buf_len_);
1213 1238
1214 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_READ_INFO); 1239 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_READ_INFO);
1215 return entry_->disk_entry->ReadData(kResponseInfoIndex, 0, read_buf_.get(), 1240 return entry_->disk_entry->ReadData(kResponseInfoIndex, 0, read_buf_.get(),
1216 io_buf_len_, io_callback_); 1241 io_buf_len_, io_callback_);
1217 } 1242 }
1218 1243
1219 int HttpCache::Transaction::DoCacheReadResponseComplete(int result) { 1244 int HttpCache::Transaction::DoCacheReadResponseComplete(int result) {
1220 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadResponseComplete"); 1245 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadResponseComplete");
1221 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_READ_INFO, 1246 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_READ_INFO,
1222 result); 1247 result);
1223 if (result != io_buf_len_ || 1248 if (result != io_buf_len_ ||
1224 !HttpCache::ParseResponseInfo(read_buf_->data(), io_buf_len_, &response_, 1249 !HttpCache::ParseResponseInfo(read_buf_->data(), io_buf_len_, &response_,
1225 &truncated_)) { 1250 &truncated_)) {
1226 return OnCacheReadError(result, true); 1251 return OnCacheReadError(result, true);
1227 } 1252 }
1228 1253
1229 int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex); 1254 // Do not access the data size if another transaction is writing as this could
1230 int64_t full_response_length = response_.headers->GetContentLength(); 1255 // lead to a race TODO(crbug.com/713354).
1256 if (!cache_->IsWritingInProgress(entry_)) {
1257 int current_size = entry_->GetDataSize(kResponseContentIndex, this);
1258 int64_t full_response_length = response_.headers->GetContentLength();
1231 1259
1232 // Some resources may have slipped in as truncated when they're not. 1260 // Some resources may have slipped in as truncated when they're not.
1233 if (full_response_length == current_size) 1261 if (full_response_length == current_size)
1234 truncated_ = false; 1262 truncated_ = false;
1235 1263
1236 // The state machine's handling of StopCaching unfortunately doesn't deal well 1264 // The state machine's handling of StopCaching unfortunately doesn't deal
1237 // with resources that are larger than 2GB when there is a truncated or sparse 1265 // well with resources that are larger than 2GB when there is a truncated or
1238 // cache entry. While the state machine is reworked to resolve this, the 1266 // sparse cache entry. While the state machine is reworked to resolve this,
1239 // following logic is put in place to defer such requests to the network. The 1267 // the following logic is put in place to defer such requests to the
1240 // cache should not be storing multi gigabyte resources. See 1268 // network. The cache should not be storing multi gigabyte resources. See
1241 // http://crbug.com/89567. 1269 // http://crbug.com/89567.
Randy Smith (Not in Mondays) 2017/04/25 21:11:32 Include a comment as to why this is safe to have i
shivanisha 2017/04/26 16:22:30 done
1242 if ((truncated_ || response_.headers->response_code() == 206) && 1270 if ((truncated_ || response_.headers->response_code() == 206) &&
1243 !range_requested_ && 1271 !range_requested_ &&
1244 full_response_length > std::numeric_limits<int32_t>::max()) { 1272 full_response_length > std::numeric_limits<int32_t>::max()) {
1245 // Does not release the cache entry. If another transaction wants to use 1273 DCHECK(!partial_);
1246 // this cache entry while this transaction is active, the second transaction 1274 cache_->DoneWritingToEntry(entry_, false, this);
1247 // will fall back to the network after the timeout. 1275 entry_ = nullptr;
1248 DCHECK(!partial_); 1276 mode_ = NONE;
1249 mode_ = NONE; 1277 TransitionToState(STATE_SEND_REQUEST);
1250 TransitionToState(STATE_SEND_REQUEST); 1278 return OK;
1251 return OK; 1279 }
1252 } 1280 }
1253 1281
1254 if (response_.unused_since_prefetch != 1282 if (response_.unused_since_prefetch !=
1255 !!(request_->load_flags & LOAD_PREFETCH)) { 1283 !!(request_->load_flags & LOAD_PREFETCH)) {
1256 // Either this is the first use of an entry since it was prefetched XOR 1284 // Either this is the first use of an entry since it was prefetched XOR
1257 // this is a prefetch. The value of response.unused_since_prefetch is 1285 // this is a prefetch. The value of response.unused_since_prefetch is
1258 // valid for this transaction but the bit needs to be flipped in storage. 1286 // valid for this transaction but the bit needs to be flipped in storage.
1259 TransitionToState(STATE_TOGGLE_UNUSED_SINCE_PREFETCH); 1287 TransitionToState(STATE_TOGGLE_UNUSED_SINCE_PREFETCH);
1260 return OK; 1288 return OK;
1261 } 1289 }
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
1323 } 1351 }
1324 1352
1325 int HttpCache::Transaction::DoCacheQueryData() { 1353 int HttpCache::Transaction::DoCacheQueryData() {
1326 TransitionToState(STATE_CACHE_QUERY_DATA_COMPLETE); 1354 TransitionToState(STATE_CACHE_QUERY_DATA_COMPLETE);
1327 return entry_->disk_entry->ReadyForSparseIO(io_callback_); 1355 return entry_->disk_entry->ReadyForSparseIO(io_callback_);
1328 } 1356 }
1329 1357
1330 int HttpCache::Transaction::DoCacheQueryDataComplete(int result) { 1358 int HttpCache::Transaction::DoCacheQueryDataComplete(int result) {
1331 DCHECK_EQ(OK, result); 1359 DCHECK_EQ(OK, result);
1332 if (!cache_.get()) { 1360 if (!cache_.get()) {
1333 TransitionToState(STATE_NONE); 1361 TransitionToState(STATE_FINISH_HEADERS);
1334 return ERR_UNEXPECTED; 1362 return ERR_UNEXPECTED;
1335 } 1363 }
1336 1364
1337 return ValidateEntryHeadersAndContinue(); 1365 return ValidateEntryHeadersAndContinue();
1338 } 1366 }
1339 1367
1340 // We may end up here multiple times for a given request. 1368 // We may end up here multiple times for a given request.
1341 int HttpCache::Transaction::DoStartPartialCacheValidation() { 1369 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1342 if (mode_ == NONE) { 1370 if (mode_ == NONE) {
1343 TransitionToState(STATE_NONE); 1371 TransitionToState(STATE_FINISH_HEADERS);
1344 return OK; 1372 return OK;
1345 } 1373 }
1346 1374
1347 TransitionToState(STATE_COMPLETE_PARTIAL_CACHE_VALIDATION); 1375 TransitionToState(STATE_COMPLETE_PARTIAL_CACHE_VALIDATION);
1348 return partial_->ShouldValidateCache(entry_->disk_entry, io_callback_); 1376 return partial_->ShouldValidateCache(entry_->disk_entry, io_callback_);
1349 } 1377 }
1350 1378
1351 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result) { 1379 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result) {
1352 if (!result) { 1380 if (!result) {
1353 // This is the end of the request. 1381 // This is the end of the request.
1354 if (mode_ & WRITE) { 1382 if (mode_ & WRITE) {
1355 DoneWritingToEntry(true); 1383 DoneWritingToEntry(true);
1356 } else { 1384 } else {
1357 cache_->DoneReadingFromEntry(entry_, this); 1385 cache_->DoneReadingFromEntry(entry_, this);
1358 entry_ = NULL; 1386 entry_ = NULL;
1359 } 1387 }
1360 TransitionToState(STATE_NONE); 1388 TransitionToState(STATE_FINISH_HEADERS);
1361 return result; 1389 return result;
1362 } 1390 }
1363 1391
1364 if (result < 0) { 1392 if (result < 0) {
1365 TransitionToState(STATE_NONE); 1393 TransitionToState(STATE_FINISH_HEADERS);
1366 return result; 1394 return result;
1367 } 1395 }
1368 1396
1369 partial_->PrepareCacheValidation(entry_->disk_entry, 1397 partial_->PrepareCacheValidation(entry_->disk_entry,
1370 &custom_request_->extra_headers); 1398 &custom_request_->extra_headers);
1371 1399
1372 if (reading_ && partial_->IsCurrentRangeCached()) { 1400 if (reading_ && partial_->IsCurrentRangeCached()) {
1373 TransitionToState(STATE_CACHE_READ_DATA); 1401 TransitionToState(STATE_CACHE_READ_DATA);
1374 return OK; 1402 return OK;
1375 } 1403 }
1376 1404
1377 return BeginCacheValidation(); 1405 return BeginCacheValidation();
1378 } 1406 }
1379 1407
1380 int HttpCache::Transaction::DoSendRequest() { 1408 int HttpCache::Transaction::DoSendRequest() {
1381 TRACE_EVENT0("io", "HttpCacheTransaction::DoSendRequest"); 1409 TRACE_EVENT0("io", "HttpCacheTransaction::DoSendRequest");
1382 DCHECK(mode_ & WRITE || mode_ == NONE); 1410 DCHECK(mode_ & WRITE || mode_ == NONE);
1383 DCHECK(!network_trans_.get()); 1411 DCHECK(!network_trans_.get());
1384 1412
1385 send_request_since_ = TimeTicks::Now(); 1413 send_request_since_ = TimeTicks::Now();
1386 1414
1387 // Create a network transaction. 1415 // Create a network transaction.
1388 int rv = 1416 int rv =
1389 cache_->network_layer_->CreateTransaction(priority_, &network_trans_); 1417 cache_->network_layer_->CreateTransaction(priority_, &network_trans_);
1390 if (rv != OK) { 1418 if (rv != OK) {
1391 TransitionToState(STATE_NONE); 1419 TransitionToState(STATE_FINISH_HEADERS);
1392 return rv; 1420 return rv;
1393 } 1421 }
1394 network_trans_->SetBeforeNetworkStartCallback(before_network_start_callback_); 1422 network_trans_->SetBeforeNetworkStartCallback(before_network_start_callback_);
1395 network_trans_->SetBeforeHeadersSentCallback(before_headers_sent_callback_); 1423 network_trans_->SetBeforeHeadersSentCallback(before_headers_sent_callback_);
1396 1424
1397 // Old load timing information, if any, is now obsolete. 1425 // Old load timing information, if any, is now obsolete.
1398 old_network_trans_load_timing_.reset(); 1426 old_network_trans_load_timing_.reset();
1399 old_remote_endpoint_ = IPEndPoint(); 1427 old_remote_endpoint_ = IPEndPoint();
1400 1428
1401 if (websocket_handshake_stream_base_create_helper_) 1429 if (websocket_handshake_stream_base_create_helper_)
1402 network_trans_->SetWebSocketHandshakeStreamCreateHelper( 1430 network_trans_->SetWebSocketHandshakeStreamCreateHelper(
1403 websocket_handshake_stream_base_create_helper_); 1431 websocket_handshake_stream_base_create_helper_);
1404 1432
1405 TransitionToState(STATE_SEND_REQUEST_COMPLETE); 1433 TransitionToState(STATE_SEND_REQUEST_COMPLETE);
1406 rv = network_trans_->Start(request_, io_callback_, net_log_); 1434 rv = network_trans_->Start(request_, io_callback_, net_log_);
1407 return rv; 1435 return rv;
1408 } 1436 }
1409 1437
1410 int HttpCache::Transaction::DoSendRequestComplete(int result) { 1438 int HttpCache::Transaction::DoSendRequestComplete(int result) {
1411 TRACE_EVENT0("io", "HttpCacheTransaction::DoSendRequestComplete"); 1439 TRACE_EVENT0("io", "HttpCacheTransaction::DoSendRequestComplete");
1412 if (!cache_.get()) { 1440 if (!cache_.get()) {
1413 TransitionToState(STATE_NONE); 1441 TransitionToState(STATE_FINISH_HEADERS);
1414 return ERR_UNEXPECTED; 1442 return ERR_UNEXPECTED;
1415 } 1443 }
1416 1444
1417 // If we tried to conditionalize the request and failed, we know 1445 // If we tried to conditionalize the request and failed, we know
1418 // we won't be reading from the cache after this point. 1446 // we won't be reading from the cache after this point.
1419 if (couldnt_conditionalize_request_) 1447 if (couldnt_conditionalize_request_)
1420 mode_ = WRITE; 1448 mode_ = WRITE;
1421 1449
1422 if (result == OK) { 1450 if (result == OK) {
1423 TransitionToState(STATE_SUCCESSFUL_SEND_REQUEST); 1451 TransitionToState(STATE_SUCCESSFUL_SEND_REQUEST);
(...skipping 10 matching lines...) Expand all
1434 // so GetResponseInfo() should never return NULL here. 1462 // so GetResponseInfo() should never return NULL here.
1435 DCHECK(response); 1463 DCHECK(response);
1436 response_.ssl_info = response->ssl_info; 1464 response_.ssl_info = response->ssl_info;
1437 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) { 1465 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
1438 DCHECK(response); 1466 DCHECK(response);
1439 response_.cert_request_info = response->cert_request_info; 1467 response_.cert_request_info = response->cert_request_info;
1440 } else if (response_.was_cached) { 1468 } else if (response_.was_cached) {
1441 DoneWritingToEntry(true); 1469 DoneWritingToEntry(true);
1442 } 1470 }
1443 1471
1444 TransitionToState(STATE_NONE); 1472 TransitionToState(STATE_FINISH_HEADERS);
1445 return result; 1473 return result;
1446 } 1474 }
1447 1475
1448 // We received the response headers and there is no error. 1476 // We received the response headers and there is no error.
1449 int HttpCache::Transaction::DoSuccessfulSendRequest() { 1477 int HttpCache::Transaction::DoSuccessfulSendRequest() {
1450 TRACE_EVENT0("io", "HttpCacheTransaction::DoSuccessfulSendRequest"); 1478 TRACE_EVENT0("io", "HttpCacheTransaction::DoSuccessfulSendRequest");
1451 DCHECK(!new_response_); 1479 DCHECK(!new_response_);
1452 const HttpResponseInfo* new_response = network_trans_->GetResponseInfo(); 1480 const HttpResponseInfo* new_response = network_trans_->GetResponseInfo();
1453 1481
1454 if (new_response->headers->response_code() == 401 || 1482 if (new_response->headers->response_code() == 401 ||
1455 new_response->headers->response_code() == 407) { 1483 new_response->headers->response_code() == 407) {
1456 SetAuthResponse(*new_response); 1484 SetAuthResponse(*new_response);
1457 if (!reading_) { 1485 if (!reading_) {
1458 TransitionToState(STATE_NONE); 1486 TransitionToState(STATE_FINISH_HEADERS);
1459 return OK; 1487 return OK;
1460 } 1488 }
1461 1489
1462 // We initiated a second request the caller doesn't know about. We should be 1490 // We initiated a second request the caller doesn't know about. We should be
1463 // able to authenticate this request because we should have authenticated 1491 // able to authenticate this request because we should have authenticated
1464 // this URL moments ago. 1492 // this URL moments ago.
1465 if (IsReadyToRestartForAuth()) { 1493 if (IsReadyToRestartForAuth()) {
1466 DCHECK(!response_.auth_challenge.get()); 1494 DCHECK(!response_.auth_challenge.get());
1467 TransitionToState(STATE_SEND_REQUEST_COMPLETE); 1495 TransitionToState(STATE_SEND_REQUEST_COMPLETE);
1468 // In theory we should check to see if there are new cookies, but there 1496 // In theory we should check to see if there are new cookies, but there
1469 // is no way to do that from here. 1497 // is no way to do that from here.
1470 return network_trans_->RestartWithAuth(AuthCredentials(), io_callback_); 1498 return network_trans_->RestartWithAuth(AuthCredentials(), io_callback_);
1471 } 1499 }
1472 1500
1473 // We have to perform cleanup at this point so that at least the next 1501 // We have to perform cleanup at this point so that at least the next
1474 // request can succeed. We do not retry at this point, because data 1502 // request can succeed. We do not retry at this point, because data
1475 // has been read and we have no way to gather credentials. We would 1503 // has been read and we have no way to gather credentials. We would
1476 // fail again, and potentially loop. This can happen if the credentials 1504 // fail again, and potentially loop. This can happen if the credentials
1477 // expire while chrome is suspended. 1505 // expire while chrome is suspended.
1478 if (entry_) 1506 if (entry_)
1479 DoomPartialEntry(false); 1507 DoomPartialEntry(false);
1480 mode_ = NONE; 1508 mode_ = NONE;
1481 partial_.reset(); 1509 partial_.reset();
1482 ResetNetworkTransaction(); 1510 ResetNetworkTransaction();
1483 TransitionToState(STATE_NONE); 1511 TransitionToState(STATE_FINISH_HEADERS);
1484 return ERR_CACHE_AUTH_FAILURE_AFTER_READ; 1512 return ERR_CACHE_AUTH_FAILURE_AFTER_READ;
1485 } 1513 }
1486 1514
1487 new_response_ = new_response; 1515 new_response_ = new_response;
1488 if (!ValidatePartialResponse() && !auth_response_.headers.get()) { 1516 if (!ValidatePartialResponse() && !auth_response_.headers.get()) {
1489 // Something went wrong with this request and we have to restart it. 1517 // Something went wrong with this request and we have to restart it.
1490 // If we have an authentication response, we are exposed to weird things 1518 // If we have an authentication response, we are exposed to weird things
1491 // hapenning if the user cancels the authentication before we receive 1519 // hapenning if the user cancels the authentication before we receive
1492 // the new response. 1520 // the new response.
1493 net_log_.AddEvent(NetLogEventType::HTTP_CACHE_RE_SEND_PARTIAL_REQUEST); 1521 net_log_.AddEvent(NetLogEventType::HTTP_CACHE_RE_SEND_PARTIAL_REQUEST);
(...skipping 17 matching lines...) Expand all
1511 UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_NOT_IN_CACHE); 1539 UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_NOT_IN_CACHE);
1512 } 1540 }
1513 1541
1514 // Invalidate any cached GET with a successful PUT or DELETE. 1542 // Invalidate any cached GET with a successful PUT or DELETE.
1515 if (mode_ == WRITE && 1543 if (mode_ == WRITE &&
1516 (request_->method == "PUT" || request_->method == "DELETE")) { 1544 (request_->method == "PUT" || request_->method == "DELETE")) {
1517 if (NonErrorResponse(new_response->headers->response_code())) { 1545 if (NonErrorResponse(new_response->headers->response_code())) {
1518 int ret = cache_->DoomEntry(cache_key_, NULL); 1546 int ret = cache_->DoomEntry(cache_key_, NULL);
1519 DCHECK_EQ(OK, ret); 1547 DCHECK_EQ(OK, ret);
1520 } 1548 }
1521 cache_->DoneWritingToEntry(entry_, true); 1549 cache_->DoneWritingToEntry(entry_, true, this);
1522 entry_ = NULL; 1550 entry_ = NULL;
1523 mode_ = NONE; 1551 mode_ = NONE;
1524 } 1552 }
1525 1553
1526 // Invalidate any cached GET with a successful POST. 1554 // Invalidate any cached GET with a successful POST.
1527 if (!(effective_load_flags_ & LOAD_DISABLE_CACHE) && 1555 if (!(effective_load_flags_ & LOAD_DISABLE_CACHE) &&
1528 request_->method == "POST" && 1556 request_->method == "POST" &&
1529 NonErrorResponse(new_response->headers->response_code())) { 1557 NonErrorResponse(new_response->headers->response_code())) {
1530 cache_->DoomMainEntryForUrl(request_->url); 1558 cache_->DoomMainEntryForUrl(request_->url);
1531 } 1559 }
1532 1560
1533 RecordNoStoreHeaderHistogram(request_->load_flags, new_response); 1561 RecordNoStoreHeaderHistogram(request_->load_flags, new_response);
1534 1562
1535 if (new_response_->headers->response_code() == 416 && 1563 if (new_response_->headers->response_code() == 416 &&
1536 (request_->method == "GET" || request_->method == "POST")) { 1564 (request_->method == "GET" || request_->method == "POST")) {
1537 // If there is an active entry it may be destroyed with this transaction. 1565 // If there is an active entry it may be destroyed with this transaction.
1538 SetResponse(*new_response_); 1566 SetResponse(*new_response_);
1539 TransitionToState(STATE_NONE); 1567 TransitionToState(STATE_FINISH_HEADERS);
1540 return OK; 1568 return OK;
1541 } 1569 }
1542 1570
1543 // Are we expecting a response to a conditional query? 1571 // Are we expecting a response to a conditional query?
1544 if (mode_ == READ_WRITE || mode_ == UPDATE) { 1572 if (mode_ == READ_WRITE || mode_ == UPDATE) {
1545 if (new_response->headers->response_code() == 304 || handling_206_) { 1573 if (new_response->headers->response_code() == 304 || handling_206_) {
1546 UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_VALIDATED); 1574 UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_VALIDATED);
1547 TransitionToState(STATE_UPDATE_CACHED_RESPONSE); 1575 TransitionToState(STATE_UPDATE_CACHED_RESPONSE);
1548 return OK; 1576 return OK;
1549 } 1577 }
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
1617 DCHECK(!handling_206_); 1645 DCHECK(!handling_206_);
1618 // We got a "not modified" response and already updated the corresponding 1646 // We got a "not modified" response and already updated the corresponding
1619 // cache entry above. 1647 // cache entry above.
1620 // 1648 //
1621 // By closing the cached entry now, we make sure that the 304 rather than 1649 // By closing the cached entry now, we make sure that the 304 rather than
1622 // the cached 200 response, is what will be returned to the user. 1650 // the cached 200 response, is what will be returned to the user.
1623 DoneWritingToEntry(true); 1651 DoneWritingToEntry(true);
1624 } else if (entry_ && !handling_206_) { 1652 } else if (entry_ && !handling_206_) {
1625 DCHECK_EQ(READ_WRITE, mode_); 1653 DCHECK_EQ(READ_WRITE, mode_);
1626 if (!partial_ || partial_->IsLastRange()) { 1654 if (!partial_ || partial_->IsLastRange()) {
1627 cache_->ConvertWriterToReader(entry_);
1628 mode_ = READ; 1655 mode_ = READ;
1629 } 1656 }
1630 // We no longer need the network transaction, so destroy it. 1657 // We no longer need the network transaction, so destroy it.
1631 ResetNetworkTransaction(); 1658 ResetNetworkTransaction();
1632 } else if (entry_ && handling_206_ && truncated_ && 1659 } else if (entry_ && handling_206_ && truncated_ &&
1633 partial_->initial_validation()) { 1660 partial_->initial_validation()) {
1634 // We just finished the validation of a truncated entry, and the server 1661 // We just finished the validation of a truncated entry, and the server
1635 // is willing to resume the operation. Now we go back and start serving 1662 // is willing to resume the operation. Now we go back and start serving
1636 // the first part to the user. 1663 // the first part to the user.
1637 ResetNetworkTransaction(); 1664 ResetNetworkTransaction();
(...skipping 17 matching lines...) Expand all
1655 if (handling_206_ && partial_) 1682 if (handling_206_ && partial_)
1656 partial_->FixContentLength(new_response_->headers.get()); 1683 partial_->FixContentLength(new_response_->headers.get());
1657 1684
1658 SetResponse(*new_response_); 1685 SetResponse(*new_response_);
1659 1686
1660 if (request_->method == "HEAD") { 1687 if (request_->method == "HEAD") {
1661 // This response is replacing the cached one. 1688 // This response is replacing the cached one.
1662 DoneWritingToEntry(false); 1689 DoneWritingToEntry(false);
1663 mode_ = NONE; 1690 mode_ = NONE;
1664 new_response_ = NULL; 1691 new_response_ = NULL;
1665 TransitionToState(STATE_NONE); 1692 TransitionToState(STATE_FINISH_HEADERS);
1666 return OK; 1693 return OK;
1667 } 1694 }
1668 1695
1669 if (handling_206_ && !CanResume(false)) { 1696 if (handling_206_ && !CanResume(false)) {
1670 // There is no point in storing this resource because it will never be used. 1697 // There is no point in storing this resource because it will never be used.
1671 // This may change if we support LOAD_ONLY_FROM_CACHE with sparse entries. 1698 // This may change if we support LOAD_ONLY_FROM_CACHE with sparse entries.
1672 DoneWritingToEntry(false); 1699 DoneWritingToEntry(false);
1673 if (partial_) 1700 if (partial_)
1674 partial_->FixResponseHeaders(response_.headers.get(), true); 1701 partial_->FixResponseHeaders(response_.headers.get(), true);
1675 TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); 1702 TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED);
1676 return OK; 1703 return OK;
1677 } 1704 }
1678 1705
1679 TransitionToState(STATE_CACHE_WRITE_RESPONSE); 1706 TransitionToState(STATE_CACHE_WRITE_RESPONSE);
1680 return OK; 1707 return OK;
1681 } 1708 }
1682 1709
1683 int HttpCache::Transaction::DoCacheWriteResponse() { 1710 int HttpCache::Transaction::DoCacheWriteResponse() {
1684 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteResponse"); 1711 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteResponse");
1685 TransitionToState(STATE_CACHE_WRITE_RESPONSE_COMPLETE); 1712 TransitionToState(STATE_CACHE_WRITE_RESPONSE_COMPLETE);
1713
1714 // Invalidate any current entry with a successful response if this transaction
1715 // cannot write to this entry. This transaction then continues to read from
1716 // the network without writing to the backend.
1717 bool is_match = response_.headers->response_code() == 304;
1718 if (entry_ && response_.headers &&
1719 !cache_->CanTransactionWriteResponseHeaders(entry_, this, is_match)) {
1720 cache_->DoneWritingToEntry(entry_, false, this);
1721 entry_ = nullptr;
1722 mode_ = NONE;
1723 return OK;
1724 }
1725
1686 return WriteResponseInfoToEntry(truncated_); 1726 return WriteResponseInfoToEntry(truncated_);
1687 } 1727 }
1688 1728
1689 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result) { 1729 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result) {
1690 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteResponseComplete"); 1730 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteResponseComplete");
1691 TransitionToState(STATE_TRUNCATE_CACHED_DATA); 1731 TransitionToState(STATE_TRUNCATE_CACHED_DATA);
1692 return OnWriteResponseInfoToEntryComplete(result); 1732 return OnWriteResponseInfoToEntryComplete(result);
1693 } 1733 }
1694 1734
1695 int HttpCache::Transaction::DoTruncateCachedData() { 1735 int HttpCache::Transaction::DoTruncateCachedData() {
(...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after
1737 } 1777 }
1738 1778
1739 TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); 1779 TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED);
1740 return OK; 1780 return OK;
1741 } 1781 }
1742 1782
1743 int HttpCache::Transaction::DoPartialHeadersReceived() { 1783 int HttpCache::Transaction::DoPartialHeadersReceived() {
1744 new_response_ = NULL; 1784 new_response_ = NULL;
1745 1785
1746 if (!partial_) { 1786 if (!partial_) {
1747 if (entry_ && entry_->disk_entry->GetDataSize(kMetadataIndex)) 1787 if (entry_ && entry_->GetDataSize(kMetadataIndex, this)) {
1748 TransitionToState(STATE_CACHE_READ_METADATA); 1788 TransitionToState(STATE_CACHE_READ_METADATA);
1749 else 1789 } else {
1750 TransitionToState(STATE_NONE); 1790 DCHECK(!reading_);
1791 TransitionToState(STATE_FINISH_HEADERS);
1792 }
1751 return OK; 1793 return OK;
1752 } 1794 }
1753 1795
1754 if (reading_) { 1796 if (reading_) {
1755 if (network_trans_.get()) { 1797 if (network_trans_.get()) {
1756 TransitionToState(STATE_NETWORK_READ); 1798 TransitionToState(STATE_NETWORK_READ);
1757 } else { 1799 } else {
1758 TransitionToState(STATE_CACHE_READ_DATA); 1800 TransitionToState(STATE_CACHE_READ_DATA);
1759 } 1801 }
1760 } else if (mode_ != NONE) { 1802 } else if (mode_ != NONE) {
1761 // We are about to return the headers for a byte-range request to the user, 1803 // We are about to return the headers for a byte-range request to the user,
1762 // so let's fix them. 1804 // so let's fix them.
1763 partial_->FixResponseHeaders(response_.headers.get(), true); 1805 partial_->FixResponseHeaders(response_.headers.get(), true);
1764 TransitionToState(STATE_NONE); 1806 TransitionToState(STATE_FINISH_HEADERS);
1765 } else { 1807 } else {
1766 TransitionToState(STATE_NONE); 1808 TransitionToState(STATE_FINISH_HEADERS);
1767 } 1809 }
1768 return OK; 1810 return OK;
1769 } 1811 }
1770 1812
1813 int HttpCache::Transaction::DoHeadersPhaseCannotProceed() {
1814 // If its the Start state machine and it cannot proceed due to a cache
1815 // failure, restart this transaction.
1816 DCHECK(!reading_);
1817 TransitionToState(STATE_INIT_ENTRY);
1818 cache_entry_status_ = CacheEntryStatus::ENTRY_UNDEFINED;
1819 entry_ = nullptr;
1820 mode_ = original_mode_;
1821 if (network_trans_)
1822 network_trans_.reset();
1823 return OK;
1824 }
1825
1826 int HttpCache::Transaction::DoFinishHeaders(int result) {
1827 if (!entry_ || result != OK) {
1828 TransitionToState(STATE_NONE);
1829 return result;
1830 }
1831
1832 TransitionToState(STATE_FINISH_HEADERS_COMPLETE);
1833
1834 // If it was an auth failure or 416, this transaction should continue to be
1835 // headers_transaction till consumer takes an action, so no need to do
1836 // anything now.
1837 if (auth_response_.headers.get() ||
1838 (new_response_ && new_response_->headers &&
1839 new_response_->headers->response_code() == 416))
1840 return OK;
1841
1842 // If there is no response body to be written or read, it does not need to
1843 // wait.
1844 if (request_->method == "HEAD")
1845 return OK;
1846
1847 // If the transaction needs to wait because another transaction is still
1848 // writing the response body, it will return ERR_IO_PENDING now and the
1849 // io_callback_ will be invoked when the wait is done.
1850 return cache_->DoneWithResponseHeaders(entry_, this);
1851 }
1852
1853 int HttpCache::Transaction::DoFinishHeadersComplete(int rv) {
1854 if (rv == ERR_CACHE_RACE) {
1855 TransitionToState(STATE_HEADERS_PHASE_CANNOT_PROCEED);
1856 return OK;
1857 }
1858
1859 TransitionToState(STATE_NONE);
1860 return rv;
1861 }
1862
1771 int HttpCache::Transaction::DoCacheReadMetadata() { 1863 int HttpCache::Transaction::DoCacheReadMetadata() {
1772 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadMetadata"); 1864 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadMetadata");
1773 DCHECK(entry_); 1865 DCHECK(entry_);
1774 DCHECK(!response_.metadata.get()); 1866 DCHECK(!response_.metadata.get());
1775 TransitionToState(STATE_CACHE_READ_METADATA_COMPLETE); 1867 TransitionToState(STATE_CACHE_READ_METADATA_COMPLETE);
1776 1868
1777 response_.metadata = 1869 response_.metadata =
1778 new IOBufferWithSize(entry_->disk_entry->GetDataSize(kMetadataIndex)); 1870 new IOBufferWithSize(entry_->GetDataSize(kMetadataIndex, this));
1779 1871
1780 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_READ_INFO); 1872 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_READ_INFO);
1781 return entry_->disk_entry->ReadData(kMetadataIndex, 0, 1873 return entry_->disk_entry->ReadData(kMetadataIndex, 0,
1782 response_.metadata.get(), 1874 response_.metadata.get(),
1783 response_.metadata->size(), 1875 response_.metadata->size(),
1784 io_callback_); 1876 io_callback_);
1785 } 1877 }
1786 1878
1787 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result) { 1879 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result) {
1788 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadMetadataComplete"); 1880 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheReadMetadataComplete");
1789 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_READ_INFO, 1881 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_READ_INFO,
1790 result); 1882 result);
1791 if (result != response_.metadata->size()) 1883 if (result != response_.metadata->size())
1792 return OnCacheReadError(result, false); 1884 return OnCacheReadError(result, false);
1793 TransitionToState(STATE_NONE); 1885
1886 TransitionToState(STATE_FINISH_HEADERS);
1794 return OK; 1887 return OK;
1795 } 1888 }
1796 1889
1797 int HttpCache::Transaction::DoNetworkRead() { 1890 int HttpCache::Transaction::DoNetworkRead() {
1798 TRACE_EVENT0("io", "HttpCacheTransaction::DoNetworkRead"); 1891 TRACE_EVENT0("io", "HttpCacheTransaction::DoNetworkRead");
1799 TransitionToState(STATE_NETWORK_READ_COMPLETE); 1892 TransitionToState(STATE_NETWORK_READ_COMPLETE);
1800 return network_trans_->Read(read_buf_.get(), io_buf_len_, io_callback_); 1893 return network_trans_->Read(read_buf_.get(), io_buf_len_, io_callback_);
1801 } 1894 }
1802 1895
1803 int HttpCache::Transaction::DoNetworkReadComplete(int result) { 1896 int HttpCache::Transaction::DoNetworkReadComplete(int result) {
(...skipping 77 matching lines...) Expand 10 before | Expand all | Expand 10 after
1881 TransitionToState(STATE_CACHE_WRITE_DATA_COMPLETE); 1974 TransitionToState(STATE_CACHE_WRITE_DATA_COMPLETE);
1882 write_len_ = num_bytes; 1975 write_len_ = num_bytes;
1883 if (entry_) { 1976 if (entry_) {
1884 if (net_log_.IsCapturing()) 1977 if (net_log_.IsCapturing())
1885 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_WRITE_DATA); 1978 net_log_.BeginEvent(NetLogEventType::HTTP_CACHE_WRITE_DATA);
1886 } 1979 }
1887 1980
1888 if (!entry_ || !num_bytes) 1981 if (!entry_ || !num_bytes)
1889 return num_bytes; 1982 return num_bytes;
1890 1983
1891 int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex); 1984 int current_size = entry_->GetDataSize(kResponseContentIndex, this);
1892 return WriteToEntry(kResponseContentIndex, current_size, read_buf_.get(), 1985 return WriteToEntry(kResponseContentIndex, current_size, read_buf_.get(),
1893 num_bytes, io_callback_); 1986 num_bytes, io_callback_);
1894 } 1987 }
1895 1988
1896 int HttpCache::Transaction::DoCacheWriteDataComplete(int result) { 1989 int HttpCache::Transaction::DoCacheWriteDataComplete(int result) {
1897 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteDataComplete"); 1990 TRACE_EVENT0("io", "HttpCacheTransaction::DoCacheWriteDataComplete");
1898 if (entry_) { 1991 if (entry_) {
1899 if (net_log_.IsCapturing()) { 1992 if (net_log_.IsCapturing()) {
1900 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_WRITE_DATA, 1993 net_log_.EndEventWithNetErrorCode(NetLogEventType::HTTP_CACHE_WRITE_DATA,
1901 result); 1994 result);
1902 } 1995 }
1903 } 1996 }
1904 if (!cache_.get()) { 1997 if (!cache_.get()) {
1905 TransitionToState(STATE_NONE); 1998 TransitionToState(STATE_NONE);
1906 return ERR_UNEXPECTED; 1999 return ERR_UNEXPECTED;
1907 } 2000 }
1908 2001
1909 if (result != write_len_) { 2002 if (result != write_len_) {
1910 DLOG(ERROR) << "failed to write response data to cache"; 2003 DLOG(ERROR) << "failed to write response data to cache";
1911 DoneWritingToEntry(false); 2004 DoneWritingToEntry(false);
1912 2005
1913 // We want to ignore errors writing to disk and just keep reading from 2006 // We want to ignore errors writing to disk and just keep reading from
1914 // the network. 2007 // the network.
1915 result = write_len_; 2008 result = write_len_;
1916 } else if (!done_reading_ && entry_ && (!partial_ || truncated_)) { 2009 } else if (!done_reading_ && entry_ && (!partial_ || truncated_)) {
1917 int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex); 2010 int current_size = entry_->GetDataSize(kResponseContentIndex, this);
1918 int64_t body_size = response_.headers->GetContentLength(); 2011 int64_t body_size = response_.headers->GetContentLength();
1919 if (body_size >= 0 && body_size <= current_size) 2012 if (body_size >= 0 && body_size <= current_size)
1920 done_reading_ = true; 2013 done_reading_ = true;
1921 } 2014 }
1922 2015
1923 if (partial_) { 2016 if (partial_) {
1924 // This may be the last request. 2017 // This may be the last request.
1925 if (result != 0 || truncated_ || 2018 if (result != 0 || truncated_ ||
1926 !(partial_->IsLastRange() || mode_ == WRITE)) { 2019 !(partial_->IsLastRange() || mode_ == WRITE)) {
1927 return DoPartialNetworkReadCompleted(result); 2020 return DoPartialNetworkReadCompleted(result);
(...skipping 152 matching lines...) Expand 10 before | Expand all | Expand 10 after
2080 return false; 2173 return false;
2081 2174
2082 return true; 2175 return true;
2083 } 2176 }
2084 2177
2085 int HttpCache::Transaction::BeginCacheRead() { 2178 int HttpCache::Transaction::BeginCacheRead() {
2086 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges. 2179 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
2087 // TODO(jkarlin): Either handle this case or DCHECK. 2180 // TODO(jkarlin): Either handle this case or DCHECK.
2088 if (response_.headers->response_code() == 206 || partial_) { 2181 if (response_.headers->response_code() == 206 || partial_) {
2089 NOTREACHED(); 2182 NOTREACHED();
2090 TransitionToState(STATE_NONE); 2183 TransitionToState(STATE_FINISH_HEADERS);
2091 return ERR_CACHE_MISS; 2184 return ERR_CACHE_MISS;
2092 } 2185 }
2093 2186
2094 // We don't have the whole resource. 2187 // We don't have the whole resource.
2095 if (truncated_) { 2188 if (truncated_) {
2096 TransitionToState(STATE_NONE); 2189 TransitionToState(STATE_FINISH_HEADERS);
2097 return ERR_CACHE_MISS; 2190 return ERR_CACHE_MISS;
2098 } 2191 }
2099 2192
2100 if (RequiresValidation()) { 2193 if (RequiresValidation()) {
2101 TransitionToState(STATE_NONE); 2194 TransitionToState(STATE_FINISH_HEADERS);
2102 return ERR_CACHE_MISS; 2195 return ERR_CACHE_MISS;
2103 } 2196 }
2104 2197
2105 if (request_->method == "HEAD") 2198 if (request_->method == "HEAD")
2106 FixHeadersForHead(); 2199 FixHeadersForHead();
2107 2200
2108 if (entry_->disk_entry->GetDataSize(kMetadataIndex)) 2201 if (entry_->GetDataSize(kMetadataIndex, this))
2109 TransitionToState(STATE_CACHE_READ_METADATA); 2202 TransitionToState(STATE_CACHE_READ_METADATA);
2110 else 2203 else
2111 TransitionToState(STATE_NONE); 2204 TransitionToState(STATE_FINISH_HEADERS);
2112 2205
2113 return OK; 2206 return OK;
2114 } 2207 }
2115 2208
2116 int HttpCache::Transaction::BeginCacheValidation() { 2209 int HttpCache::Transaction::BeginCacheValidation() {
2117 DCHECK_EQ(mode_, READ_WRITE); 2210 DCHECK_EQ(mode_, READ_WRITE);
2118 2211
2119 bool skip_validation = !RequiresValidation(); 2212 bool skip_validation = !RequiresValidation();
2120 2213
2121 if (request_->method == "HEAD" && 2214 if (request_->method == "HEAD" &&
(...skipping 439 matching lines...) Expand 10 before | Expand all | Expand 10 after
2561 if (partial_) { 2654 if (partial_) {
2562 if (truncated_ || is_sparse_ || !invalid_range_) { 2655 if (truncated_ || is_sparse_ || !invalid_range_) {
2563 // We are going to return the saved response headers to the caller, so 2656 // We are going to return the saved response headers to the caller, so
2564 // we may need to adjust them first. 2657 // we may need to adjust them first.
2565 TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED); 2658 TransitionToState(STATE_PARTIAL_HEADERS_RECEIVED);
2566 return OK; 2659 return OK;
2567 } else { 2660 } else {
2568 partial_.reset(); 2661 partial_.reset();
2569 } 2662 }
2570 } 2663 }
2571 cache_->ConvertWriterToReader(entry_); 2664
2572 mode_ = READ; 2665 mode_ = READ;
2573 2666
2574 if (request_->method == "HEAD") 2667 if (request_->method == "HEAD")
2575 FixHeadersForHead(); 2668 FixHeadersForHead();
2576 2669
2577 if (entry_->disk_entry->GetDataSize(kMetadataIndex)) 2670 if (entry_->GetDataSize(kMetadataIndex, this))
2578 TransitionToState(STATE_CACHE_READ_METADATA); 2671 TransitionToState(STATE_CACHE_READ_METADATA);
2579 else 2672 else
2580 TransitionToState(STATE_NONE); 2673 TransitionToState(STATE_FINISH_HEADERS);
2581 return OK; 2674 return OK;
2582 } 2675 }
2583 2676
2584 int HttpCache::Transaction::WriteToEntry(int index, int offset, 2677 int HttpCache::Transaction::WriteToEntry(int index, int offset,
2585 IOBuffer* data, int data_len, 2678 IOBuffer* data, int data_len,
2586 const CompletionCallback& callback) { 2679 const CompletionCallback& callback) {
2587 if (!entry_) 2680 if (!entry_)
2588 return data_len; 2681 return data_len;
2589 2682
2590 int rv = 0; 2683 int rv = 0;
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
2649 } 2742 }
2650 return OK; 2743 return OK;
2651 } 2744 }
2652 2745
2653 void HttpCache::Transaction::DoneWritingToEntry(bool success) { 2746 void HttpCache::Transaction::DoneWritingToEntry(bool success) {
2654 if (!entry_) 2747 if (!entry_)
2655 return; 2748 return;
2656 2749
2657 RecordHistograms(); 2750 RecordHistograms();
2658 2751
2659 cache_->DoneWritingToEntry(entry_, success); 2752 cache_->DoneWritingToEntry(entry_, success, this);
2660 entry_ = NULL; 2753 entry_ = NULL;
2661 mode_ = NONE; // switch to 'pass through' mode 2754 mode_ = NONE; // switch to 'pass through' mode
2662 } 2755 }
2663 2756
2664 int HttpCache::Transaction::OnCacheReadError(int result, bool restart) { 2757 int HttpCache::Transaction::OnCacheReadError(int result, bool restart) {
2665 DLOG(ERROR) << "ReadData failed: " << result; 2758 DLOG(ERROR) << "ReadData failed: " << result;
2666 const int result_for_histogram = std::max(0, -result); 2759 const int result_for_histogram = std::max(0, -result);
2667 if (restart) { 2760 if (restart) {
2668 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable", 2761 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2669 result_for_histogram); 2762 result_for_histogram);
(...skipping 124 matching lines...) Expand 10 before | Expand all | Expand 10 after
2794 // Last-Modified................ 49% 2887 // Last-Modified................ 49%
2795 // Etag......................... 19% 2888 // Etag......................... 19%
2796 // Accept-Ranges: bytes......... 25% 2889 // Accept-Ranges: bytes......... 25%
2797 // Accept-Ranges: none.......... 0.4% 2890 // Accept-Ranges: none.......... 0.4%
2798 // Strong Validator............. 50% 2891 // Strong Validator............. 50%
2799 // Strong Validator + ranges.... 24% 2892 // Strong Validator + ranges.... 24%
2800 // Strong Validator + CL........ 49% 2893 // Strong Validator + CL........ 49%
2801 // 2894 //
2802 bool HttpCache::Transaction::CanResume(bool has_data) { 2895 bool HttpCache::Transaction::CanResume(bool has_data) {
2803 // Double check that there is something worth keeping. 2896 // Double check that there is something worth keeping.
2804 if (has_data && !entry_->disk_entry->GetDataSize(kResponseContentIndex)) 2897 if (has_data && !entry_->GetDataSize(kResponseContentIndex, this))
2805 return false; 2898 return false;
2806 2899
2807 if (request_->method != "GET") 2900 if (request_->method != "GET")
2808 return false; 2901 return false;
2809 2902
2810 // Note that if this is a 206, content-length was already fixed after calling 2903 // Note that if this is a 206, content-length was already fixed after calling
2811 // PartialData::ResponseHeadersOK(). 2904 // PartialData::ResponseHeadersOK().
2812 if (response_.headers->GetContentLength() <= 0 || 2905 if (response_.headers->GetContentLength() <= 0 ||
2813 response_.headers->HasHeaderValue("Accept-Ranges", "none") || 2906 response_.headers->HasHeaderValue("Accept-Ranges", "none") ||
2814 !response_.headers->HasStrongValidators()) { 2907 !response_.headers->HasStrongValidators()) {
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after
2860 bool validation_request = 2953 bool validation_request =
2861 cache_entry_status_ == CacheEntryStatus::ENTRY_VALIDATED || 2954 cache_entry_status_ == CacheEntryStatus::ENTRY_VALIDATED ||
2862 cache_entry_status_ == CacheEntryStatus::ENTRY_UPDATED; 2955 cache_entry_status_ == CacheEntryStatus::ENTRY_UPDATED;
2863 2956
2864 bool stale_request = 2957 bool stale_request =
2865 validation_cause_ == VALIDATION_CAUSE_STALE && 2958 validation_cause_ == VALIDATION_CAUSE_STALE &&
2866 (validation_request || 2959 (validation_request ||
2867 cache_entry_status_ == CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE); 2960 cache_entry_status_ == CacheEntryStatus::ENTRY_CANT_CONDITIONALIZE);
2868 int64_t freshness_periods_since_last_used = 0; 2961 int64_t freshness_periods_since_last_used = 0;
2869 2962
2870 if (stale_request) { 2963 if (stale_request && !open_entry_last_used_.is_null()) {
2964 // Note that we are not able to capture those transactions' histograms which
2965 // when added to entry, the response was being written by another
2966 // transaction because getting the last used timestamp might lead to a data
2967 // race in that case. TODO(crbug.com/713354).
2968
2871 // For stale entries, record how many freshness periods have elapsed since 2969 // For stale entries, record how many freshness periods have elapsed since
2872 // the entry was last used. 2970 // the entry was last used.
2873 DCHECK(!open_entry_last_used_.is_null());
2874 DCHECK(!stale_entry_freshness_.is_zero()); 2971 DCHECK(!stale_entry_freshness_.is_zero());
2875 base::TimeDelta time_since_use = base::Time::Now() - open_entry_last_used_; 2972 base::TimeDelta time_since_use = base::Time::Now() - open_entry_last_used_;
2876 freshness_periods_since_last_used = 2973 freshness_periods_since_last_used =
2877 (time_since_use * 1000) / stale_entry_freshness_; 2974 (time_since_use * 1000) / stale_entry_freshness_;
2878 2975
2879 if (validation_request) { 2976 if (validation_request) {
2880 int64_t age_in_freshness_periods = 2977 int64_t age_in_freshness_periods =
2881 (stale_entry_age_ * 100) / stale_entry_freshness_; 2978 (stale_entry_age_ * 100) / stale_entry_freshness_;
2882 if (cache_entry_status_ == CacheEntryStatus::ENTRY_VALIDATED) { 2979 if (cache_entry_status_ == CacheEntryStatus::ENTRY_VALIDATED) {
2883 UMA_HISTOGRAM_COUNTS("HttpCache.StaleEntry.Validated.Age", 2980 UMA_HISTOGRAM_COUNTS("HttpCache.StaleEntry.Validated.Age",
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
3017 } 3114 }
3018 3115
3019 void HttpCache::Transaction::TransitionToState(State state) { 3116 void HttpCache::Transaction::TransitionToState(State state) {
3020 // Ensure that the state is only set once per Do* state. 3117 // Ensure that the state is only set once per Do* state.
3021 DCHECK(in_do_loop_); 3118 DCHECK(in_do_loop_);
3022 DCHECK_EQ(STATE_UNSET, next_state_) << "Next state is " << state; 3119 DCHECK_EQ(STATE_UNSET, next_state_) << "Next state is " << state;
3023 next_state_ = state; 3120 next_state_ = state;
3024 } 3121 }
3025 3122
3026 } // namespace net 3123 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698