forked from chromium/chromium
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp_cache.cc
1530 lines (1305 loc) · 52 KB
/
http_cache.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_cache.h"
#include <algorithm>
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/compiler_specific.h"
#include "base/feature_list.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/pickle.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/strcat.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/trace_event/memory_allocator_dump.h"
#include "base/trace_event/memory_usage_estimator.h"
#include "base/trace_event/process_memory_dump.h"
#include "net/base/cache_type.h"
#include "net/base/features.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/net_errors.h"
#include "net/base/upload_data_stream.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache_lookup_manager.h"
#include "net/http/http_cache_transaction.h"
#include "net/http/http_cache_writers.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_util.h"
#include "net/log/net_log_with_source.h"
#include "net/quic/quic_server_info.h"
#if defined(OS_POSIX)
#include <unistd.h>
#endif
namespace net {
namespace {
// True if any HTTP cache has been initialized.
bool g_init_cache = false;
// True if split cache is enabled by default. Must be set before any HTTP cache
// has been initialized.
bool g_enable_split_cache = false;
} // namespace
const char HttpCache::kDoubleKeyPrefix[] = "_dk_";
const char HttpCache::kDoubleKeySeparator[] = " ";
const char HttpCache::kSubframeDocumentResourcePrefix[] = "s_";
HttpCache::DefaultBackend::DefaultBackend(CacheType type,
BackendType backend_type,
const base::FilePath& path,
int max_bytes,
bool hard_reset)
: type_(type),
backend_type_(backend_type),
path_(path),
max_bytes_(max_bytes),
hard_reset_(hard_reset) {}
HttpCache::DefaultBackend::~DefaultBackend() = default;
// static
std::unique_ptr<HttpCache::BackendFactory> HttpCache::DefaultBackend::InMemory(
int max_bytes) {
return std::make_unique<DefaultBackend>(MEMORY_CACHE, CACHE_BACKEND_DEFAULT,
base::FilePath(), max_bytes, false);
}
int HttpCache::DefaultBackend::CreateBackend(
NetLog* net_log,
std::unique_ptr<disk_cache::Backend>* backend,
CompletionOnceCallback callback) {
DCHECK_GE(max_bytes_, 0);
disk_cache::ResetHandling reset_handling =
hard_reset_ ? disk_cache::ResetHandling::kReset
: disk_cache::ResetHandling::kResetOnError;
UMA_HISTOGRAM_BOOLEAN("HttpCache.HardReset", hard_reset_);
#if defined(OS_ANDROID)
if (app_status_listener_) {
return disk_cache::CreateCacheBackend(
type_, backend_type_, path_, max_bytes_, reset_handling, net_log,
backend, std::move(callback), app_status_listener_);
}
#endif
return disk_cache::CreateCacheBackend(type_, backend_type_, path_, max_bytes_,
reset_handling, net_log, backend,
std::move(callback));
}
#if defined(OS_ANDROID)
void HttpCache::DefaultBackend::SetAppStatusListener(
base::android::ApplicationStatusListener* app_status_listener) {
app_status_listener_ = app_status_listener;
}
#endif
//-----------------------------------------------------------------------------
HttpCache::ActiveEntry::ActiveEntry(disk_cache::Entry* entry, bool opened_in)
: disk_entry(entry), opened(opened_in) {}
HttpCache::ActiveEntry::~ActiveEntry() {
if (disk_entry) {
disk_entry->Close();
disk_entry = nullptr;
}
}
size_t HttpCache::ActiveEntry::EstimateMemoryUsage() const {
// Skip |disk_entry| which is tracked in simple_backend_impl; Skip |readers|
// and |add_to_entry_queue| because the Transactions are owned by their
// respective URLRequestHttpJobs.
return 0;
}
bool HttpCache::ActiveEntry::HasNoTransactions() {
return (!writers || writers->IsEmpty()) && readers.empty() &&
add_to_entry_queue.empty() && done_headers_queue.empty() &&
!headers_transaction;
}
bool HttpCache::ActiveEntry::SafeToDestroy() {
return HasNoTransactions() && !writers && !will_process_queued_transactions;
}
bool HttpCache::ActiveEntry::TransactionInReaders(
Transaction* transaction) const {
return readers.count(transaction) > 0;
}
//-----------------------------------------------------------------------------
// This structure keeps track of work items that are attempting to create or
// open cache entries or the backend itself.
struct HttpCache::PendingOp {
PendingOp()
: entry(nullptr), entry_opened(false), callback_will_delete(false) {}
~PendingOp() = default;
// Returns the estimate of dynamically allocated memory in bytes.
size_t EstimateMemoryUsage() const {
// Note that backend isn't counted because it doesn't provide an EMU
// function.
return base::trace_event::EstimateMemoryUsage(writer) +
base::trace_event::EstimateMemoryUsage(pending_queue);
}
disk_cache::Entry* entry;
bool entry_opened; // rather than created.
std::unique_ptr<disk_cache::Backend> backend;
std::unique_ptr<WorkItem> writer;
// True if there is a posted OnPendingOpComplete() task that might delete
// |this| without removing it from |pending_ops_|. Note that since
// OnPendingOpComplete() is static, it will not get cancelled when HttpCache
// is destroyed.
bool callback_will_delete;
WorkItemList pending_queue;
};
//-----------------------------------------------------------------------------
// A work item encapsulates a single request to the backend with all the
// information needed to complete that request.
class HttpCache::WorkItem {
public:
WorkItem(WorkItemOperation operation,
Transaction* transaction,
ActiveEntry** entry)
: operation_(operation),
transaction_(transaction),
entry_(entry),
backend_(nullptr) {}
WorkItem(WorkItemOperation operation,
Transaction* transaction,
CompletionOnceCallback callback,
disk_cache::Backend** backend)
: operation_(operation),
transaction_(transaction),
entry_(nullptr),
callback_(std::move(callback)),
backend_(backend) {}
~WorkItem() = default;
// Calls back the transaction with the result of the operation.
void NotifyTransaction(int result, ActiveEntry* entry) {
DCHECK(!entry || entry->disk_entry);
if (entry_)
*entry_ = entry;
if (transaction_)
transaction_->io_callback().Run(result);
}
// Notifies the caller about the operation completion. Returns true if the
// callback was invoked.
bool DoCallback(int result, disk_cache::Backend* backend) {
if (backend_)
*backend_ = backend;
if (!callback_.is_null()) {
std::move(callback_).Run(result);
return true;
}
return false;
}
WorkItemOperation operation() { return operation_; }
void ClearTransaction() { transaction_ = nullptr; }
void ClearEntry() { entry_ = nullptr; }
void ClearCallback() { callback_.Reset(); }
bool Matches(Transaction* transaction) const {
return transaction == transaction_;
}
bool IsValid() const {
return transaction_ || entry_ || !callback_.is_null();
}
// Returns the estimate of dynamically allocated memory in bytes.
size_t EstimateMemoryUsage() const { return 0; }
private:
WorkItemOperation operation_;
Transaction* transaction_;
ActiveEntry** entry_;
CompletionOnceCallback callback_; // User callback.
disk_cache::Backend** backend_;
};
//-----------------------------------------------------------------------------
HttpCache::HttpCache(HttpNetworkSession* session,
std::unique_ptr<BackendFactory> backend_factory,
bool is_main_cache)
: HttpCache(std::make_unique<HttpNetworkLayer>(session),
std::move(backend_factory),
is_main_cache) {
g_init_cache = true;
}
HttpCache::HttpCache(std::unique_ptr<HttpTransactionFactory> network_layer,
std::unique_ptr<BackendFactory> backend_factory,
bool is_main_cache)
: net_log_(nullptr),
backend_factory_(std::move(backend_factory)),
building_backend_(false),
bypass_lock_for_test_(false),
bypass_lock_after_headers_for_test_(false),
fail_conditionalization_for_test_(false),
mode_(NORMAL),
network_layer_(std::move(network_layer)),
clock_(base::DefaultClock::GetInstance()) {
g_init_cache = true;
HttpNetworkSession* session = network_layer_->GetSession();
// Session may be NULL in unittests.
// TODO(mmenke): Seems like tests could be changed to provide a session,
// rather than having logic only used in unit tests here.
if (!session)
return;
net_log_ = session->net_log();
if (!is_main_cache)
return;
session->SetServerPushDelegate(
std::make_unique<HttpCacheLookupManager>(this));
}
HttpCache::~HttpCache() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
// Transactions should see an invalid cache after this point; otherwise they
// could see an inconsistent object (half destroyed).
weak_factory_.InvalidateWeakPtrs();
// If we have any active entries remaining, then we need to deactivate them.
// We may have some pending tasks to process queued transactions ,but since
// those won't run (due to our destruction), we can simply ignore the
// corresponding flags.
while (!active_entries_.empty()) {
ActiveEntry* entry = active_entries_.begin()->second.get();
entry->will_process_queued_transactions = false;
entry->add_to_entry_queue.clear();
entry->readers.clear();
entry->done_headers_queue.clear();
entry->headers_transaction = nullptr;
entry->writers.reset();
DeactivateEntry(entry);
}
doomed_entries_.clear();
// Before deleting pending_ops_, we have to make sure that the disk cache is
// done with said operations, or it will attempt to use deleted data.
disk_cache_.reset();
for (auto pending_it = pending_ops_.begin(); pending_it != pending_ops_.end();
++pending_it) {
// We are not notifying the transactions about the cache going away, even
// though they are waiting for a callback that will never fire.
PendingOp* pending_op = pending_it->second;
pending_op->writer.reset();
bool delete_pending_op = true;
if (building_backend_ && pending_op->callback_will_delete) {
// If we don't have a backend, when its construction finishes it will
// deliver the callbacks.
delete_pending_op = false;
}
pending_op->pending_queue.clear();
if (delete_pending_op)
delete pending_op;
}
}
int HttpCache::GetBackend(disk_cache::Backend** backend,
CompletionOnceCallback callback) {
DCHECK(!callback.is_null());
if (disk_cache_.get()) {
*backend = disk_cache_.get();
return OK;
}
return CreateBackend(backend, std::move(callback));
}
disk_cache::Backend* HttpCache::GetCurrentBackend() const {
return disk_cache_.get();
}
// static
bool HttpCache::ParseResponseInfo(const char* data, int len,
HttpResponseInfo* response_info,
bool* response_truncated) {
base::Pickle pickle(data, len);
return response_info->InitFromPickle(pickle, response_truncated);
}
void HttpCache::CloseAllConnections(int net_error,
const char* net_log_reason_utf8) {
HttpNetworkSession* session = GetSession();
if (session)
session->CloseAllConnections(net_error, net_log_reason_utf8);
}
void HttpCache::CloseIdleConnections(const char* net_log_reason_utf8) {
HttpNetworkSession* session = GetSession();
if (session)
session->CloseIdleConnections(net_log_reason_utf8);
}
void HttpCache::OnExternalCacheHit(
const GURL& url,
const std::string& http_method,
const NetworkIsolationKey& network_isolation_key,
bool is_subframe_document_resource) {
if (!disk_cache_.get() || mode_ == DISABLE)
return;
HttpRequestInfo request_info;
request_info.url = url;
request_info.method = http_method;
request_info.network_isolation_key = network_isolation_key;
request_info.is_subframe_document_resource = is_subframe_document_resource;
std::string key = GenerateCacheKey(&request_info);
disk_cache_->OnExternalCacheHit(key);
}
int HttpCache::CreateTransaction(
RequestPriority priority,
std::unique_ptr<HttpTransaction>* transaction) {
// Do lazy initialization of disk cache if needed.
if (!disk_cache_.get()) {
// We don't care about the result.
CreateBackend(nullptr, CompletionOnceCallback());
}
HttpCache::Transaction* new_transaction =
new HttpCache::Transaction(priority, this);
if (bypass_lock_for_test_)
new_transaction->BypassLockForTest();
if (bypass_lock_after_headers_for_test_)
new_transaction->BypassLockAfterHeadersForTest();
if (fail_conditionalization_for_test_)
new_transaction->FailConditionalizationForTest();
transaction->reset(new_transaction);
return OK;
}
HttpCache* HttpCache::GetCache() {
return this;
}
HttpNetworkSession* HttpCache::GetSession() {
return network_layer_->GetSession();
}
std::unique_ptr<HttpTransactionFactory>
HttpCache::SetHttpNetworkTransactionFactoryForTesting(
std::unique_ptr<HttpTransactionFactory> new_network_layer) {
std::unique_ptr<HttpTransactionFactory> old_network_layer(
std::move(network_layer_));
network_layer_ = std::move(new_network_layer);
return old_network_layer;
}
void HttpCache::DumpMemoryStats(base::trace_event::ProcessMemoryDump* pmd,
const std::string& parent_absolute_name) const {
// Skip tracking members like |clock_| and |backend_factory_| because they
// don't allocate.
std::string name = parent_absolute_name + "/http_cache";
base::trace_event::MemoryAllocatorDump* dump = pmd->CreateAllocatorDump(name);
size_t size = base::trace_event::EstimateMemoryUsage(active_entries_) +
base::trace_event::EstimateMemoryUsage(doomed_entries_) +
base::trace_event::EstimateMemoryUsage(pending_ops_);
if (disk_cache_)
size += disk_cache_->DumpMemoryStats(pmd, name);
dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
base::trace_event::MemoryAllocatorDump::kUnitsBytes, size);
}
std::string HttpCache::GetResourceURLFromHttpCacheKey(const std::string& key) {
// Search the key to see whether it begins with |kDoubleKeyPrefix|. If so,
// then the entry was double-keyed.
if (base::StartsWith(key, kDoubleKeyPrefix, base::CompareCase::SENSITIVE)) {
// Find the rightmost occurrence of |kDoubleKeySeparator|, as when both
// the top-frame origin and the initiator are added to the key, there will
// be two occurrences of |kDoubleKeySeparator|. When the cache entry is
// originally written to disk, GenerateCacheKey method calls
// HttpUtil::SpecForRequest method, which has a DCHECK to ensure that
// the original resource url is valid, and hence will not contain the
// unescaped whitespace of |kDoubleKeySeparator|.
size_t separator_position = key.rfind(kDoubleKeySeparator);
DCHECK_NE(separator_position, std::string::npos);
size_t separator_size = strlen(kDoubleKeySeparator);
size_t start_position = separator_position + separator_size;
DCHECK_LE(start_position, key.size() - 1);
return key.substr(start_position);
}
return key;
}
// static
std::string HttpCache::GenerateCacheKeyForTest(const HttpRequestInfo* request) {
return GenerateCacheKey(request);
}
// static
void HttpCache::SplitCacheFeatureEnableByDefault() {
CHECK(!g_enable_split_cache && !g_init_cache);
if (!base::FeatureList::GetInstance()->IsFeatureOverridden(
"SplitCacheByNetworkIsolationKey")) {
g_enable_split_cache = true;
}
}
// static
bool HttpCache::IsSplitCacheEnabled() {
return base::FeatureList::IsEnabled(
features::kSplitCacheByNetworkIsolationKey) ||
g_enable_split_cache;
}
// static
void HttpCache::ClearGlobalsForTesting() {
// Reset these so that unit tests can work.
g_init_cache = false;
g_enable_split_cache = false;
}
//-----------------------------------------------------------------------------
net::Error HttpCache::CreateAndSetWorkItem(ActiveEntry** entry,
Transaction* transaction,
WorkItemOperation operation,
PendingOp* pending_op) {
auto item = std::make_unique<WorkItem>(operation, transaction, entry);
if (pending_op->writer) {
pending_op->pending_queue.push_back(std::move(item));
return ERR_IO_PENDING;
}
DCHECK(pending_op->pending_queue.empty());
pending_op->writer = std::move(item);
return OK;
}
int HttpCache::CreateBackend(disk_cache::Backend** backend,
CompletionOnceCallback callback) {
if (!backend_factory_.get())
return ERR_FAILED;
building_backend_ = true;
const bool callback_is_null = callback.is_null();
std::unique_ptr<WorkItem> item = std::make_unique<WorkItem>(
WI_CREATE_BACKEND, nullptr, std::move(callback), backend);
// This is the only operation that we can do that is not related to any given
// entry, so we use an empty key for it.
PendingOp* pending_op = GetPendingOp(std::string());
if (pending_op->writer) {
if (!callback_is_null)
pending_op->pending_queue.push_back(std::move(item));
return ERR_IO_PENDING;
}
DCHECK(pending_op->pending_queue.empty());
pending_op->writer = std::move(item);
int rv = backend_factory_->CreateBackend(
net_log_, &pending_op->backend,
base::BindOnce(&HttpCache::OnPendingOpComplete, GetWeakPtr(),
pending_op));
if (rv == ERR_IO_PENDING) {
pending_op->callback_will_delete = true;
return rv;
}
pending_op->writer->ClearCallback();
OnPendingOpComplete(GetWeakPtr(), pending_op, rv);
return rv;
}
int HttpCache::GetBackendForTransaction(Transaction* transaction) {
if (disk_cache_.get())
return OK;
if (!building_backend_)
return ERR_FAILED;
std::unique_ptr<WorkItem> item = std::make_unique<WorkItem>(
WI_CREATE_BACKEND, transaction, CompletionOnceCallback(), nullptr);
PendingOp* pending_op = GetPendingOp(std::string());
DCHECK(pending_op->writer);
pending_op->pending_queue.push_back(std::move(item));
return ERR_IO_PENDING;
}
// static
// Generate a key that can be used inside the cache.
std::string HttpCache::GenerateCacheKey(const HttpRequestInfo* request) {
std::string isolation_key;
if (IsSplitCacheEnabled()) {
// Prepend the key with |kDoubleKeyPrefix| = "_dk_" to mark it as
// double-keyed (and makes it an invalid url so that it doesn't get
// confused with a single-keyed entry). Separate the origin and url
// with invalid whitespace character |kDoubleKeySeparator|.
DCHECK(request->network_isolation_key.IsFullyPopulated());
std::string subframe_document_resource_prefix =
request->is_subframe_document_resource ? kSubframeDocumentResourcePrefix
: "";
isolation_key = base::StrCat(
{kDoubleKeyPrefix, subframe_document_resource_prefix,
request->network_isolation_key.ToString(), kDoubleKeySeparator});
}
// Strip out the reference, username, and password sections of the URL and
// concatenate with the network isolation key if we are splitting the cache.
std::string url = isolation_key + HttpUtil::SpecForRequest(request->url);
// No valid URL can begin with numerals, so we should not have to worry
// about collisions with normal URLs.
if (request->upload_data_stream &&
request->upload_data_stream->identifier()) {
url.insert(0,
base::StringPrintf("%" PRId64 "/",
request->upload_data_stream->identifier()));
}
return url;
}
void HttpCache::DoomActiveEntry(const std::string& key) {
auto it = active_entries_.find(key);
if (it == active_entries_.end())
return;
// This is not a performance critical operation, this is handling an error
// condition so it is OK to look up the entry again.
int rv = DoomEntry(key, nullptr);
DCHECK_EQ(OK, rv);
}
int HttpCache::DoomEntry(const std::string& key, Transaction* transaction) {
// Need to abandon the ActiveEntry, but any transaction attached to the entry
// should not be impacted. Dooming an entry only means that it will no
// longer be returned by FindActiveEntry (and it will also be destroyed once
// all consumers are finished with the entry).
auto it = active_entries_.find(key);
if (it == active_entries_.end()) {
DCHECK(transaction);
return AsyncDoomEntry(key, transaction);
}
std::unique_ptr<ActiveEntry> entry = std::move(it->second);
active_entries_.erase(it);
// We keep track of doomed entries so that we can ensure that they are
// cleaned up properly when the cache is destroyed.
ActiveEntry* entry_ptr = entry.get();
DCHECK_EQ(0u, doomed_entries_.count(entry_ptr));
doomed_entries_[entry_ptr] = std::move(entry);
entry_ptr->disk_entry->Doom();
entry_ptr->doomed = true;
DCHECK(!entry_ptr->SafeToDestroy());
return OK;
}
int HttpCache::AsyncDoomEntry(const std::string& key,
Transaction* transaction) {
PendingOp* pending_op = GetPendingOp(key);
int rv =
CreateAndSetWorkItem(nullptr, transaction, WI_DOOM_ENTRY, pending_op);
if (rv != OK)
return rv;
net::RequestPriority priority =
transaction ? transaction->priority() : net::LOWEST;
rv = disk_cache_->DoomEntry(key, priority,
base::BindOnce(&HttpCache::OnPendingOpComplete,
GetWeakPtr(), pending_op));
if (rv == ERR_IO_PENDING) {
pending_op->callback_will_delete = true;
return rv;
}
pending_op->writer->ClearTransaction();
OnPendingOpComplete(GetWeakPtr(), pending_op, rv);
return rv;
}
void HttpCache::DoomMainEntryForUrl(const GURL& url,
const NetworkIsolationKey& isolation_key,
bool is_subframe_document_resource) {
if (!disk_cache_)
return;
HttpRequestInfo temp_info;
temp_info.url = url;
temp_info.method = "GET";
temp_info.network_isolation_key = isolation_key;
temp_info.is_subframe_document_resource = is_subframe_document_resource;
std::string key = GenerateCacheKey(&temp_info);
// Defer to DoomEntry if there is an active entry, otherwise call
// AsyncDoomEntry without triggering a callback.
if (active_entries_.count(key))
DoomEntry(key, nullptr);
else
AsyncDoomEntry(key, nullptr);
}
void HttpCache::FinalizeDoomedEntry(ActiveEntry* entry) {
DCHECK(entry->doomed);
DCHECK(entry->SafeToDestroy());
auto it = doomed_entries_.find(entry);
DCHECK(it != doomed_entries_.end());
doomed_entries_.erase(it);
}
HttpCache::ActiveEntry* HttpCache::FindActiveEntry(const std::string& key) {
auto it = active_entries_.find(key);
return it != active_entries_.end() ? it->second.get() : nullptr;
}
HttpCache::ActiveEntry* HttpCache::ActivateEntry(disk_cache::Entry* disk_entry,
bool opened) {
DCHECK(!FindActiveEntry(disk_entry->GetKey()));
ActiveEntry* entry = new ActiveEntry(disk_entry, opened);
active_entries_[disk_entry->GetKey()] = base::WrapUnique(entry);
return entry;
}
void HttpCache::DeactivateEntry(ActiveEntry* entry) {
DCHECK(!entry->doomed);
DCHECK(entry->disk_entry);
DCHECK(entry->SafeToDestroy());
std::string key = entry->disk_entry->GetKey();
if (key.empty())
return SlowDeactivateEntry(entry);
auto it = active_entries_.find(key);
DCHECK(it != active_entries_.end());
DCHECK(it->second.get() == entry);
active_entries_.erase(it);
}
// We don't know this entry's key so we have to find it without it.
void HttpCache::SlowDeactivateEntry(ActiveEntry* entry) {
for (auto it = active_entries_.begin(); it != active_entries_.end(); ++it) {
if (it->second.get() == entry) {
active_entries_.erase(it);
break;
}
}
}
HttpCache::PendingOp* HttpCache::GetPendingOp(const std::string& key) {
DCHECK(!FindActiveEntry(key));
auto it = pending_ops_.find(key);
if (it != pending_ops_.end())
return it->second;
PendingOp* operation = new PendingOp();
pending_ops_[key] = operation;
return operation;
}
void HttpCache::DeletePendingOp(PendingOp* pending_op) {
std::string key;
if (pending_op->entry)
key = pending_op->entry->GetKey();
if (!key.empty()) {
auto it = pending_ops_.find(key);
DCHECK(it != pending_ops_.end());
pending_ops_.erase(it);
} else {
for (auto it = pending_ops_.begin(); it != pending_ops_.end(); ++it) {
if (it->second == pending_op) {
pending_ops_.erase(it);
break;
}
}
}
DCHECK(pending_op->pending_queue.empty());
delete pending_op;
}
int HttpCache::OpenOrCreateEntry(const std::string& key,
ActiveEntry** entry,
Transaction* transaction) {
DCHECK(!FindActiveEntry(key));
PendingOp* pending_op = GetPendingOp(key);
int rv = CreateAndSetWorkItem(entry, transaction, WI_OPEN_OR_CREATE_ENTRY,
pending_op);
if (rv != OK)
return rv;
disk_cache::EntryResult entry_result = disk_cache_->OpenOrCreateEntry(
key, transaction->priority(),
base::BindOnce(&HttpCache::OnPendingCreationOpComplete, GetWeakPtr(),
pending_op));
rv = entry_result.net_error();
if (rv == ERR_IO_PENDING) {
pending_op->callback_will_delete = true;
return ERR_IO_PENDING;
}
pending_op->writer->ClearTransaction();
OnPendingCreationOpComplete(GetWeakPtr(), pending_op,
std::move(entry_result));
return rv;
}
int HttpCache::OpenEntry(const std::string& key,
ActiveEntry** entry,
Transaction* transaction) {
DCHECK(!FindActiveEntry(key));
PendingOp* pending_op = GetPendingOp(key);
int rv = CreateAndSetWorkItem(entry, transaction, WI_OPEN_ENTRY, pending_op);
if (rv != OK)
return rv;
disk_cache::EntryResult entry_result = disk_cache_->OpenEntry(
key, transaction->priority(),
base::BindOnce(&HttpCache::OnPendingCreationOpComplete, GetWeakPtr(),
pending_op));
rv = entry_result.net_error();
if (rv == ERR_IO_PENDING) {
pending_op->callback_will_delete = true;
return ERR_IO_PENDING;
}
pending_op->writer->ClearTransaction();
OnPendingCreationOpComplete(GetWeakPtr(), pending_op,
std::move(entry_result));
return rv;
}
int HttpCache::CreateEntry(const std::string& key,
ActiveEntry** entry,
Transaction* transaction) {
if (FindActiveEntry(key)) {
return ERR_CACHE_RACE;
}
PendingOp* pending_op = GetPendingOp(key);
int rv =
CreateAndSetWorkItem(entry, transaction, WI_CREATE_ENTRY, pending_op);
if (rv != OK)
return rv;
disk_cache::EntryResult entry_result = disk_cache_->CreateEntry(
key, transaction->priority(),
base::BindOnce(&HttpCache::OnPendingCreationOpComplete, GetWeakPtr(),
pending_op));
rv = entry_result.net_error();
if (rv == ERR_IO_PENDING) {
pending_op->callback_will_delete = true;
return ERR_IO_PENDING;
}
pending_op->writer->ClearTransaction();
OnPendingCreationOpComplete(GetWeakPtr(), pending_op,
std::move(entry_result));
return rv;
}
void HttpCache::DestroyEntry(ActiveEntry* entry) {
if (entry->doomed) {
FinalizeDoomedEntry(entry);
} else {
DeactivateEntry(entry);
}
}
int HttpCache::AddTransactionToEntry(ActiveEntry* entry,
Transaction* transaction) {
DCHECK(entry);
DCHECK(entry->disk_entry);
// Always add a new transaction to the queue to maintain FIFO order.
entry->add_to_entry_queue.push_back(transaction);
ProcessQueuedTransactions(entry);
return ERR_IO_PENDING;
}
int HttpCache::DoneWithResponseHeaders(ActiveEntry* entry,
Transaction* transaction,
bool is_partial) {
// If |transaction| is the current writer, do nothing. This can happen for
// range requests since they can go back to headers phase after starting to
// write.
if (entry->writers && entry->writers->HasTransaction(transaction)) {
DCHECK(is_partial && entry->writers->GetTransactionsCount() == 1);
return OK;
}
DCHECK_EQ(entry->headers_transaction, transaction);
entry->headers_transaction = nullptr;
// If transaction is responsible for writing the response body, then do not go
// through done_headers_queue for performance benefit. (Also, in case of
// writer transaction, the consumer sometimes depend on synchronous behaviour
// e.g. while computing raw headers size. (crbug.com/711766))
if ((transaction->mode() & Transaction::WRITE) && !entry->writers &&
entry->readers.empty()) {
AddTransactionToWriters(entry, transaction,
CanTransactionJoinExistingWriters(transaction));
ProcessQueuedTransactions(entry);
return OK;
}
entry->done_headers_queue.push_back(transaction);
ProcessQueuedTransactions(entry);
return ERR_IO_PENDING;
}
void HttpCache::DoneWithEntry(ActiveEntry* entry,
Transaction* transaction,
bool entry_is_complete,
bool is_partial) {
bool is_mode_read_only = transaction->mode() == Transaction::READ;
if (!entry_is_complete && !is_mode_read_only && is_partial)
entry->disk_entry->CancelSparseIO();
// Transaction is waiting in the done_headers_queue.
auto it = std::find(entry->done_headers_queue.begin(),
entry->done_headers_queue.end(), transaction);
if (it != entry->done_headers_queue.end()) {
entry->done_headers_queue.erase(it);
// Restart other transactions if this transaction could have written
// response body.
if (!entry_is_complete && !is_mode_read_only)
ProcessEntryFailure(entry);
return;
}
// Transaction is removed in the headers phase.
if (transaction == entry->headers_transaction) {
entry->headers_transaction = nullptr;
if (entry_is_complete || is_mode_read_only) {
ProcessQueuedTransactions(entry);
} else {
// Restart other transactions if this transaction could have written
// response body.
ProcessEntryFailure(entry);
}
return;
}
// Transaction is removed in the writing phase.
if (entry->writers && entry->writers->HasTransaction(transaction)) {
entry->writers->RemoveTransaction(transaction,
entry_is_complete /* success */);
return;
}
// Transaction is reading from the entry.
DCHECK(!entry->writers);
auto readers_it = entry->readers.find(transaction);
DCHECK(readers_it != entry->readers.end());
entry->readers.erase(readers_it);
ProcessQueuedTransactions(entry);
}
void HttpCache::WritersDoomEntryRestartTransactions(ActiveEntry* entry) {
DCHECK(!entry->writers->IsEmpty());
ProcessEntryFailure(entry);
}
void HttpCache::WritersDoneWritingToEntry(ActiveEntry* entry,
bool success,
bool should_keep_entry,
TransactionSet make_readers) {
// Impacts the queued transactions in one of the following ways:
// - restart them but do not doom the entry since entry can be saved in
// its truncated form.
// - restart them and doom/destroy the entry since entry does not
// have valid contents.
// - let them continue by invoking their callback since entry is
// successfully written.
DCHECK(entry->writers);
DCHECK(entry->writers->IsEmpty());
DCHECK(success || make_readers.empty());
if (!success && should_keep_entry) {
// Restart already validated transactions so that they are able to read
// the truncated status of the entry.
RestartHeadersPhaseTransactions(entry);
entry->writers.reset();
if (entry->SafeToDestroy()) {
DestroyEntry(entry);
}
return;
}
if (success) {
// Add any idle writers to readers.
for (auto* reader : make_readers) {
reader->WriteModeTransactionAboutToBecomeReader();
entry->readers.insert(reader);
}
// Reset writers here so that WriteModeTransactionAboutToBecomeReader can
// access the network transaction.
entry->writers.reset();
ProcessQueuedTransactions(entry);
} else {
entry->writers.reset();
ProcessEntryFailure(entry);
}
}
void HttpCache::DoomEntryValidationNoMatch(ActiveEntry* entry) {
// Validating transaction received a non-matching response.