summaryrefslogtreecommitdiffstats
path: root/dom/indexedDB/IndexedDatabaseManager.cpp
blob: e63dd793cfd0501a39a125b40c2c5bd99581b8fb (plain)
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
/* -*- 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 "IndexedDatabaseManager.h"

#include "chrome/common/ipc_channel.h"  // for IPC::Channel::kMaximumMessageSize
#include "nsIScriptError.h"
#include "nsIScriptGlobalObject.h"

#include "jsapi.h"
#include "js/Object.h"              // JS::GetClass
#include "js/PropertyAndElement.h"  // JS_DefineProperty
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/ContentEvents.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/Preferences.h"
#include "mozilla/ResultExtensions.h"
#include "mozilla/dom/DOMException.h"
#include "mozilla/dom/ErrorEvent.h"
#include "mozilla/dom/ErrorEventBinding.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/dom/RootedDictionary.h"
#include "mozilla/dom/quota/Assertions.h"
#include "mozilla/dom/quota/ResultExtensions.h"
#include "mozilla/intl/LocaleCanonicalizer.h"
#include "mozilla/ipc/BackgroundChild.h"
#include "mozilla/ipc/PBackgroundChild.h"
#include "nsContentUtils.h"
#include "mozilla/Logging.h"

#include "ActorsChild.h"
#include "DatabaseFileManager.h"
#include "IDBEvents.h"
#include "IDBFactory.h"
#include "IDBKeyRange.h"
#include "IDBRequest.h"
#include "IndexedDBCommon.h"
#include "ProfilerHelpers.h"
#include "ScriptErrorHelper.h"
#include "nsCharSeparatedTokenizer.h"

// Bindings for ResolveConstructors
#include "mozilla/dom/IDBCursorBinding.h"
#include "mozilla/dom/IDBDatabaseBinding.h"
#include "mozilla/dom/IDBFactoryBinding.h"
#include "mozilla/dom/IDBIndexBinding.h"
#include "mozilla/dom/IDBKeyRangeBinding.h"
#include "mozilla/dom/IDBObjectStoreBinding.h"
#include "mozilla/dom/IDBOpenDBRequestBinding.h"
#include "mozilla/dom/IDBRequestBinding.h"
#include "mozilla/dom/IDBTransactionBinding.h"
#include "mozilla/dom/IDBVersionChangeEventBinding.h"

#define IDB_STR "indexedDB"

namespace mozilla::dom {
namespace indexedDB {

using namespace mozilla::dom::quota;
using namespace mozilla::ipc;

class FileManagerInfo {
 public:
  [[nodiscard]] SafeRefPtr<DatabaseFileManager> GetFileManager(
      PersistenceType aPersistenceType, const nsAString& aName) const;

  [[nodiscard]] SafeRefPtr<DatabaseFileManager>
  GetFileManagerByDatabaseFilePath(PersistenceType aPersistenceType,
                                   const nsAString& aDatabaseFilePath) const;

  const nsTArray<SafeRefPtr<DatabaseFileManager>>& GetFileManagers(
      PersistenceType aPersistenceType) const;

  void AddFileManager(SafeRefPtr<DatabaseFileManager> aFileManager);

  bool HasFileManagers() const {
    AssertIsOnIOThread();

    return !mPersistentStorageFileManagers.IsEmpty() ||
           !mTemporaryStorageFileManagers.IsEmpty() ||
           !mDefaultStorageFileManagers.IsEmpty() ||
           !mPrivateStorageFileManagers.IsEmpty();
  }

  void InvalidateAllFileManagers() const;

  void InvalidateAndRemoveFileManagers(PersistenceType aPersistenceType);

  void InvalidateAndRemoveFileManager(PersistenceType aPersistenceType,
                                      const nsAString& aName);

 private:
  nsTArray<SafeRefPtr<DatabaseFileManager>>& GetArray(
      PersistenceType aPersistenceType);

  const nsTArray<SafeRefPtr<DatabaseFileManager>>& GetImmutableArray(
      PersistenceType aPersistenceType) const {
    return const_cast<FileManagerInfo*>(this)->GetArray(aPersistenceType);
  }

  nsTArray<SafeRefPtr<DatabaseFileManager>> mPersistentStorageFileManagers;
  nsTArray<SafeRefPtr<DatabaseFileManager>> mTemporaryStorageFileManagers;
  nsTArray<SafeRefPtr<DatabaseFileManager>> mDefaultStorageFileManagers;
  nsTArray<SafeRefPtr<DatabaseFileManager>> mPrivateStorageFileManagers;
};

}  // namespace indexedDB

using namespace mozilla::dom::indexedDB;

namespace {

// The threshold we use for structured clone data storing.
// Anything smaller than the threshold is compressed and stored in the database.
// Anything larger is compressed and stored outside the database.
const int32_t kDefaultDataThresholdBytes = 1024 * 1024;  // 1MB

// The maximal size of a serialized object to be transfered through IPC.
const int32_t kDefaultMaxSerializedMsgSize = IPC::Channel::kMaximumMessageSize;

// The maximum number of records to preload (in addition to the one requested by
// the child).
//
// TODO: The current number was chosen for no particular reason. Telemetry
// should be added to determine whether this is a reasonable number for an
// overwhelming majority of cases.
const int32_t kDefaultMaxPreloadExtraRecords = 64;

#define IDB_PREF_BRANCH_ROOT "dom.indexedDB."

const char kDataThresholdPref[] = IDB_PREF_BRANCH_ROOT "dataThreshold";
const char kPrefMaxSerilizedMsgSize[] =
    IDB_PREF_BRANCH_ROOT "maxSerializedMsgSize";
const char kPrefMaxPreloadExtraRecords[] =
    IDB_PREF_BRANCH_ROOT "maxPreloadExtraRecords";

#define IDB_PREF_LOGGING_BRANCH_ROOT IDB_PREF_BRANCH_ROOT "logging."

const char kPrefLoggingEnabled[] = IDB_PREF_LOGGING_BRANCH_ROOT "enabled";
const char kPrefLoggingDetails[] = IDB_PREF_LOGGING_BRANCH_ROOT "details";

const char kPrefLoggingProfiler[] =
    IDB_PREF_LOGGING_BRANCH_ROOT "profiler-marks";

#undef IDB_PREF_LOGGING_BRANCH_ROOT
#undef IDB_PREF_BRANCH_ROOT

StaticMutex gDBManagerMutex;
StaticRefPtr<IndexedDatabaseManager> gDBManager MOZ_GUARDED_BY(gDBManagerMutex);
bool gInitialized MOZ_GUARDED_BY(gDBManagerMutex) = false;
bool gClosed MOZ_GUARDED_BY(gDBManagerMutex) = false;

Atomic<int32_t> gDataThresholdBytes(0);
Atomic<int32_t> gMaxSerializedMsgSize(0);
Atomic<int32_t> gMaxPreloadExtraRecords(0);

void DataThresholdPrefChangedCallback(const char* aPrefName, void* aClosure) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(!strcmp(aPrefName, kDataThresholdPref));
  MOZ_ASSERT(!aClosure);

  int32_t dataThresholdBytes =
      Preferences::GetInt(aPrefName, kDefaultDataThresholdBytes);

  // The magic -1 is for use only by tests that depend on stable blob file id's.
  if (dataThresholdBytes == -1) {
    dataThresholdBytes = INT32_MAX;
  }

  gDataThresholdBytes = dataThresholdBytes;
}

void MaxSerializedMsgSizePrefChangeCallback(const char* aPrefName,
                                            void* aClosure) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(!strcmp(aPrefName, kPrefMaxSerilizedMsgSize));
  MOZ_ASSERT(!aClosure);

  gMaxSerializedMsgSize =
      Preferences::GetInt(aPrefName, kDefaultMaxSerializedMsgSize);
  MOZ_ASSERT(gMaxSerializedMsgSize > 0);
}

void MaxPreloadExtraRecordsPrefChangeCallback(const char* aPrefName,
                                              void* aClosure) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(!strcmp(aPrefName, kPrefMaxPreloadExtraRecords));
  MOZ_ASSERT(!aClosure);

  gMaxPreloadExtraRecords =
      Preferences::GetInt(aPrefName, kDefaultMaxPreloadExtraRecords);
  MOZ_ASSERT(gMaxPreloadExtraRecords >= 0);

  // TODO: We could also allow setting a negative value to preload all available
  // records, but this doesn't seem to be too useful in general, and it would
  // require adaptations in ActorsParent.cpp
}

auto DatabaseNameMatchPredicate(const nsAString* const aName) {
  MOZ_ASSERT(aName);
  return [aName](const auto& fileManager) {
    return fileManager->DatabaseName() == *aName;
  };
}

auto DatabaseFilePathMatchPredicate(const nsAString* const aDatabaseFilePath) {
  MOZ_ASSERT(aDatabaseFilePath);
  return [aDatabaseFilePath](const auto& fileManager) {
    return fileManager->DatabaseFilePath() == *aDatabaseFilePath;
  };
}

}  // namespace

IndexedDatabaseManager::IndexedDatabaseManager() : mBackgroundActor(nullptr) {
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
}

IndexedDatabaseManager::~IndexedDatabaseManager() {
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");

  if (mBackgroundActor) {
    mBackgroundActor->SendDeleteMeInternal();
    MOZ_ASSERT(!mBackgroundActor, "SendDeleteMeInternal should have cleared!");
  }
}

bool IndexedDatabaseManager::sIsMainProcess = false;
bool IndexedDatabaseManager::sFullSynchronousMode = false;

mozilla::LazyLogModule IndexedDatabaseManager::sLoggingModule("IndexedDB");

Atomic<IndexedDatabaseManager::LoggingMode>
    IndexedDatabaseManager::sLoggingMode(
        IndexedDatabaseManager::Logging_Disabled);

// static
IndexedDatabaseManager* IndexedDatabaseManager::GetOrCreate() {
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");

  StaticMutexAutoLock lock(gDBManagerMutex);

  if (gClosed) {
    NS_ERROR("Calling GetOrCreate() after shutdown!");
    return nullptr;
  }

  if (!gDBManager) {
    sIsMainProcess = XRE_IsParentProcess();

    if (gInitialized) {
      NS_ERROR("Initialized more than once?!");
    }

    RefPtr<IndexedDatabaseManager> instance(new IndexedDatabaseManager());

    {
      StaticMutexAutoUnlock unlock(gDBManagerMutex);

      QM_TRY(MOZ_TO_RESULT(instance->Init()), nullptr);
    }

    gDBManager = instance;

    ClearOnShutdown(&gDBManager);

    gInitialized = true;
  }

  return gDBManager;
}

// static
IndexedDatabaseManager* IndexedDatabaseManager::Get() {
  StaticMutexAutoLock lock(gDBManagerMutex);

  // Does not return an owning reference.
  return gDBManager;
}

nsresult IndexedDatabaseManager::Init() {
  NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");

  // By default IndexedDB uses SQLite with PRAGMA synchronous = NORMAL. This
  // guarantees (unlike synchronous = OFF) atomicity and consistency, but not
  // necessarily durability in situations such as power loss. This preference
  // allows enabling PRAGMA synchronous = FULL on SQLite, which does guarantee
  // durability, but with an extra fsync() and the corresponding performance
  // hit.
  sFullSynchronousMode = Preferences::GetBool("dom.indexedDB.fullSynchronous");

  Preferences::RegisterCallback(LoggingModePrefChangedCallback,
                                kPrefLoggingDetails);

  Preferences::RegisterCallback(LoggingModePrefChangedCallback,
                                kPrefLoggingProfiler);

  Preferences::RegisterCallbackAndCall(LoggingModePrefChangedCallback,
                                       kPrefLoggingEnabled);

  Preferences::RegisterCallbackAndCall(DataThresholdPrefChangedCallback,
                                       kDataThresholdPref);

  Preferences::RegisterCallbackAndCall(MaxSerializedMsgSizePrefChangeCallback,
                                       kPrefMaxSerilizedMsgSize);

  Preferences::RegisterCallbackAndCall(MaxPreloadExtraRecordsPrefChangeCallback,
                                       kPrefMaxPreloadExtraRecords);

  return NS_OK;
}

void IndexedDatabaseManager::Destroy() {
  {
    StaticMutexAutoLock lock(gDBManagerMutex);

    // Setting the closed flag prevents the service from being recreated.
    // Don't set it though if there's no real instance created.
    if (gInitialized && gClosed) {
      NS_ERROR("Shutdown more than once?!");
    }

    gClosed = true;
  }

  Preferences::UnregisterCallback(LoggingModePrefChangedCallback,
                                  kPrefLoggingDetails);

  Preferences::UnregisterCallback(LoggingModePrefChangedCallback,
                                  kPrefLoggingProfiler);

  Preferences::UnregisterCallback(LoggingModePrefChangedCallback,
                                  kPrefLoggingEnabled);

  Preferences::UnregisterCallback(DataThresholdPrefChangedCallback,
                                  kDataThresholdPref);

  Preferences::UnregisterCallback(MaxSerializedMsgSizePrefChangeCallback,
                                  kPrefMaxSerilizedMsgSize);

  delete this;
}

// static
bool IndexedDatabaseManager::ResolveSandboxBinding(JSContext* aCx) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(
      JS::GetClass(JS::CurrentGlobalOrNull(aCx))->flags & JSCLASS_DOM_GLOBAL,
      "Passed object is not a global object!");

  // We need to ensure that the manager has been created already here so that we
  // load preferences that may control which properties are exposed.
  if (NS_WARN_IF(!GetOrCreate())) {
    return false;
  }

  if (!IDBCursor_Binding::GetConstructorObject(aCx) ||
      !IDBCursorWithValue_Binding::GetConstructorObject(aCx) ||
      !IDBDatabase_Binding::GetConstructorObject(aCx) ||
      !IDBFactory_Binding::GetConstructorObject(aCx) ||
      !IDBIndex_Binding::GetConstructorObject(aCx) ||
      !IDBKeyRange_Binding::GetConstructorObject(aCx) ||
      !IDBObjectStore_Binding::GetConstructorObject(aCx) ||
      !IDBOpenDBRequest_Binding::GetConstructorObject(aCx) ||
      !IDBRequest_Binding::GetConstructorObject(aCx) ||
      !IDBTransaction_Binding::GetConstructorObject(aCx) ||
      !IDBVersionChangeEvent_Binding::GetConstructorObject(aCx)) {
    return false;
  }

  return true;
}

// static
bool IndexedDatabaseManager::DefineIndexedDB(JSContext* aCx,
                                             JS::Handle<JSObject*> aGlobal) {
  MOZ_ASSERT(NS_IsMainThread());
  MOZ_ASSERT(JS::GetClass(aGlobal)->flags & JSCLASS_DOM_GLOBAL,
             "Passed object is not a global object!");

  nsIGlobalObject* global = xpc::CurrentNativeGlobal(aCx);
  if (NS_WARN_IF(!global)) {
    return false;
  }

  QM_TRY_UNWRAP(auto factory, IDBFactory::CreateForMainThreadJS(global), false);

  MOZ_ASSERT(factory, "This should never fail for chrome!");

  JS::Rooted<JS::Value> indexedDB(aCx);
  js::AssertSameCompartment(aCx, aGlobal);
  if (!GetOrCreateDOMReflector(aCx, factory, &indexedDB)) {
    return false;
  }

  return JS_DefineProperty(aCx, aGlobal, IDB_STR, indexedDB, JSPROP_ENUMERATE);
}

// static
bool IndexedDatabaseManager::IsClosed() {
  StaticMutexAutoLock lock(gDBManagerMutex);

  return gClosed;
}

#ifdef DEBUG
// static
bool IndexedDatabaseManager::IsMainProcess() {
  NS_ASSERTION(Get(),
               "IsMainProcess() called before indexedDB has been initialized!");
  NS_ASSERTION((XRE_IsParentProcess()) == sIsMainProcess,
               "XRE_GetProcessType changed its tune!");
  return sIsMainProcess;
}

// static
IndexedDatabaseManager::LoggingMode IndexedDatabaseManager::GetLoggingMode() {
  MOZ_ASSERT(Get(),
             "GetLoggingMode called before IndexedDatabaseManager has been "
             "initialized!");

  return sLoggingMode;
}

// static
mozilla::LogModule* IndexedDatabaseManager::GetLoggingModule() {
  MOZ_ASSERT(Get(),
             "GetLoggingModule called before IndexedDatabaseManager has been "
             "initialized!");

  return sLoggingModule;
}

#endif  // DEBUG

// static
bool IndexedDatabaseManager::FullSynchronous() {
  MOZ_ASSERT(Get(),
             "FullSynchronous() called before indexedDB has been initialized!");

  return sFullSynchronousMode;
}

// static
uint32_t IndexedDatabaseManager::DataThreshold() {
  MOZ_ASSERT(Get(),
             "DataThreshold() called before indexedDB has been initialized!");

  return gDataThresholdBytes;
}

// static
uint32_t IndexedDatabaseManager::MaxSerializedMsgSize() {
  MOZ_ASSERT(
      Get(),
      "MaxSerializedMsgSize() called before indexedDB has been initialized!");
  MOZ_ASSERT(gMaxSerializedMsgSize > 0);

  return gMaxSerializedMsgSize;
}

// static
int32_t IndexedDatabaseManager::MaxPreloadExtraRecords() {
  MOZ_ASSERT(Get(),
             "MaxPreloadExtraRecords() called before indexedDB has been "
             "initialized!");

  return gMaxPreloadExtraRecords;
}

void IndexedDatabaseManager::ClearBackgroundActor() {
  MOZ_ASSERT(NS_IsMainThread());

  mBackgroundActor = nullptr;
}

SafeRefPtr<DatabaseFileManager> IndexedDatabaseManager::GetFileManager(
    PersistenceType aPersistenceType, const nsACString& aOrigin,
    const nsAString& aDatabaseName) {
  AssertIsOnIOThread();

  FileManagerInfo* info;
  if (!mFileManagerInfos.Get(aOrigin, &info)) {
    return nullptr;
  }

  return info->GetFileManager(aPersistenceType, aDatabaseName);
}

SafeRefPtr<DatabaseFileManager>
IndexedDatabaseManager::GetFileManagerByDatabaseFilePath(
    PersistenceType aPersistenceType, const nsACString& aOrigin,
    const nsAString& aDatabaseFilePath) {
  AssertIsOnIOThread();

  FileManagerInfo* info;
  if (!mFileManagerInfos.Get(aOrigin, &info)) {
    return nullptr;
  }

  return info->GetFileManagerByDatabaseFilePath(aPersistenceType,
                                                aDatabaseFilePath);
}

const nsTArray<SafeRefPtr<DatabaseFileManager>>&
IndexedDatabaseManager::GetFileManagers(PersistenceType aPersistenceType,
                                        const nsACString& aOrigin) {
  AssertIsOnIOThread();

  FileManagerInfo* info;
  if (!mFileManagerInfos.Get(aOrigin, &info)) {
    static nsTArray<SafeRefPtr<DatabaseFileManager>> emptyArray;
    return emptyArray;
  }

  return info->GetFileManagers(aPersistenceType);
}

void IndexedDatabaseManager::AddFileManager(
    SafeRefPtr<DatabaseFileManager> aFileManager) {
  AssertIsOnIOThread();
  MOZ_ASSERT(aFileManager);

  const auto& origin = aFileManager->Origin();
  mFileManagerInfos.GetOrInsertNew(origin)->AddFileManager(
      std::move(aFileManager));
}

void IndexedDatabaseManager::InvalidateAllFileManagers() {
  AssertIsOnIOThread();

  for (const auto& fileManagerInfo : mFileManagerInfos.Values()) {
    fileManagerInfo->InvalidateAllFileManagers();
  }

  mFileManagerInfos.Clear();
}

void IndexedDatabaseManager::InvalidateFileManagers(
    PersistenceType aPersistenceType) {
  AssertIsOnIOThread();

  for (auto iter = mFileManagerInfos.Iter(); !iter.Done(); iter.Next()) {
    iter.Data()->InvalidateAndRemoveFileManagers(aPersistenceType);

    if (!iter.Data()->HasFileManagers()) {
      iter.Remove();
    }
  }
}

void IndexedDatabaseManager::InvalidateFileManagers(
    PersistenceType aPersistenceType, const nsACString& aOrigin) {
  AssertIsOnIOThread();
  MOZ_ASSERT(!aOrigin.IsEmpty());

  FileManagerInfo* info;
  if (!mFileManagerInfos.Get(aOrigin, &info)) {
    return;
  }

  info->InvalidateAndRemoveFileManagers(aPersistenceType);

  if (!info->HasFileManagers()) {
    mFileManagerInfos.Remove(aOrigin);
  }
}

void IndexedDatabaseManager::InvalidateFileManager(
    PersistenceType aPersistenceType, const nsACString& aOrigin,
    const nsAString& aDatabaseName) {
  AssertIsOnIOThread();

  FileManagerInfo* info;
  if (!mFileManagerInfos.Get(aOrigin, &info)) {
    return;
  }

  info->InvalidateAndRemoveFileManager(aPersistenceType, aDatabaseName);

  if (!info->HasFileManagers()) {
    mFileManagerInfos.Remove(aOrigin);
  }
}

nsresult IndexedDatabaseManager::BlockAndGetFileReferences(
    PersistenceType aPersistenceType, const nsACString& aOrigin,
    const nsAString& aDatabaseName, int64_t aFileId, int32_t* aRefCnt,
    int32_t* aDBRefCnt, bool* aResult) {
  MOZ_ASSERT(NS_IsMainThread());

  if (NS_WARN_IF(!StaticPrefs::dom_indexedDB_testing())) {
    return NS_ERROR_UNEXPECTED;
  }

  if (!mBackgroundActor) {
    PBackgroundChild* bgActor = BackgroundChild::GetForCurrentThread();
    if (NS_WARN_IF(!bgActor)) {
      return NS_ERROR_FAILURE;
    }

    BackgroundUtilsChild* actor = new BackgroundUtilsChild(this);

    // We don't set event target for BackgroundUtilsChild because:
    // 1. BackgroundUtilsChild is a singleton.
    // 2. SendGetFileReferences is a sync operation to be returned asap if
    // unlabeled.
    // 3. The rest operations like DeleteMe/__delete__ only happens at shutdown.
    // Hence, we should keep it unlabeled.
    mBackgroundActor = static_cast<BackgroundUtilsChild*>(
        bgActor->SendPBackgroundIndexedDBUtilsConstructor(actor));
  }

  if (NS_WARN_IF(!mBackgroundActor)) {
    return NS_ERROR_FAILURE;
  }

  if (!mBackgroundActor->SendGetFileReferences(
          aPersistenceType, nsCString(aOrigin), nsString(aDatabaseName),
          aFileId, aRefCnt, aDBRefCnt, aResult)) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

nsresult IndexedDatabaseManager::FlushPendingFileDeletions() {
  MOZ_ASSERT(NS_IsMainThread());

  if (NS_WARN_IF(!StaticPrefs::dom_indexedDB_testing())) {
    return NS_ERROR_UNEXPECTED;
  }

  PBackgroundChild* bgActor = BackgroundChild::GetForCurrentThread();
  if (NS_WARN_IF(!bgActor)) {
    return NS_ERROR_FAILURE;
  }

  if (!bgActor->SendFlushPendingFileDeletions()) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}

// static
void IndexedDatabaseManager::LoggingModePrefChangedCallback(
    const char* /* aPrefName */, void* /* aClosure */) {
  MOZ_ASSERT(NS_IsMainThread());

  if (!Preferences::GetBool(kPrefLoggingEnabled)) {
    sLoggingMode = Logging_Disabled;
    return;
  }

  bool useProfiler = Preferences::GetBool(kPrefLoggingProfiler);
#if !defined(MOZ_GECKO_PROFILER)
  if (useProfiler) {
    NS_WARNING(
        "IndexedDB cannot create profiler marks because this build does "
        "not have profiler extensions enabled!");
    useProfiler = false;
  }
#endif

  const bool logDetails = Preferences::GetBool(kPrefLoggingDetails);

  if (useProfiler) {
    sLoggingMode = logDetails ? Logging_DetailedProfilerMarks
                              : Logging_ConciseProfilerMarks;
  } else {
    sLoggingMode = logDetails ? Logging_Detailed : Logging_Concise;
  }
}

nsresult IndexedDatabaseManager::EnsureLocale() {
  MOZ_ASSERT(NS_IsMainThread());

  nsAutoCString acceptLang;
  Preferences::GetLocalizedCString("intl.accept_languages", acceptLang);

  // Split values on commas.
  for (const auto& lang :
       nsCCharSeparatedTokenizer(acceptLang, ',').ToRange()) {
    mozilla::intl::LocaleCanonicalizer::Vector asciiString{};
    auto result = mozilla::intl::LocaleCanonicalizer::CanonicalizeICULevel1(
        PromiseFlatCString(lang).get(), asciiString);
    if (result.isOk()) {
      mLocale.AssignASCII(asciiString);
      break;
    }
  }

  if (mLocale.IsEmpty()) {
    mLocale.AssignLiteral("en_US");
  }

  return NS_OK;
}

// static
const nsCString& IndexedDatabaseManager::GetLocale() {
  IndexedDatabaseManager* idbManager = Get();
  MOZ_ASSERT(idbManager, "IDBManager is not ready!");

  MOZ_ASSERT(!idbManager->mLocale.IsEmpty());
  return idbManager->mLocale;
}

SafeRefPtr<DatabaseFileManager> FileManagerInfo::GetFileManager(
    PersistenceType aPersistenceType, const nsAString& aName) const {
  AssertIsOnIOThread();

  const auto& managers = GetImmutableArray(aPersistenceType);

  const auto end = managers.cend();
  const auto foundIt =
      std::find_if(managers.cbegin(), end, DatabaseNameMatchPredicate(&aName));

  return foundIt != end ? foundIt->clonePtr() : nullptr;
}

SafeRefPtr<DatabaseFileManager>
FileManagerInfo::GetFileManagerByDatabaseFilePath(
    PersistenceType aPersistenceType,
    const nsAString& aDatabaseFilePath) const {
  AssertIsOnIOThread();

  const auto& managers = GetImmutableArray(aPersistenceType);

  const auto end = managers.cend();
  const auto foundIt =
      std::find_if(managers.cbegin(), end,
                   DatabaseFilePathMatchPredicate(&aDatabaseFilePath));

  return foundIt != end ? foundIt->clonePtr() : nullptr;
}

const nsTArray<SafeRefPtr<DatabaseFileManager>>&
FileManagerInfo::GetFileManagers(PersistenceType aPersistenceType) const {
  AssertIsOnIOThread();

  return GetImmutableArray(aPersistenceType);
}

void FileManagerInfo::AddFileManager(
    SafeRefPtr<DatabaseFileManager> aFileManager) {
  AssertIsOnIOThread();

  nsTArray<SafeRefPtr<DatabaseFileManager>>& managers =
      GetArray(aFileManager->Type());

  NS_ASSERTION(!managers.Contains(aFileManager), "Adding more than once?!");

  managers.AppendElement(std::move(aFileManager));
}

void FileManagerInfo::InvalidateAllFileManagers() const {
  AssertIsOnIOThread();

  uint32_t i;

  for (i = 0; i < mPersistentStorageFileManagers.Length(); i++) {
    mPersistentStorageFileManagers[i]->Invalidate();
  }

  for (i = 0; i < mTemporaryStorageFileManagers.Length(); i++) {
    mTemporaryStorageFileManagers[i]->Invalidate();
  }

  for (i = 0; i < mDefaultStorageFileManagers.Length(); i++) {
    mDefaultStorageFileManagers[i]->Invalidate();
  }

  for (i = 0; i < mPrivateStorageFileManagers.Length(); i++) {
    mPrivateStorageFileManagers[i]->Invalidate();
  }
}

void FileManagerInfo::InvalidateAndRemoveFileManagers(
    PersistenceType aPersistenceType) {
  AssertIsOnIOThread();

  nsTArray<SafeRefPtr<DatabaseFileManager>>& managers =
      GetArray(aPersistenceType);

  for (uint32_t i = 0; i < managers.Length(); i++) {
    managers[i]->Invalidate();
  }

  managers.Clear();
}

void FileManagerInfo::InvalidateAndRemoveFileManager(
    PersistenceType aPersistenceType, const nsAString& aName) {
  AssertIsOnIOThread();

  auto& managers = GetArray(aPersistenceType);
  const auto end = managers.cend();
  const auto foundIt =
      std::find_if(managers.cbegin(), end, DatabaseNameMatchPredicate(&aName));

  if (foundIt != end) {
    (*foundIt)->Invalidate();
    managers.RemoveElementAt(foundIt.GetIndex());
  }
}

nsTArray<SafeRefPtr<DatabaseFileManager>>& FileManagerInfo::GetArray(
    PersistenceType aPersistenceType) {
  switch (aPersistenceType) {
    case PERSISTENCE_TYPE_PERSISTENT:
      return mPersistentStorageFileManagers;
    case PERSISTENCE_TYPE_TEMPORARY:
      return mTemporaryStorageFileManagers;
    case PERSISTENCE_TYPE_DEFAULT:
      return mDefaultStorageFileManagers;
    case PERSISTENCE_TYPE_PRIVATE:
      return mPrivateStorageFileManagers;

    case PERSISTENCE_TYPE_INVALID:
    default:
      MOZ_CRASH("Bad storage type value!");
  }
}

}  // namespace mozilla::dom