Bug 1850713: remove duplicated setting of early hint preloader id in `ScriptLoader...
[gecko.git] / dom / indexedDB / IDBTransaction.cpp
blobd984bcacdfc4813c585cfacef16b06386babddf3
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "IDBTransaction.h"
9 #include "BackgroundChildImpl.h"
10 #include "IDBDatabase.h"
11 #include "IDBEvents.h"
12 #include "IDBObjectStore.h"
13 #include "IDBRequest.h"
14 #include "mozilla/ErrorResult.h"
15 #include "mozilla/EventDispatcher.h"
16 #include "mozilla/HoldDropJSObjects.h"
17 #include "mozilla/dom/DOMException.h"
18 #include "mozilla/dom/DOMStringList.h"
19 #include "mozilla/dom/WorkerRef.h"
20 #include "mozilla/dom/WorkerPrivate.h"
21 #include "mozilla/ipc/BackgroundChild.h"
22 #include "mozilla/ScopeExit.h"
23 #include "nsPIDOMWindow.h"
24 #include "nsQueryObject.h"
25 #include "nsServiceManagerUtils.h"
26 #include "nsTHashtable.h"
27 #include "ProfilerHelpers.h"
28 #include "ReportInternalError.h"
29 #include "ThreadLocal.h"
31 // Include this last to avoid path problems on Windows.
32 #include "ActorsChild.h"
34 namespace {
35 using namespace mozilla::dom::indexedDB;
36 using namespace mozilla::ipc;
38 // TODO: Move this to xpcom/ds.
39 template <typename T, typename Range, typename Transformation>
40 nsTHashtable<T> TransformToHashtable(const Range& aRange,
41 const Transformation& aTransformation) {
42 // TODO: Determining the size of the range is not syntactically necessary (and
43 // requires random access iterators if expressed this way). It is a
44 // performance optimization. We could resort to std::distance to support any
45 // iterator category, but this would lead to a double iteration of the range
46 // in case of non-random-access iterators. It is hard to determine in general
47 // if double iteration or reallocation is worse.
48 auto res = nsTHashtable<T>(aRange.cend() - aRange.cbegin());
49 // TOOD: std::transform could be used if nsTHashtable had an insert_iterator,
50 // and this would also allow a more generic version not depending on
51 // nsTHashtable at all.
52 for (const auto& item : aRange) {
53 res.PutEntry(aTransformation(item));
55 return res;
58 ThreadLocal* GetIndexedDBThreadLocal() {
59 BackgroundChildImpl::ThreadLocal* const threadLocal =
60 BackgroundChildImpl::GetThreadLocalForCurrentThread();
61 MOZ_ASSERT(threadLocal);
63 ThreadLocal* idbThreadLocal = threadLocal->mIndexedDBThreadLocal.get();
64 MOZ_ASSERT(idbThreadLocal);
66 return idbThreadLocal;
68 } // namespace
70 namespace mozilla::dom {
72 using namespace mozilla::dom::indexedDB;
73 using namespace mozilla::ipc;
75 bool IDBTransaction::HasTransactionChild() const {
76 return (mMode == Mode::VersionChange
77 ? static_cast<void*>(
78 mBackgroundActor.mVersionChangeBackgroundActor)
79 : mBackgroundActor.mNormalBackgroundActor) != nullptr;
82 template <typename Func>
83 auto IDBTransaction::DoWithTransactionChild(const Func& aFunc) const {
84 MOZ_ASSERT(HasTransactionChild());
85 return mMode == Mode::VersionChange
86 ? aFunc(*mBackgroundActor.mVersionChangeBackgroundActor)
87 : aFunc(*mBackgroundActor.mNormalBackgroundActor);
90 IDBTransaction::IDBTransaction(IDBDatabase* const aDatabase,
91 const nsTArray<nsString>& aObjectStoreNames,
92 const Mode aMode, nsString aFilename,
93 const uint32_t aLineNo, const uint32_t aColumn,
94 CreatedFromFactoryFunction /*aDummy*/)
95 : DOMEventTargetHelper(aDatabase),
96 mDatabase(aDatabase),
97 mObjectStoreNames(aObjectStoreNames.Clone()),
98 mLoggingSerialNumber(GetIndexedDBThreadLocal()->NextTransactionSN(aMode)),
99 mNextObjectStoreId(0),
100 mNextIndexId(0),
101 mAbortCode(NS_OK),
102 mPendingRequestCount(0),
103 mFilename(std::move(aFilename)),
104 mLineNo(aLineNo),
105 mColumn(aColumn),
106 mMode(aMode),
107 mRegistered(false),
108 mNotedActiveTransaction(false) {
109 MOZ_ASSERT(aDatabase);
110 aDatabase->AssertIsOnOwningThread();
112 // This also nulls mBackgroundActor.mVersionChangeBackgroundActor, so this is
113 // valid also for mMode == Mode::VersionChange.
114 mBackgroundActor.mNormalBackgroundActor = nullptr;
116 #ifdef DEBUG
117 if (!aObjectStoreNames.IsEmpty()) {
118 // Make sure the array is properly sorted.
119 MOZ_ASSERT(
120 std::is_sorted(aObjectStoreNames.cbegin(), aObjectStoreNames.cend()));
122 // Make sure there are no duplicates in our objectStore names.
123 MOZ_ASSERT(aObjectStoreNames.cend() ==
124 std::adjacent_find(aObjectStoreNames.cbegin(),
125 aObjectStoreNames.cend()));
127 #endif
129 mozilla::HoldJSObjects(this);
132 IDBTransaction::~IDBTransaction() {
133 AssertIsOnOwningThread();
134 MOZ_ASSERT(!mPendingRequestCount);
135 MOZ_ASSERT(mReadyState != ReadyState::Active);
136 MOZ_ASSERT(mReadyState != ReadyState::Inactive);
137 MOZ_ASSERT(mReadyState != ReadyState::Committing);
138 MOZ_ASSERT(!mNotedActiveTransaction);
139 MOZ_ASSERT(mSentCommitOrAbort);
140 MOZ_ASSERT_IF(HasTransactionChild(), mFiredCompleteOrAbort);
142 if (mRegistered) {
143 mDatabase->UnregisterTransaction(*this);
144 #ifdef DEBUG
145 mRegistered = false;
146 #endif
149 if (HasTransactionChild()) {
150 if (mMode == Mode::VersionChange) {
151 mBackgroundActor.mVersionChangeBackgroundActor->SendDeleteMeInternal(
152 /* aFailedConstructor */ false);
153 } else {
154 mBackgroundActor.mNormalBackgroundActor->SendDeleteMeInternal();
157 MOZ_ASSERT(!HasTransactionChild(),
158 "SendDeleteMeInternal should have cleared!");
160 mozilla::DropJSObjects(this);
163 // static
164 SafeRefPtr<IDBTransaction> IDBTransaction::CreateVersionChange(
165 IDBDatabase* const aDatabase,
166 BackgroundVersionChangeTransactionChild* const aActor,
167 const NotNull<IDBOpenDBRequest*> aOpenRequest,
168 const int64_t aNextObjectStoreId, const int64_t aNextIndexId) {
169 MOZ_ASSERT(aDatabase);
170 aDatabase->AssertIsOnOwningThread();
171 MOZ_ASSERT(aActor);
172 MOZ_ASSERT(aNextObjectStoreId > 0);
173 MOZ_ASSERT(aNextIndexId > 0);
175 const nsTArray<nsString> emptyObjectStoreNames;
177 nsString filename;
178 uint32_t lineNo, column;
179 aOpenRequest->GetCallerLocation(filename, &lineNo, &column);
180 auto transaction = MakeSafeRefPtr<IDBTransaction>(
181 aDatabase, emptyObjectStoreNames, Mode::VersionChange,
182 std::move(filename), lineNo, column, CreatedFromFactoryFunction{});
184 transaction->NoteActiveTransaction();
186 transaction->mBackgroundActor.mVersionChangeBackgroundActor = aActor;
187 transaction->mNextObjectStoreId = aNextObjectStoreId;
188 transaction->mNextIndexId = aNextIndexId;
190 aDatabase->RegisterTransaction(*transaction);
191 transaction->mRegistered = true;
193 return transaction;
196 // static
197 SafeRefPtr<IDBTransaction> IDBTransaction::Create(
198 JSContext* const aCx, IDBDatabase* const aDatabase,
199 const nsTArray<nsString>& aObjectStoreNames, const Mode aMode) {
200 MOZ_ASSERT(aDatabase);
201 aDatabase->AssertIsOnOwningThread();
202 MOZ_ASSERT(!aObjectStoreNames.IsEmpty());
203 MOZ_ASSERT(aMode == Mode::ReadOnly || aMode == Mode::ReadWrite ||
204 aMode == Mode::ReadWriteFlush || aMode == Mode::Cleanup);
206 nsString filename;
207 uint32_t lineNo, column;
208 IDBRequest::CaptureCaller(aCx, filename, &lineNo, &column);
209 auto transaction = MakeSafeRefPtr<IDBTransaction>(
210 aDatabase, aObjectStoreNames, aMode, std::move(filename), lineNo, column,
211 CreatedFromFactoryFunction{});
213 if (!NS_IsMainThread()) {
214 WorkerPrivate* const workerPrivate = GetCurrentThreadWorkerPrivate();
215 MOZ_ASSERT(workerPrivate);
217 workerPrivate->AssertIsOnWorkerThread();
219 RefPtr<StrongWorkerRef> workerRef = StrongWorkerRef::Create(
220 workerPrivate, "IDBTransaction",
221 [transaction = AsRefPtr(transaction.clonePtr())]() {
222 transaction->AssertIsOnOwningThread();
223 if (!transaction->IsCommittingOrFinished()) {
224 IDB_REPORT_INTERNAL_ERR();
225 transaction->AbortInternal(NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR,
226 nullptr);
229 if (NS_WARN_IF(!workerRef)) {
230 #ifdef DEBUG
231 // Silence the destructor assertions if we never made this object live.
232 transaction->mReadyState = ReadyState::Finished;
233 transaction->mSentCommitOrAbort.Flip();
234 #endif
235 return nullptr;
238 transaction->mWorkerRef = std::move(workerRef);
241 nsCOMPtr<nsIRunnable> runnable =
242 do_QueryObject(transaction.unsafeGetRawPtr());
243 nsContentUtils::AddPendingIDBTransaction(runnable.forget());
245 aDatabase->RegisterTransaction(*transaction);
246 transaction->mRegistered = true;
248 return transaction;
251 // static
252 Maybe<IDBTransaction&> IDBTransaction::MaybeCurrent() {
253 using namespace mozilla::ipc;
255 MOZ_ASSERT(BackgroundChild::GetForCurrentThread());
257 return GetIndexedDBThreadLocal()->MaybeCurrentTransactionRef();
260 #ifdef DEBUG
262 void IDBTransaction::AssertIsOnOwningThread() const {
263 MOZ_ASSERT(mDatabase);
264 mDatabase->AssertIsOnOwningThread();
267 #endif // DEBUG
269 void IDBTransaction::SetBackgroundActor(
270 indexedDB::BackgroundTransactionChild* const aBackgroundActor) {
271 AssertIsOnOwningThread();
272 MOZ_ASSERT(aBackgroundActor);
273 MOZ_ASSERT(!mBackgroundActor.mNormalBackgroundActor);
274 MOZ_ASSERT(mMode != Mode::VersionChange);
276 NoteActiveTransaction();
278 mBackgroundActor.mNormalBackgroundActor = aBackgroundActor;
281 BackgroundRequestChild* IDBTransaction::StartRequest(
282 MovingNotNull<RefPtr<mozilla::dom::IDBRequest> > aRequest,
283 const RequestParams& aParams) {
284 AssertIsOnOwningThread();
285 MOZ_ASSERT(aParams.type() != RequestParams::T__None);
287 BackgroundRequestChild* const actor =
288 new BackgroundRequestChild(std::move(aRequest));
290 DoWithTransactionChild([actor, &aParams](auto& transactionChild) {
291 transactionChild.SendPBackgroundIDBRequestConstructor(actor, aParams);
294 // Balanced in BackgroundRequestChild::Recv__delete__().
295 OnNewRequest();
297 return actor;
300 void IDBTransaction::OpenCursor(PBackgroundIDBCursorChild& aBackgroundActor,
301 const OpenCursorParams& aParams) {
302 AssertIsOnOwningThread();
303 MOZ_ASSERT(aParams.type() != OpenCursorParams::T__None);
305 DoWithTransactionChild([&aBackgroundActor, &aParams](auto& actor) {
306 actor.SendPBackgroundIDBCursorConstructor(&aBackgroundActor, aParams);
309 // Balanced in BackgroundCursorChild::RecvResponse().
310 OnNewRequest();
313 void IDBTransaction::RefreshSpec(const bool aMayDelete) {
314 AssertIsOnOwningThread();
316 for (auto& objectStore : mObjectStores) {
317 objectStore->RefreshSpec(aMayDelete);
320 for (auto& objectStore : mDeletedObjectStores) {
321 objectStore->RefreshSpec(false);
325 void IDBTransaction::OnNewRequest() {
326 AssertIsOnOwningThread();
328 if (!mPendingRequestCount) {
329 MOZ_ASSERT(ReadyState::Active == mReadyState);
330 mStarted.Flip();
333 ++mPendingRequestCount;
336 void IDBTransaction::OnRequestFinished(
337 const bool aRequestCompletedSuccessfully) {
338 AssertIsOnOwningThread();
339 MOZ_ASSERT(mReadyState != ReadyState::Active);
340 MOZ_ASSERT_IF(mReadyState == ReadyState::Finished, !NS_SUCCEEDED(mAbortCode));
341 MOZ_ASSERT(mPendingRequestCount);
343 --mPendingRequestCount;
345 if (!mPendingRequestCount) {
346 if (mSentCommitOrAbort) {
347 return;
350 if (aRequestCompletedSuccessfully) {
351 if (mReadyState == ReadyState::Inactive) {
352 mReadyState = ReadyState::Committing;
355 if (NS_SUCCEEDED(mAbortCode)) {
356 SendCommit(true);
357 } else {
358 SendAbort(mAbortCode);
360 } else {
361 // Don't try to send any more messages to the parent if the request actor
362 // was killed. Set our state accordingly to Finished.
363 mReadyState = ReadyState::Finished;
364 mSentCommitOrAbort.Flip();
365 IDB_LOG_MARK_CHILD_TRANSACTION(
366 "Request actor was killed, transaction will be aborted",
367 "IDBTransaction abort", LoggingSerialNumber());
372 void IDBTransaction::SendCommit(const bool aAutoCommit) {
373 AssertIsOnOwningThread();
374 MOZ_ASSERT(NS_SUCCEEDED(mAbortCode));
375 MOZ_ASSERT(IsCommittingOrFinished());
377 // Don't do this in the macro because we always need to increment the serial
378 // number to keep in sync with the parent.
379 const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();
381 IDB_LOG_MARK_CHILD_TRANSACTION_REQUEST(
382 "Committing transaction (%s)", "IDBTransaction commit (%s)",
383 LoggingSerialNumber(), requestSerialNumber,
384 aAutoCommit ? "automatically" : "explicitly");
386 const auto lastRequestSerialNumber =
387 [this, aAutoCommit,
388 requestSerialNumber]() -> Maybe<decltype(requestSerialNumber)> {
389 if (aAutoCommit) {
390 return Nothing();
393 // In case of an explicit commit, we need to note the serial number of the
394 // last request to check if a request submitted before the commit request
395 // failed. If we are currently in an event handler for a request on this
396 // transaction, ignore this request. This is used to synchronize the
397 // transaction's committing state with the parent side, to abort the
398 // transaction in case of a request resulting in an error (see
399 // https://w3c.github.io/IndexedDB/#async-execute-request, step 5.3.). With
400 // automatic commit, this is not necessary, as the transaction's state will
401 // only be set to committing after the last request completed.
402 const auto maybeCurrentTransaction =
403 BackgroundChildImpl::GetThreadLocalForCurrentThread()
404 ->mIndexedDBThreadLocal->MaybeCurrentTransactionRef();
405 const bool dispatchingEventForThisTransaction =
406 maybeCurrentTransaction && &maybeCurrentTransaction.ref() == this;
408 return Some(requestSerialNumber
409 ? (requestSerialNumber -
410 (dispatchingEventForThisTransaction ? 0 : 1))
411 : 0);
412 }();
414 DoWithTransactionChild([lastRequestSerialNumber](auto& actor) {
415 actor.SendCommit(lastRequestSerialNumber);
418 mSentCommitOrAbort.Flip();
421 void IDBTransaction::SendAbort(const nsresult aResultCode) {
422 AssertIsOnOwningThread();
423 MOZ_ASSERT(NS_FAILED(aResultCode));
424 MOZ_ASSERT(IsCommittingOrFinished());
426 // Don't do this in the macro because we always need to increment the serial
427 // number to keep in sync with the parent.
428 const uint64_t requestSerialNumber = IDBRequest::NextSerialNumber();
430 IDB_LOG_MARK_CHILD_TRANSACTION_REQUEST(
431 "Aborting transaction with result 0x%" PRIx32,
432 "IDBTransaction abort (0x%" PRIx32 ")", LoggingSerialNumber(),
433 requestSerialNumber, static_cast<uint32_t>(aResultCode));
435 DoWithTransactionChild(
436 [aResultCode](auto& actor) { actor.SendAbort(aResultCode); });
438 mSentCommitOrAbort.Flip();
441 void IDBTransaction::NoteActiveTransaction() {
442 AssertIsOnOwningThread();
443 MOZ_ASSERT(!mNotedActiveTransaction);
445 mDatabase->NoteActiveTransaction();
446 mNotedActiveTransaction = true;
449 void IDBTransaction::MaybeNoteInactiveTransaction() {
450 AssertIsOnOwningThread();
452 if (mNotedActiveTransaction) {
453 mDatabase->NoteInactiveTransaction();
454 mNotedActiveTransaction = false;
458 void IDBTransaction::GetCallerLocation(nsAString& aFilename,
459 uint32_t* const aLineNo,
460 uint32_t* const aColumn) const {
461 AssertIsOnOwningThread();
462 MOZ_ASSERT(aLineNo);
463 MOZ_ASSERT(aColumn);
465 aFilename = mFilename;
466 *aLineNo = mLineNo;
467 *aColumn = mColumn;
470 RefPtr<IDBObjectStore> IDBTransaction::CreateObjectStore(
471 ObjectStoreSpec& aSpec) {
472 AssertIsOnOwningThread();
473 MOZ_ASSERT(aSpec.metadata().id());
474 MOZ_ASSERT(Mode::VersionChange == mMode);
475 MOZ_ASSERT(mBackgroundActor.mVersionChangeBackgroundActor);
476 MOZ_ASSERT(IsActive());
478 #ifdef DEBUG
480 // TODO: Bind name outside of lambda capture as a workaround for GCC 7 bug
481 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66735.
482 const auto& name = aSpec.metadata().name();
483 // TODO: Use #ifdef and local variable as a workaround for Bug 1583449.
484 const bool objectStoreNameDoesNotYetExist =
485 std::all_of(mObjectStores.cbegin(), mObjectStores.cend(),
486 [&name](const auto& objectStore) {
487 return objectStore->Name() != name;
489 MOZ_ASSERT(objectStoreNameDoesNotYetExist);
491 #endif
493 MOZ_ALWAYS_TRUE(
494 mBackgroundActor.mVersionChangeBackgroundActor->SendCreateObjectStore(
495 aSpec.metadata()));
497 RefPtr<IDBObjectStore> objectStore = IDBObjectStore::Create(
498 SafeRefPtr{this, AcquireStrongRefFromRawPtr{}}, aSpec);
499 MOZ_ASSERT(objectStore);
501 mObjectStores.AppendElement(objectStore);
503 return objectStore;
506 void IDBTransaction::DeleteObjectStore(const int64_t aObjectStoreId) {
507 AssertIsOnOwningThread();
508 MOZ_ASSERT(aObjectStoreId);
509 MOZ_ASSERT(Mode::VersionChange == mMode);
510 MOZ_ASSERT(mBackgroundActor.mVersionChangeBackgroundActor);
511 MOZ_ASSERT(IsActive());
513 MOZ_ALWAYS_TRUE(
514 mBackgroundActor.mVersionChangeBackgroundActor->SendDeleteObjectStore(
515 aObjectStoreId));
517 const auto foundIt =
518 std::find_if(mObjectStores.begin(), mObjectStores.end(),
519 [aObjectStoreId](const auto& objectStore) {
520 return objectStore->Id() == aObjectStoreId;
522 if (foundIt != mObjectStores.end()) {
523 auto& objectStore = *foundIt;
524 objectStore->NoteDeletion();
526 RefPtr<IDBObjectStore>* deletedObjectStore =
527 mDeletedObjectStores.AppendElement();
528 deletedObjectStore->swap(objectStore);
530 mObjectStores.RemoveElementAt(foundIt);
534 void IDBTransaction::RenameObjectStore(const int64_t aObjectStoreId,
535 const nsAString& aName) const {
536 AssertIsOnOwningThread();
537 MOZ_ASSERT(aObjectStoreId);
538 MOZ_ASSERT(Mode::VersionChange == mMode);
539 MOZ_ASSERT(mBackgroundActor.mVersionChangeBackgroundActor);
540 MOZ_ASSERT(IsActive());
542 MOZ_ALWAYS_TRUE(
543 mBackgroundActor.mVersionChangeBackgroundActor->SendRenameObjectStore(
544 aObjectStoreId, nsString(aName)));
547 void IDBTransaction::CreateIndex(
548 IDBObjectStore* const aObjectStore,
549 const indexedDB::IndexMetadata& aMetadata) const {
550 AssertIsOnOwningThread();
551 MOZ_ASSERT(aObjectStore);
552 MOZ_ASSERT(aMetadata.id());
553 MOZ_ASSERT(Mode::VersionChange == mMode);
554 MOZ_ASSERT(mBackgroundActor.mVersionChangeBackgroundActor);
555 MOZ_ASSERT(IsActive());
557 MOZ_ALWAYS_TRUE(
558 mBackgroundActor.mVersionChangeBackgroundActor->SendCreateIndex(
559 aObjectStore->Id(), aMetadata));
562 void IDBTransaction::DeleteIndex(IDBObjectStore* const aObjectStore,
563 const int64_t aIndexId) const {
564 AssertIsOnOwningThread();
565 MOZ_ASSERT(aObjectStore);
566 MOZ_ASSERT(aIndexId);
567 MOZ_ASSERT(Mode::VersionChange == mMode);
568 MOZ_ASSERT(mBackgroundActor.mVersionChangeBackgroundActor);
569 MOZ_ASSERT(IsActive());
571 MOZ_ALWAYS_TRUE(
572 mBackgroundActor.mVersionChangeBackgroundActor->SendDeleteIndex(
573 aObjectStore->Id(), aIndexId));
576 void IDBTransaction::RenameIndex(IDBObjectStore* const aObjectStore,
577 const int64_t aIndexId,
578 const nsAString& aName) const {
579 AssertIsOnOwningThread();
580 MOZ_ASSERT(aObjectStore);
581 MOZ_ASSERT(aIndexId);
582 MOZ_ASSERT(Mode::VersionChange == mMode);
583 MOZ_ASSERT(mBackgroundActor.mVersionChangeBackgroundActor);
584 MOZ_ASSERT(IsActive());
586 MOZ_ALWAYS_TRUE(
587 mBackgroundActor.mVersionChangeBackgroundActor->SendRenameIndex(
588 aObjectStore->Id(), aIndexId, nsString(aName)));
591 void IDBTransaction::AbortInternal(const nsresult aAbortCode,
592 RefPtr<DOMException> aError) {
593 AssertIsOnOwningThread();
594 MOZ_ASSERT(NS_FAILED(aAbortCode));
595 MOZ_ASSERT(!IsCommittingOrFinished());
597 const bool isVersionChange = mMode == Mode::VersionChange;
598 const bool needToSendAbort = !mStarted;
600 mAbortCode = aAbortCode;
601 mReadyState = ReadyState::Finished;
602 mError = std::move(aError);
604 if (isVersionChange) {
605 // If a version change transaction is aborted, we must revert the world
606 // back to its previous state unless we're being invalidated after the
607 // transaction already completed.
608 if (!mDatabase->IsInvalidated()) {
609 mDatabase->RevertToPreviousState();
612 // We do the reversion only for the mObjectStores/mDeletedObjectStores but
613 // not for the mIndexes/mDeletedIndexes of each IDBObjectStore because it's
614 // time-consuming(O(m*n)) and mIndexes/mDeletedIndexes won't be used anymore
615 // in IDBObjectStore::(Create|Delete)Index() and IDBObjectStore::Index() in
616 // which all the executions are returned earlier by
617 // !transaction->IsActive().
619 const nsTArray<ObjectStoreSpec>& specArray =
620 mDatabase->Spec()->objectStores();
622 if (specArray.IsEmpty()) {
623 // This case is specially handled as a performance optimization, it is
624 // equivalent to the else block.
625 mObjectStores.Clear();
626 } else {
627 const auto validIds = TransformToHashtable<nsUint64HashKey>(
628 specArray, [](const auto& spec) {
629 const int64_t objectStoreId = spec.metadata().id();
630 MOZ_ASSERT(objectStoreId);
631 return static_cast<uint64_t>(objectStoreId);
634 mObjectStores.RemoveLastElements(
635 mObjectStores.end() -
636 std::remove_if(mObjectStores.begin(), mObjectStores.end(),
637 [&validIds](const auto& objectStore) {
638 return !validIds.Contains(
639 uint64_t(objectStore->Id()));
640 }));
642 std::copy_if(std::make_move_iterator(mDeletedObjectStores.begin()),
643 std::make_move_iterator(mDeletedObjectStores.end()),
644 MakeBackInserter(mObjectStores),
645 [&validIds](const auto& deletedObjectStore) {
646 const int64_t objectStoreId = deletedObjectStore->Id();
647 MOZ_ASSERT(objectStoreId);
648 return validIds.Contains(uint64_t(objectStoreId));
651 mDeletedObjectStores.Clear();
654 // Fire the abort event if there are no outstanding requests. Otherwise the
655 // abort event will be fired when all outstanding requests finish.
656 if (needToSendAbort) {
657 SendAbort(aAbortCode);
660 if (isVersionChange) {
661 mDatabase->Close();
665 void IDBTransaction::Abort(IDBRequest* const aRequest) {
666 AssertIsOnOwningThread();
667 MOZ_ASSERT(aRequest);
669 if (IsCommittingOrFinished()) {
670 // Already started (and maybe finished) the commit or abort so there is
671 // nothing to do here.
672 return;
675 ErrorResult rv;
676 RefPtr<DOMException> error = aRequest->GetError(rv);
678 // TODO: Do we deliberately ignore rv here? Isn't there a static analysis that
679 // prevents that?
681 AbortInternal(aRequest->GetErrorCode(), std::move(error));
684 void IDBTransaction::Abort(const nsresult aErrorCode) {
685 AssertIsOnOwningThread();
687 if (IsCommittingOrFinished()) {
688 // Already started (and maybe finished) the commit or abort so there is
689 // nothing to do here.
690 return;
693 AbortInternal(aErrorCode, DOMException::Create(aErrorCode));
696 // Specified by https://w3c.github.io/IndexedDB/#dom-idbtransaction-abort.
697 void IDBTransaction::Abort(ErrorResult& aRv) {
698 AssertIsOnOwningThread();
700 if (IsCommittingOrFinished()) {
701 aRv = NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR;
702 return;
705 mReadyState = ReadyState::Inactive;
707 AbortInternal(NS_ERROR_DOM_INDEXEDDB_ABORT_ERR, nullptr);
709 mAbortedByScript.Flip();
712 // Specified by https://w3c.github.io/IndexedDB/#dom-idbtransaction-commit.
713 void IDBTransaction::Commit(ErrorResult& aRv) {
714 AssertIsOnOwningThread();
716 if (mReadyState != ReadyState::Active || !mNotedActiveTransaction) {
717 aRv = NS_ERROR_DOM_INVALID_STATE_ERR;
718 return;
721 MOZ_ASSERT(!mSentCommitOrAbort);
723 MOZ_ASSERT(mReadyState == ReadyState::Active);
724 mReadyState = ReadyState::Committing;
725 if (NS_WARN_IF(NS_FAILED(mAbortCode))) {
726 SendAbort(mAbortCode);
727 aRv = mAbortCode;
728 return;
731 #ifdef DEBUG
732 mWasExplicitlyCommitted.Flip();
733 #endif
735 SendCommit(false);
738 void IDBTransaction::FireCompleteOrAbortEvents(const nsresult aResult) {
739 AssertIsOnOwningThread();
740 MOZ_ASSERT(!mFiredCompleteOrAbort);
742 mReadyState = ReadyState::Finished;
744 #ifdef DEBUG
745 mFiredCompleteOrAbort.Flip();
746 #endif
748 // Make sure we drop the WorkerRef when this function completes.
749 const auto scopeExit = MakeScopeExit([&] { mWorkerRef = nullptr; });
751 RefPtr<Event> event;
752 if (NS_SUCCEEDED(aResult)) {
753 event = CreateGenericEvent(this, nsDependentString(kCompleteEventType),
754 eDoesNotBubble, eNotCancelable);
755 MOZ_ASSERT(event);
757 // If we hit this assertion, it probably means transaction object on the
758 // parent process doesn't propagate error properly.
759 MOZ_ASSERT(NS_SUCCEEDED(mAbortCode));
760 } else {
761 if (aResult == NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR) {
762 mDatabase->SetQuotaExceeded();
765 if (!mError && !mAbortedByScript) {
766 mError = DOMException::Create(aResult);
769 event = CreateGenericEvent(this, nsDependentString(kAbortEventType),
770 eDoesBubble, eNotCancelable);
771 MOZ_ASSERT(event);
773 if (NS_SUCCEEDED(mAbortCode)) {
774 mAbortCode = aResult;
778 if (NS_SUCCEEDED(mAbortCode)) {
779 IDB_LOG_MARK_CHILD_TRANSACTION("Firing 'complete' event",
780 "IDBTransaction 'complete' event",
781 mLoggingSerialNumber);
782 } else {
783 IDB_LOG_MARK_CHILD_TRANSACTION(
784 "Firing 'abort' event with error 0x%" PRIx32,
785 "IDBTransaction 'abort' event (0x%" PRIx32 ")", mLoggingSerialNumber,
786 static_cast<uint32_t>(mAbortCode));
789 IgnoredErrorResult rv;
790 DispatchEvent(*event, rv);
791 if (rv.Failed()) {
792 NS_WARNING("DispatchEvent failed!");
795 // Normally, we note inactive transaction here instead of
796 // IDBTransaction::ClearBackgroundActor() because here is the earliest place
797 // to know that it becomes non-blocking to allow the scheduler to start the
798 // preemption as soon as it can.
799 // Note: If the IDBTransaction object is held by the script,
800 // ClearBackgroundActor() will be done in ~IDBTransaction() until garbage
801 // collected after its window is closed which prevents us to preempt its
802 // window immediately after committed.
803 MaybeNoteInactiveTransaction();
806 int64_t IDBTransaction::NextObjectStoreId() {
807 AssertIsOnOwningThread();
808 MOZ_ASSERT(Mode::VersionChange == mMode);
810 return mNextObjectStoreId++;
813 int64_t IDBTransaction::NextIndexId() {
814 AssertIsOnOwningThread();
815 MOZ_ASSERT(Mode::VersionChange == mMode);
817 return mNextIndexId++;
820 void IDBTransaction::InvalidateCursorCaches() {
821 AssertIsOnOwningThread();
823 for (const auto& cursor : mCursors) {
824 cursor->InvalidateCachedResponses();
828 void IDBTransaction::RegisterCursor(IDBCursor& aCursor) {
829 AssertIsOnOwningThread();
831 mCursors.AppendElement(WrapNotNullUnchecked(&aCursor));
834 void IDBTransaction::UnregisterCursor(IDBCursor& aCursor) {
835 AssertIsOnOwningThread();
837 DebugOnly<bool> removed = mCursors.RemoveElement(&aCursor);
838 MOZ_ASSERT(removed);
841 nsIGlobalObject* IDBTransaction::GetParentObject() const {
842 AssertIsOnOwningThread();
844 return mDatabase->GetParentObject();
847 IDBTransactionMode IDBTransaction::GetMode(ErrorResult& aRv) const {
848 AssertIsOnOwningThread();
850 switch (mMode) {
851 case Mode::ReadOnly:
852 return IDBTransactionMode::Readonly;
854 case Mode::ReadWrite:
855 return IDBTransactionMode::Readwrite;
857 case Mode::ReadWriteFlush:
858 return IDBTransactionMode::Readwriteflush;
860 case Mode::Cleanup:
861 return IDBTransactionMode::Cleanup;
863 case Mode::VersionChange:
864 return IDBTransactionMode::Versionchange;
866 case Mode::Invalid:
867 default:
868 MOZ_CRASH("Bad mode!");
872 DOMException* IDBTransaction::GetError() const {
873 AssertIsOnOwningThread();
875 return mError;
878 RefPtr<DOMStringList> IDBTransaction::ObjectStoreNames() const {
879 AssertIsOnOwningThread();
881 if (mMode == Mode::VersionChange) {
882 return mDatabase->ObjectStoreNames();
885 auto list = MakeRefPtr<DOMStringList>();
886 list->StringArray() = mObjectStoreNames.Clone();
887 return list;
890 RefPtr<IDBObjectStore> IDBTransaction::ObjectStore(const nsAString& aName,
891 ErrorResult& aRv) {
892 AssertIsOnOwningThread();
894 if (IsCommittingOrFinished()) {
895 aRv.ThrowInvalidStateError("Transaction is already committing or done.");
896 return nullptr;
899 auto* const spec = [this, &aName]() -> ObjectStoreSpec* {
900 if (IDBTransaction::Mode::VersionChange == mMode ||
901 mObjectStoreNames.Contains(aName)) {
902 return mDatabase->LookupModifiableObjectStoreSpec(
903 [&aName](const auto& objectStore) {
904 return objectStore.metadata().name() == aName;
907 return nullptr;
908 }();
910 if (!spec) {
911 aRv.Throw(NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR);
912 return nullptr;
915 RefPtr<IDBObjectStore> objectStore;
917 const auto foundIt = std::find_if(
918 mObjectStores.cbegin(), mObjectStores.cend(),
919 [desiredId = spec->metadata().id()](const auto& existingObjectStore) {
920 return existingObjectStore->Id() == desiredId;
922 if (foundIt != mObjectStores.cend()) {
923 objectStore = *foundIt;
924 } else {
925 objectStore = IDBObjectStore::Create(
926 SafeRefPtr{this, AcquireStrongRefFromRawPtr{}}, *spec);
927 MOZ_ASSERT(objectStore);
929 mObjectStores.AppendElement(objectStore);
932 return objectStore;
935 NS_IMPL_ADDREF_INHERITED(IDBTransaction, DOMEventTargetHelper)
936 NS_IMPL_RELEASE_INHERITED(IDBTransaction, DOMEventTargetHelper)
938 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(IDBTransaction)
939 NS_INTERFACE_MAP_ENTRY(nsIRunnable)
940 NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
942 NS_IMPL_CYCLE_COLLECTION_CLASS(IDBTransaction)
944 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(IDBTransaction,
945 DOMEventTargetHelper)
946 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDatabase)
947 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mError)
948 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mObjectStores)
949 NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mDeletedObjectStores)
950 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
952 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(IDBTransaction,
953 DOMEventTargetHelper)
954 // Don't unlink mDatabase!
955 NS_IMPL_CYCLE_COLLECTION_UNLINK(mError)
956 NS_IMPL_CYCLE_COLLECTION_UNLINK(mObjectStores)
957 NS_IMPL_CYCLE_COLLECTION_UNLINK(mDeletedObjectStores)
958 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
960 JSObject* IDBTransaction::WrapObject(JSContext* const aCx,
961 JS::Handle<JSObject*> aGivenProto) {
962 AssertIsOnOwningThread();
964 return IDBTransaction_Binding::Wrap(aCx, this, std::move(aGivenProto));
967 void IDBTransaction::GetEventTargetParent(EventChainPreVisitor& aVisitor) {
968 AssertIsOnOwningThread();
970 aVisitor.mCanHandle = true;
971 aVisitor.SetParentTarget(mDatabase, false);
974 NS_IMETHODIMP
975 IDBTransaction::Run() {
976 AssertIsOnOwningThread();
978 // TODO: Instead of checking for Finished and Committing states here, we could
979 // remove the transaction from the pending IDB transactions list on
980 // abort/commit.
982 if (ReadyState::Finished == mReadyState) {
983 // There are three cases where mReadyState is set to Finished: In
984 // FileCompleteOrAbortEvents, AbortInternal and in CommitIfNotStarted. We
985 // shouldn't get here after CommitIfNotStarted again.
986 MOZ_ASSERT(mFiredCompleteOrAbort || IsAborted());
987 return NS_OK;
990 if (ReadyState::Committing == mReadyState) {
991 MOZ_ASSERT(mSentCommitOrAbort);
992 return NS_OK;
994 // We're back at the event loop, no longer newborn, so
995 // return to Inactive state:
996 // https://w3c.github.io/IndexedDB/#cleanup-indexed-database-transactions.
997 MOZ_ASSERT(ReadyState::Active == mReadyState);
998 mReadyState = ReadyState::Inactive;
1000 CommitIfNotStarted();
1002 return NS_OK;
1005 void IDBTransaction::CommitIfNotStarted() {
1006 AssertIsOnOwningThread();
1008 MOZ_ASSERT(ReadyState::Inactive == mReadyState);
1010 // Maybe commit if there were no requests generated.
1011 if (!mStarted) {
1012 MOZ_ASSERT(!mPendingRequestCount);
1013 mReadyState = ReadyState::Finished;
1015 SendCommit(true);
1019 } // namespace mozilla::dom