forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathManager.cpp
2127 lines (1731 loc) · 72.2 KB
/
Manager.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/dom/cache/Manager.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/Mutex.h"
#include "mozilla/StaticMutex.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/cache/Context.h"
#include "mozilla/dom/cache/DBAction.h"
#include "mozilla/dom/cache/DBSchema.h"
#include "mozilla/dom/cache/FileUtils.h"
#include "mozilla/dom/cache/ManagerId.h"
#include "mozilla/dom/cache/CacheTypes.h"
#include "mozilla/dom/cache/SavedTypes.h"
#include "mozilla/dom/cache/StreamList.h"
#include "mozilla/dom/cache/Types.h"
#include "mozilla/dom/quota/Client.h"
#include "mozilla/dom/quota/ClientImpl.h"
#include "mozilla/dom/quota/QuotaManager.h"
#include "mozilla/ipc/BackgroundParent.h"
#include "mozStorageHelper.h"
#include "nsIInputStream.h"
#include "nsID.h"
#include "nsIFile.h"
#include "nsIThread.h"
#include "nsThreadUtils.h"
#include "nsTObserverArray.h"
#include "QuotaClientImpl.h"
namespace mozilla::dom::cache {
using mozilla::dom::quota::Client;
using mozilla::dom::quota::CloneFileAndAppend;
using mozilla::dom::quota::DirectoryLock;
namespace {
/**
* Note: The aCommitHook argument will be invoked while a lock is held. Callers
* should be careful not to pass a hook that might lock on something else and
* trigger a deadlock.
*/
template <typename Callable>
nsresult MaybeUpdatePaddingFile(nsIFile* aBaseDir, mozIStorageConnection* aConn,
const int64_t aIncreaseSize,
const int64_t aDecreaseSize,
Callable aCommitHook) {
MOZ_ASSERT(!NS_IsMainThread());
MOZ_DIAGNOSTIC_ASSERT(aBaseDir);
MOZ_DIAGNOSTIC_ASSERT(aConn);
MOZ_DIAGNOSTIC_ASSERT(aIncreaseSize >= 0);
MOZ_DIAGNOSTIC_ASSERT(aDecreaseSize >= 0);
RefPtr<CacheQuotaClient> cacheQuotaClient = CacheQuotaClient::Get();
MOZ_DIAGNOSTIC_ASSERT(cacheQuotaClient);
QM_TRY(MOZ_TO_RESULT(cacheQuotaClient->MaybeUpdatePaddingFileInternal(
*aBaseDir, *aConn, aIncreaseSize, aDecreaseSize, aCommitHook)));
return NS_OK;
}
// An Action that is executed when a Context is first created. It ensures that
// the directory and database are setup properly. This lets other actions
// not worry about these details.
class SetupAction final : public SyncDBAction {
public:
SetupAction() : SyncDBAction(DBAction::Create) {}
virtual nsresult RunSyncWithDBOnTarget(
const CacheDirectoryMetadata& aDirectoryMetadata, nsIFile* aDBDir,
mozIStorageConnection* aConn) override {
MOZ_DIAGNOSTIC_ASSERT(aDBDir);
QM_TRY(MOZ_TO_RESULT(BodyCreateDir(*aDBDir)));
// executes in its own transaction
QM_TRY(MOZ_TO_RESULT(db::CreateOrMigrateSchema(*aConn)));
// If the Context marker file exists, then the last session was
// not cleanly shutdown. In these cases sqlite will ensure that
// the database is valid, but we might still orphan data. Both
// Cache objects and body files can be referenced by DOM objects
// after they are "removed" from their parent. So we need to
// look and see if any of these late access objects have been
// orphaned.
//
// Note, this must be done after any schema version updates to
// ensure our DBSchema methods work correctly.
if (MarkerFileExists(aDirectoryMetadata)) {
NS_WARNING("Cache not shutdown cleanly! Cleaning up stale data...");
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
QM_TRY(MOZ_TO_RESULT(trans.Start()));
// Clean up orphaned Cache objects
QM_TRY_INSPECT(const auto& orphanedCacheIdList,
db::FindOrphanedCacheIds(*aConn));
QM_TRY_INSPECT(
const CheckedInt64& overallDeletedPaddingSize,
Reduce(
orphanedCacheIdList, CheckedInt64(0),
[aConn, &aDirectoryMetadata, &aDBDir](
CheckedInt64 oldValue, const Maybe<const CacheId&>& element)
-> Result<CheckedInt64, nsresult> {
QM_TRY_INSPECT(const auto& deletionInfo,
db::DeleteCacheId(*aConn, *element));
QM_TRY(MOZ_TO_RESULT(
BodyDeleteFiles(aDirectoryMetadata, *aDBDir,
deletionInfo.mDeletedBodyIdList)));
if (deletionInfo.mDeletedPaddingSize > 0) {
DecreaseUsageForDirectoryMetadata(
aDirectoryMetadata, deletionInfo.mDeletedPaddingSize);
}
return oldValue + deletionInfo.mDeletedPaddingSize;
}));
// Clean up orphaned body objects
QM_TRY_INSPECT(const auto& knownBodyIdList, db::GetKnownBodyIds(*aConn));
QM_TRY(MOZ_TO_RESULT(BodyDeleteOrphanedFiles(aDirectoryMetadata, *aDBDir,
knownBodyIdList)));
// Commit() explicitly here, because we want to ensure the padding file
// has the correct content.
// We'll restore padding file below, so just warn here if failure happens.
//
// XXX Before, if MaybeUpdatePaddingFile failed but we didn't enter the if
// body below, we would have propagated the MaybeUpdatePaddingFile
// failure, but if we entered it and RestorePaddingFile succeeded, we
// would have returned NS_OK. Now, we will never propagate a
// MaybeUpdatePaddingFile failure.
QM_WARNONLY_TRY(QM_TO_RESULT(
MaybeUpdatePaddingFile(aDBDir, aConn, /* aIncreaceSize */ 0,
overallDeletedPaddingSize.value(),
[&trans]() { return trans.Commit(); })));
}
if (DirectoryPaddingFileExists(*aDBDir, DirPaddingFile::TMP_FILE) ||
!DirectoryPaddingFileExists(*aDBDir, DirPaddingFile::FILE)) {
QM_TRY(MOZ_TO_RESULT(RestorePaddingFile(aDBDir, aConn)));
}
return NS_OK;
}
};
// ----------------------------------------------------------------------------
// Action that is executed when we determine that content has stopped using
// a body file that has been orphaned.
class DeleteOrphanedBodyAction final : public Action {
public:
using DeletedBodyIdList = AutoTArray<nsID, 64>;
explicit DeleteOrphanedBodyAction(DeletedBodyIdList&& aDeletedBodyIdList)
: mDeletedBodyIdList(std::move(aDeletedBodyIdList)) {}
explicit DeleteOrphanedBodyAction(const nsID& aBodyId)
: mDeletedBodyIdList{aBodyId} {}
void RunOnTarget(SafeRefPtr<Resolver> aResolver,
const Maybe<CacheDirectoryMetadata>& aDirectoryMetadata,
Data*) override {
MOZ_DIAGNOSTIC_ASSERT(aResolver);
MOZ_DIAGNOSTIC_ASSERT(aDirectoryMetadata);
MOZ_DIAGNOSTIC_ASSERT(aDirectoryMetadata->mDir);
// Note that since DeleteOrphanedBodyAction isn't used while the context is
// being initialized, we don't need to check for cancellation here.
const auto resolve = [&aResolver](const nsresult rv) {
aResolver->Resolve(rv);
};
QM_TRY_INSPECT(const auto& dbDir,
CloneFileAndAppend(*aDirectoryMetadata->mDir, u"cache"_ns),
QM_VOID, resolve);
QM_TRY(MOZ_TO_RESULT(BodyDeleteFiles(*aDirectoryMetadata, *dbDir,
mDeletedBodyIdList)),
QM_VOID, resolve);
aResolver->Resolve(NS_OK);
}
private:
DeletedBodyIdList mDeletedBodyIdList;
};
bool IsHeadRequest(const CacheRequest& aRequest,
const CacheQueryParams& aParams) {
return !aParams.ignoreMethod() &&
aRequest.method().LowerCaseEqualsLiteral("head");
}
bool IsHeadRequest(const Maybe<CacheRequest>& aRequest,
const CacheQueryParams& aParams) {
if (aRequest.isSome()) {
return !aParams.ignoreMethod() &&
aRequest.ref().method().LowerCaseEqualsLiteral("head");
}
return false;
}
auto MatchByCacheId(CacheId aCacheId) {
return [aCacheId](const auto& entry) { return entry.mCacheId == aCacheId; };
}
auto MatchByBodyId(const nsID& aBodyId) {
return [&aBodyId](const auto& entry) { return entry.mBodyId == aBodyId; };
}
} // namespace
// ----------------------------------------------------------------------------
// Singleton class to track Manager instances and ensure there is only
// one for each unique ManagerId.
class Manager::Factory {
public:
friend class StaticAutoPtr<Manager::Factory>;
static Result<SafeRefPtr<Manager>, nsresult> AcquireCreateIfNonExistent(
const SafeRefPtr<ManagerId>& aManagerId) {
mozilla::ipc::AssertIsOnBackgroundThread();
// If we get here during/after quota manager shutdown, we bail out.
MOZ_ASSERT(AppShutdown::GetCurrentShutdownPhase() <
ShutdownPhase::AppShutdownQM);
if (AppShutdown::GetCurrentShutdownPhase() >=
ShutdownPhase::AppShutdownQM) {
NS_WARNING(
"Attempt to AcquireCreateIfNonExistent a Manager during QM "
"shutdown.");
return Err(NS_ERROR_ILLEGAL_DURING_SHUTDOWN);
}
// Ensure there is a factory instance. This forces the Acquire() call
// below to use the same factory.
QM_TRY(MOZ_TO_RESULT(MaybeCreateInstance()));
SafeRefPtr<Manager> ref = Acquire(*aManagerId);
if (!ref) {
// TODO: replace this with a thread pool (bug 1119864)
// XXX Can't use QM_TRY_INSPECT because that causes a clang-plugin
// error of the NoNewThreadsChecker.
nsCOMPtr<nsIThread> ioThread;
QM_TRY(MOZ_TO_RESULT(
NS_NewNamedThread("DOMCacheThread", getter_AddRefs(ioThread))));
ref = MakeSafeRefPtr<Manager>(aManagerId.clonePtr(), ioThread,
ConstructorGuard{});
// There may be an old manager for this origin in the process of
// cleaning up. We need to tell the new manager about this so
// that it won't actually start until the old manager is done.
const SafeRefPtr<Manager> oldManager = Acquire(*aManagerId, Closing);
ref->Init(oldManager.maybeDeref());
MOZ_ASSERT(!sFactory->mManagerList.Contains(ref));
sFactory->mManagerList.AppendElement(
WrapNotNullUnchecked(ref.unsafeGetRawPtr()));
}
return ref;
}
static void Remove(Manager& aManager) {
mozilla::ipc::AssertIsOnBackgroundThread();
MOZ_DIAGNOSTIC_ASSERT(sFactory);
MOZ_ALWAYS_TRUE(sFactory->mManagerList.RemoveElement(&aManager));
// This might both happen in late shutdown such that this event
// is executed even after the QuotaManager singleton passed away
// or if the QuotaManager has not yet been created.
quota::QuotaManager::SafeMaybeRecordQuotaClientShutdownStep(
quota::Client::DOMCACHE, "Manager removed"_ns);
// clean up the factory singleton if there are no more managers
MaybeDestroyInstance();
}
static void Abort(const Client::DirectoryLockIdTable& aDirectoryLockIds) {
mozilla::ipc::AssertIsOnBackgroundThread();
AbortMatching([&aDirectoryLockIds](const auto& manager) {
// Check if the Manager holds an acquired DirectoryLock. Origin clearing
// can't be blocked by this Manager if there is no acquired DirectoryLock.
// If there is an acquired DirectoryLock, check if the table contains the
// lock for the Manager.
return Client::IsLockForObjectAcquiredAndContainedInLockTable(
manager, aDirectoryLockIds);
});
}
static void AbortAll() {
mozilla::ipc::AssertIsOnBackgroundThread();
AbortMatching([](const auto&) { return true; });
}
static void ShutdownAll() {
mozilla::ipc::AssertIsOnBackgroundThread();
if (!sFactory) {
return;
}
MOZ_DIAGNOSTIC_ASSERT(!sFactory->mManagerList.IsEmpty());
{
// Note that we are synchronously calling shutdown code here. If any
// of the shutdown code synchronously decides to delete the Factory
// we need to delay that delete until the end of this method.
AutoRestore<bool> restore(sFactory->mInSyncAbortOrShutdown);
sFactory->mInSyncAbortOrShutdown = true;
for (const auto& manager : sFactory->mManagerList.ForwardRange()) {
auto pinnedManager =
SafeRefPtr{manager.get(), AcquireStrongRefFromRawPtr{}};
pinnedManager->Shutdown();
}
}
MaybeDestroyInstance();
}
static bool IsShutdownAllComplete() {
mozilla::ipc::AssertIsOnBackgroundThread();
return !sFactory;
}
#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
static void RecordMayNotDeleteCSCP(int32_t aCacheStreamControlParentId) {
if (sFactory) {
sFactory->mPotentiallyUnreleasedCSCP.AppendElement(
aCacheStreamControlParentId);
}
}
static void RecordHaveDeletedCSCP(int32_t aCacheStreamControlParentId) {
if (sFactory) {
sFactory->mPotentiallyUnreleasedCSCP.RemoveElement(
aCacheStreamControlParentId);
}
}
#endif
static nsCString GetShutdownStatus() {
mozilla::ipc::AssertIsOnBackgroundThread();
nsCString data;
if (sFactory && !sFactory->mManagerList.IsEmpty()) {
data.Append(
"Managers: "_ns +
IntToCString(static_cast<uint64_t>(sFactory->mManagerList.Length())) +
" ("_ns);
for (const auto& manager : sFactory->mManagerList.NonObservingRange()) {
data.Append(quota::AnonymizedOriginString(
manager->GetManagerId().QuotaOrigin()));
data.AppendLiteral(": ");
data.Append(manager->GetState() == State::Open ? "Open"_ns
: "Closing"_ns);
data.AppendLiteral(", ");
}
data.AppendLiteral(" ) ");
if (sFactory->mPotentiallyUnreleasedCSCP.Length() > 0) {
data.Append(
"There have been CSCP instances whose"
"Send__delete__ might not have freed them.");
}
}
return data;
}
private:
Factory() : mInSyncAbortOrShutdown(false) {
MOZ_COUNT_CTOR(cache::Manager::Factory);
}
~Factory() {
MOZ_COUNT_DTOR(cache::Manager::Factory);
MOZ_DIAGNOSTIC_ASSERT(mManagerList.IsEmpty());
MOZ_DIAGNOSTIC_ASSERT(!mInSyncAbortOrShutdown);
}
static nsresult MaybeCreateInstance() {
mozilla::ipc::AssertIsOnBackgroundThread();
if (!sFactory) {
// We cannot use ClearOnShutdown() here because we're not on the main
// thread. Instead, we delete sFactory in Factory::Remove() after the
// last manager is removed. ShutdownObserver ensures this happens
// before shutdown.
sFactory = new Factory();
}
// Never return sFactory to code outside Factory. We need to delete it
// out from under ourselves just before we return from Remove(). This
// would be (even more) dangerous if other code had a pointer to the
// factory itself.
return NS_OK;
}
static void MaybeDestroyInstance() {
mozilla::ipc::AssertIsOnBackgroundThread();
MOZ_DIAGNOSTIC_ASSERT(sFactory);
// If the factory is is still in use then we cannot delete yet. This
// could be due to managers still existing or because we are in the
// middle of aborting or shutting down. We need to be careful not to delete
// ourself synchronously during shutdown.
if (!sFactory->mManagerList.IsEmpty() || sFactory->mInSyncAbortOrShutdown) {
return;
}
sFactory = nullptr;
}
static SafeRefPtr<Manager> Acquire(const ManagerId& aManagerId,
State aState = Open) {
mozilla::ipc::AssertIsOnBackgroundThread();
QM_TRY(MOZ_TO_RESULT(MaybeCreateInstance()), nullptr);
// Iterate in reverse to find the most recent, matching Manager. This
// is important when looking for a Closing Manager. If a new Manager
// chains to an old Manager we want it to be the most recent one.
const auto range = Reversed(sFactory->mManagerList.NonObservingRange());
const auto foundIt = std::find_if(
range.begin(), range.end(), [aState, &aManagerId](const auto& manager) {
return aState == manager->GetState() &&
*manager->mManagerId == aManagerId;
});
return foundIt != range.end()
? SafeRefPtr{foundIt->get(), AcquireStrongRefFromRawPtr{}}
: nullptr;
}
template <typename Condition>
static void AbortMatching(const Condition& aCondition) {
mozilla::ipc::AssertIsOnBackgroundThread();
if (!sFactory) {
return;
}
MOZ_DIAGNOSTIC_ASSERT(!sFactory->mManagerList.IsEmpty());
{
// Note that we are synchronously calling abort code here. If any
// of the shutdown code synchronously decides to delete the Factory
// we need to delay that delete until the end of this method.
AutoRestore<bool> restore(sFactory->mInSyncAbortOrShutdown);
sFactory->mInSyncAbortOrShutdown = true;
for (const auto& manager : sFactory->mManagerList.ForwardRange()) {
if (aCondition(*manager)) {
auto pinnedManager =
SafeRefPtr{manager.get(), AcquireStrongRefFromRawPtr{}};
pinnedManager->Abort();
}
}
}
MaybeDestroyInstance();
}
// Singleton created on demand and deleted when last Manager is cleared
// in Remove().
// PBackground thread only.
static StaticAutoPtr<Factory> sFactory;
// Weak references as we don't want to keep Manager objects alive forever.
// When a Manager is destroyed it calls Factory::Remove() to clear itself.
// PBackground thread only.
nsTObserverArray<NotNull<Manager*>> mManagerList;
// This flag is set when we are looping through the list and calling Abort()
// or Shutdown() on each Manager. We need to be careful not to synchronously
// trigger the deletion of the factory while still executing this loop.
bool mInSyncAbortOrShutdown;
nsTArray<int32_t> mPotentiallyUnreleasedCSCP;
};
// static
StaticAutoPtr<Manager::Factory> Manager::Factory::sFactory;
// ----------------------------------------------------------------------------
// Abstract class to help implement the various Actions. The vast majority
// of Actions are synchronous and need to report back to a Listener on the
// Manager.
class Manager::BaseAction : public SyncDBAction {
protected:
BaseAction(SafeRefPtr<Manager> aManager, ListenerId aListenerId)
: SyncDBAction(DBAction::Existing),
mManager(std::move(aManager)),
mListenerId(aListenerId) {}
virtual void Complete(Listener* aListener, ErrorResult&& aRv) = 0;
virtual void CompleteOnInitiatingThread(nsresult aRv) override {
NS_ASSERT_OWNINGTHREAD(Manager::BaseAction);
Listener* listener = mManager->GetListener(mListenerId);
if (listener) {
Complete(listener, ErrorResult(aRv));
}
// ensure we release the manager on the initiating thread
mManager = nullptr;
}
SafeRefPtr<Manager> mManager;
const ListenerId mListenerId;
};
// ----------------------------------------------------------------------------
// Action that is executed when we determine that content has stopped using
// a Cache object that has been orphaned.
class Manager::DeleteOrphanedCacheAction final : public SyncDBAction {
public:
DeleteOrphanedCacheAction(SafeRefPtr<Manager> aManager, CacheId aCacheId)
: SyncDBAction(DBAction::Existing),
mManager(std::move(aManager)),
mCacheId(aCacheId) {}
virtual nsresult RunSyncWithDBOnTarget(
const CacheDirectoryMetadata& aDirectoryMetadata, nsIFile* aDBDir,
mozIStorageConnection* aConn) override {
mDirectoryMetadata.emplace(aDirectoryMetadata);
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
QM_TRY(MOZ_TO_RESULT(trans.Start()));
QM_TRY_UNWRAP(mDeletionInfo, db::DeleteCacheId(*aConn, mCacheId));
QM_TRY(MOZ_TO_RESULT(MaybeUpdatePaddingFile(
aDBDir, aConn, /* aIncreaceSize */ 0, mDeletionInfo.mDeletedPaddingSize,
[&trans]() mutable { return trans.Commit(); })));
return NS_OK;
}
virtual void CompleteOnInitiatingThread(nsresult aRv) override {
// If the transaction fails, we shouldn't delete the body files and decrease
// their padding size.
if (NS_FAILED(aRv)) {
mDeletionInfo.mDeletedBodyIdList.Clear();
mDeletionInfo.mDeletedPaddingSize = 0;
}
mManager->NoteOrphanedBodyIdList(mDeletionInfo.mDeletedBodyIdList);
if (mDeletionInfo.mDeletedPaddingSize > 0) {
DecreaseUsageForDirectoryMetadata(*mDirectoryMetadata,
mDeletionInfo.mDeletedPaddingSize);
}
// ensure we release the manager on the initiating thread
mManager = nullptr;
}
private:
SafeRefPtr<Manager> mManager;
const CacheId mCacheId;
DeletionInfo mDeletionInfo;
Maybe<CacheDirectoryMetadata> mDirectoryMetadata;
};
// ----------------------------------------------------------------------------
class Manager::CacheMatchAction final : public Manager::BaseAction {
public:
CacheMatchAction(SafeRefPtr<Manager> aManager, ListenerId aListenerId,
CacheId aCacheId, const CacheMatchArgs& aArgs,
SafeRefPtr<StreamList> aStreamList)
: BaseAction(std::move(aManager), aListenerId),
mCacheId(aCacheId),
mArgs(aArgs),
mStreamList(std::move(aStreamList)),
mFoundResponse(false) {}
virtual nsresult RunSyncWithDBOnTarget(
const CacheDirectoryMetadata& aDirectoryMetadata, nsIFile* aDBDir,
mozIStorageConnection* aConn) override {
MOZ_DIAGNOSTIC_ASSERT(aDBDir);
QM_TRY_INSPECT(
const auto& maybeResponse,
db::CacheMatch(*aConn, mCacheId, mArgs.request(), mArgs.params()));
mFoundResponse = maybeResponse.isSome();
if (mFoundResponse) {
mResponse = std::move(maybeResponse.ref());
}
if (!mFoundResponse || !mResponse.mHasBodyId ||
IsHeadRequest(mArgs.request(), mArgs.params())) {
mResponse.mHasBodyId = false;
return NS_OK;
}
nsCOMPtr<nsIInputStream> stream;
if (mArgs.openMode() == OpenMode::Eager) {
QM_TRY_UNWRAP(stream,
BodyOpen(aDirectoryMetadata, *aDBDir, mResponse.mBodyId));
}
mStreamList->Add(mResponse.mBodyId, std::move(stream));
return NS_OK;
}
virtual void Complete(Listener* aListener, ErrorResult&& aRv) override {
if (!mFoundResponse) {
aListener->OnOpComplete(std::move(aRv), CacheMatchResult(Nothing()));
} else {
mStreamList->Activate(mCacheId);
aListener->OnOpComplete(std::move(aRv), CacheMatchResult(Nothing()),
mResponse, *mStreamList);
}
mStreamList = nullptr;
}
virtual bool MatchesCacheId(CacheId aCacheId) const override {
return aCacheId == mCacheId;
}
private:
const CacheId mCacheId;
const CacheMatchArgs mArgs;
SafeRefPtr<StreamList> mStreamList;
bool mFoundResponse;
SavedResponse mResponse;
};
// ----------------------------------------------------------------------------
class Manager::CacheMatchAllAction final : public Manager::BaseAction {
public:
CacheMatchAllAction(SafeRefPtr<Manager> aManager, ListenerId aListenerId,
CacheId aCacheId, const CacheMatchAllArgs& aArgs,
SafeRefPtr<StreamList> aStreamList)
: BaseAction(std::move(aManager), aListenerId),
mCacheId(aCacheId),
mArgs(aArgs),
mStreamList(std::move(aStreamList)) {}
virtual nsresult RunSyncWithDBOnTarget(
const CacheDirectoryMetadata& aDirectoryMetadata, nsIFile* aDBDir,
mozIStorageConnection* aConn) override {
MOZ_DIAGNOSTIC_ASSERT(aDBDir);
QM_TRY_UNWRAP(mSavedResponses,
db::CacheMatchAll(*aConn, mCacheId, mArgs.maybeRequest(),
mArgs.params()));
for (uint32_t i = 0; i < mSavedResponses.Length(); ++i) {
if (!mSavedResponses[i].mHasBodyId ||
IsHeadRequest(mArgs.maybeRequest(), mArgs.params())) {
mSavedResponses[i].mHasBodyId = false;
continue;
}
nsCOMPtr<nsIInputStream> stream;
if (mArgs.openMode() == OpenMode::Eager) {
QM_TRY_UNWRAP(stream, BodyOpen(aDirectoryMetadata, *aDBDir,
mSavedResponses[i].mBodyId));
}
mStreamList->Add(mSavedResponses[i].mBodyId, std::move(stream));
}
return NS_OK;
}
virtual void Complete(Listener* aListener, ErrorResult&& aRv) override {
mStreamList->Activate(mCacheId);
aListener->OnOpComplete(std::move(aRv), CacheMatchAllResult(),
mSavedResponses, *mStreamList);
mStreamList = nullptr;
}
virtual bool MatchesCacheId(CacheId aCacheId) const override {
return aCacheId == mCacheId;
}
private:
const CacheId mCacheId;
const CacheMatchAllArgs mArgs;
SafeRefPtr<StreamList> mStreamList;
nsTArray<SavedResponse> mSavedResponses;
};
// ----------------------------------------------------------------------------
// This is the most complex Action. It puts a request/response pair into the
// Cache. It does not complete until all of the body data has been saved to
// disk. This means its an asynchronous Action.
class Manager::CachePutAllAction final : public DBAction {
public:
CachePutAllAction(
SafeRefPtr<Manager> aManager, ListenerId aListenerId, CacheId aCacheId,
const nsTArray<CacheRequestResponse>& aPutList,
const nsTArray<nsCOMPtr<nsIInputStream>>& aRequestStreamList,
const nsTArray<nsCOMPtr<nsIInputStream>>& aResponseStreamList)
: DBAction(DBAction::Existing),
mManager(std::move(aManager)),
mListenerId(aListenerId),
mCacheId(aCacheId),
mList(aPutList.Length()),
mExpectedAsyncCopyCompletions(1),
mAsyncResult(NS_OK),
mMutex("cache::Manager::CachePutAllAction"),
mUpdatedPaddingSize(0),
mDeletedPaddingSize(0) {
MOZ_DIAGNOSTIC_ASSERT(!aPutList.IsEmpty());
MOZ_DIAGNOSTIC_ASSERT(aPutList.Length() == aRequestStreamList.Length());
MOZ_DIAGNOSTIC_ASSERT(aPutList.Length() == aResponseStreamList.Length());
for (uint32_t i = 0; i < aPutList.Length(); ++i) {
Entry* entry = mList.AppendElement();
entry->mRequest = aPutList[i].request();
entry->mRequestStream = aRequestStreamList[i];
entry->mResponse = aPutList[i].response();
entry->mResponseStream = aResponseStreamList[i];
}
}
private:
~CachePutAllAction() = default;
virtual void RunWithDBOnTarget(
SafeRefPtr<Resolver> aResolver,
const CacheDirectoryMetadata& aDirectoryMetadata, nsIFile* aDBDir,
mozIStorageConnection* aConn) override {
MOZ_DIAGNOSTIC_ASSERT(aResolver);
MOZ_DIAGNOSTIC_ASSERT(aDBDir);
MOZ_DIAGNOSTIC_ASSERT(aConn);
MOZ_DIAGNOSTIC_ASSERT(!mResolver);
MOZ_DIAGNOSTIC_ASSERT(!mDBDir);
MOZ_DIAGNOSTIC_ASSERT(!mConn);
MOZ_DIAGNOSTIC_ASSERT(!mTarget);
mTarget = GetCurrentSerialEventTarget();
MOZ_DIAGNOSTIC_ASSERT(mTarget);
// We should be pre-initialized to expect one async completion. This is
// the "manual" completion we call at the end of this method in all
// cases.
MOZ_DIAGNOSTIC_ASSERT(mExpectedAsyncCopyCompletions == 1);
mResolver = std::move(aResolver);
mDBDir = aDBDir;
mConn = aConn;
mDirectoryMetadata.emplace(aDirectoryMetadata);
// File bodies are streamed to disk via asynchronous copying. Start
// this copying now. Each copy will eventually result in a call
// to OnAsyncCopyComplete().
const nsresult rv = [this, &aDirectoryMetadata]() -> nsresult {
QM_TRY(CollectEachInRange(
mList, [this, &aDirectoryMetadata](auto& entry) -> nsresult {
QM_TRY(MOZ_TO_RESULT(
StartStreamCopy(aDirectoryMetadata, entry, RequestStream,
&mExpectedAsyncCopyCompletions)));
QM_TRY(MOZ_TO_RESULT(
StartStreamCopy(aDirectoryMetadata, entry, ResponseStream,
&mExpectedAsyncCopyCompletions)));
return NS_OK;
}));
return NS_OK;
}();
// Always call OnAsyncCopyComplete() manually here. This covers the
// case where there is no async copying and also reports any startup
// errors correctly. If we hit an error, then OnAsyncCopyComplete()
// will cancel any async copying.
OnAsyncCopyComplete(rv);
}
// Called once for each asynchronous file copy whether it succeeds or
// fails. If a file copy is canceled, it still calls this method with
// an error code.
void OnAsyncCopyComplete(nsresult aRv) {
MOZ_ASSERT(mTarget->IsOnCurrentThread());
MOZ_DIAGNOSTIC_ASSERT(mConn);
MOZ_DIAGNOSTIC_ASSERT(mResolver);
MOZ_DIAGNOSTIC_ASSERT(mExpectedAsyncCopyCompletions > 0);
// Explicitly check for cancellation here to catch a race condition.
// Consider:
//
// 1) NS_AsyncCopy() executes on IO thread, but has not saved its
// copy context yet.
// 2) CancelAllStreamCopying() occurs on PBackground thread
// 3) Copy context from (1) is saved on IO thread.
//
// Checking for cancellation here catches this condition when we
// first call OnAsyncCopyComplete() manually from RunWithDBOnTarget().
//
// This explicit cancellation check also handles the case where we
// are canceled just after all stream copying completes. We should
// abort the synchronous DB operations in this case if we have not
// started them yet.
if (NS_SUCCEEDED(aRv) && IsCanceled()) {
aRv = NS_ERROR_ABORT;
}
// If any of the async copies fail, we need to still wait for them all to
// complete. Cancel any other streams still working and remember the
// error. All canceled streams will call OnAsyncCopyComplete().
if (NS_FAILED(aRv) && NS_SUCCEEDED(mAsyncResult)) {
CancelAllStreamCopying();
mAsyncResult = aRv;
}
// Check to see if async copying is still on-going. If so, then simply
// return for now. We must wait for a later OnAsyncCopyComplete() call.
mExpectedAsyncCopyCompletions -= 1;
if (mExpectedAsyncCopyCompletions > 0) {
return;
}
// We have finished with all async copying. Indicate this by clearing all
// our copy contexts.
{
MutexAutoLock lock(mMutex);
mCopyContextList.Clear();
}
// An error occurred while async copying. Terminate the Action.
// DoResolve() will clean up any files we may have written.
if (NS_FAILED(mAsyncResult)) {
DoResolve(mAsyncResult);
return;
}
mozStorageTransaction trans(mConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
QM_TRY(MOZ_TO_RESULT(trans.Start()), QM_VOID);
const nsresult rv = [this, &trans]() -> nsresult {
QM_TRY(CollectEachInRange(mList, [this](Entry& e) -> nsresult {
if (e.mRequestStream) {
QM_TRY(MOZ_TO_RESULT(BodyFinalizeWrite(*mDBDir, e.mRequestBodyId)));
}
if (e.mResponseStream) {
// Gerenate padding size for opaque response if needed.
if (e.mResponse.type() == ResponseType::Opaque) {
// It'll generate padding if we've not set it yet.
QM_TRY(MOZ_TO_RESULT(BodyMaybeUpdatePaddingSize(
*mDirectoryMetadata, *mDBDir, e.mResponseBodyId,
e.mResponse.paddingInfo(), &e.mResponse.paddingSize())));
MOZ_DIAGNOSTIC_ASSERT(INT64_MAX - e.mResponse.paddingSize() >=
mUpdatedPaddingSize);
mUpdatedPaddingSize += e.mResponse.paddingSize();
}
QM_TRY(MOZ_TO_RESULT(BodyFinalizeWrite(*mDBDir, e.mResponseBodyId)));
}
QM_TRY_UNWRAP(
auto deletionInfo,
db::CachePut(*mConn, mCacheId, e.mRequest,
e.mRequestStream ? &e.mRequestBodyId : nullptr,
e.mResponse,
e.mResponseStream ? &e.mResponseBodyId : nullptr));
const int64_t deletedPaddingSize = deletionInfo.mDeletedPaddingSize;
mDeletedBodyIdList = std::move(deletionInfo.mDeletedBodyIdList);
MOZ_DIAGNOSTIC_ASSERT(INT64_MAX - mDeletedPaddingSize >=
deletedPaddingSize);
mDeletedPaddingSize += deletedPaddingSize;
return NS_OK;
}));
// Update padding file when it's necessary
QM_TRY(MOZ_TO_RESULT(MaybeUpdatePaddingFile(
mDBDir, mConn, mUpdatedPaddingSize, mDeletedPaddingSize,
[&trans]() mutable { return trans.Commit(); })));
return NS_OK;
}();
DoResolve(rv);
}
virtual void CompleteOnInitiatingThread(nsresult aRv) override {
NS_ASSERT_OWNINGTHREAD(Action);
for (uint32_t i = 0; i < mList.Length(); ++i) {
mList[i].mRequestStream = nullptr;
mList[i].mResponseStream = nullptr;
}
// If the transaction fails, we shouldn't delete the body files and decrease
// their padding size.
if (NS_FAILED(aRv)) {
mDeletedBodyIdList.Clear();
mDeletedPaddingSize = 0;
}
mManager->NoteOrphanedBodyIdList(mDeletedBodyIdList);
if (mDeletedPaddingSize > 0) {
DecreaseUsageForDirectoryMetadata(*mDirectoryMetadata,
mDeletedPaddingSize);
}
Listener* listener = mManager->GetListener(mListenerId);
mManager = nullptr;
if (listener) {
listener->OnOpComplete(ErrorResult(aRv), CachePutAllResult());
}
}
virtual void CancelOnInitiatingThread() override {
NS_ASSERT_OWNINGTHREAD(Action);
Action::CancelOnInitiatingThread();
CancelAllStreamCopying();
}
virtual bool MatchesCacheId(CacheId aCacheId) const override {
NS_ASSERT_OWNINGTHREAD(Action);
return aCacheId == mCacheId;
}
struct Entry {
CacheRequest mRequest;
nsCOMPtr<nsIInputStream> mRequestStream;
nsID mRequestBodyId;
nsCOMPtr<nsISupports> mRequestCopyContext;
CacheResponse mResponse;
nsCOMPtr<nsIInputStream> mResponseStream;
nsID mResponseBodyId;
nsCOMPtr<nsISupports> mResponseCopyContext;
};
enum StreamId { RequestStream, ResponseStream };
nsresult StartStreamCopy(const CacheDirectoryMetadata& aDirectoryMetadata,
Entry& aEntry, StreamId aStreamId,
uint32_t* aCopyCountOut) {
MOZ_ASSERT(mTarget->IsOnCurrentThread());
MOZ_DIAGNOSTIC_ASSERT(aCopyCountOut);
if (IsCanceled()) {
return NS_ERROR_ABORT;
}
MOZ_DIAGNOSTIC_ASSERT(aStreamId == RequestStream ||
aStreamId == ResponseStream);
const auto& source = aStreamId == RequestStream ? aEntry.mRequestStream
: aEntry.mResponseStream;
if (!source) {
return NS_OK;
}
QM_TRY_INSPECT((const auto& [bodyId, copyContext]),
BodyStartWriteStream(aDirectoryMetadata, *mDBDir, *source,
this, AsyncCopyCompleteFunc));
if (aStreamId == RequestStream) {