From 71848c23a4d09bbb7eff1b27d2cb28904e35240d Mon Sep 17 00:00:00 2001 From: Moonchild Date: Fri, 24 Jul 2020 11:09:54 +0000 Subject: Issue #1587 Part 11 (followup 1): Implement multithreaded signals for workers. --- dom/cache/TypeUtils.cpp | 6 +- dom/fetch/Fetch.cpp | 45 +- dom/fetch/Fetch.h | 3 + dom/fetch/FetchConsumer.cpp | 1413 +++++++++++++++--------------- dom/fetch/FetchConsumer.h | 6 + dom/fetch/Request.cpp | 34 +- dom/fetch/Request.h | 13 +- dom/fetch/Response.cpp | 11 +- dom/fetch/Response.h | 10 +- dom/webidl/Request.webidl | 4 + dom/workers/ScriptLoader.cpp | 2 +- dom/workers/ServiceWorkerPrivate.cpp | 2 +- dom/workers/ServiceWorkerScriptCache.cpp | 2 +- 13 files changed, 823 insertions(+), 728 deletions(-) diff --git a/dom/cache/TypeUtils.cpp b/dom/cache/TypeUtils.cpp index f8c5cd7be..5c3661d66 100644 --- a/dom/cache/TypeUtils.cpp +++ b/dom/cache/TypeUtils.cpp @@ -253,7 +253,7 @@ TypeUtils::ToResponse(const CacheResponse& aIn) { if (aIn.type() == ResponseType::Error) { RefPtr error = InternalResponse::NetworkError(); - RefPtr r = new Response(GetGlobalObject(), error); + RefPtr r = new Response(GetGlobalObject(), error, nullptr); return r.forget(); } @@ -302,7 +302,7 @@ TypeUtils::ToResponse(const CacheResponse& aIn) } MOZ_DIAGNOSTIC_ASSERT(ir); - RefPtr ref = new Response(GetGlobalObject(), ir); + RefPtr ref = new Response(GetGlobalObject(), ir, nullptr); return ref.forget(); } already_AddRefed @@ -345,7 +345,7 @@ already_AddRefed TypeUtils::ToRequest(const CacheRequest& aIn) { RefPtr internalRequest = ToInternalRequest(aIn); - RefPtr request = new Request(GetGlobalObject(), internalRequest); + RefPtr request = new Request(GetGlobalObject(), internalRequest, nullptr); return request.forget(); } diff --git a/dom/fetch/Fetch.cpp b/dom/fetch/Fetch.cpp index 191f4cfc3..f0350fbce 100644 --- a/dom/fetch/Fetch.cpp +++ b/dom/fetch/Fetch.cpp @@ -111,6 +111,12 @@ public: return mSignalMainThread; } + AbortSignal* + GetSignalForTargetThread() + { + return mFollowingSignal; + } + void Shutdown() { @@ -161,7 +167,7 @@ public: } AbortSignal* - GetAbortSignal() + GetAbortSignalForMainThread() { MOZ_ASSERT(NS_IsMainThread()); @@ -172,6 +178,18 @@ public: return mSignalProxy->GetOrCreateSignalForMainThread(); } + AbortSignal* + GetAbortSignalForTargetThread() + { + mPromiseProxy->GetWorkerPrivate()->AssertIsOnWorkerThread(); + + if (!mSignalProxy) { + return nullptr; + } + + return mSignalProxy->GetSignalForTargetThread(); + } + void OnResponseAvailableInternal(InternalResponse* aResponse) override; @@ -205,14 +223,16 @@ class MainThreadFetchResolver final : public FetchDriverObserver RefPtr mPromise; RefPtr mResponse; RefPtr mFetchObserver; + RefPtr mSignal; nsCOMPtr mDocument; NS_DECL_OWNINGTHREAD public: - MainThreadFetchResolver(Promise* aPromise, FetchObserver* aObserver) + MainThreadFetchResolver(Promise* aPromise, FetchObserver* aObserver, AbortSignal* aSignal) : mPromise(aPromise) , mFetchObserver(aObserver) + , mSignal(aSignal) {} void @@ -287,7 +307,7 @@ public: fetch->SetWorkerScript(spec); } - RefPtr signal = mResolver->GetAbortSignal(); + RefPtr signal = mResolver->GetAbortSignalForMainThread(); // ...but release it before calling Fetch, because mResolver's callback can // be called synchronously and they want the mutex, too. @@ -329,10 +349,7 @@ FetchRequest(nsIGlobalObject* aGlobal, const RequestOrUSVString& aInput, RefPtr r = request->GetInternalRequest(); - RefPtr signal; - if (aInit.mSignal.WasPassed()) { - signal = &aInit.mSignal.Value(); - } + RefPtr signal = request->GetSignal(); if (signal && signal->Aborted()) { // An already aborted signal should reject immediately. @@ -373,7 +390,7 @@ FetchRequest(nsIGlobalObject* aGlobal, const RequestOrUSVString& aInput, } RefPtr resolver = - new MainThreadFetchResolver(p, observer); + new MainThreadFetchResolver(p, observer, signal); RefPtr fetch = new FetchDriver(r, principal, loadGroup); fetch->SetDocument(doc); resolver->SetDocument(doc); @@ -416,7 +433,7 @@ MainThreadFetchResolver::OnResponseAvailableInternal(InternalResponse* aResponse } nsCOMPtr go = mPromise->GetParentObject(); - mResponse = new Response(go, aResponse); + mResponse = new Response(go, aResponse, mSignal); mPromise->MaybeResolve(mResponse); } else { if (mFetchObserver) { @@ -479,7 +496,7 @@ public: } RefPtr global = aWorkerPrivate->GlobalScope(); - RefPtr response = new Response(global, mInternalResponse); + RefPtr response = new Response(global, mInternalResponse, mResolver->GetAbortSignalForTargetThread()); promise->MaybeResolve(response); } else { if (mResolver->mFetchObserver) { @@ -926,6 +943,12 @@ template already_AddRefed FetchBody::ConsumeBody(FetchConsumeType aType, ErrorResult& aRv) { + RefPtr signal = DerivedClass()->GetSignal(); + if (signal && signal->Aborted()) { + aRv.Throw(NS_ERROR_DOM_ABORT_ERR); + return nullptr; + } + if (BodyUsed()) { aRv.ThrowTypeError(); return nullptr; @@ -935,7 +958,7 @@ FetchBody::ConsumeBody(FetchConsumeType aType, ErrorResult& aRv) RefPtr promise = FetchBodyConsumer::Create(DerivedClass()->GetParentObject(), - this, aType, aRv); + this, signal, aType, aRv); if (NS_WARN_IF(aRv.Failed())) { return nullptr; } diff --git a/dom/fetch/Fetch.h b/dom/fetch/Fetch.h index fc50d3fda..842066152 100644 --- a/dom/fetch/Fetch.h +++ b/dom/fetch/Fetch.h @@ -162,6 +162,9 @@ public: return mMimeType; } + virtual AbortSignal* + GetSignal() const = 0; + protected: FetchBody(); diff --git a/dom/fetch/FetchConsumer.cpp b/dom/fetch/FetchConsumer.cpp index e82e5ec51..581f014d9 100644 --- a/dom/fetch/FetchConsumer.cpp +++ b/dom/fetch/FetchConsumer.cpp @@ -1,699 +1,714 @@ -/* -*- 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 "Fetch.h" -#include "FetchConsumer.h" - -#include "nsIInputStreamPump.h" -#include "nsProxyRelease.h" -#include "WorkerPrivate.h" -#include "WorkerRunnable.h" -#include "WorkerScope.h" -#include "Workers.h" - -namespace mozilla { -namespace dom { - -using namespace workers; - -namespace { - -template -class FetchBodyWorkerHolder final : public workers::WorkerHolder -{ - RefPtr> mConsumer; - bool mWasNotified; - -public: - explicit FetchBodyWorkerHolder(FetchBodyConsumer* aConsumer) - : mConsumer(aConsumer) - , mWasNotified(false) - { - MOZ_ASSERT(aConsumer); - } - - ~FetchBodyWorkerHolder() = default; - - bool Notify(workers::Status aStatus) override - { - MOZ_ASSERT(aStatus > workers::Running); - if (!mWasNotified) { - mWasNotified = true; - mConsumer->ShutDownMainThreadConsuming(); - } - - return true; - } -}; - -template -class BeginConsumeBodyRunnable final : public Runnable -{ - RefPtr> mFetchBodyConsumer; - -public: - explicit BeginConsumeBodyRunnable(FetchBodyConsumer* aConsumer) - : mFetchBodyConsumer(aConsumer) - { } - - NS_IMETHOD - Run() override - { - mFetchBodyConsumer->BeginConsumeBodyMainThread(); - return NS_OK; - } -}; - -/* - * Called on successfully reading the complete stream. - */ -template -class ContinueConsumeBodyRunnable final : public MainThreadWorkerRunnable -{ - RefPtr> mFetchBodyConsumer; - nsresult mStatus; - uint32_t mLength; - uint8_t* mResult; - -public: - ContinueConsumeBodyRunnable(FetchBodyConsumer* aFetchBodyConsumer, - nsresult aStatus, uint32_t aLength, - uint8_t* aResult) - : MainThreadWorkerRunnable(aFetchBodyConsumer->GetWorkerPrivate()) - , mFetchBodyConsumer(aFetchBodyConsumer) - , mStatus(aStatus) - , mLength(aLength) - , mResult(aResult) - { - MOZ_ASSERT(NS_IsMainThread()); - } - - bool - WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override - { - mFetchBodyConsumer->ContinueConsumeBody(mStatus, mLength, mResult); - return true; - } -}; - -template -class FailConsumeBodyWorkerRunnable : public MainThreadWorkerControlRunnable -{ - RefPtr> mBodyConsumer; - -public: - explicit FailConsumeBodyWorkerRunnable(FetchBodyConsumer* aBodyConsumer) - : MainThreadWorkerControlRunnable(aBodyConsumer->GetWorkerPrivate()) - , mBodyConsumer(aBodyConsumer) - { - AssertIsOnMainThread(); - } - - bool - WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override - { - mBodyConsumer->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr); - return true; - } -}; - -/* - * In case of failure to create a stream pump or dispatch stream completion to - * worker, ensure we cleanup properly. Thread agnostic. - */ -template -class MOZ_STACK_CLASS AutoFailConsumeBody final -{ - RefPtr> mBodyConsumer; - -public: - explicit AutoFailConsumeBody(FetchBodyConsumer* aBodyConsumer) - : mBodyConsumer(aBodyConsumer) - {} - - ~AutoFailConsumeBody() - { - AssertIsOnMainThread(); - - if (mBodyConsumer) { - if (mBodyConsumer->GetWorkerPrivate()) { - RefPtr> r = - new FailConsumeBodyWorkerRunnable(mBodyConsumer); - if (!r->Dispatch()) { - MOZ_CRASH("We are going to leak"); - } - } else { - mBodyConsumer->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr); - } - } - } - - void - DontFail() - { - mBodyConsumer = nullptr; - } -}; - -/* - * Called on successfully reading the complete stream for Blob. - */ -template -class ContinueConsumeBlobBodyRunnable final : public MainThreadWorkerRunnable -{ - RefPtr> mFetchBodyConsumer; - RefPtr mBlobImpl; - -public: - ContinueConsumeBlobBodyRunnable(FetchBodyConsumer* aFetchBodyConsumer, - BlobImpl* aBlobImpl) - : MainThreadWorkerRunnable(aFetchBodyConsumer->GetWorkerPrivate()) - , mFetchBodyConsumer(aFetchBodyConsumer) - , mBlobImpl(aBlobImpl) - { - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(mBlobImpl); - } - - bool - WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override - { - mFetchBodyConsumer->ContinueConsumeBlobBody(mBlobImpl); - return true; - } -}; - -template -class ConsumeBodyDoneObserver : public nsIStreamLoaderObserver - , public MutableBlobStorageCallback -{ - RefPtr> mFetchBodyConsumer; - -public: - NS_DECL_THREADSAFE_ISUPPORTS - - explicit ConsumeBodyDoneObserver(FetchBodyConsumer* aFetchBodyConsumer) - : mFetchBodyConsumer(aFetchBodyConsumer) - { } - - NS_IMETHOD - OnStreamComplete(nsIStreamLoader* aLoader, - nsISupports* aCtxt, - nsresult aStatus, - uint32_t aResultLength, - const uint8_t* aResult) override - { - MOZ_ASSERT(NS_IsMainThread()); - - // The loading is completed. Let's nullify the pump before continuing the - // consuming of the body. - mFetchBodyConsumer->NullifyConsumeBodyPump(); - - uint8_t* nonconstResult = const_cast(aResult); - if (mFetchBodyConsumer->GetWorkerPrivate()) { - RefPtr> r = - new ContinueConsumeBodyRunnable(mFetchBodyConsumer, - aStatus, - aResultLength, - nonconstResult); - if (!r->Dispatch()) { - NS_WARNING("Could not dispatch ConsumeBodyRunnable"); - // Return failure so that aResult is freed. - return NS_ERROR_FAILURE; - } - } else { - mFetchBodyConsumer->ContinueConsumeBody(aStatus, aResultLength, - nonconstResult); - } - - // FetchBody is responsible for data. - return NS_SUCCESS_ADOPTED_DATA; - } - - virtual void BlobStoreCompleted(MutableBlobStorage* aBlobStorage, - Blob* aBlob, - nsresult aRv) override - { - // On error. - if (NS_FAILED(aRv)) { - OnStreamComplete(nullptr, nullptr, aRv, 0, nullptr); - return; - } - - // The loading is completed. Let's nullify the pump before continuing the - // consuming of the body. - mFetchBodyConsumer->NullifyConsumeBodyPump(); - - MOZ_ASSERT(aBlob); - - if (mFetchBodyConsumer->GetWorkerPrivate()) { - RefPtr> r = - new ContinueConsumeBlobBodyRunnable(mFetchBodyConsumer, - aBlob->Impl()); - - if (!r->Dispatch()) { - NS_WARNING("Could not dispatch ConsumeBlobBodyRunnable"); - return; - } - } else { - mFetchBodyConsumer->ContinueConsumeBlobBody(aBlob->Impl()); - } - } - -private: - virtual ~ConsumeBodyDoneObserver() - { } -}; - -template -NS_IMPL_ADDREF(ConsumeBodyDoneObserver) -template -NS_IMPL_RELEASE(ConsumeBodyDoneObserver) -template -NS_INTERFACE_MAP_BEGIN(ConsumeBodyDoneObserver) - NS_INTERFACE_MAP_ENTRY(nsIStreamLoaderObserver) - NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamLoaderObserver) -NS_INTERFACE_MAP_END - -} // anonymous - -template -/* static */ already_AddRefed -FetchBodyConsumer::Create(nsIGlobalObject* aGlobal, - FetchBody* aBody, - FetchConsumeType aType, - ErrorResult& aRv) -{ - MOZ_ASSERT(aBody); - - nsCOMPtr bodyStream; - aBody->DerivedClass()->GetBody(getter_AddRefs(bodyStream)); - if (!bodyStream) { - aRv = NS_NewCStringInputStream(getter_AddRefs(bodyStream), EmptyCString()); - if (NS_WARN_IF(aRv.Failed())) { - return nullptr; - } - } - - RefPtr promise = Promise::Create(aGlobal, aRv); - if (aRv.Failed()) { - return nullptr; - } - - WorkerPrivate* workerPrivate = nullptr; - if (!NS_IsMainThread()) { - workerPrivate = GetCurrentThreadWorkerPrivate(); - MOZ_ASSERT(workerPrivate); - } - - RefPtr> consumer = - new FetchBodyConsumer(aGlobal, workerPrivate, aBody, bodyStream, - promise, aType); - - if (!NS_IsMainThread()) { - MOZ_ASSERT(workerPrivate); - if (NS_WARN_IF(!consumer->RegisterWorkerHolder())) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - } else { - nsCOMPtr os = mozilla::services::GetObserverService(); - if (NS_WARN_IF(!os)) { - aRv.Throw(NS_ERROR_FAILURE); - return nullptr; - } - - aRv = os->AddObserver(consumer, DOM_WINDOW_DESTROYED_TOPIC, true); - if (NS_WARN_IF(aRv.Failed())) { - return nullptr; - } - - aRv = os->AddObserver(consumer, DOM_WINDOW_FROZEN_TOPIC, true); - if (NS_WARN_IF(aRv.Failed())) { - return nullptr; - } - } - - nsCOMPtr r = new BeginConsumeBodyRunnable(consumer); - - aRv = NS_DispatchToMainThread(r.forget()); - - if (NS_WARN_IF(aRv.Failed())) { - return nullptr; - } - - return promise.forget(); -} - -template -void -FetchBodyConsumer::ReleaseObject() -{ - AssertIsOnTargetThread(); - - if (NS_IsMainThread()) { - nsCOMPtr os = mozilla::services::GetObserverService(); - if (os) { - os->RemoveObserver(this, DOM_WINDOW_DESTROYED_TOPIC); - os->RemoveObserver(this, DOM_WINDOW_FROZEN_TOPIC); - } - } - - mGlobal = nullptr; - mWorkerHolder = nullptr; - -#ifdef DEBUG - mBody = nullptr; -#endif -} - -template -FetchBodyConsumer::FetchBodyConsumer(nsIGlobalObject* aGlobalObject, - WorkerPrivate* aWorkerPrivate, - FetchBody* aBody, - nsIInputStream* aBodyStream, - Promise* aPromise, - FetchConsumeType aType) - : mTargetThread(NS_GetCurrentThread()) -#ifdef DEBUG - , mBody(aBody) -#endif - , mBodyStream(aBodyStream) - , mBlobStorageType(MutableBlobStorage::eOnlyInMemory) - , mGlobal(aGlobalObject) - , mWorkerPrivate(aWorkerPrivate) - , mConsumeType(aType) - , mConsumePromise(aPromise) - , mBodyConsumed(false) - , mShuttingDown(false) -{ - MOZ_ASSERT(aBody); - MOZ_ASSERT(aBodyStream); - MOZ_ASSERT(aPromise); - - const mozilla::UniquePtr& principalInfo = - aBody->DerivedClass()->GetPrincipalInfo(); - // We support temporary file for blobs only if the principal is known and - // it's system or content not in private Browsing. - if (principalInfo && - (principalInfo->type() == mozilla::ipc::PrincipalInfo::TSystemPrincipalInfo || - (principalInfo->type() == mozilla::ipc::PrincipalInfo::TContentPrincipalInfo && - principalInfo->get_ContentPrincipalInfo().attrs().mPrivateBrowsingId == 0))) { - mBlobStorageType = MutableBlobStorage::eCouldBeInTemporaryFile; - } - - mBodyMimeType = aBody->MimeType(); -} - -template -FetchBodyConsumer::~FetchBodyConsumer() -{ -} - -template -void -FetchBodyConsumer::AssertIsOnTargetThread() const -{ - MOZ_ASSERT(NS_GetCurrentThread() == mTargetThread); -} - -template -bool -FetchBodyConsumer::RegisterWorkerHolder() -{ - MOZ_ASSERT(mWorkerPrivate); - mWorkerPrivate->AssertIsOnWorkerThread(); - - MOZ_ASSERT(!mWorkerHolder); - mWorkerHolder.reset(new FetchBodyWorkerHolder(this)); - - if (!mWorkerHolder->HoldWorker(mWorkerPrivate, Closing)) { - NS_WARNING("Failed to add workerHolder"); - mWorkerHolder = nullptr; - return false; - } - - return true; -} - -/* - * BeginConsumeBodyMainThread() will automatically reject the consume promise - * and clean up on any failures, so there is no need for callers to do so, - * reflected in a lack of error return code. - */ -template -void -FetchBodyConsumer::BeginConsumeBodyMainThread() -{ - AssertIsOnMainThread(); - - AutoFailConsumeBody autoReject(this); - - if (mShuttingDown) { - // We haven't started yet, but we have been terminated. AutoFailConsumeBody - // will dispatch a runnable to release resources. - return; - } - - nsCOMPtr pump; - nsresult rv = NS_NewInputStreamPump(getter_AddRefs(pump), - mBodyStream, -1, -1, 0, 0, false); - if (NS_WARN_IF(NS_FAILED(rv))) { - return; - } - - RefPtr> p = - new ConsumeBodyDoneObserver(this); - - nsCOMPtr listener; - if (mConsumeType == CONSUME_BLOB) { - listener = new MutableBlobStreamListener(mBlobStorageType, nullptr, - mBodyMimeType, p); - } else { - nsCOMPtr loader; - rv = NS_NewStreamLoader(getter_AddRefs(loader), p); - if (NS_WARN_IF(NS_FAILED(rv))) { - return; - } - - listener = loader; - } - - rv = pump->AsyncRead(listener, nullptr); - if (NS_WARN_IF(NS_FAILED(rv))) { - return; - } - - // Now that everything succeeded, we can assign the pump to a pointer that - // stays alive for the lifetime of the FetchConsumer. - mConsumeBodyPump = pump; - - // It is ok for retargeting to fail and reads to happen on the main thread. - autoReject.DontFail(); - - // Try to retarget, otherwise fall back to main thread. - nsCOMPtr rr = do_QueryInterface(pump); - if (rr) { - nsCOMPtr sts = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); - rv = rr->RetargetDeliveryTo(sts); - if (NS_WARN_IF(NS_FAILED(rv))) { - NS_WARNING("Retargeting failed"); - } - } -} - -template -void -FetchBodyConsumer::ContinueConsumeBody(nsresult aStatus, - uint32_t aResultLength, - uint8_t* aResult) -{ - AssertIsOnTargetThread(); - - if (mBodyConsumed) { - return; - } - mBodyConsumed = true; - - // Just a precaution to ensure ContinueConsumeBody is not called out of - // sync with a body read. - MOZ_ASSERT(mBody->BodyUsed()); - - auto autoFree = mozilla::MakeScopeExit([&] { - free(aResult); - }); - - MOZ_ASSERT(mConsumePromise); - RefPtr localPromise = mConsumePromise.forget(); - - RefPtr> self = this; - auto autoReleaseObject = mozilla::MakeScopeExit([&] { - self->ReleaseObject(); - }); - - if (NS_WARN_IF(NS_FAILED(aStatus))) { - localPromise->MaybeReject(NS_ERROR_DOM_ABORT_ERR); - } - - // Don't warn here since we warned above. - if (NS_FAILED(aStatus)) { - return; - } - - // Finish successfully consuming body according to type. - MOZ_ASSERT(aResult); - - AutoJSAPI jsapi; - if (!jsapi.Init(mGlobal)) { - localPromise->MaybeReject(NS_ERROR_UNEXPECTED); - return; - } - - JSContext* cx = jsapi.cx(); - ErrorResult error; - - switch (mConsumeType) { - case CONSUME_ARRAYBUFFER: { - JS::Rooted arrayBuffer(cx); - BodyUtil::ConsumeArrayBuffer(cx, &arrayBuffer, aResultLength, aResult, - error); - - if (!error.Failed()) { - JS::Rooted val(cx); - val.setObjectOrNull(arrayBuffer); - - localPromise->MaybeResolve(cx, val); - // ArrayBuffer takes over ownership. - aResult = nullptr; - } - break; - } - case CONSUME_BLOB: { - MOZ_CRASH("This should not happen."); - break; - } - case CONSUME_FORMDATA: { - nsCString data; - data.Adopt(reinterpret_cast(aResult), aResultLength); - aResult = nullptr; - - RefPtr fd = - BodyUtil::ConsumeFormData(mGlobal, mBodyMimeType, data, error); - if (!error.Failed()) { - localPromise->MaybeResolve(fd); - } - break; - } - case CONSUME_TEXT: - // fall through handles early exit. - case CONSUME_JSON: { - nsString decoded; - if (NS_SUCCEEDED(BodyUtil::ConsumeText(aResultLength, aResult, decoded))) { - if (mConsumeType == CONSUME_TEXT) { - localPromise->MaybeResolve(decoded); - } else { - JS::Rooted json(cx); - BodyUtil::ConsumeJson(cx, &json, decoded, error); - if (!error.Failed()) { - localPromise->MaybeResolve(cx, json); - } - } - }; - break; - } - default: - NS_NOTREACHED("Unexpected consume body type"); - } - - error.WouldReportJSException(); - if (error.Failed()) { - localPromise->MaybeReject(error); - } -} - -template -void -FetchBodyConsumer::ContinueConsumeBlobBody(BlobImpl* aBlobImpl) -{ - AssertIsOnTargetThread(); - MOZ_ASSERT(mConsumeType == CONSUME_BLOB); - - if (mBodyConsumed) { - return; - } - mBodyConsumed = true; - - // Just a precaution to ensure ContinueConsumeBody is not called out of - // sync with a body read. - MOZ_ASSERT(mBody->BodyUsed()); - - MOZ_ASSERT(mConsumePromise); - RefPtr localPromise = mConsumePromise.forget(); - - RefPtr blob = dom::Blob::Create(mGlobal, aBlobImpl); - MOZ_ASSERT(blob); - - localPromise->MaybeResolve(blob); - - ReleaseObject(); -} - -template -void -FetchBodyConsumer::ShutDownMainThreadConsuming() -{ - if (!NS_IsMainThread()) { - RefPtr> self = this; - - nsCOMPtr r = NS_NewRunnableFunction( - [self] () { self->ShutDownMainThreadConsuming(); }); - - MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(r.forget())); - return; - } - - // We need this because maybe, mConsumeBodyPump has not been created yet. We - // must be sure that we don't try to do it. - mShuttingDown = true; - - if (mConsumeBodyPump) { - mConsumeBodyPump->Cancel(NS_BINDING_ABORTED); - mConsumeBodyPump = nullptr; - } -} - -template -NS_IMETHODIMP -FetchBodyConsumer::Observe(nsISupports* aSubject, - const char* aTopic, - const char16_t* aData) -{ - AssertIsOnMainThread(); - - MOZ_ASSERT((strcmp(aTopic, DOM_WINDOW_FROZEN_TOPIC) == 0) || - (strcmp(aTopic, DOM_WINDOW_DESTROYED_TOPIC) == 0)); - - nsCOMPtr window = do_QueryInterface(mGlobal); - if (SameCOMIdentity(aSubject, window)) { - ContinueConsumeBody(NS_BINDING_ABORTED, 0, nullptr); - } - - return NS_OK; -} - -template -NS_IMPL_ADDREF(FetchBodyConsumer) - -template -NS_IMPL_RELEASE(FetchBodyConsumer) - -template -NS_IMPL_QUERY_INTERFACE(FetchBodyConsumer, - nsIObserver, - nsISupportsWeakReference) - -} // namespace dom -} // namespace mozilla +/* -*- 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 "Fetch.h" +#include "FetchConsumer.h" + +#include "nsIInputStreamPump.h" +#include "nsProxyRelease.h" +#include "WorkerPrivate.h" +#include "WorkerRunnable.h" +#include "WorkerScope.h" +#include "Workers.h" + +namespace mozilla { +namespace dom { + +using namespace workers; + +namespace { + +template +class FetchBodyWorkerHolder final : public workers::WorkerHolder +{ + RefPtr> mConsumer; + bool mWasNotified; + +public: + explicit FetchBodyWorkerHolder(FetchBodyConsumer* aConsumer) + : mConsumer(aConsumer) + , mWasNotified(false) + { + MOZ_ASSERT(aConsumer); + } + + ~FetchBodyWorkerHolder() = default; + + bool Notify(workers::Status aStatus) override + { + MOZ_ASSERT(aStatus > workers::Running); + if (!mWasNotified) { + mWasNotified = true; + mConsumer->ShutDownMainThreadConsuming(); + } + + return true; + } +}; + +template +class BeginConsumeBodyRunnable final : public Runnable +{ + RefPtr> mFetchBodyConsumer; + +public: + explicit BeginConsumeBodyRunnable(FetchBodyConsumer* aConsumer) + : mFetchBodyConsumer(aConsumer) + { } + + NS_IMETHOD + Run() override + { + mFetchBodyConsumer->BeginConsumeBodyMainThread(); + return NS_OK; + } +}; + +/* + * Called on successfully reading the complete stream. + */ +template +class ContinueConsumeBodyRunnable final : public MainThreadWorkerRunnable +{ + RefPtr> mFetchBodyConsumer; + nsresult mStatus; + uint32_t mLength; + uint8_t* mResult; + +public: + ContinueConsumeBodyRunnable(FetchBodyConsumer* aFetchBodyConsumer, + nsresult aStatus, uint32_t aLength, + uint8_t* aResult) + : MainThreadWorkerRunnable(aFetchBodyConsumer->GetWorkerPrivate()) + , mFetchBodyConsumer(aFetchBodyConsumer) + , mStatus(aStatus) + , mLength(aLength) + , mResult(aResult) + { + MOZ_ASSERT(NS_IsMainThread()); + } + + bool + WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override + { + mFetchBodyConsumer->ContinueConsumeBody(mStatus, mLength, mResult); + return true; + } +}; + +template +class FailConsumeBodyWorkerRunnable : public MainThreadWorkerControlRunnable +{ + RefPtr> mBodyConsumer; + +public: + explicit FailConsumeBodyWorkerRunnable(FetchBodyConsumer* aBodyConsumer) + : MainThreadWorkerControlRunnable(aBodyConsumer->GetWorkerPrivate()) + , mBodyConsumer(aBodyConsumer) + { + AssertIsOnMainThread(); + } + + bool + WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override + { + mBodyConsumer->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr); + return true; + } +}; + +/* + * In case of failure to create a stream pump or dispatch stream completion to + * worker, ensure we cleanup properly. Thread agnostic. + */ +template +class MOZ_STACK_CLASS AutoFailConsumeBody final +{ + RefPtr> mBodyConsumer; + +public: + explicit AutoFailConsumeBody(FetchBodyConsumer* aBodyConsumer) + : mBodyConsumer(aBodyConsumer) + {} + + ~AutoFailConsumeBody() + { + AssertIsOnMainThread(); + + if (mBodyConsumer) { + if (mBodyConsumer->GetWorkerPrivate()) { + RefPtr> r = + new FailConsumeBodyWorkerRunnable(mBodyConsumer); + if (!r->Dispatch()) { + MOZ_CRASH("We are going to leak"); + } + } else { + mBodyConsumer->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr); + } + } + } + + void + DontFail() + { + mBodyConsumer = nullptr; + } +}; + +/* + * Called on successfully reading the complete stream for Blob. + */ +template +class ContinueConsumeBlobBodyRunnable final : public MainThreadWorkerRunnable +{ + RefPtr> mFetchBodyConsumer; + RefPtr mBlobImpl; + +public: + ContinueConsumeBlobBodyRunnable(FetchBodyConsumer* aFetchBodyConsumer, + BlobImpl* aBlobImpl) + : MainThreadWorkerRunnable(aFetchBodyConsumer->GetWorkerPrivate()) + , mFetchBodyConsumer(aFetchBodyConsumer) + , mBlobImpl(aBlobImpl) + { + MOZ_ASSERT(NS_IsMainThread()); + MOZ_ASSERT(mBlobImpl); + } + + bool + WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override + { + mFetchBodyConsumer->ContinueConsumeBlobBody(mBlobImpl); + return true; + } +}; + +template +class ConsumeBodyDoneObserver : public nsIStreamLoaderObserver + , public MutableBlobStorageCallback +{ + RefPtr> mFetchBodyConsumer; + +public: + NS_DECL_THREADSAFE_ISUPPORTS + + explicit ConsumeBodyDoneObserver(FetchBodyConsumer* aFetchBodyConsumer) + : mFetchBodyConsumer(aFetchBodyConsumer) + { } + + NS_IMETHOD + OnStreamComplete(nsIStreamLoader* aLoader, + nsISupports* aCtxt, + nsresult aStatus, + uint32_t aResultLength, + const uint8_t* aResult) override + { + MOZ_ASSERT(NS_IsMainThread()); + + // The loading is completed. Let's nullify the pump before continuing the + // consuming of the body. + mFetchBodyConsumer->NullifyConsumeBodyPump(); + + uint8_t* nonconstResult = const_cast(aResult); + if (mFetchBodyConsumer->GetWorkerPrivate()) { + RefPtr> r = + new ContinueConsumeBodyRunnable(mFetchBodyConsumer, + aStatus, + aResultLength, + nonconstResult); + if (!r->Dispatch()) { + NS_WARNING("Could not dispatch ConsumeBodyRunnable"); + // Return failure so that aResult is freed. + return NS_ERROR_FAILURE; + } + } else { + mFetchBodyConsumer->ContinueConsumeBody(aStatus, aResultLength, + nonconstResult); + } + + // FetchBody is responsible for data. + return NS_SUCCESS_ADOPTED_DATA; + } + + virtual void BlobStoreCompleted(MutableBlobStorage* aBlobStorage, + Blob* aBlob, + nsresult aRv) override + { + // On error. + if (NS_FAILED(aRv)) { + OnStreamComplete(nullptr, nullptr, aRv, 0, nullptr); + return; + } + + // The loading is completed. Let's nullify the pump before continuing the + // consuming of the body. + mFetchBodyConsumer->NullifyConsumeBodyPump(); + + MOZ_ASSERT(aBlob); + + if (mFetchBodyConsumer->GetWorkerPrivate()) { + RefPtr> r = + new ContinueConsumeBlobBodyRunnable(mFetchBodyConsumer, + aBlob->Impl()); + + if (!r->Dispatch()) { + NS_WARNING("Could not dispatch ConsumeBlobBodyRunnable"); + return; + } + } else { + mFetchBodyConsumer->ContinueConsumeBlobBody(aBlob->Impl()); + } + } + +private: + virtual ~ConsumeBodyDoneObserver() + { } +}; + +template +NS_IMPL_ADDREF(ConsumeBodyDoneObserver) +template +NS_IMPL_RELEASE(ConsumeBodyDoneObserver) +template +NS_INTERFACE_MAP_BEGIN(ConsumeBodyDoneObserver) + NS_INTERFACE_MAP_ENTRY(nsIStreamLoaderObserver) + NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamLoaderObserver) +NS_INTERFACE_MAP_END + +} // anonymous + +template +/* static */ already_AddRefed +FetchBodyConsumer::Create(nsIGlobalObject* aGlobal, + FetchBody* aBody, + AbortSignal* aSignal, + FetchConsumeType aType, + ErrorResult& aRv) +{ + MOZ_ASSERT(aBody); + + nsCOMPtr bodyStream; + aBody->DerivedClass()->GetBody(getter_AddRefs(bodyStream)); + if (!bodyStream) { + aRv = NS_NewCStringInputStream(getter_AddRefs(bodyStream), EmptyCString()); + if (NS_WARN_IF(aRv.Failed())) { + return nullptr; + } + } + + RefPtr promise = Promise::Create(aGlobal, aRv); + if (aRv.Failed()) { + return nullptr; + } + + WorkerPrivate* workerPrivate = nullptr; + if (!NS_IsMainThread()) { + workerPrivate = GetCurrentThreadWorkerPrivate(); + MOZ_ASSERT(workerPrivate); + } + + RefPtr> consumer = + new FetchBodyConsumer(aGlobal, workerPrivate, aBody, bodyStream, + promise, aType); + + if (!NS_IsMainThread()) { + MOZ_ASSERT(workerPrivate); + if (NS_WARN_IF(!consumer->RegisterWorkerHolder())) { + aRv.Throw(NS_ERROR_FAILURE); + return nullptr; + } + } else { + nsCOMPtr os = mozilla::services::GetObserverService(); + if (NS_WARN_IF(!os)) { + aRv.Throw(NS_ERROR_FAILURE); + return nullptr; + } + + aRv = os->AddObserver(consumer, DOM_WINDOW_DESTROYED_TOPIC, true); + if (NS_WARN_IF(aRv.Failed())) { + return nullptr; + } + + aRv = os->AddObserver(consumer, DOM_WINDOW_FROZEN_TOPIC, true); + if (NS_WARN_IF(aRv.Failed())) { + return nullptr; + } + } + + nsCOMPtr r = new BeginConsumeBodyRunnable(consumer); + + aRv = NS_DispatchToMainThread(r.forget()); + + if (NS_WARN_IF(aRv.Failed())) { + return nullptr; + } + + if (aSignal) { + consumer->Follow(aSignal); + } + + return promise.forget(); +} + +template +void +FetchBodyConsumer::ReleaseObject() +{ + AssertIsOnTargetThread(); + + if (NS_IsMainThread()) { + nsCOMPtr os = mozilla::services::GetObserverService(); + if (os) { + os->RemoveObserver(this, DOM_WINDOW_DESTROYED_TOPIC); + os->RemoveObserver(this, DOM_WINDOW_FROZEN_TOPIC); + } + } + + mGlobal = nullptr; + mWorkerHolder = nullptr; + +#ifdef DEBUG + mBody = nullptr; +#endif + + Unfollow(); +} + +template +FetchBodyConsumer::FetchBodyConsumer(nsIGlobalObject* aGlobalObject, + WorkerPrivate* aWorkerPrivate, + FetchBody* aBody, + nsIInputStream* aBodyStream, + Promise* aPromise, + FetchConsumeType aType) + : mTargetThread(NS_GetCurrentThread()) +#ifdef DEBUG + , mBody(aBody) +#endif + , mBodyStream(aBodyStream) + , mBlobStorageType(MutableBlobStorage::eOnlyInMemory) + , mGlobal(aGlobalObject) + , mWorkerPrivate(aWorkerPrivate) + , mConsumeType(aType) + , mConsumePromise(aPromise) + , mBodyConsumed(false) + , mShuttingDown(false) +{ + MOZ_ASSERT(aBody); + MOZ_ASSERT(aBodyStream); + MOZ_ASSERT(aPromise); + + const mozilla::UniquePtr& principalInfo = + aBody->DerivedClass()->GetPrincipalInfo(); + // We support temporary file for blobs only if the principal is known and + // it's system or content not in private Browsing. + if (principalInfo && + (principalInfo->type() == mozilla::ipc::PrincipalInfo::TSystemPrincipalInfo || + (principalInfo->type() == mozilla::ipc::PrincipalInfo::TContentPrincipalInfo && + principalInfo->get_ContentPrincipalInfo().attrs().mPrivateBrowsingId == 0))) { + mBlobStorageType = MutableBlobStorage::eCouldBeInTemporaryFile; + } + + mBodyMimeType = aBody->MimeType(); +} + +template +FetchBodyConsumer::~FetchBodyConsumer() +{ +} + +template +void +FetchBodyConsumer::AssertIsOnTargetThread() const +{ + MOZ_ASSERT(NS_GetCurrentThread() == mTargetThread); +} + +template +bool +FetchBodyConsumer::RegisterWorkerHolder() +{ + MOZ_ASSERT(mWorkerPrivate); + mWorkerPrivate->AssertIsOnWorkerThread(); + + MOZ_ASSERT(!mWorkerHolder); + mWorkerHolder.reset(new FetchBodyWorkerHolder(this)); + + if (!mWorkerHolder->HoldWorker(mWorkerPrivate, Closing)) { + NS_WARNING("Failed to add workerHolder"); + mWorkerHolder = nullptr; + return false; + } + + return true; +} + +/* + * BeginConsumeBodyMainThread() will automatically reject the consume promise + * and clean up on any failures, so there is no need for callers to do so, + * reflected in a lack of error return code. + */ +template +void +FetchBodyConsumer::BeginConsumeBodyMainThread() +{ + AssertIsOnMainThread(); + + AutoFailConsumeBody autoReject(this); + + if (mShuttingDown) { + // We haven't started yet, but we have been terminated. AutoFailConsumeBody + // will dispatch a runnable to release resources. + return; + } + + nsCOMPtr pump; + nsresult rv = NS_NewInputStreamPump(getter_AddRefs(pump), + mBodyStream, -1, -1, 0, 0, false); + if (NS_WARN_IF(NS_FAILED(rv))) { + return; + } + + RefPtr> p = + new ConsumeBodyDoneObserver(this); + + nsCOMPtr listener; + if (mConsumeType == CONSUME_BLOB) { + listener = new MutableBlobStreamListener(mBlobStorageType, nullptr, + mBodyMimeType, p); + } else { + nsCOMPtr loader; + rv = NS_NewStreamLoader(getter_AddRefs(loader), p); + if (NS_WARN_IF(NS_FAILED(rv))) { + return; + } + + listener = loader; + } + + rv = pump->AsyncRead(listener, nullptr); + if (NS_WARN_IF(NS_FAILED(rv))) { + return; + } + + // Now that everything succeeded, we can assign the pump to a pointer that + // stays alive for the lifetime of the FetchConsumer. + mConsumeBodyPump = pump; + + // It is ok for retargeting to fail and reads to happen on the main thread. + autoReject.DontFail(); + + // Try to retarget, otherwise fall back to main thread. + nsCOMPtr rr = do_QueryInterface(pump); + if (rr) { + nsCOMPtr sts = do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID); + rv = rr->RetargetDeliveryTo(sts); + if (NS_WARN_IF(NS_FAILED(rv))) { + NS_WARNING("Retargeting failed"); + } + } +} + +template +void +FetchBodyConsumer::ContinueConsumeBody(nsresult aStatus, + uint32_t aResultLength, + uint8_t* aResult) +{ + AssertIsOnTargetThread(); + + if (mBodyConsumed) { + return; + } + mBodyConsumed = true; + + // Just a precaution to ensure ContinueConsumeBody is not called out of + // sync with a body read. + MOZ_ASSERT(mBody->BodyUsed()); + + auto autoFree = mozilla::MakeScopeExit([&] { + free(aResult); + }); + + MOZ_ASSERT(mConsumePromise); + RefPtr localPromise = mConsumePromise.forget(); + + RefPtr> self = this; + auto autoReleaseObject = mozilla::MakeScopeExit([&] { + self->ReleaseObject(); + }); + + if (NS_WARN_IF(NS_FAILED(aStatus))) { + localPromise->MaybeReject(NS_ERROR_DOM_ABORT_ERR); + } + + // Don't warn here since we warned above. + if (NS_FAILED(aStatus)) { + return; + } + + // Finish successfully consuming body according to type. + MOZ_ASSERT(aResult); + + AutoJSAPI jsapi; + if (!jsapi.Init(mGlobal)) { + localPromise->MaybeReject(NS_ERROR_UNEXPECTED); + return; + } + + JSContext* cx = jsapi.cx(); + ErrorResult error; + + switch (mConsumeType) { + case CONSUME_ARRAYBUFFER: { + JS::Rooted arrayBuffer(cx); + BodyUtil::ConsumeArrayBuffer(cx, &arrayBuffer, aResultLength, aResult, + error); + + if (!error.Failed()) { + JS::Rooted val(cx); + val.setObjectOrNull(arrayBuffer); + + localPromise->MaybeResolve(cx, val); + // ArrayBuffer takes over ownership. + aResult = nullptr; + } + break; + } + case CONSUME_BLOB: { + MOZ_CRASH("This should not happen."); + break; + } + case CONSUME_FORMDATA: { + nsCString data; + data.Adopt(reinterpret_cast(aResult), aResultLength); + aResult = nullptr; + + RefPtr fd = + BodyUtil::ConsumeFormData(mGlobal, mBodyMimeType, data, error); + if (!error.Failed()) { + localPromise->MaybeResolve(fd); + } + break; + } + case CONSUME_TEXT: + // fall through handles early exit. + case CONSUME_JSON: { + nsString decoded; + if (NS_SUCCEEDED(BodyUtil::ConsumeText(aResultLength, aResult, decoded))) { + if (mConsumeType == CONSUME_TEXT) { + localPromise->MaybeResolve(decoded); + } else { + JS::Rooted json(cx); + BodyUtil::ConsumeJson(cx, &json, decoded, error); + if (!error.Failed()) { + localPromise->MaybeResolve(cx, json); + } + } + }; + break; + } + default: + NS_NOTREACHED("Unexpected consume body type"); + } + + error.WouldReportJSException(); + if (error.Failed()) { + localPromise->MaybeReject(error); + } +} + +template +void +FetchBodyConsumer::ContinueConsumeBlobBody(BlobImpl* aBlobImpl) +{ + AssertIsOnTargetThread(); + MOZ_ASSERT(mConsumeType == CONSUME_BLOB); + + if (mBodyConsumed) { + return; + } + mBodyConsumed = true; + + // Just a precaution to ensure ContinueConsumeBody is not called out of + // sync with a body read. + MOZ_ASSERT(mBody->BodyUsed()); + + MOZ_ASSERT(mConsumePromise); + RefPtr localPromise = mConsumePromise.forget(); + + RefPtr blob = dom::Blob::Create(mGlobal, aBlobImpl); + MOZ_ASSERT(blob); + + localPromise->MaybeResolve(blob); + + ReleaseObject(); +} + +template +void +FetchBodyConsumer::ShutDownMainThreadConsuming() +{ + if (!NS_IsMainThread()) { + RefPtr> self = this; + + nsCOMPtr r = NS_NewRunnableFunction( + [self] () { self->ShutDownMainThreadConsuming(); }); + + MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(r.forget())); + return; + } + + // We need this because maybe, mConsumeBodyPump has not been created yet. We + // must be sure that we don't try to do it. + mShuttingDown = true; + + if (mConsumeBodyPump) { + mConsumeBodyPump->Cancel(NS_BINDING_ABORTED); + mConsumeBodyPump = nullptr; + } +} + +template +NS_IMETHODIMP +FetchBodyConsumer::Observe(nsISupports* aSubject, + const char* aTopic, + const char16_t* aData) +{ + AssertIsOnMainThread(); + + MOZ_ASSERT((strcmp(aTopic, DOM_WINDOW_FROZEN_TOPIC) == 0) || + (strcmp(aTopic, DOM_WINDOW_DESTROYED_TOPIC) == 0)); + + nsCOMPtr window = do_QueryInterface(mGlobal); + if (SameCOMIdentity(aSubject, window)) { + ContinueConsumeBody(NS_BINDING_ABORTED, 0, nullptr); + } + + return NS_OK; +} + +template +void +FetchBodyConsumer::Aborted() +{ + AssertIsOnTargetThread(); + ContinueConsumeBody(NS_ERROR_DOM_ABORT_ERR, 0, nullptr); +} + +template +NS_IMPL_ADDREF(FetchBodyConsumer) + +template +NS_IMPL_RELEASE(FetchBodyConsumer) + +template +NS_IMPL_QUERY_INTERFACE(FetchBodyConsumer, + nsIObserver, + nsISupportsWeakReference) + +} // namespace dom +} // namespace mozilla diff --git a/dom/fetch/FetchConsumer.h b/dom/fetch/FetchConsumer.h index 2b5725342..77af09d9b 100644 --- a/dom/fetch/FetchConsumer.h +++ b/dom/fetch/FetchConsumer.h @@ -11,6 +11,7 @@ #include "nsIInputStream.h" #include "nsIObserver.h" #include "nsWeakReference.h" +#include "mozilla/dom/AbortSignal.h" #include "mozilla/dom/MutableBlobStorage.h" class nsIThread; @@ -34,6 +35,7 @@ template class FetchBody; template class FetchBodyConsumer final : public nsIObserver , public nsSupportsWeakReference + , public AbortSignal::Follower { public: NS_DECL_THREADSAFE_ISUPPORTS @@ -42,6 +44,7 @@ public: static already_AddRefed Create(nsIGlobalObject* aGlobal, FetchBody* aBody, + AbortSignal* aSignal, FetchConsumeType aType, ErrorResult& aRv); @@ -73,6 +76,9 @@ public: mConsumeBodyPump = nullptr; } + // Override AbortSignal::Follower::Aborted + void Aborted() override; + private: FetchBodyConsumer(nsIGlobalObject* aGlobalObject, workers::WorkerPrivate* aWorkerPrivate, diff --git a/dom/fetch/Request.cpp b/dom/fetch/Request.cpp index 6a7885b1a..ba268d331 100644 --- a/dom/fetch/Request.cpp +++ b/dom/fetch/Request.cpp @@ -37,15 +37,18 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Request) NS_INTERFACE_MAP_ENTRY(nsISupports) NS_INTERFACE_MAP_END -Request::Request(nsIGlobalObject* aOwner, InternalRequest* aRequest) +Request::Request(nsIGlobalObject* aOwner, InternalRequest* aRequest, AbortSignal* aSignal) : FetchBody() , mOwner(aOwner) , mRequest(aRequest) + , mSignal(aSignal) { MOZ_ASSERT(aRequest->Headers()->Guard() == HeadersGuardEnum::Immutable || aRequest->Headers()->Guard() == HeadersGuardEnum::Request || aRequest->Headers()->Guard() == HeadersGuardEnum::Request_no_cors); SetMimeType(); + + // aSignal can be null. } Request::~Request() @@ -286,6 +289,8 @@ Request::Constructor(const GlobalObject& aGlobal, RefPtr request; nsCOMPtr global = do_QueryInterface(aGlobal.GetAsSupports()); + + RefPtr signal; if (aInput.IsRequest()) { RefPtr inputReq = &aInput.GetAsRequest(); @@ -300,6 +305,7 @@ Request::Constructor(const GlobalObject& aGlobal, } request = inputReq->GetInternalRequest(); + signal = inputReq->GetOrCreateSignal(); } else { // aInput is USVString. // We need to get url before we create a InternalRequest. @@ -418,6 +424,10 @@ Request::Constructor(const GlobalObject& aGlobal, request->SetReferrerPolicy(aInit.mReferrerPolicy.Value()); } + if (aInit.mSignal.WasPassed()) { + signal = &aInit.mSignal.Value(); + } + if (NS_IsMainThread()) { nsCOMPtr window = do_QueryInterface(global); if (window) { @@ -579,7 +589,7 @@ Request::Constructor(const GlobalObject& aGlobal, } } - RefPtr domRequest = new Request(global, request); + RefPtr domRequest = new Request(global, request, signal); domRequest->SetMimeType(); if (aInput.IsRequest()) { @@ -595,7 +605,7 @@ Request::Constructor(const GlobalObject& aGlobal, } already_AddRefed -Request::Clone(ErrorResult& aRv) const +Request::Clone(ErrorResult& aRv) { if (BodyUsed()) { aRv.ThrowTypeError(); @@ -608,7 +618,7 @@ Request::Clone(ErrorResult& aRv) const return nullptr; } - RefPtr request = new Request(mOwner, ir); + RefPtr request = new Request(mOwner, ir, GetOrCreateSignal()); return request.forget(); } @@ -622,5 +632,21 @@ Request::Headers_() return mHeaders; } +AbortSignal* +Request::GetOrCreateSignal() +{ + if (!mSignal) { + mSignal = new AbortSignal(false); + } + + return mSignal; +} + +AbortSignal* +Request::GetSignal() const +{ + return mSignal; +} + } // namespace dom } // namespace mozilla diff --git a/dom/fetch/Request.h b/dom/fetch/Request.h index f6fe9be7b..34cbc52cf 100644 --- a/dom/fetch/Request.h +++ b/dom/fetch/Request.h @@ -33,7 +33,7 @@ class Request final : public nsISupports NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Request) public: - Request(nsIGlobalObject* aOwner, InternalRequest* aRequest); + Request(nsIGlobalObject* aOwner, InternalRequest* aRequest, AbortSignal* aSignal); static bool RequestContextEnabled(JSContext* aCx, JSObject* aObj); @@ -142,7 +142,7 @@ public: } already_AddRefed - Clone(ErrorResult& aRv) const; + Clone(ErrorResult& aRv); already_AddRefed GetInternalRequest(); @@ -153,13 +153,22 @@ public: return mRequest->GetPrincipalInfo(); } + AbortSignal* + GetOrCreateSignal(); + + // This can return a null AbortSignal. + AbortSignal* + GetSignal() const override; + private: ~Request(); nsCOMPtr mOwner; RefPtr mRequest; + // Lazily created. RefPtr mHeaders; + RefPtr mSignal; }; } // namespace dom diff --git a/dom/fetch/Response.cpp b/dom/fetch/Response.cpp index e35de0e12..241614286 100644 --- a/dom/fetch/Response.cpp +++ b/dom/fetch/Response.cpp @@ -34,10 +34,11 @@ NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Response) NS_INTERFACE_MAP_ENTRY(nsISupports) NS_INTERFACE_MAP_END -Response::Response(nsIGlobalObject* aGlobal, InternalResponse* aInternalResponse) +Response::Response(nsIGlobalObject* aGlobal, InternalResponse* aInternalResponse, AbortSignal* aSignal) : FetchBody() , mOwner(aGlobal) , mInternalResponse(aInternalResponse) + , mSignal(aSignal) { MOZ_ASSERT(aInternalResponse->Headers()->Guard() == HeadersGuardEnum::Immutable || aInternalResponse->Headers()->Guard() == HeadersGuardEnum::Response); @@ -53,7 +54,7 @@ Response::Error(const GlobalObject& aGlobal) { nsCOMPtr global = do_QueryInterface(aGlobal.GetAsSupports()); RefPtr error = InternalResponse::NetworkError(); - RefPtr r = new Response(global, error); + RefPtr r = new Response(global, error, nullptr); return r.forget(); } @@ -173,7 +174,7 @@ Response::Constructor(const GlobalObject& aGlobal, internalResponse->InitChannelInfo(worker->GetChannelInfo()); } - RefPtr r = new Response(global, internalResponse); + RefPtr r = new Response(global, internalResponse, nullptr); if (aInit.mHeaders.WasPassed()) { internalResponse->Headers()->Clear(); @@ -236,7 +237,7 @@ Response::Clone(ErrorResult& aRv) const } RefPtr ir = mInternalResponse->Clone(); - RefPtr response = new Response(mOwner, ir); + RefPtr response = new Response(mOwner, ir, mSignal); return response.forget(); } @@ -250,7 +251,7 @@ Response::CloneUnfiltered(ErrorResult& aRv) const RefPtr clone = mInternalResponse->Clone(); RefPtr ir = clone->Unfiltered(); - RefPtr ref = new Response(mOwner, ir); + RefPtr ref = new Response(mOwner, ir, mSignal); return ref.forget(); } diff --git a/dom/fetch/Response.h b/dom/fetch/Response.h index de367bef6..ca86c3458 100644 --- a/dom/fetch/Response.h +++ b/dom/fetch/Response.h @@ -33,7 +33,7 @@ class Response final : public nsISupports NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Response) public: - Response(nsIGlobalObject* aGlobal, InternalResponse* aInternalResponse); + Response(nsIGlobalObject* aGlobal, InternalResponse* aInternalResponse, AbortSignal* aSignal); Response(const Response& aOther) = delete; @@ -134,13 +134,21 @@ public: already_AddRefed GetInternalResponse() const; + AbortSignal* + GetSignal() const override + { + return mSignal; + } + private: ~Response(); nsCOMPtr mOwner; RefPtr mInternalResponse; + // Lazily created RefPtr mHeaders; + RefPtr mSignal; }; } // namespace dom diff --git a/dom/webidl/Request.webidl b/dom/webidl/Request.webidl index fe6a63ec0..57bea5db6 100644 --- a/dom/webidl/Request.webidl +++ b/dom/webidl/Request.webidl @@ -27,6 +27,10 @@ interface Request { readonly attribute RequestRedirect redirect; readonly attribute DOMString integrity; + [Func="AbortController::IsEnabled", + BinaryName="getOrCreateSignal"] + readonly attribute AbortSignal signal; + [Throws, NewObject] Request clone(); diff --git a/dom/workers/ScriptLoader.cpp b/dom/workers/ScriptLoader.cpp index bcec94dcb..80e136384 100644 --- a/dom/workers/ScriptLoader.cpp +++ b/dom/workers/ScriptLoader.cpp @@ -694,7 +694,7 @@ private: ir->SetPrincipalInfo(Move(principalInfo)); RefPtr response = - new mozilla::dom::Response(mCacheCreator->Global(), ir); + new mozilla::dom::Response(mCacheCreator->Global(), ir, nullptr); mozilla::dom::RequestOrUSVString request; diff --git a/dom/workers/ServiceWorkerPrivate.cpp b/dom/workers/ServiceWorkerPrivate.cpp index 23ae3b366..571ceca37 100644 --- a/dom/workers/ServiceWorkerPrivate.cpp +++ b/dom/workers/ServiceWorkerPrivate.cpp @@ -1510,7 +1510,7 @@ private: if (NS_WARN_IF(!global)) { return false; } - RefPtr request = new Request(global, internalReq); + RefPtr request = new Request(global, internalReq, nullptr); MOZ_ASSERT_IF(internalReq->IsNavigationRequest(), request->Redirect() == RequestRedirect::Manual); diff --git a/dom/workers/ServiceWorkerScriptCache.cpp b/dom/workers/ServiceWorkerScriptCache.cpp index 707b689e8..3db58e694 100644 --- a/dom/workers/ServiceWorkerScriptCache.cpp +++ b/dom/workers/ServiceWorkerScriptCache.cpp @@ -554,7 +554,7 @@ private: ir->SetPrincipalInfo(Move(mPrincipalInfo)); } - RefPtr response = new Response(aCache->GetGlobalObject(), ir); + RefPtr response = new Response(aCache->GetGlobalObject(), ir, nullptr); RequestOrUSVString request; request.SetAsUSVString().Rebind(URL().Data(), URL().Length()); -- cgit v1.2.3