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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
|
/* -*- 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/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/ipc/BackgroundParent.h"
#include "mozStorageHelper.h"
#include "nsIInputStream.h"
#include "nsID.h"
#include "nsIFile.h"
#include "nsIThread.h"
#include "nsThreadUtils.h"
#include "nsTObserverArray.h"
namespace mozilla {
namespace dom {
namespace cache {
namespace {
// 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 QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
nsresult rv = BodyCreateDir(aDBDir);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
// executes in its own transaction
rv = db::CreateOrMigrateSchema(aConn);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
// 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(aQuotaInfo)) {
NS_WARNING("Cache not shutdown cleanly! Cleaning up stale data...");
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
// Clean up orphaned Cache objects
AutoTArray<CacheId, 8> orphanedCacheIdList;
nsresult rv = db::FindOrphanedCacheIds(aConn, orphanedCacheIdList);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
for (uint32_t i = 0; i < orphanedCacheIdList.Length(); ++i) {
AutoTArray<nsID, 16> deletedBodyIdList;
rv = db::DeleteCacheId(aConn, orphanedCacheIdList[i], deletedBodyIdList);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
rv = BodyDeleteFiles(aDBDir, deletedBodyIdList);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
}
// Clean up orphaned body objects
AutoTArray<nsID, 64> knownBodyIdList;
rv = db::GetKnownBodyIds(aConn, knownBodyIdList);
rv = BodyDeleteOrphanedFiles(aDBDir, knownBodyIdList);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
}
return rv;
}
};
// ----------------------------------------------------------------------------
// 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:
explicit DeleteOrphanedBodyAction(const nsTArray<nsID>& aDeletedBodyIdList)
: mDeletedBodyIdList(aDeletedBodyIdList)
{ }
explicit DeleteOrphanedBodyAction(const nsID& aBodyId)
{
mDeletedBodyIdList.AppendElement(aBodyId);
}
virtual void
RunOnTarget(Resolver* aResolver, const QuotaInfo& aQuotaInfo, Data*) override
{
MOZ_DIAGNOSTIC_ASSERT(aResolver);
MOZ_DIAGNOSTIC_ASSERT(aQuotaInfo.mDir);
// Note that since DeleteOrphanedBodyAction isn't used while the context is
// being initialized, we don't need to check for cancellation here.
nsCOMPtr<nsIFile> dbDir;
nsresult rv = aQuotaInfo.mDir->Clone(getter_AddRefs(dbDir));
if (NS_WARN_IF(NS_FAILED(rv))) {
aResolver->Resolve(rv);
return;
}
rv = dbDir->Append(NS_LITERAL_STRING("cache"));
if (NS_WARN_IF(NS_FAILED(rv))) {
aResolver->Resolve(rv);
return;
}
rv = BodyDeleteFiles(dbDir, mDeletedBodyIdList);
Unused << NS_WARN_IF(NS_FAILED(rv));
aResolver->Resolve(rv);
}
private:
nsTArray<nsID> mDeletedBodyIdList;
};
bool IsHeadRequest(const CacheRequest& aRequest, const CacheQueryParams& aParams)
{
return !aParams.ignoreMethod() && aRequest.method().LowerCaseEqualsLiteral("head");
}
bool IsHeadRequest(const CacheRequestOrVoid& aRequest, const CacheQueryParams& aParams)
{
if (aRequest.type() == CacheRequestOrVoid::TCacheRequest) {
return !aParams.ignoreMethod() &&
aRequest.get_CacheRequest().method().LowerCaseEqualsLiteral("head");
}
return false;
}
} // 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 nsresult
GetOrCreate(ManagerId* aManagerId, Manager** aManagerOut)
{
mozilla::ipc::AssertIsOnBackgroundThread();
// Ensure there is a factory instance. This forces the Get() call
// below to use the same factory.
nsresult rv = MaybeCreateInstance();
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
RefPtr<Manager> ref = Get(aManagerId);
if (!ref) {
// TODO: replace this with a thread pool (bug 1119864)
nsCOMPtr<nsIThread> ioThread;
rv = NS_NewNamedThread("DOMCacheThread", getter_AddRefs(ioThread));
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
ref = new Manager(aManagerId, ioThread);
// 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.
RefPtr<Manager> oldManager = Get(aManagerId, Closing);
ref->Init(oldManager);
MOZ_ASSERT(!sFactory->mManagerList.Contains(ref));
sFactory->mManagerList.AppendElement(ref);
}
ref.forget(aManagerOut);
return NS_OK;
}
static already_AddRefed<Manager>
Get(ManagerId* aManagerId, State aState = Open)
{
mozilla::ipc::AssertIsOnBackgroundThread();
nsresult rv = MaybeCreateInstance();
if (NS_WARN_IF(NS_FAILED(rv))) { return 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.
ManagerList::BackwardIterator iter(sFactory->mManagerList);
while (iter.HasMore()) {
RefPtr<Manager> manager = iter.GetNext();
if (aState == manager->GetState() && *manager->mManagerId == *aManagerId) {
return manager.forget();
}
}
return nullptr;
}
static void
Remove(Manager* aManager)
{
mozilla::ipc::AssertIsOnBackgroundThread();
MOZ_DIAGNOSTIC_ASSERT(aManager);
MOZ_DIAGNOSTIC_ASSERT(sFactory);
MOZ_ALWAYS_TRUE(sFactory->mManagerList.RemoveElement(aManager));
// clean up the factory singleton if there are no more managers
MaybeDestroyInstance();
}
static void
Abort(const nsACString& aOrigin)
{
mozilla::ipc::AssertIsOnBackgroundThread();
if (!sFactory) {
return;
}
MOZ_DIAGNOSTIC_ASSERT(!sFactory->mManagerList.IsEmpty());
{
ManagerList::ForwardIterator iter(sFactory->mManagerList);
while (iter.HasMore()) {
RefPtr<Manager> manager = iter.GetNext();
if (aOrigin.IsVoid() ||
manager->mManagerId->QuotaOrigin() == aOrigin) {
manager->Abort();
}
}
}
}
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->mInSyncShutdown);
sFactory->mInSyncShutdown = true;
ManagerList::ForwardIterator iter(sFactory->mManagerList);
while (iter.HasMore()) {
RefPtr<Manager> manager = iter.GetNext();
manager->Shutdown();
}
}
MaybeDestroyInstance();
}
static bool
IsShutdownAllComplete()
{
mozilla::ipc::AssertIsOnBackgroundThread();
return !sFactory;
}
private:
Factory()
: mInSyncShutdown(false)
{
MOZ_COUNT_CTOR(cache::Manager::Factory);
}
~Factory()
{
MOZ_COUNT_DTOR(cache::Manager::Factory);
MOZ_DIAGNOSTIC_ASSERT(mManagerList.IsEmpty());
MOZ_DIAGNOSTIC_ASSERT(!mInSyncShutdown);
}
static nsresult
MaybeCreateInstance()
{
mozilla::ipc::AssertIsOnBackgroundThread();
if (!sFactory) {
// Be clear about what we are locking. sFactory is bg thread only, so
// we don't need to lock it here. Just protect sFactoryShutdown and
// sBackgroundThread.
{
StaticMutexAutoLock lock(sMutex);
if (sFactoryShutdown) {
return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
}
}
// 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 shutting down. We need to be careful not to delete ourself
// synchronously during shutdown.
if (!sFactory->mManagerList.IsEmpty() || sFactory->mInSyncShutdown) {
return;
}
sFactory = nullptr;
}
// Singleton created on demand and deleted when last Manager is cleared
// in Remove().
// PBackground thread only.
static StaticAutoPtr<Factory> sFactory;
// protects following static attribute
static StaticMutex sMutex;
// Indicate if shutdown has occurred to block re-creation of sFactory.
// Must hold sMutex to access.
static bool sFactoryShutdown;
// 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.
typedef nsTObserverArray<Manager*> ManagerList;
ManagerList mManagerList;
// This flag is set when we are looping through the list and calling
// Shutdown() on each Manager. We need to be careful not to synchronously
// trigger the deletion of the factory while still executing this loop.
bool mInSyncShutdown;
};
// static
StaticAutoPtr<Manager::Factory> Manager::Factory::sFactory;
// static
StaticMutex Manager::Factory::sMutex;
// static
bool Manager::Factory::sFactoryShutdown = false;
// ----------------------------------------------------------------------------
// 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(Manager* aManager, ListenerId aListenerId)
: SyncDBAction(DBAction::Existing)
, mManager(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;
}
RefPtr<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(Manager* aManager, CacheId aCacheId)
: SyncDBAction(DBAction::Existing)
, mManager(aManager)
, mCacheId(aCacheId)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
nsresult rv = db::DeleteCacheId(aConn, mCacheId, mDeletedBodyIdList);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
rv = trans.Commit();
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
return rv;
}
virtual void
CompleteOnInitiatingThread(nsresult aRv) override
{
mManager->NoteOrphanedBodyIdList(mDeletedBodyIdList);
// ensure we release the manager on the initiating thread
mManager = nullptr;
}
private:
RefPtr<Manager> mManager;
const CacheId mCacheId;
nsTArray<nsID> mDeletedBodyIdList;
};
// ----------------------------------------------------------------------------
class Manager::CacheMatchAction final : public Manager::BaseAction
{
public:
CacheMatchAction(Manager* aManager, ListenerId aListenerId,
CacheId aCacheId, const CacheMatchArgs& aArgs,
StreamList* aStreamList)
: BaseAction(aManager, aListenerId)
, mCacheId(aCacheId)
, mArgs(aArgs)
, mStreamList(aStreamList)
, mFoundResponse(false)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
nsresult rv = db::CacheMatch(aConn, mCacheId, mArgs.request(),
mArgs.params(), &mFoundResponse, &mResponse);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (!mFoundResponse || !mResponse.mHasBodyId
|| IsHeadRequest(mArgs.request(), mArgs.params())) {
mResponse.mHasBodyId = false;
return rv;
}
nsCOMPtr<nsIInputStream> stream;
rv = BodyOpen(aQuotaInfo, aDBDir, mResponse.mBodyId, getter_AddRefs(stream));
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (NS_WARN_IF(!stream)) { return NS_ERROR_FILE_NOT_FOUND; }
mStreamList->Add(mResponse.mBodyId, stream);
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
if (!mFoundResponse) {
aListener->OnOpComplete(Move(aRv), CacheMatchResult(void_t()));
} else {
mStreamList->Activate(mCacheId);
aListener->OnOpComplete(Move(aRv), CacheMatchResult(void_t()), mResponse,
mStreamList);
}
mStreamList = nullptr;
}
virtual bool MatchesCacheId(CacheId aCacheId) const override
{
return aCacheId == mCacheId;
}
private:
const CacheId mCacheId;
const CacheMatchArgs mArgs;
RefPtr<StreamList> mStreamList;
bool mFoundResponse;
SavedResponse mResponse;
};
// ----------------------------------------------------------------------------
class Manager::CacheMatchAllAction final : public Manager::BaseAction
{
public:
CacheMatchAllAction(Manager* aManager, ListenerId aListenerId,
CacheId aCacheId, const CacheMatchAllArgs& aArgs,
StreamList* aStreamList)
: BaseAction(aManager, aListenerId)
, mCacheId(aCacheId)
, mArgs(aArgs)
, mStreamList(aStreamList)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
nsresult rv = db::CacheMatchAll(aConn, mCacheId, mArgs.requestOrVoid(),
mArgs.params(), mSavedResponses);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
for (uint32_t i = 0; i < mSavedResponses.Length(); ++i) {
if (!mSavedResponses[i].mHasBodyId
|| IsHeadRequest(mArgs.requestOrVoid(), mArgs.params())) {
mSavedResponses[i].mHasBodyId = false;
continue;
}
nsCOMPtr<nsIInputStream> stream;
rv = BodyOpen(aQuotaInfo, aDBDir, mSavedResponses[i].mBodyId,
getter_AddRefs(stream));
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (NS_WARN_IF(!stream)) { return NS_ERROR_FILE_NOT_FOUND; }
mStreamList->Add(mSavedResponses[i].mBodyId, stream);
}
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
mStreamList->Activate(mCacheId);
aListener->OnOpComplete(Move(aRv), CacheMatchAllResult(), mSavedResponses,
mStreamList);
mStreamList = nullptr;
}
virtual bool MatchesCacheId(CacheId aCacheId) const override
{
return aCacheId == mCacheId;
}
private:
const CacheId mCacheId;
const CacheMatchAllArgs mArgs;
RefPtr<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(Manager* aManager, ListenerId aListenerId,
CacheId aCacheId,
const nsTArray<CacheRequestResponse>& aPutList,
const nsTArray<nsCOMPtr<nsIInputStream>>& aRequestStreamList,
const nsTArray<nsCOMPtr<nsIInputStream>>& aResponseStreamList)
: DBAction(DBAction::Existing)
, mManager(aManager)
, mListenerId(aListenerId)
, mCacheId(aCacheId)
, mList(aPutList.Length())
, mExpectedAsyncCopyCompletions(1)
, mAsyncResult(NS_OK)
, mMutex("cache::Manager::CachePutAllAction")
{
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() { }
virtual void
RunWithDBOnTarget(Resolver* aResolver, const QuotaInfo& aQuotaInfo,
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(!mTargetThread);
mTargetThread = NS_GetCurrentThread();
MOZ_DIAGNOSTIC_ASSERT(mTargetThread);
// 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 = aResolver;
mDBDir = aDBDir;
mConn = aConn;
// File bodies are streamed to disk via asynchronous copying. Start
// this copying now. Each copy will eventually result in a call
// to OnAsyncCopyComplete().
nsresult rv = NS_OK;
for (uint32_t i = 0; i < mList.Length(); ++i) {
rv = StartStreamCopy(aQuotaInfo, mList[i], RequestStream,
&mExpectedAsyncCopyCompletions);
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
rv = StartStreamCopy(aQuotaInfo, mList[i], ResponseStream,
&mExpectedAsyncCopyCompletions);
if (NS_WARN_IF(NS_FAILED(rv))) {
break;
}
}
// 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(mTargetThread == NS_GetCurrentThread());
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);
nsresult rv = NS_OK;
for (uint32_t i = 0; i < mList.Length(); ++i) {
Entry& e = mList[i];
if (e.mRequestStream) {
rv = BodyFinalizeWrite(mDBDir, e.mRequestBodyId);
if (NS_WARN_IF(NS_FAILED(rv))) {
DoResolve(rv);
return;
}
}
if (e.mResponseStream) {
rv = BodyFinalizeWrite(mDBDir, e.mResponseBodyId);
if (NS_WARN_IF(NS_FAILED(rv))) {
DoResolve(rv);
return;
}
}
rv = db::CachePut(mConn, mCacheId, e.mRequest,
e.mRequestStream ? &e.mRequestBodyId : nullptr,
e.mResponse,
e.mResponseStream ? &e.mResponseBodyId : nullptr,
mDeletedBodyIdList);
if (NS_WARN_IF(NS_FAILED(rv))) {
DoResolve(rv);
return;
}
}
rv = trans.Commit();
Unused << NS_WARN_IF(NS_FAILED(rv));
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;
}
mManager->NoteOrphanedBodyIdList(mDeletedBodyIdList);
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 QuotaInfo& aQuotaInfo, Entry& aEntry,
StreamId aStreamId, uint32_t* aCopyCountOut)
{
MOZ_ASSERT(mTargetThread == NS_GetCurrentThread());
MOZ_DIAGNOSTIC_ASSERT(aCopyCountOut);
if (IsCanceled()) {
return NS_ERROR_ABORT;
}
nsCOMPtr<nsIInputStream> source;
nsID* bodyId;
if (aStreamId == RequestStream) {
source = aEntry.mRequestStream;
bodyId = &aEntry.mRequestBodyId;
} else {
MOZ_DIAGNOSTIC_ASSERT(aStreamId == ResponseStream);
source = aEntry.mResponseStream;
bodyId = &aEntry.mResponseBodyId;
}
if (!source) {
return NS_OK;
}
nsCOMPtr<nsISupports> copyContext;
nsresult rv = BodyStartWriteStream(aQuotaInfo, mDBDir, source, this,
AsyncCopyCompleteFunc, bodyId,
getter_AddRefs(copyContext));
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
mBodyIdWrittenList.AppendElement(*bodyId);
if (copyContext) {
MutexAutoLock lock(mMutex);
mCopyContextList.AppendElement(copyContext);
}
*aCopyCountOut += 1;
return rv;
}
void
CancelAllStreamCopying()
{
// May occur on either owning thread or target thread
MutexAutoLock lock(mMutex);
for (uint32_t i = 0; i < mCopyContextList.Length(); ++i) {
BodyCancelWrite(mDBDir, mCopyContextList[i]);
}
mCopyContextList.Clear();
}
static void
AsyncCopyCompleteFunc(void* aClosure, nsresult aRv)
{
// May be on any thread, including STS event target.
MOZ_DIAGNOSTIC_ASSERT(aClosure);
// Weak ref as we are guaranteed to the action is alive until
// CompleteOnInitiatingThread is called.
CachePutAllAction* action = static_cast<CachePutAllAction*>(aClosure);
action->CallOnAsyncCopyCompleteOnTargetThread(aRv);
}
void
CallOnAsyncCopyCompleteOnTargetThread(nsresult aRv)
{
// May be on any thread, including STS event target. Non-owning runnable
// here since we are guaranteed the Action will survive until
// CompleteOnInitiatingThread is called.
nsCOMPtr<nsIRunnable> runnable = NewNonOwningRunnableMethod<nsresult>(
this, &CachePutAllAction::OnAsyncCopyComplete, aRv);
MOZ_ALWAYS_SUCCEEDS(
mTargetThread->Dispatch(runnable, nsIThread::DISPATCH_NORMAL));
}
void
DoResolve(nsresult aRv)
{
MOZ_ASSERT(mTargetThread == NS_GetCurrentThread());
// DoResolve() must not be called until all async copying has completed.
#ifdef DEBUG
{
MutexAutoLock lock(mMutex);
MOZ_ASSERT(mCopyContextList.IsEmpty());
}
#endif
// Clean up any files we might have written before hitting the error.
if (NS_FAILED(aRv)) {
BodyDeleteFiles(mDBDir, mBodyIdWrittenList);
}
// Must be released on the target thread where it was opened.
mConn = nullptr;
// Drop our ref to the target thread as we are done with this thread.
// Also makes our thread assertions catch any incorrect method calls
// after resolve.
mTargetThread = nullptr;
// Make sure to de-ref the resolver per the Action API contract.
RefPtr<Action::Resolver> resolver;
mResolver.swap(resolver);
resolver->Resolve(aRv);
}
// initiating thread only
RefPtr<Manager> mManager;
const ListenerId mListenerId;
// Set on initiating thread, read on target thread. State machine guarantees
// these are not modified while being read by the target thread.
const CacheId mCacheId;
nsTArray<Entry> mList;
uint32_t mExpectedAsyncCopyCompletions;
// target thread only
RefPtr<Resolver> mResolver;
nsCOMPtr<nsIFile> mDBDir;
nsCOMPtr<mozIStorageConnection> mConn;
nsCOMPtr<nsIThread> mTargetThread;
nsresult mAsyncResult;
nsTArray<nsID> mBodyIdWrittenList;
// Written to on target thread, accessed on initiating thread after target
// thread activity is guaranteed complete
nsTArray<nsID> mDeletedBodyIdList;
// accessed from any thread while mMutex locked
Mutex mMutex;
nsTArray<nsCOMPtr<nsISupports>> mCopyContextList;
};
// ----------------------------------------------------------------------------
class Manager::CacheDeleteAction final : public Manager::BaseAction
{
public:
CacheDeleteAction(Manager* aManager, ListenerId aListenerId,
CacheId aCacheId, const CacheDeleteArgs& aArgs)
: BaseAction(aManager, aListenerId)
, mCacheId(aCacheId)
, mArgs(aArgs)
, mSuccess(false)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
nsresult rv = db::CacheDelete(aConn, mCacheId, mArgs.request(),
mArgs.params(), mDeletedBodyIdList,
&mSuccess);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
rv = trans.Commit();
if (NS_WARN_IF(NS_FAILED(rv))) {
mSuccess = false;
return rv;
}
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
mManager->NoteOrphanedBodyIdList(mDeletedBodyIdList);
aListener->OnOpComplete(Move(aRv), CacheDeleteResult(mSuccess));
}
virtual bool MatchesCacheId(CacheId aCacheId) const override
{
return aCacheId == mCacheId;
}
private:
const CacheId mCacheId;
const CacheDeleteArgs mArgs;
bool mSuccess;
nsTArray<nsID> mDeletedBodyIdList;
};
// ----------------------------------------------------------------------------
class Manager::CacheKeysAction final : public Manager::BaseAction
{
public:
CacheKeysAction(Manager* aManager, ListenerId aListenerId,
CacheId aCacheId, const CacheKeysArgs& aArgs,
StreamList* aStreamList)
: BaseAction(aManager, aListenerId)
, mCacheId(aCacheId)
, mArgs(aArgs)
, mStreamList(aStreamList)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
nsresult rv = db::CacheKeys(aConn, mCacheId, mArgs.requestOrVoid(),
mArgs.params(), mSavedRequests);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
for (uint32_t i = 0; i < mSavedRequests.Length(); ++i) {
if (!mSavedRequests[i].mHasBodyId
|| IsHeadRequest(mArgs.requestOrVoid(), mArgs.params())) {
mSavedRequests[i].mHasBodyId = false;
continue;
}
nsCOMPtr<nsIInputStream> stream;
rv = BodyOpen(aQuotaInfo, aDBDir, mSavedRequests[i].mBodyId,
getter_AddRefs(stream));
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (NS_WARN_IF(!stream)) { return NS_ERROR_FILE_NOT_FOUND; }
mStreamList->Add(mSavedRequests[i].mBodyId, stream);
}
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
mStreamList->Activate(mCacheId);
aListener->OnOpComplete(Move(aRv), CacheKeysResult(), mSavedRequests,
mStreamList);
mStreamList = nullptr;
}
virtual bool MatchesCacheId(CacheId aCacheId) const override
{
return aCacheId == mCacheId;
}
private:
const CacheId mCacheId;
const CacheKeysArgs mArgs;
RefPtr<StreamList> mStreamList;
nsTArray<SavedRequest> mSavedRequests;
};
// ----------------------------------------------------------------------------
class Manager::StorageMatchAction final : public Manager::BaseAction
{
public:
StorageMatchAction(Manager* aManager, ListenerId aListenerId,
Namespace aNamespace,
const StorageMatchArgs& aArgs,
StreamList* aStreamList)
: BaseAction(aManager, aListenerId)
, mNamespace(aNamespace)
, mArgs(aArgs)
, mStreamList(aStreamList)
, mFoundResponse(false)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
nsresult rv = db::StorageMatch(aConn, mNamespace, mArgs.request(),
mArgs.params(), &mFoundResponse,
&mSavedResponse);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (!mFoundResponse || !mSavedResponse.mHasBodyId
|| IsHeadRequest(mArgs.request(), mArgs.params())) {
mSavedResponse.mHasBodyId = false;
return rv;
}
nsCOMPtr<nsIInputStream> stream;
rv = BodyOpen(aQuotaInfo, aDBDir, mSavedResponse.mBodyId,
getter_AddRefs(stream));
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (NS_WARN_IF(!stream)) { return NS_ERROR_FILE_NOT_FOUND; }
mStreamList->Add(mSavedResponse.mBodyId, stream);
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
if (!mFoundResponse) {
aListener->OnOpComplete(Move(aRv), StorageMatchResult(void_t()));
} else {
mStreamList->Activate(mSavedResponse.mCacheId);
aListener->OnOpComplete(Move(aRv), StorageMatchResult(void_t()), mSavedResponse,
mStreamList);
}
mStreamList = nullptr;
}
private:
const Namespace mNamespace;
const StorageMatchArgs mArgs;
RefPtr<StreamList> mStreamList;
bool mFoundResponse;
SavedResponse mSavedResponse;
};
// ----------------------------------------------------------------------------
class Manager::StorageHasAction final : public Manager::BaseAction
{
public:
StorageHasAction(Manager* aManager, ListenerId aListenerId,
Namespace aNamespace, const StorageHasArgs& aArgs)
: BaseAction(aManager, aListenerId)
, mNamespace(aNamespace)
, mArgs(aArgs)
, mCacheFound(false)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
CacheId cacheId;
return db::StorageGetCacheId(aConn, mNamespace, mArgs.key(),
&mCacheFound, &cacheId);
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
aListener->OnOpComplete(Move(aRv), StorageHasResult(mCacheFound));
}
private:
const Namespace mNamespace;
const StorageHasArgs mArgs;
bool mCacheFound;
};
// ----------------------------------------------------------------------------
class Manager::StorageOpenAction final : public Manager::BaseAction
{
public:
StorageOpenAction(Manager* aManager, ListenerId aListenerId,
Namespace aNamespace, const StorageOpenArgs& aArgs)
: BaseAction(aManager, aListenerId)
, mNamespace(aNamespace)
, mArgs(aArgs)
, mCacheId(INVALID_CACHE_ID)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
// Cache does not exist, create it instead
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
// Look for existing cache
bool cacheFound;
nsresult rv = db::StorageGetCacheId(aConn, mNamespace, mArgs.key(),
&cacheFound, &mCacheId);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (cacheFound) {
MOZ_DIAGNOSTIC_ASSERT(mCacheId != INVALID_CACHE_ID);
return rv;
}
rv = db::CreateCacheId(aConn, &mCacheId);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
rv = db::StoragePutCache(aConn, mNamespace, mArgs.key(), mCacheId);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
rv = trans.Commit();
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
MOZ_DIAGNOSTIC_ASSERT(mCacheId != INVALID_CACHE_ID);
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
MOZ_DIAGNOSTIC_ASSERT(aRv.Failed() || mCacheId != INVALID_CACHE_ID);
aListener->OnOpComplete(Move(aRv), StorageOpenResult(), mCacheId);
}
private:
const Namespace mNamespace;
const StorageOpenArgs mArgs;
CacheId mCacheId;
};
// ----------------------------------------------------------------------------
class Manager::StorageDeleteAction final : public Manager::BaseAction
{
public:
StorageDeleteAction(Manager* aManager, ListenerId aListenerId,
Namespace aNamespace, const StorageDeleteArgs& aArgs)
: BaseAction(aManager, aListenerId)
, mNamespace(aNamespace)
, mArgs(aArgs)
, mCacheDeleted(false)
, mCacheId(INVALID_CACHE_ID)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
mozStorageTransaction trans(aConn, false,
mozIStorageConnection::TRANSACTION_IMMEDIATE);
bool exists;
nsresult rv = db::StorageGetCacheId(aConn, mNamespace, mArgs.key(),
&exists, &mCacheId);
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
if (!exists) {
mCacheDeleted = false;
return NS_OK;
}
rv = db::StorageForgetCache(aConn, mNamespace, mArgs.key());
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
rv = trans.Commit();
if (NS_WARN_IF(NS_FAILED(rv))) { return rv; }
mCacheDeleted = true;
return rv;
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
if (mCacheDeleted) {
// If content is referencing this cache, mark it orphaned to be
// deleted later.
if (!mManager->SetCacheIdOrphanedIfRefed(mCacheId)) {
// no outstanding references, delete immediately
RefPtr<Context> context = mManager->mContext;
if (context->IsCanceled()) {
context->NoteOrphanedData();
} else {
context->CancelForCacheId(mCacheId);
RefPtr<Action> action =
new DeleteOrphanedCacheAction(mManager, mCacheId);
context->Dispatch(action);
}
}
}
aListener->OnOpComplete(Move(aRv), StorageDeleteResult(mCacheDeleted));
}
private:
const Namespace mNamespace;
const StorageDeleteArgs mArgs;
bool mCacheDeleted;
CacheId mCacheId;
};
// ----------------------------------------------------------------------------
class Manager::StorageKeysAction final : public Manager::BaseAction
{
public:
StorageKeysAction(Manager* aManager, ListenerId aListenerId,
Namespace aNamespace)
: BaseAction(aManager, aListenerId)
, mNamespace(aNamespace)
{ }
virtual nsresult
RunSyncWithDBOnTarget(const QuotaInfo& aQuotaInfo, nsIFile* aDBDir,
mozIStorageConnection* aConn) override
{
return db::StorageGetKeys(aConn, mNamespace, mKeys);
}
virtual void
Complete(Listener* aListener, ErrorResult&& aRv) override
{
if (aRv.Failed()) {
mKeys.Clear();
}
aListener->OnOpComplete(Move(aRv), StorageKeysResult(mKeys));
}
private:
const Namespace mNamespace;
nsTArray<nsString> mKeys;
};
// ----------------------------------------------------------------------------
//static
Manager::ListenerId Manager::sNextListenerId = 0;
void
Manager::Listener::OnOpComplete(ErrorResult&& aRv, const CacheOpResult& aResult)
{
OnOpComplete(Move(aRv), aResult, INVALID_CACHE_ID, nsTArray<SavedResponse>(),
nsTArray<SavedRequest>(), nullptr);
}
void
Manager::Listener::OnOpComplete(ErrorResult&& aRv, const CacheOpResult& aResult,
CacheId aOpenedCacheId)
{
OnOpComplete(Move(aRv), aResult, aOpenedCacheId, nsTArray<SavedResponse>(),
nsTArray<SavedRequest>(), nullptr);
}
void
Manager::Listener::OnOpComplete(ErrorResult&& aRv, const CacheOpResult& aResult,
const SavedResponse& aSavedResponse,
StreamList* aStreamList)
{
AutoTArray<SavedResponse, 1> responseList;
responseList.AppendElement(aSavedResponse);
OnOpComplete(Move(aRv), aResult, INVALID_CACHE_ID, responseList,
nsTArray<SavedRequest>(), aStreamList);
}
void
Manager::Listener::OnOpComplete(ErrorResult&& aRv, const CacheOpResult& aResult,
const nsTArray<SavedResponse>& aSavedResponseList,
StreamList* aStreamList)
{
OnOpComplete(Move(aRv), aResult, INVALID_CACHE_ID, aSavedResponseList,
nsTArray<SavedRequest>(), aStreamList);
}
void
Manager::Listener::OnOpComplete(ErrorResult&& aRv, const CacheOpResult& aResult,
const nsTArray<SavedRequest>& aSavedRequestList,
StreamList* aStreamList)
{
OnOpComplete(Move(aRv), aResult, INVALID_CACHE_ID, nsTArray<SavedResponse>(),
aSavedRequestList, aStreamList);
}
// static
nsresult
Manager::GetOrCreate(ManagerId* aManagerId, Manager** aManagerOut)
{
mozilla::ipc::AssertIsOnBackgroundThread();
return Factory::GetOrCreate(aManagerId, aManagerOut);
}
// static
already_AddRefed<Manager>
Manager::Get(ManagerId* aManagerId)
{
mozilla::ipc::AssertIsOnBackgroundThread();
return Factory::Get(aManagerId);
}
// static
void
Manager::ShutdownAll()
{
mozilla::ipc::AssertIsOnBackgroundThread();
Factory::ShutdownAll();
while (!Factory::IsShutdownAllComplete()) {
if (!NS_ProcessNextEvent()) {
NS_WARNING("Something bad happened!");
break;
}
}
}
// static
void
Manager::Abort(const nsACString& aOrigin)
{
mozilla::ipc::AssertIsOnBackgroundThread();
Factory::Abort(aOrigin);
}
void
Manager::RemoveListener(Listener* aListener)
{
NS_ASSERT_OWNINGTHREAD(Manager);
// There may not be a listener here in the case where an actor is killed
// before it can perform any actual async requests on Manager.
mListeners.RemoveElement(aListener, ListenerEntryListenerComparator());
MOZ_ASSERT(!mListeners.Contains(aListener,
ListenerEntryListenerComparator()));
MaybeAllowContextToClose();
}
void
Manager::RemoveContext(Context* aContext)
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(mContext);
MOZ_DIAGNOSTIC_ASSERT(mContext == aContext);
// Whether the Context destruction was triggered from the Manager going
// idle or the underlying storage being invalidated, we should know we
// are closing before the Context is destroyed.
MOZ_DIAGNOSTIC_ASSERT(mState == Closing);
// Before forgetting the Context, check to see if we have any outstanding
// cache or body objects waiting for deletion. If so, note that we've
// orphaned data so it will be cleaned up on the next open.
for (uint32_t i = 0; i < mCacheIdRefs.Length(); ++i) {
if (mCacheIdRefs[i].mOrphaned) {
aContext->NoteOrphanedData();
break;
}
}
for (uint32_t i = 0; i < mBodyIdRefs.Length(); ++i) {
if (mBodyIdRefs[i].mOrphaned) {
aContext->NoteOrphanedData();
break;
}
}
mContext = nullptr;
// Once the context is gone, we can immediately remove ourself from the
// Factory list. We don't need to block shutdown by staying in the list
// any more.
Factory::Remove(this);
}
void
Manager::NoteClosing()
{
NS_ASSERT_OWNINGTHREAD(Manager);
// This can be called more than once legitimately through different paths.
mState = Closing;
}
Manager::State
Manager::GetState() const
{
NS_ASSERT_OWNINGTHREAD(Manager);
return mState;
}
void
Manager::AddRefCacheId(CacheId aCacheId)
{
NS_ASSERT_OWNINGTHREAD(Manager);
for (uint32_t i = 0; i < mCacheIdRefs.Length(); ++i) {
if (mCacheIdRefs[i].mCacheId == aCacheId) {
mCacheIdRefs[i].mCount += 1;
return;
}
}
CacheIdRefCounter* entry = mCacheIdRefs.AppendElement();
entry->mCacheId = aCacheId;
entry->mCount = 1;
entry->mOrphaned = false;
}
void
Manager::ReleaseCacheId(CacheId aCacheId)
{
NS_ASSERT_OWNINGTHREAD(Manager);
for (uint32_t i = 0; i < mCacheIdRefs.Length(); ++i) {
if (mCacheIdRefs[i].mCacheId == aCacheId) {
#if defined(DEBUG) || !defined(RELEASE_OR_BETA)
uint32_t oldRef = mCacheIdRefs[i].mCount;
#endif
mCacheIdRefs[i].mCount -= 1;
MOZ_DIAGNOSTIC_ASSERT(mCacheIdRefs[i].mCount < oldRef);
if (mCacheIdRefs[i].mCount == 0) {
bool orphaned = mCacheIdRefs[i].mOrphaned;
mCacheIdRefs.RemoveElementAt(i);
RefPtr<Context> context = mContext;
// If the context is already gone, then orphan flag should have been
// set in RemoveContext().
if (orphaned && context) {
if (context->IsCanceled()) {
context->NoteOrphanedData();
} else {
context->CancelForCacheId(aCacheId);
RefPtr<Action> action = new DeleteOrphanedCacheAction(this,
aCacheId);
context->Dispatch(action);
}
}
}
MaybeAllowContextToClose();
return;
}
}
MOZ_ASSERT_UNREACHABLE("Attempt to release CacheId that is not referenced!");
}
void
Manager::AddRefBodyId(const nsID& aBodyId)
{
NS_ASSERT_OWNINGTHREAD(Manager);
for (uint32_t i = 0; i < mBodyIdRefs.Length(); ++i) {
if (mBodyIdRefs[i].mBodyId == aBodyId) {
mBodyIdRefs[i].mCount += 1;
return;
}
}
BodyIdRefCounter* entry = mBodyIdRefs.AppendElement();
entry->mBodyId = aBodyId;
entry->mCount = 1;
entry->mOrphaned = false;
}
void
Manager::ReleaseBodyId(const nsID& aBodyId)
{
NS_ASSERT_OWNINGTHREAD(Manager);
for (uint32_t i = 0; i < mBodyIdRefs.Length(); ++i) {
if (mBodyIdRefs[i].mBodyId == aBodyId) {
#if defined(DEBUG) || !defined(RELEASE_OR_BETA)
uint32_t oldRef = mBodyIdRefs[i].mCount;
#endif
mBodyIdRefs[i].mCount -= 1;
MOZ_DIAGNOSTIC_ASSERT(mBodyIdRefs[i].mCount < oldRef);
if (mBodyIdRefs[i].mCount < 1) {
bool orphaned = mBodyIdRefs[i].mOrphaned;
mBodyIdRefs.RemoveElementAt(i);
RefPtr<Context> context = mContext;
// If the context is already gone, then orphan flag should have been
// set in RemoveContext().
if (orphaned && context) {
if (context->IsCanceled()) {
context->NoteOrphanedData();
} else {
RefPtr<Action> action = new DeleteOrphanedBodyAction(aBodyId);
context->Dispatch(action);
}
}
}
MaybeAllowContextToClose();
return;
}
}
MOZ_ASSERT_UNREACHABLE("Attempt to release BodyId that is not referenced!");
}
already_AddRefed<ManagerId>
Manager::GetManagerId() const
{
RefPtr<ManagerId> ref = mManagerId;
return ref.forget();
}
void
Manager::AddStreamList(StreamList* aStreamList)
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(aStreamList);
mStreamLists.AppendElement(aStreamList);
}
void
Manager::RemoveStreamList(StreamList* aStreamList)
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(aStreamList);
mStreamLists.RemoveElement(aStreamList);
}
void
Manager::ExecuteCacheOp(Listener* aListener, CacheId aCacheId,
const CacheOpArgs& aOpArgs)
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(aListener);
MOZ_DIAGNOSTIC_ASSERT(aOpArgs.type() != CacheOpArgs::TCachePutAllArgs);
if (NS_WARN_IF(mState == Closing)) {
aListener->OnOpComplete(ErrorResult(NS_ERROR_FAILURE), void_t());
return;
}
RefPtr<Context> context = mContext;
MOZ_DIAGNOSTIC_ASSERT(!context->IsCanceled());
RefPtr<StreamList> streamList = new StreamList(this, context);
ListenerId listenerId = SaveListener(aListener);
RefPtr<Action> action;
switch(aOpArgs.type()) {
case CacheOpArgs::TCacheMatchArgs:
action = new CacheMatchAction(this, listenerId, aCacheId,
aOpArgs.get_CacheMatchArgs(), streamList);
break;
case CacheOpArgs::TCacheMatchAllArgs:
action = new CacheMatchAllAction(this, listenerId, aCacheId,
aOpArgs.get_CacheMatchAllArgs(),
streamList);
break;
case CacheOpArgs::TCacheDeleteArgs:
action = new CacheDeleteAction(this, listenerId, aCacheId,
aOpArgs.get_CacheDeleteArgs());
break;
case CacheOpArgs::TCacheKeysArgs:
action = new CacheKeysAction(this, listenerId, aCacheId,
aOpArgs.get_CacheKeysArgs(), streamList);
break;
default:
MOZ_CRASH("Unknown Cache operation!");
}
context->Dispatch(action);
}
void
Manager::ExecuteStorageOp(Listener* aListener, Namespace aNamespace,
const CacheOpArgs& aOpArgs)
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(aListener);
if (NS_WARN_IF(mState == Closing)) {
aListener->OnOpComplete(ErrorResult(NS_ERROR_FAILURE), void_t());
return;
}
RefPtr<Context> context = mContext;
MOZ_DIAGNOSTIC_ASSERT(!context->IsCanceled());
RefPtr<StreamList> streamList = new StreamList(this, context);
ListenerId listenerId = SaveListener(aListener);
RefPtr<Action> action;
switch(aOpArgs.type()) {
case CacheOpArgs::TStorageMatchArgs:
action = new StorageMatchAction(this, listenerId, aNamespace,
aOpArgs.get_StorageMatchArgs(),
streamList);
break;
case CacheOpArgs::TStorageHasArgs:
action = new StorageHasAction(this, listenerId, aNamespace,
aOpArgs.get_StorageHasArgs());
break;
case CacheOpArgs::TStorageOpenArgs:
action = new StorageOpenAction(this, listenerId, aNamespace,
aOpArgs.get_StorageOpenArgs());
break;
case CacheOpArgs::TStorageDeleteArgs:
action = new StorageDeleteAction(this, listenerId, aNamespace,
aOpArgs.get_StorageDeleteArgs());
break;
case CacheOpArgs::TStorageKeysArgs:
action = new StorageKeysAction(this, listenerId, aNamespace);
break;
default:
MOZ_CRASH("Unknown CacheStorage operation!");
}
context->Dispatch(action);
}
void
Manager::ExecutePutAll(Listener* aListener, CacheId aCacheId,
const nsTArray<CacheRequestResponse>& aPutList,
const nsTArray<nsCOMPtr<nsIInputStream>>& aRequestStreamList,
const nsTArray<nsCOMPtr<nsIInputStream>>& aResponseStreamList)
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(aListener);
if (NS_WARN_IF(mState == Closing)) {
aListener->OnOpComplete(ErrorResult(NS_ERROR_FAILURE), CachePutAllResult());
return;
}
RefPtr<Context> context = mContext;
MOZ_DIAGNOSTIC_ASSERT(!context->IsCanceled());
ListenerId listenerId = SaveListener(aListener);
RefPtr<Action> action = new CachePutAllAction(this, listenerId, aCacheId,
aPutList, aRequestStreamList,
aResponseStreamList);
context->Dispatch(action);
}
Manager::Manager(ManagerId* aManagerId, nsIThread* aIOThread)
: mManagerId(aManagerId)
, mIOThread(aIOThread)
, mContext(nullptr)
, mShuttingDown(false)
, mState(Open)
{
MOZ_DIAGNOSTIC_ASSERT(mManagerId);
MOZ_DIAGNOSTIC_ASSERT(mIOThread);
}
Manager::~Manager()
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(mState == Closing);
MOZ_DIAGNOSTIC_ASSERT(!mContext);
nsCOMPtr<nsIThread> ioThread;
mIOThread.swap(ioThread);
// Don't spin the event loop in the destructor waiting for the thread to
// shutdown. Defer this to the main thread, instead.
MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(NewRunnableMethod(ioThread, &nsIThread::Shutdown)));
}
void
Manager::Init(Manager* aOldManager)
{
NS_ASSERT_OWNINGTHREAD(Manager);
RefPtr<Context> oldContext;
if (aOldManager) {
oldContext = aOldManager->mContext;
}
// Create the context immediately. Since there can at most be one Context
// per Manager now, this lets us cleanly call Factory::Remove() once the
// Context goes away.
RefPtr<Action> setupAction = new SetupAction();
RefPtr<Context> ref = Context::Create(this, mIOThread, setupAction,
oldContext);
mContext = ref;
}
void
Manager::Shutdown()
{
NS_ASSERT_OWNINGTHREAD(Manager);
// Ignore duplicate attempts to shutdown. This can occur when we start
// a browser initiated shutdown and then run ~Manager() which also
// calls Shutdown().
if (mShuttingDown) {
return;
}
mShuttingDown = true;
// Note that we are closing to prevent any new requests from coming in and
// creating a new Context. We must ensure all Contexts and IO operations are
// complete before shutdown proceeds.
NoteClosing();
// If there is a context, then cancel and only note that we are done after
// its cleaned up.
if (mContext) {
RefPtr<Context> context = mContext;
context->CancelAll();
return;
}
}
void
Manager::Abort()
{
NS_ASSERT_OWNINGTHREAD(Manager);
MOZ_DIAGNOSTIC_ASSERT(mContext);
// Note that we are closing to prevent any new requests from coming in and
// creating a new Context. We must ensure all Contexts and IO operations are
// complete before origin clear proceeds.
NoteClosing();
// Cancel and only note that we are done after the context is cleaned up.
RefPtr<Context> context = mContext;
context->CancelAll();
}
Manager::ListenerId
Manager::SaveListener(Listener* aListener)
{
NS_ASSERT_OWNINGTHREAD(Manager);
// Once a Listener is added, we keep a reference to it until its
// removed. Since the same Listener might make multiple requests,
// ensure we only have a single reference in our list.
ListenerList::index_type index =
mListeners.IndexOf(aListener, 0, ListenerEntryListenerComparator());
if (index != ListenerList::NoIndex) {
return mListeners[index].mId;
}
ListenerId id = sNextListenerId;
sNextListenerId += 1;
mListeners.AppendElement(ListenerEntry(id, aListener));
return id;
}
Manager::Listener*
Manager::GetListener(ListenerId aListenerId) const
{
NS_ASSERT_OWNINGTHREAD(Manager);
ListenerList::index_type index =
mListeners.IndexOf(aListenerId, 0, ListenerEntryIdComparator());
if (index != ListenerList::NoIndex) {
return mListeners[index].mListener;
}
// This can legitimately happen if the actor is deleted while a request is
// in process. For example, the child process OOMs.
return nullptr;
}
bool
Manager::SetCacheIdOrphanedIfRefed(CacheId aCacheId)
{
NS_ASSERT_OWNINGTHREAD(Manager);
for (uint32_t i = 0; i < mCacheIdRefs.Length(); ++i) {
if (mCacheIdRefs[i].mCacheId == aCacheId) {
MOZ_DIAGNOSTIC_ASSERT(mCacheIdRefs[i].mCount > 0);
MOZ_DIAGNOSTIC_ASSERT(!mCacheIdRefs[i].mOrphaned);
mCacheIdRefs[i].mOrphaned = true;
return true;
}
}
return false;
}
// TODO: provide way to set body non-orphaned if its added back to a cache (bug 1110479)
bool
Manager::SetBodyIdOrphanedIfRefed(const nsID& aBodyId)
{
NS_ASSERT_OWNINGTHREAD(Manager);
for (uint32_t i = 0; i < mBodyIdRefs.Length(); ++i) {
if (mBodyIdRefs[i].mBodyId == aBodyId) {
MOZ_DIAGNOSTIC_ASSERT(mBodyIdRefs[i].mCount > 0);
MOZ_DIAGNOSTIC_ASSERT(!mBodyIdRefs[i].mOrphaned);
mBodyIdRefs[i].mOrphaned = true;
return true;
}
}
return false;
}
void
Manager::NoteOrphanedBodyIdList(const nsTArray<nsID>& aDeletedBodyIdList)
{
NS_ASSERT_OWNINGTHREAD(Manager);
AutoTArray<nsID, 64> deleteNowList;
deleteNowList.SetCapacity(aDeletedBodyIdList.Length());
for (uint32_t i = 0; i < aDeletedBodyIdList.Length(); ++i) {
if (!SetBodyIdOrphanedIfRefed(aDeletedBodyIdList[i])) {
deleteNowList.AppendElement(aDeletedBodyIdList[i]);
}
}
// TODO: note that we need to check these bodies for staleness on startup (bug 1110446)
RefPtr<Context> context = mContext;
if (!deleteNowList.IsEmpty() && context && !context->IsCanceled()) {
RefPtr<Action> action = new DeleteOrphanedBodyAction(deleteNowList);
context->Dispatch(action);
}
}
void
Manager::MaybeAllowContextToClose()
{
NS_ASSERT_OWNINGTHREAD(Manager);
// If we have an active context, but we have no more users of the Manager,
// then let it shut itself down. We must wait for all possible users of
// Cache state information to complete before doing this. Once we allow
// the Context to close we may not reliably get notified of storage
// invalidation.
RefPtr<Context> context = mContext;
if (context && mListeners.IsEmpty()
&& mCacheIdRefs.IsEmpty()
&& mBodyIdRefs.IsEmpty()) {
// Mark this Manager as invalid so that it won't get used again. We don't
// want to start any new operations once we allow the Context to close since
// it may race with the underlying storage getting invalidated.
NoteClosing();
context->AllowToClose();
}
}
} // namespace cache
} // namespace dom
} // namespace mozilla
|