Backed out changeset 88fbb17e3c20 (bug 1865637) for causing animation related mochite...
[gecko.git] / js / public / Promise.h
blob221d6fdfeebd84c224b745324f9836640e845ee7
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sts=4 et sw=4 tw=99:
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 #ifndef js_Promise_h
8 #define js_Promise_h
10 #include "mozilla/Attributes.h"
12 #include "jstypes.h"
14 #include "js/RootingAPI.h"
15 #include "js/TypeDecls.h"
16 #include "js/UniquePtr.h"
18 namespace JS {
20 class JS_PUBLIC_API AutoDebuggerJobQueueInterruption;
22 /**
23 * Abstract base class for an ECMAScript Job Queue:
24 * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-jobs-and-job-queues
26 * SpiderMonkey doesn't schedule Promise resolution jobs itself; instead, the
27 * embedding can provide an instance of this class SpiderMonkey can use to do
28 * that scheduling.
30 * The JavaScript shell includes a simple implementation adequate for running
31 * tests. Browsers need to augment job handling to meet their own additional
32 * requirements, so they can provide their own implementation.
34 class JS_PUBLIC_API JobQueue {
35 public:
36 virtual ~JobQueue() = default;
38 /**
39 * Ask the embedding for the incumbent global.
41 * SpiderMonkey doesn't itself have a notion of incumbent globals as defined
42 * by the HTML spec, so we need the embedding to provide this. See
43 * dom/script/ScriptSettings.h for details.
45 virtual JSObject* getIncumbentGlobal(JSContext* cx) = 0;
47 /**
48 * Enqueue a reaction job `job` for `promise`, which was allocated at
49 * `allocationSite`. Provide `incumbentGlobal` as the incumbent global for
50 * the reaction job's execution.
52 * `promise` can be null if the promise is optimized out.
53 * `promise` is guaranteed not to be optimized out if the promise has
54 * non-default user-interaction flag.
56 virtual bool enqueuePromiseJob(JSContext* cx, JS::HandleObject promise,
57 JS::HandleObject job,
58 JS::HandleObject allocationSite,
59 JS::HandleObject incumbentGlobal) = 0;
61 /**
62 * Run all jobs in the queue. Running one job may enqueue others; continue to
63 * run jobs until the queue is empty.
65 * Calling this method at the wrong time can break the web. The HTML spec
66 * indicates exactly when the job queue should be drained (in HTML jargon,
67 * when it should "perform a microtask checkpoint"), and doing so at other
68 * times can incompatibly change the semantics of programs that use promises
69 * or other microtask-based features.
71 * This method is called only via AutoDebuggerJobQueueInterruption, used by
72 * the Debugger API implementation to ensure that the debuggee's job queue is
73 * protected from the debugger's own activity. See the comments on
74 * AutoDebuggerJobQueueInterruption.
76 virtual void runJobs(JSContext* cx) = 0;
78 /**
79 * Return true if the job queue is empty, false otherwise.
81 virtual bool empty() const = 0;
83 protected:
84 friend class AutoDebuggerJobQueueInterruption;
86 /**
87 * A saved job queue, represented however the JobQueue implementation pleases.
88 * Use AutoDebuggerJobQueueInterruption rather than trying to construct one of
89 * these directly; see documentation there.
91 * Destructing an instance of this class should assert that the current queue
92 * is empty, and then restore the queue the instance captured.
94 class SavedJobQueue {
95 public:
96 virtual ~SavedJobQueue() = default;
99 /**
100 * Capture this JobQueue's current job queue as a SavedJobQueue and return it,
101 * leaving the JobQueue's job queue empty. Destroying the returned object
102 * should assert that this JobQueue's current job queue is empty, and restore
103 * the original queue.
105 * On OOM, this should call JS_ReportOutOfMemory on the given JSContext,
106 * and return a null UniquePtr.
108 virtual js::UniquePtr<SavedJobQueue> saveJobQueue(JSContext*) = 0;
112 * Tell SpiderMonkey to use `queue` to schedule promise reactions.
114 * SpiderMonkey does not take ownership of the queue; it is the embedding's
115 * responsibility to clean it up after the runtime is destroyed.
117 extern JS_PUBLIC_API void SetJobQueue(JSContext* cx, JobQueue* queue);
120 * [SMDOC] Protecting the debuggee's job/microtask queue from debugger activity.
122 * When the JavaScript debugger interrupts the execution of some debuggee code
123 * (for a breakpoint, for example), the debuggee's execution must be paused
124 * while the developer takes time to look at it. During this interruption, other
125 * tabs should remain active and usable. If the debuggee shares a main thread
126 * with non-debuggee tabs, that means that the thread will have to process
127 * non-debuggee HTML tasks and microtasks as usual, even as the debuggee's are
128 * on hold until the debugger lets it continue execution. (Letting debuggee
129 * microtasks run during the interruption would mean that, from the debuggee's
130 * point of view, their side effects would take place wherever the breakpoint
131 * was set - in general, not a place other code should ever run, and a violation
132 * of the run-to-completion rule.)
134 * This means that, even though the timing and ordering of microtasks is
135 * carefully specified by the standard - and important to preserve for
136 * compatibility and predictability - debugger use may, correctly, have the
137 * effect of reordering microtasks. During the interruption, microtasks enqueued
138 * by non-debuggee tabs must run immediately alongside their HTML tasks as
139 * usual, whereas any debuggee microtasks that were in the queue when the
140 * interruption began must wait for the debuggee to be continued - and thus run
141 * after microtasks enqueued after they were.
143 * Fortunately, this reordering is visible only at the global level: when
144 * implemented correctly, it is not detectable by an individual debuggee. Note
145 * that a debuggee should generally be a complete unit of similar-origin related
146 * browsing contexts. Since non-debuggee activity falls outside that unit, it
147 * should never be visible to the debuggee (except via mechanisms that are
148 * already asynchronous, like events), so the debuggee should be unable to
149 * detect non-debuggee microtasks running when they normally would not. As long
150 * as behavior *visible to the debuggee* is unaffected by the interruption, we
151 * have respected the spirit of the rule.
153 * Of course, even as we accept the general principle that interrupting the
154 * debuggee should have as little detectable effect as possible, we still permit
155 * the developer to do things like evaluate expressions at the console that have
156 * arbitrary effects on the debuggee's state—effects that could never occur
157 * naturally at that point in the program. But since these are explicitly
158 * requested by the developer, who presumably knows what they're doing, we
159 * support this as best we can. If the developer evaluates an expression in the
160 * console that resolves a promise, it seems most natural for the promise's
161 * reaction microtasks to run immediately, within the interruption. This is an
162 * 'unnatural' time for the microtasks to run, but no more unnatural than the
163 * evaluation that triggered them.
165 * So the overall behavior we need is as follows:
167 * - When the debugger interrupts a debuggee, the debuggee's microtask queue
168 * must be saved.
170 * - When debuggee execution resumes, the debuggee's microtask queue must be
171 * restored exactly as it was when the interruption occurred.
173 * - Non-debuggee task and microtask execution must take place normally during
174 * the interruption.
176 * Since each HTML task begins with an empty microtask queue, and it should not
177 * be possible for a task to mix debuggee and non-debuggee code, interrupting a
178 * debuggee should always find a microtask queue containing exclusively debuggee
179 * microtasks, if any. So saving and restoring the microtask queue should affect
180 * only the debuggee, not any non-debuggee content.
182 * AutoDebuggerJobQueueInterruption
183 * --------------------------------
185 * AutoDebuggerJobQueueInterruption is an RAII class, meant for use by the
186 * Debugger API implementation, that takes care of saving and restoring the
187 * queue.
189 * Constructing and initializing an instance of AutoDebuggerJobQueueInterruption
190 * sets aside the given JSContext's job queue, leaving the JSContext's queue
191 * empty. When the AutoDebuggerJobQueueInterruption instance is destroyed, it
192 * asserts that the JSContext's current job queue (holding jobs enqueued while
193 * the AutoDebuggerJobQueueInterruption was alive) is empty, and restores the
194 * saved queue to the JSContext.
196 * Since the Debugger API's behavior is up to us, we can specify that Debugger
197 * hooks begin execution with an empty job queue, and that we drain the queue
198 * after each hook function has run. This drain will be visible to debugger
199 * hooks, and makes hook calls resemble HTML tasks, with their own automatic
200 * microtask checkpoint. But, the drain will be invisible to the debuggee, as
201 * its queue is preserved across the hook invocation.
203 * To protect the debuggee's job queue, Debugger takes care to invoke callback
204 * functions only within the scope of an AutoDebuggerJobQueueInterruption
205 * instance.
207 * Why not let the hook functions themselves take care of this?
208 * ------------------------------------------------------------
210 * Certainly, we could leave responsibility for saving and restoring the job
211 * queue to the Debugger hook functions themselves.
213 * In fact, early versions of this change tried making the devtools server save
214 * and restore the queue explicitly, but because hooks are set and changed in
215 * numerous places, it was hard to be confident that every case had been
216 * covered, and it seemed that future changes could easily introduce new holes.
218 * Later versions of this change modified the accessor properties on the
219 * Debugger objects' prototypes to automatically protect the job queue when
220 * calling hooks, but the effect was essentially a monkeypatch applied to an API
221 * we defined and control, which doesn't make sense.
223 * In the end, since promises have become such a pervasive part of JavaScript
224 * programming, almost any imaginable use of Debugger would need to provide some
225 * kind of protection for the debuggee's job queue, so it makes sense to simply
226 * handle it once, carefully, in the implementation of Debugger itself.
228 class MOZ_RAII JS_PUBLIC_API AutoDebuggerJobQueueInterruption {
229 public:
230 explicit AutoDebuggerJobQueueInterruption();
231 ~AutoDebuggerJobQueueInterruption();
233 bool init(JSContext* cx);
234 bool initialized() const { return !!saved; }
237 * Drain the job queue. (In HTML terminology, perform a microtask checkpoint.)
239 * To make Debugger hook calls more like HTML tasks or ECMAScript jobs,
240 * Debugger promises that each hook begins execution with a clean microtask
241 * queue, and that a microtask checkpoint (queue drain) takes place after each
242 * hook returns, successfully or otherwise.
244 * To ensure these debugger-introduced microtask checkpoints serve only the
245 * hook's microtasks, and never affect the debuggee's, the Debugger API
246 * implementation uses only this method to perform the checkpoints, thereby
247 * statically ensuring that an AutoDebuggerJobQueueInterruption is in scope to
248 * protect the debuggee.
250 * SavedJobQueue implementations are required to assert that the queue is
251 * empty before restoring the debuggee's queue. If the Debugger API ever fails
252 * to perform a microtask checkpoint after calling a hook, that assertion will
253 * fail, catching the mistake.
255 void runJobs();
257 private:
258 JSContext* cx;
259 js::UniquePtr<JobQueue::SavedJobQueue> saved;
262 enum class PromiseRejectionHandlingState { Unhandled, Handled };
264 typedef void (*PromiseRejectionTrackerCallback)(
265 JSContext* cx, bool mutedErrors, JS::HandleObject promise,
266 JS::PromiseRejectionHandlingState state, void* data);
269 * Sets the callback that's invoked whenever a Promise is rejected without
270 * a rejection handler, and when a Promise that was previously rejected
271 * without a handler gets a handler attached.
273 extern JS_PUBLIC_API void SetPromiseRejectionTrackerCallback(
274 JSContext* cx, PromiseRejectionTrackerCallback callback,
275 void* data = nullptr);
278 * Inform the runtime that the job queue is empty and the embedding is going to
279 * execute its last promise job. The runtime may now choose to skip creating
280 * promise jobs for asynchronous execution and instead continue execution
281 * synchronously. More specifically, this optimization is used to skip the
282 * standard job queuing behavior for `await` operations in async functions.
284 * This function may be called before executing the last job in the job queue.
285 * When it was called, JobQueueMayNotBeEmpty must be called in order to restore
286 * the default job queuing behavior before the embedding enqueues its next job
287 * into the job queue.
289 extern JS_PUBLIC_API void JobQueueIsEmpty(JSContext* cx);
292 * Inform the runtime that job queue is no longer empty. The runtime can now no
293 * longer skip creating promise jobs for asynchronous execution, because
294 * pending jobs in the job queue must be executed first to preserve the FIFO
295 * (first in - first out) property of the queue. This effectively undoes
296 * JobQueueIsEmpty and re-enables the standard job queuing behavior.
298 * This function must be called whenever enqueuing a job to the job queue when
299 * JobQueueIsEmpty was called previously.
301 extern JS_PUBLIC_API void JobQueueMayNotBeEmpty(JSContext* cx);
304 * Returns a new instance of the Promise builtin class in the current
305 * compartment, with the right slot layout.
307 * The `executor` can be a `nullptr`. In that case, the only way to resolve or
308 * reject the returned promise is via the `JS::ResolvePromise` and
309 * `JS::RejectPromise` JSAPI functions.
311 extern JS_PUBLIC_API JSObject* NewPromiseObject(JSContext* cx,
312 JS::HandleObject executor);
315 * Returns true if the given object is an unwrapped PromiseObject, false
316 * otherwise.
318 extern JS_PUBLIC_API bool IsPromiseObject(JS::HandleObject obj);
321 * Returns the current compartment's original Promise constructor.
323 extern JS_PUBLIC_API JSObject* GetPromiseConstructor(JSContext* cx);
326 * Returns the current compartment's original Promise.prototype.
328 extern JS_PUBLIC_API JSObject* GetPromisePrototype(JSContext* cx);
330 // Keep this in sync with the PROMISE_STATE defines in SelfHostingDefines.h.
331 enum class PromiseState { Pending, Fulfilled, Rejected };
334 * Returns the given Promise's state as a JS::PromiseState enum value.
336 * Returns JS::PromiseState::Pending if the given object is a wrapper that
337 * can't safely be unwrapped.
339 extern JS_PUBLIC_API PromiseState GetPromiseState(JS::HandleObject promise);
342 * Returns the given Promise's process-unique ID.
344 JS_PUBLIC_API uint64_t GetPromiseID(JS::HandleObject promise);
347 * Returns the given Promise's result: either the resolution value for
348 * fulfilled promises, or the rejection reason for rejected ones.
350 extern JS_PUBLIC_API JS::Value GetPromiseResult(JS::HandleObject promise);
353 * Returns whether the given promise's rejection is already handled or not.
355 * The caller must check the given promise is rejected before checking it's
356 * handled or not.
358 extern JS_PUBLIC_API bool GetPromiseIsHandled(JS::HandleObject promise);
361 * Given a settled (i.e. fulfilled or rejected, not pending) promise, sets
362 * |promise.[[PromiseIsHandled]]| to true and removes it from the list of
363 * unhandled rejected promises.
365 extern JS_PUBLIC_API bool SetSettledPromiseIsHandled(JSContext* cx,
366 JS::HandleObject promise);
369 * Given a promise (settled or not), sets |promise.[[PromiseIsHandled]]| to true
370 * and removes it from the list of unhandled rejected promises if it's settled.
372 [[nodiscard]] extern JS_PUBLIC_API bool SetAnyPromiseIsHandled(
373 JSContext* cx, JS::HandleObject promise);
376 * Returns a js::SavedFrame linked list of the stack that lead to the given
377 * Promise's allocation.
379 extern JS_PUBLIC_API JSObject* GetPromiseAllocationSite(
380 JS::HandleObject promise);
382 extern JS_PUBLIC_API JSObject* GetPromiseResolutionSite(
383 JS::HandleObject promise);
385 #ifdef DEBUG
386 extern JS_PUBLIC_API void DumpPromiseAllocationSite(JSContext* cx,
387 JS::HandleObject promise);
389 extern JS_PUBLIC_API void DumpPromiseResolutionSite(JSContext* cx,
390 JS::HandleObject promise);
391 #endif
394 * Calls the current compartment's original Promise.resolve on the original
395 * Promise constructor, with `resolutionValue` passed as an argument.
397 extern JS_PUBLIC_API JSObject* CallOriginalPromiseResolve(
398 JSContext* cx, JS::HandleValue resolutionValue);
401 * Calls the current compartment's original Promise.reject on the original
402 * Promise constructor, with `resolutionValue` passed as an argument.
404 extern JS_PUBLIC_API JSObject* CallOriginalPromiseReject(
405 JSContext* cx, JS::HandleValue rejectionValue);
408 * Resolves the given Promise with the given `resolutionValue`.
410 * Calls the `resolve` function that was passed to the executor function when
411 * the Promise was created.
413 extern JS_PUBLIC_API bool ResolvePromise(JSContext* cx,
414 JS::HandleObject promiseObj,
415 JS::HandleValue resolutionValue);
418 * Rejects the given `promise` with the given `rejectionValue`.
420 * Calls the `reject` function that was passed to the executor function when
421 * the Promise was created.
423 extern JS_PUBLIC_API bool RejectPromise(JSContext* cx,
424 JS::HandleObject promiseObj,
425 JS::HandleValue rejectionValue);
428 * Create a Promise with the given fulfill/reject handlers, that will be
429 * fulfilled/rejected with the value/reason that the promise `promise` is
430 * fulfilled/rejected with.
432 * This function basically acts like `promise.then(onFulfilled, onRejected)`,
433 * except that its behavior is unaffected by changes to `Promise`,
434 * `Promise[Symbol.species]`, `Promise.prototype.then`, `promise.constructor`,
435 * `promise.then`, and so on.
437 * This function throws if `promise` is not a Promise from this or another
438 * realm.
440 * This function will assert if `onFulfilled` or `onRejected` is non-null and
441 * also not IsCallable.
443 extern JS_PUBLIC_API JSObject* CallOriginalPromiseThen(
444 JSContext* cx, JS::HandleObject promise, JS::HandleObject onFulfilled,
445 JS::HandleObject onRejected);
448 * Unforgeable, optimized version of the JS builtin Promise.prototype.then.
450 * Takes a Promise instance and nullable `onFulfilled`/`onRejected` callables to
451 * enqueue as reactions for that promise. In contrast to Promise.prototype.then,
452 * this doesn't create and return a new Promise instance.
454 * Throws a TypeError if `promise` isn't a Promise (or possibly a different
455 * error if it's a security wrapper or dead object proxy).
457 extern JS_PUBLIC_API bool AddPromiseReactions(JSContext* cx,
458 JS::HandleObject promise,
459 JS::HandleObject onFulfilled,
460 JS::HandleObject onRejected);
463 * Unforgeable, optimized version of the JS builtin Promise.prototype.then.
465 * Takes a Promise instance and nullable `onFulfilled`/`onRejected` callables to
466 * enqueue as reactions for that promise. In contrast to Promise.prototype.then,
467 * this doesn't create and return a new Promise instance.
469 * Throws a TypeError if `promise` isn't a Promise (or possibly a different
470 * error if it's a security wrapper or dead object proxy).
472 * If `onRejected` is null and `promise` is rejected, this function -- unlike
473 * the function above -- will not report an unhandled rejection.
475 extern JS_PUBLIC_API bool AddPromiseReactionsIgnoringUnhandledRejection(
476 JSContext* cx, JS::HandleObject promise, JS::HandleObject onFulfilled,
477 JS::HandleObject onRejected);
479 // This enum specifies whether a promise is expected to keep track of
480 // information that is useful for embedders to implement user activation
481 // behavior handling as specified in the HTML spec:
482 // https://html.spec.whatwg.org/multipage/interaction.html#triggered-by-user-activation
483 // By default, promises created by SpiderMonkey do not make any attempt to keep
484 // track of information about whether an activation behavior was being processed
485 // when the original promise in a promise chain was created. If the embedder
486 // sets either of the HadUserInteractionAtCreation or
487 // DidntHaveUserInteractionAtCreation flags on a promise after creating it,
488 // SpiderMonkey will propagate that flag to newly created promises when
489 // processing Promise#then and will make it possible to query this flag off of a
490 // promise further down the chain later using the
491 // GetPromiseUserInputEventHandlingState() API.
492 enum class PromiseUserInputEventHandlingState {
493 // Don't keep track of this state (default for all promises)
494 DontCare,
495 // Keep track of this state, the original promise in the chain was created
496 // while an activation behavior was being processed.
497 HadUserInteractionAtCreation,
498 // Keep track of this state, the original promise in the chain was created
499 // while an activation behavior was not being processed.
500 DidntHaveUserInteractionAtCreation
504 * Returns the given Promise's activation behavior state flag per above as a
505 * JS::PromiseUserInputEventHandlingState value. All promises are created with
506 * the DontCare state by default.
508 * Returns JS::PromiseUserInputEventHandlingState::DontCare if the given object
509 * is a wrapper that can't safely be unwrapped.
511 extern JS_PUBLIC_API PromiseUserInputEventHandlingState
512 GetPromiseUserInputEventHandlingState(JS::HandleObject promise);
515 * Sets the given Promise's activation behavior state flag per above as a
516 * JS::PromiseUserInputEventHandlingState value.
518 * Returns false if the given object is a wrapper that can't safely be
519 * unwrapped.
521 extern JS_PUBLIC_API bool SetPromiseUserInputEventHandlingState(
522 JS::HandleObject promise, JS::PromiseUserInputEventHandlingState state);
525 * Unforgeable version of the JS builtin Promise.all.
527 * Takes a HandleObjectVector of Promise objects and returns a promise that's
528 * resolved with an array of resolution values when all those promises have
529 * been resolved, or rejected with the rejection value of the first rejected
530 * promise.
532 * Asserts that all objects in the `promises` vector are, maybe wrapped,
533 * instances of `Promise` or a subclass of `Promise`.
535 extern JS_PUBLIC_API JSObject* GetWaitForAllPromise(
536 JSContext* cx, JS::HandleObjectVector promises);
539 * The Dispatchable interface allows the embedding to call SpiderMonkey
540 * on a JSContext thread when requested via DispatchToEventLoopCallback.
542 class JS_PUBLIC_API Dispatchable {
543 protected:
544 // Dispatchables are created and destroyed by SpiderMonkey.
545 Dispatchable() = default;
546 virtual ~Dispatchable() = default;
548 public:
549 // ShuttingDown indicates that SpiderMonkey should abort async tasks to
550 // expedite shutdown.
551 enum MaybeShuttingDown { NotShuttingDown, ShuttingDown };
553 // Called by the embedding after DispatchToEventLoopCallback succeeds.
554 virtual void run(JSContext* cx, MaybeShuttingDown maybeShuttingDown) = 0;
558 * Callback to dispatch a JS::Dispatchable to a JSContext's thread's event loop.
560 * The DispatchToEventLoopCallback set on a particular JSContext must accept
561 * JS::Dispatchable instances and arrange for their `run` methods to be called
562 * eventually on the JSContext's thread. This is used for cross-thread dispatch,
563 * so the callback itself must be safe to call from any thread.
565 * If the callback returns `true`, it must eventually run the given
566 * Dispatchable; otherwise, SpiderMonkey may leak memory or hang.
568 * The callback may return `false` to indicate that the JSContext's thread is
569 * shutting down and is no longer accepting runnables. Shutting down is a
570 * one-way transition: once the callback has rejected a runnable, it must reject
571 * all subsequently submitted runnables as well.
573 * To establish a DispatchToEventLoopCallback, the embedding may either call
574 * InitDispatchToEventLoop to provide its own, or call js::UseInternalJobQueues
575 * to select a default implementation built into SpiderMonkey. This latter
576 * depends on the embedding to call js::RunJobs on the JavaScript thread to
577 * process queued Dispatchables at appropriate times.
580 typedef bool (*DispatchToEventLoopCallback)(void* closure,
581 Dispatchable* dispatchable);
583 extern JS_PUBLIC_API void InitDispatchToEventLoop(
584 JSContext* cx, DispatchToEventLoopCallback callback, void* closure);
587 * When a JSRuntime is destroyed it implicitly cancels all async tasks in
588 * progress, releasing any roots held by the task. However, this is not soon
589 * enough for cycle collection, which needs to have roots dropped earlier so
590 * that the cycle collector can transitively remove roots for a future GC. For
591 * these and other cases, the set of pending async tasks can be canceled
592 * with this call earlier than JSRuntime destruction.
595 extern JS_PUBLIC_API void ShutdownAsyncTasks(JSContext* cx);
597 } // namespace JS
599 #endif // js_Promise_h