Promise.h (21064B)
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 file, 5 * You can obtain one at http://mozilla.org/MPL/2.0/. */ 6 7 #ifndef mozilla_dom_Promise_h 8 #define mozilla_dom_Promise_h 9 10 #include <functional> 11 #include <type_traits> 12 #include <utility> 13 14 #include "ErrorList.h" 15 #include "js/RootingAPI.h" 16 #include "js/TypeDecls.h" 17 #include "mozilla/AlreadyAddRefed.h" 18 #include "mozilla/Assertions.h" 19 #include "mozilla/ErrorResult.h" 20 #include "mozilla/HoldDropJSObjects.h" 21 #include "mozilla/RefPtr.h" 22 #include "mozilla/Result.h" 23 #include "mozilla/WeakPtr.h" 24 #include "mozilla/dom/AutoEntryScript.h" 25 #include "mozilla/dom/ScriptSettings.h" 26 #include "mozilla/dom/ToJSValue.h" 27 #include "nsCycleCollectionParticipant.h" 28 #include "nsError.h" 29 #include "nsISupports.h" 30 #include "nsString.h" 31 32 class nsCycleCollectionTraversalCallback; 33 class nsIGlobalObject; 34 35 namespace JS { 36 class Value; 37 } 38 39 namespace mozilla::webgpu { 40 class PipelineError; 41 } 42 43 namespace mozilla::dom { 44 45 class AnyCallback; 46 class MediaStreamError; 47 class PromiseInit; 48 class PromiseNativeHandler; 49 class PromiseDebugging; 50 51 class Promise : public SupportsWeakPtr, public JSHolderBase { 52 friend class PromiseTask; 53 friend class PromiseWorkerProxy; 54 friend class PromiseWorkerProxyRunnable; 55 56 public: 57 NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(Promise) 58 NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(Promise) 59 60 enum PropagateUserInteraction { 61 eDontPropagateUserInteraction, 62 ePropagateUserInteraction 63 }; 64 65 // Promise creation tries to create a JS reflector for the Promise, so is 66 // fallible. Furthermore, we don't want to do JS-wrapping on a 0-refcount 67 // object, so we addref before doing that and return the addrefed pointer 68 // here. 69 // Pass ePropagateUserInteraction for aPropagateUserInteraction if you want 70 // the promise resolve handler to be called as if we were handling user 71 // input events in case we are currently handling user input events. 72 static already_AddRefed<Promise> Create( 73 nsIGlobalObject* aGlobal, ErrorResult& aRv, 74 PropagateUserInteraction aPropagateUserInteraction = 75 eDontPropagateUserInteraction); 76 77 // Same as Promise::Create but never throws, but instead: 78 // 1. Causes crash on OOM (as nearly every other web APIs do) 79 // 2. Silently creates a no-op Promise if the JS context is shut down 80 // This can be useful for implementations that produce promises but do not 81 // care whether the current global is alive to consume them. 82 // Note that PromiseObj() can return a nullptr if created this way. 83 static already_AddRefed<Promise> CreateInfallible( 84 nsIGlobalObject* aGlobal, 85 PropagateUserInteraction aPropagateUserInteraction = 86 eDontPropagateUserInteraction); 87 88 // Reports a rejected Promise by sending an error report. 89 static void ReportRejectedPromise(JSContext* aCx, 90 JS::Handle<JSObject*> aPromise); 91 92 using MaybeFunc = void (Promise::*)(JSContext*, JS::Handle<JS::Value>); 93 94 // Helpers for using Promise from C++. 95 // Most DOM objects are handled already. To add a new type T, add a 96 // ToJSValue overload in ToJSValue.h. 97 // aArg is a const reference so we can pass rvalues like integer constants 98 template <typename T> 99 void MaybeResolve(T&& aArg) { 100 MaybeSomething(std::forward<T>(aArg), &Promise::MaybeResolve); 101 } 102 103 void MaybeResolveWithUndefined(); 104 105 void MaybeReject(JS::Handle<JS::Value> aValue) { 106 MaybeSomething(aValue, &Promise::MaybeReject); 107 } 108 109 // This method is deprecated. Consumers should MaybeRejectWithDOMException if 110 // they are rejecting with a DOMException, or use one of the other 111 // MaybeReject* methods otherwise. If they have a random nsresult which may 112 // or may not correspond to a DOMException type, they should consider using an 113 // appropriate DOMException-type nsresult with an informative message and 114 // calling MaybeRejectWithDOMException. 115 inline void MaybeReject(nsresult aArg) { 116 MOZ_ASSERT(NS_FAILED(aArg)); 117 MaybeSomething(aArg, &Promise::MaybeReject); 118 } 119 120 inline void MaybeReject(ErrorResult&& aArg) { 121 MOZ_ASSERT(aArg.Failed()); 122 MaybeSomething(std::move(aArg), &Promise::MaybeReject); 123 // That should have consumed aArg. 124 MOZ_ASSERT(!aArg.Failed()); 125 } 126 127 void MaybeReject(const RefPtr<MediaStreamError>& aArg); 128 void MaybeReject(const RefPtr<webgpu::PipelineError>& aArg); 129 130 void MaybeRejectWithUndefined(); 131 132 void MaybeResolveWithClone(JSContext* aCx, JS::Handle<JS::Value> aValue); 133 void MaybeRejectWithClone(JSContext* aCx, JS::Handle<JS::Value> aValue); 134 135 // Facilities for rejecting with various spec-defined exception values. 136 #define DOMEXCEPTION(name, err) \ 137 inline void MaybeRejectWith##name(const nsACString& aMessage) { \ 138 ErrorResult res; \ 139 res.Throw##name(aMessage); \ 140 MaybeReject(std::move(res)); \ 141 } \ 142 template <int N> \ 143 void MaybeRejectWith##name(const char(&aMessage)[N]) { \ 144 MaybeRejectWith##name(nsLiteralCString(aMessage)); \ 145 } 146 147 #include "mozilla/dom/DOMExceptionNames.h" 148 149 #undef DOMEXCEPTION 150 151 template <ErrNum errorNumber, typename... Ts> 152 void MaybeRejectWithTypeError(Ts&&... aMessageArgs) { 153 ErrorResult res; 154 res.ThrowTypeError<errorNumber>(std::forward<Ts>(aMessageArgs)...); 155 MaybeReject(std::move(res)); 156 } 157 158 inline void MaybeRejectWithTypeError(const nsACString& aMessage) { 159 ErrorResult res; 160 res.ThrowTypeError(aMessage); 161 MaybeReject(std::move(res)); 162 } 163 164 template <int N> 165 void MaybeRejectWithTypeError(const char (&aMessage)[N]) { 166 MaybeRejectWithTypeError(nsLiteralCString(aMessage)); 167 } 168 169 template <ErrNum errorNumber, typename... Ts> 170 void MaybeRejectWithRangeError(Ts&&... aMessageArgs) { 171 ErrorResult res; 172 res.ThrowRangeError<errorNumber>(std::forward<Ts>(aMessageArgs)...); 173 MaybeReject(std::move(res)); 174 } 175 176 inline void MaybeRejectWithRangeError(const nsACString& aMessage) { 177 ErrorResult res; 178 res.ThrowRangeError(aMessage); 179 MaybeReject(std::move(res)); 180 } 181 182 template <int N> 183 void MaybeRejectWithRangeError(const char (&aMessage)[N]) { 184 MaybeRejectWithRangeError(nsLiteralCString(aMessage)); 185 } 186 187 // DO NOT USE MaybeRejectBrokenly with in new code. Promises should be 188 // rejected with Error instances. 189 // Note: MaybeRejectBrokenly is a template so we can use it with DOMException 190 // without instantiating the DOMException specialization of MaybeSomething in 191 // every translation unit that includes this header, because that would 192 // require use to include DOMException.h either here or in all those 193 // translation units. 194 template <typename T> 195 void MaybeRejectBrokenly(const T& aArg); // Not implemented by default; see 196 // specializations in the .cpp for 197 // the T values we support. 198 199 // If the JSContext has a pending exception then this will reject the promise 200 // with that exception and clear it from the JSContext. 201 void MaybeRejectWithExceptionFromContext(JSContext* aCx) { 202 HandleException(aCx); 203 } 204 205 // Mark a settled promise as already handled so that rejections will not 206 // be reported as unhandled. 207 bool SetSettledPromiseIsHandled(); 208 209 // Mark a promise as handled so that rejections will not be reported as 210 // unhandled. Consider using SetSettledPromiseIsHandled if this promise is 211 // expected to be settled. 212 [[nodiscard]] bool SetAnyPromiseIsHandled(); 213 214 // WebIDL 215 216 nsIGlobalObject* GetParentObject() const { return GetGlobalObject(); } 217 218 // Do the equivalent of Promise.resolve in the compartment of aGlobal. The 219 // compartment of aCx is ignored. Errors are reported on the ErrorResult; if 220 // aRv comes back !Failed(), this function MUST return a non-null value. 221 // Pass ePropagateUserInteraction for aPropagateUserInteraction if you want 222 // the promise resolve handler to be called as if we were handling user 223 // input events in case we are currently handling user input events. 224 static already_AddRefed<Promise> Resolve( 225 nsIGlobalObject* aGlobal, JSContext* aCx, JS::Handle<JS::Value> aValue, 226 ErrorResult& aRv, 227 PropagateUserInteraction aPropagateUserInteraction = 228 eDontPropagateUserInteraction); 229 230 // Do the equivalent of Promise.resolve in the compartment of aGlobal. 231 // The promise is resolved with the JS value corresponding to aValue. 232 // If this fails, the promise is rejected with the exception. 233 template <typename T> 234 static already_AddRefed<Promise> Resolve( 235 nsIGlobalObject* aGlobal, T&& aValue, ErrorResult& aError, 236 PropagateUserInteraction aPropagateUserInteraction = 237 eDontPropagateUserInteraction) { 238 AutoJSAPI jsapi; 239 if (!jsapi.Init(aGlobal)) { 240 aError.Throw(NS_ERROR_UNEXPECTED); 241 return nullptr; 242 } 243 244 JSContext* cx = jsapi.cx(); 245 JS::Rooted<JS::Value> val(cx); 246 if (!ToJSValue(cx, std::forward<T>(aValue), &val)) { 247 return Promise::RejectWithExceptionFromContext(aGlobal, cx, aError); 248 } 249 250 return Resolve(aGlobal, cx, val, aError, aPropagateUserInteraction); 251 } 252 253 // Do the equivalent of Promise.reject in the compartment of aGlobal. The 254 // compartment of aCx is ignored. Errors are reported on the ErrorResult; if 255 // aRv comes back !Failed(), this function MUST return a non-null value. 256 static already_AddRefed<Promise> Reject(nsIGlobalObject* aGlobal, 257 JSContext* aCx, 258 JS::Handle<JS::Value> aValue, 259 ErrorResult& aRv); 260 261 template <typename T> 262 static already_AddRefed<Promise> Reject(nsIGlobalObject* aGlobal, T&& aValue, 263 ErrorResult& aError) { 264 AutoJSAPI jsapi; 265 if (!jsapi.Init(aGlobal)) { 266 aError.Throw(NS_ERROR_UNEXPECTED); 267 return nullptr; 268 } 269 270 JSContext* cx = jsapi.cx(); 271 JS::Rooted<JS::Value> val(cx); 272 if (!ToJSValue(cx, std::forward<T>(aValue), &val)) { 273 return Promise::RejectWithExceptionFromContext(aGlobal, cx, aError); 274 } 275 276 return Reject(aGlobal, cx, val, aError); 277 } 278 279 static already_AddRefed<Promise> RejectWithExceptionFromContext( 280 nsIGlobalObject* aGlobal, JSContext* aCx, ErrorResult& aError); 281 282 // Do the equivalent of Promise.all in the current compartment of aCx. Errors 283 // are reported on the ErrorResult; if aRv comes back !Failed(), this function 284 // MUST return a non-null value. 285 // Pass ePropagateUserInteraction for aPropagateUserInteraction if you want 286 // the promise resolve handler to be called as if we were handling user 287 // input events in case we are currently handling user input events. 288 static already_AddRefed<Promise> All( 289 JSContext* aCx, const nsTArray<RefPtr<Promise>>& aPromiseList, 290 ErrorResult& aRv, 291 PropagateUserInteraction aPropagateUserInteraction = 292 eDontPropagateUserInteraction); 293 294 using SuccessSteps = 295 const std::function<void(const Span<JS::Heap<JS::Value>>&)>&; 296 using FailureSteps = const std::function<void(JS::Handle<JS::Value>)>&; 297 // Wait for all aPromises' results, calling either aFailureSteps if any 298 // promise rejects, or aSuccessSteps if all promises resolves. 299 // aCycleCollectedArg can be passed to keep state alive while waiting for the 300 // promises, making sure that it's cycle collected. 301 MOZ_CAN_RUN_SCRIPT 302 static void WaitForAll(nsIGlobalObject* aGlobal, 303 const Span<RefPtr<Promise>>& aPromises, 304 SuccessSteps aSuccessSteps, FailureSteps aFailureSteps, 305 nsISupports* aCycleCollectedArg = nullptr); 306 307 template <typename Callback, typename... Args> 308 using IsHandlerCallback = 309 std::is_same<already_AddRefed<Promise>, 310 decltype(std::declval<Callback>()( 311 (JSContext*)(nullptr), 312 std::declval<JS::Handle<JS::Value>>(), 313 std::declval<ErrorResult&>(), std::declval<Args>()...))>; 314 315 template <typename Callback, typename... Args> 316 using ThenResult = 317 std::enable_if_t<IsHandlerCallback<Callback, Args...>::value, 318 Result<RefPtr<Promise>, nsresult>>; 319 320 // Similar to the JavaScript then() function. Accepts two lambda function 321 // arguments, which it attaches as native resolve/reject handlers, and 322 // returns a new promise which: 323 // 1. if the ErrorResult contains an error value, rejects with it. 324 // 2. else, resolves with a return value. 325 // 326 // Any additional arguments passed after the callback functions are stored and 327 // passed as additional arguments to the functions when it is called. These 328 // values will participate in cycle collection for the promise handler, and 329 // therefore may safely form reference cycles with the promise chain. 330 // 331 // Any strong references required by the callbacks should be passed in this 332 // manner, rather than using lambda capture, lambda captures do not support 333 // cycle collection, and can easily lead to leaks. 334 template <typename ResolveCallback, typename RejectCallback, typename... Args> 335 ThenResult<ResolveCallback, Args...> ThenCatchWithCycleCollectedArgs( 336 ResolveCallback&& aOnResolve, RejectCallback&& aOnReject, 337 Args&&... aArgs); 338 339 // Same as ThenCatchWithCycleCollectedArgs, except the rejection error will 340 // simply be propagated. 341 template <typename Callback, typename... Args> 342 ThenResult<Callback, Args...> ThenWithCycleCollectedArgs( 343 Callback&& aOnResolve, Args&&... aArgs); 344 345 // Same as ThenCatchWithCycleCollectedArgs, except the resolved value will 346 // simply be propagated. 347 template <typename Callback, typename... Args> 348 ThenResult<Callback, Args...> CatchWithCycleCollectedArgs( 349 Callback&& aOnReject, Args&&... aArgs); 350 351 // Same as Then[Catch]CycleCollectedArgs but the arguments are gathered into 352 // an `std::tuple` and there is an additional `std::tuple` for JS arguments 353 // after that. 354 template <typename ResolveCallback, typename RejectCallback, 355 typename ArgsTuple, typename JSArgsTuple> 356 Result<RefPtr<Promise>, nsresult> ThenCatchWithCycleCollectedArgsJS( 357 ResolveCallback&& aOnResolve, RejectCallback&& aOnReject, 358 ArgsTuple&& aArgs, JSArgsTuple&& aJSArgs); 359 template <typename Callback, typename ArgsTuple, typename JSArgsTuple> 360 Result<RefPtr<Promise>, nsresult> ThenWithCycleCollectedArgsJS( 361 Callback&& aOnResolve, ArgsTuple&& aArgs, JSArgsTuple&& aJSArgs); 362 363 Result<RefPtr<Promise>, nsresult> ThenWithoutCycleCollection( 364 const std::function<already_AddRefed<Promise>( 365 JSContext*, JS::Handle<JS::Value>, ErrorResult& aRv)>& aCallback); 366 367 // Similar to ThenCatchWithCycleCollectedArgs but doesn't care with return 368 // values of the callbacks and does not return a new promise. 369 template <typename ResolveCallback, typename RejectCallback, typename... Args> 370 void AddCallbacksWithCycleCollectedArgs(ResolveCallback&& aOnResolve, 371 RejectCallback&& aOnReject, 372 Args&&... aArgs); 373 374 // This can be null if this promise is made after the corresponding JSContext 375 // is dead. 376 JSObject* PromiseObj() const { return mPromiseObj; } 377 378 void AppendNativeHandler(PromiseNativeHandler* aRunnable); 379 380 nsIGlobalObject* GetGlobalObject() const { return mGlobal; } 381 382 // Create a dom::Promise from a given SpiderMonkey Promise object. 383 // aPromiseObj MUST be in the compartment of aGlobal's global JS object. 384 // Pass ePropagateUserInteraction for aPropagateUserInteraction if you want 385 // the promise resolve handler to be called as if we were handling user 386 // input events in case we are currently handling user input events. 387 static already_AddRefed<Promise> CreateFromExisting( 388 nsIGlobalObject* aGlobal, JS::Handle<JSObject*> aPromiseObj, 389 PropagateUserInteraction aPropagateUserInteraction = 390 eDontPropagateUserInteraction); 391 392 enum class PromiseState { Pending, Resolved, Rejected }; 393 394 PromiseState State() const; 395 396 static already_AddRefed<Promise> CreateResolvedWithUndefined( 397 nsIGlobalObject* aGlobal, ErrorResult& aRv); 398 399 static already_AddRefed<Promise> CreateRejected( 400 nsIGlobalObject* aGlobal, JS::Handle<JS::Value> aRejectionError, 401 ErrorResult& aRv); 402 403 static already_AddRefed<Promise> CreateRejectedWithTypeError( 404 nsIGlobalObject* aGlobal, const nsACString& aMessage, ErrorResult& aRv); 405 406 // The rejection error will be consumed if the promise is successfully 407 // created, else the error will remain and rv.Failed() will keep being true. 408 // This intentionally is not an overload of CreateRejected to prevent 409 // accidental omission of the second argument. (See also bug 1762233 about 410 // removing its third argument.) 411 static already_AddRefed<Promise> CreateRejectedWithErrorResult( 412 nsIGlobalObject* aGlobal, ErrorResult& aRejectionError); 413 414 // Converts an integer or DOMException to nsresult, or otherwise returns 415 // NS_ERROR_DOM_NOT_NUMBER_ERR (which is exclusive for this function). 416 // Can be used to convert JS::Value passed to rejection handler so that native 417 // error handlers e.g. MozPromise can consume it. 418 static nsresult TryExtractNSResultFromRejectionValue( 419 JS::Handle<JS::Value> aValue); 420 421 protected: 422 template <typename ResolveCallback, typename RejectCallback, typename... Args, 423 typename... JSArgs> 424 Result<RefPtr<Promise>, nsresult> ThenCatchWithCycleCollectedArgsJSImpl( 425 Maybe<ResolveCallback>&& aOnResolve, Maybe<RejectCallback>&& aOnReject, 426 std::tuple<Args...>&& aArgs, std::tuple<JSArgs...>&& aJSArgs); 427 template <typename ResolveCallback, typename RejectCallback, typename... Args> 428 ThenResult<ResolveCallback, Args...> ThenCatchWithCycleCollectedArgsImpl( 429 Maybe<ResolveCallback>&& aOnResolve, Maybe<RejectCallback>&& aOnReject, 430 Args&&... aArgs); 431 432 // Legacy method for throwing DOMExceptions. Only used by media code at this 433 // point, via DetailedPromise. Do NOT add new uses! When this is removed, 434 // remove the friend declaration in ErrorResult.h. 435 inline void MaybeRejectWithDOMException(nsresult rv, 436 const nsACString& aMessage) { 437 ErrorResult res; 438 res.ThrowDOMException(rv, aMessage); 439 MaybeReject(std::move(res)); 440 } 441 442 struct PromiseCapability; 443 444 // Do NOT call this unless you're Promise::Create or 445 // Promise::CreateFromExisting. I wish we could enforce that from inside this 446 // class too, somehow. 447 explicit Promise(nsIGlobalObject* aGlobal); 448 449 virtual ~Promise(); 450 451 // Do JS-wrapping after Promise creation. 452 // Pass ePropagateUserInteraction for aPropagateUserInteraction if you want 453 // the promise resolve handler to be called as if we were handling user 454 // input events in case we are currently handling user input events. 455 // The error code can be: 456 // * NS_ERROR_UNEXPECTED when AutoJSAPI.Init fails 457 // * NS_ERROR_OUT_OF_MEMORY when NewPromiseObject throws OOM 458 // * NS_ERROR_NOT_INITIALIZED when NewPromiseObject fails without OOM 459 void CreateWrapper(ErrorResult& aRv, 460 PropagateUserInteraction aPropagateUserInteraction = 461 eDontPropagateUserInteraction); 462 463 private: 464 void MaybeResolve(JSContext* aCx, JS::Handle<JS::Value> aValue); 465 void MaybeReject(JSContext* aCx, JS::Handle<JS::Value> aValue); 466 467 template <typename T> 468 void MaybeSomething(T&& aArgument, MaybeFunc aFunc) { 469 if (NS_WARN_IF(!PromiseObj())) { 470 return; 471 } 472 473 AutoAllowLegacyScriptExecution exemption; 474 AutoEntryScript aes(mGlobal, "Promise resolution or rejection"); 475 JSContext* cx = aes.cx(); 476 477 JS::Rooted<JS::Value> val(cx); 478 if (!ToJSValue(cx, std::forward<T>(aArgument), &val)) { 479 HandleException(cx); 480 return; 481 } 482 483 (this->*aFunc)(cx, val); 484 } 485 486 void HandleException(JSContext* aCx); 487 488 bool MaybePropagateUserInputEventHandling(); 489 490 RefPtr<nsIGlobalObject> mGlobal; 491 492 JS::Heap<JSObject*> mPromiseObj; 493 }; 494 495 } // namespace mozilla::dom 496 497 extern "C" { 498 // These functions are used in the implementation of ffi bindings for 499 // dom::Promise from Rust in xpcom crate. 500 void DomPromise_AddRef(mozilla::dom::Promise* aPromise); 501 void DomPromise_Release(mozilla::dom::Promise* aPromise); 502 void DomPromise_RejectWithVariant(mozilla::dom::Promise* aPromise, 503 nsIVariant* aVariant); 504 void DomPromise_ResolveWithVariant(mozilla::dom::Promise* aPromise, 505 nsIVariant* aVariant); 506 } 507 508 #endif // mozilla_dom_Promise_h