Debian Codegraph @

js/public/Promise.h

raw
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/. */
6
7 #ifndef js_Promise_h
8 #define js_Promise_h
9
10 #include "mozilla/Attributes.h"
11
12 #include "jstypes.h"
13
14 #include "js/RootingAPI.h"
15 #include "js/TypeDecls.h"
16 #include "js/UniquePtr.h"
17
18 namespace JS {
19
20 class JS_PUBLIC_API AutoDebuggerJobQueueInterruption;
21
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
25 *
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.
29 *
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.
33 */
34 class JS_PUBLIC_API JobQueue {
35 public:
36 virtual ~JobQueue() = default;
37
38 /**
39 * Ask the embedding for the host defined data.
40 *
41 * This is the step 5 in
42 * https://html.spec.whatwg.org/multipage/webappapis.html#hostmakejobcallback
43 *
44 * SpiderMonkey doesn't itself have a notion of host defined data as defined
45 * by the HTML spec, so we need the embedding to provide this. See
46 * dom/script/ScriptSettings.h for details.
47 *
48 * If the embedding has the host defined data, this method should return the
49 * host defined data via the `data` out parameter and return `true`.
50 * The object in the `data` out parameter can belong to any compartment.
51 * If the embedding doesn't need the host defined data, this method should
52 * set the `data` out parameter to `nullptr` and return `true`.
53 * If any error happens while generating the host defined data, this method
54 * should set a pending exception to `cx` and return `false`.
55 */
56 virtual bool getHostDefinedData(JSContext* cx,
57 JS::MutableHandle<JSObject*> data) const = 0;
58
59 /**
60 * Enqueue a reaction job `job` for `promise`, which was allocated at
61 * `allocationSite`. Provide `hostDefineData` as the host defined data for
62 * the reaction job's execution.
63 *
64 * The `hostDefinedData` value comes from `getHostDefinedData` method.
65 * The object is unwrapped, and it can belong to a different compartment
66 * than the current compartment. It can be `nullptr` if `getHostDefinedData`
67 * returns `nullptr`.
68 *
69 * `promise` can be null if the promise is optimized out.
70 * `promise` is guaranteed not to be optimized out if the promise has
71 * non-default user-interaction flag.
72 */
73 virtual bool enqueuePromiseJob(JSContext* cx, JS::HandleObject promise,
74 JS::HandleObject job,
75 JS::HandleObject allocationSite,
76 JS::HandleObject hostDefinedData) = 0;
77
78 /**
79 * Run all jobs in the queue. Running one job may enqueue others; continue to
80 * run jobs until the queue is empty.
81 *
82 * Calling this method at the wrong time can break the web. The HTML spec
83 * indicates exactly when the job queue should be drained (in HTML jargon,
84 * when it should "perform a microtask checkpoint"), and doing so at other
85 * times can incompatibly change the semantics of programs that use promises
86 * or other microtask-based features.
87 *
88 * This method is called only via AutoDebuggerJobQueueInterruption, used by
89 * the Debugger API implementation to ensure that the debuggee's job queue is
90 * protected from the debugger's own activity. See the comments on
91 * AutoDebuggerJobQueueInterruption.
92 */
93 virtual void runJobs(JSContext* cx) = 0;
94
95 /**
96 * Return true if the job queue is empty, false otherwise.
97 */
98 virtual bool empty() const = 0;
99
100 /**
101 * Returns true if the job queue stops draining, which results in `empty()`
102 * being false after `runJobs()`.
103 */
104 virtual bool isDrainingStopped() const = 0;
105
106 protected:
107 friend class AutoDebuggerJobQueueInterruption;
108
109 /**
110 * A saved job queue, represented however the JobQueue implementation pleases.
111 * Use AutoDebuggerJobQueueInterruption rather than trying to construct one of
112 * these directly; see documentation there.
113 *
114 * Destructing an instance of this class should assert that the current queue
115 * is empty, and then restore the queue the instance captured.
116 */
117 class SavedJobQueue {
118 public:
119 virtual ~SavedJobQueue() = default;
120 };
121
122 /**
123 * Capture this JobQueue's current job queue as a SavedJobQueue and return it,
124 * leaving the JobQueue's job queue empty. Destroying the returned object
125 * should assert that this JobQueue's current job queue is empty, and restore
126 * the original queue.
127 *
128 * On OOM, this should call JS_ReportOutOfMemory on the given JSContext,
129 * and return a null UniquePtr.
130 */
131 virtual js::UniquePtr<SavedJobQueue> saveJobQueue(JSContext*) = 0;
132 };
133
134 /**
135 * Tell SpiderMonkey to use `queue` to schedule promise reactions.
136 *
137 * SpiderMonkey does not take ownership of the queue; it is the embedding's
138 * responsibility to clean it up after the runtime is destroyed.
139 */
140 extern JS_PUBLIC_API void SetJobQueue(JSContext* cx, JobQueue* queue);
141
142 /**
143 * [SMDOC] Protecting the debuggee's job/microtask queue from debugger activity.
144 *
145 * When the JavaScript debugger interrupts the execution of some debuggee code
146 * (for a breakpoint, for example), the debuggee's execution must be paused
147 * while the developer takes time to look at it. During this interruption, other
148 * tabs should remain active and usable. If the debuggee shares a main thread
149 * with non-debuggee tabs, that means that the thread will have to process
150 * non-debuggee HTML tasks and microtasks as usual, even as the debuggee's are
151 * on hold until the debugger lets it continue execution. (Letting debuggee
152 * microtasks run during the interruption would mean that, from the debuggee's
153 * point of view, their side effects would take place wherever the breakpoint
154 * was set - in general, not a place other code should ever run, and a violation
155 * of the run-to-completion rule.)
156 *
157 * This means that, even though the timing and ordering of microtasks is
158 * carefully specified by the standard - and important to preserve for
159 * compatibility and predictability - debugger use may, correctly, have the
160 * effect of reordering microtasks. During the interruption, microtasks enqueued
161 * by non-debuggee tabs must run immediately alongside their HTML tasks as
162 * usual, whereas any debuggee microtasks that were in the queue when the
163 * interruption began must wait for the debuggee to be continued - and thus run
164 * after microtasks enqueued after they were.
165 *
166 * Fortunately, this reordering is visible only at the global level: when
167 * implemented correctly, it is not detectable by an individual debuggee. Note
168 * that a debuggee should generally be a complete unit of similar-origin related
169 * browsing contexts. Since non-debuggee activity falls outside that unit, it
170 * should never be visible to the debuggee (except via mechanisms that are
171 * already asynchronous, like events), so the debuggee should be unable to
172 * detect non-debuggee microtasks running when they normally would not. As long
173 * as behavior *visible to the debuggee* is unaffected by the interruption, we
174 * have respected the spirit of the rule.
175 *
176 * Of course, even as we accept the general principle that interrupting the
177 * debuggee should have as little detectable effect as possible, we still permit
178 * the developer to do things like evaluate expressions at the console that have
179 * arbitrary effects on the debuggee's state—effects that could never occur
180 * naturally at that point in the program. But since these are explicitly
181 * requested by the developer, who presumably knows what they're doing, we
182 * support this as best we can. If the developer evaluates an expression in the
183 * console that resolves a promise, it seems most natural for the promise's
184 * reaction microtasks to run immediately, within the interruption. This is an
185 * 'unnatural' time for the microtasks to run, but no more unnatural than the
186 * evaluation that triggered them.
187 *
188 * So the overall behavior we need is as follows:
189 *
190 * - When the debugger interrupts a debuggee, the debuggee's microtask queue
191 * must be saved.
192 *
193 * - When debuggee execution resumes, the debuggee's microtask queue must be
194 * restored exactly as it was when the interruption occurred.
195 *
196 * - Non-debuggee task and microtask execution must take place normally during
197 * the interruption.
198 *
199 * Since each HTML task begins with an empty microtask queue, and it should not
200 * be possible for a task to mix debuggee and non-debuggee code, interrupting a
201 * debuggee should always find a microtask queue containing exclusively debuggee
202 * microtasks, if any. So saving and restoring the microtask queue should affect
203 * only the debuggee, not any non-debuggee content.
204 *
205 * AutoDebuggerJobQueueInterruption
206 * --------------------------------
207 *
208 * AutoDebuggerJobQueueInterruption is an RAII class, meant for use by the
209 * Debugger API implementation, that takes care of saving and restoring the
210 * queue.
211 *
212 * Constructing and initializing an instance of AutoDebuggerJobQueueInterruption
213 * sets aside the given JSContext's job queue, leaving the JSContext's queue
214 * empty. When the AutoDebuggerJobQueueInterruption instance is destroyed, it
215 * asserts that the JSContext's current job queue (holding jobs enqueued while
216 * the AutoDebuggerJobQueueInterruption was alive) is empty, and restores the
217 * saved queue to the JSContext.
218 *
219 * Since the Debugger API's behavior is up to us, we can specify that Debugger
220 * hooks begin execution with an empty job queue, and that we drain the queue
221 * after each hook function has run. This drain will be visible to debugger
222 * hooks, and makes hook calls resemble HTML tasks, with their own automatic
223 * microtask checkpoint. But, the drain will be invisible to the debuggee, as
224 * its queue is preserved across the hook invocation.
225 *
226 * To protect the debuggee's job queue, Debugger takes care to invoke callback
227 * functions only within the scope of an AutoDebuggerJobQueueInterruption
228 * instance.
229 *
230 * Why not let the hook functions themselves take care of this?
231 * ------------------------------------------------------------
232 *
233 * Certainly, we could leave responsibility for saving and restoring the job
234 * queue to the Debugger hook functions themselves.
235 *
236 * In fact, early versions of this change tried making the devtools server save
237 * and restore the queue explicitly, but because hooks are set and changed in
238 * numerous places, it was hard to be confident that every case had been
239 * covered, and it seemed that future changes could easily introduce new holes.
240 *
241 * Later versions of this change modified the accessor properties on the
242 * Debugger objects' prototypes to automatically protect the job queue when
243 * calling hooks, but the effect was essentially a monkeypatch applied to an API
244 * we defined and control, which doesn't make sense.
245 *
246 * In the end, since promises have become such a pervasive part of JavaScript
247 * programming, almost any imaginable use of Debugger would need to provide some
248 * kind of protection for the debuggee's job queue, so it makes sense to simply
249 * handle it once, carefully, in the implementation of Debugger itself.
250 */
251 class MOZ_RAII JS_PUBLIC_API AutoDebuggerJobQueueInterruption {
252 public:
253 explicit AutoDebuggerJobQueueInterruption();
254 ~AutoDebuggerJobQueueInterruption();
255
256 bool init(JSContext* cx);
257 bool initialized() const { return !!saved; }
258
259 /**
260 * Drain the job queue. (In HTML terminology, perform a microtask checkpoint.)
261 *
262 * To make Debugger hook calls more like HTML tasks or ECMAScript jobs,
263 * Debugger promises that each hook begins execution with a clean microtask
264 * queue, and that a microtask checkpoint (queue drain) takes place after each
265 * hook returns, successfully or otherwise.
266 *
267 * To ensure these debugger-introduced microtask checkpoints serve only the
268 * hook's microtasks, and never affect the debuggee's, the Debugger API
269 * implementation uses only this method to perform the checkpoints, thereby
270 * statically ensuring that an AutoDebuggerJobQueueInterruption is in scope to
271 * protect the debuggee.
272 *
273 * SavedJobQueue implementations are required to assert that the queue is
274 * empty before restoring the debuggee's queue. If the Debugger API ever fails
275 * to perform a microtask checkpoint after calling a hook, that assertion will
276 * fail, catching the mistake.
277 */
278 void runJobs();
279
280 private:
281 JSContext* cx;
282 js::UniquePtr<JobQueue::SavedJobQueue> saved;
283 };
284
285 enum class PromiseRejectionHandlingState { Unhandled, Handled };
286
287 typedef void (*PromiseRejectionTrackerCallback)(
288 JSContext* cx, bool mutedErrors, JS::HandleObject promise,
289 JS::PromiseRejectionHandlingState state, void* data);
290
291 /**
292 * Sets the callback that's invoked whenever a Promise is rejected without
293 * a rejection handler, and when a Promise that was previously rejected
294 * without a handler gets a handler attached.
295 */
296 extern JS_PUBLIC_API void SetPromiseRejectionTrackerCallback(
297 JSContext* cx, PromiseRejectionTrackerCallback callback,
298 void* data = nullptr);
299
300 /**
301 * Inform the runtime that the job queue is empty and the embedding is going to
302 * execute its last promise job. The runtime may now choose to skip creating
303 * promise jobs for asynchronous execution and instead continue execution
304 * synchronously. More specifically, this optimization is used to skip the
305 * standard job queuing behavior for `await` operations in async functions.
306 *
307 * This function may be called before executing the last job in the job queue.
308 * When it was called, JobQueueMayNotBeEmpty must be called in order to restore
309 * the default job queuing behavior before the embedding enqueues its next job
310 * into the job queue.
311 */
312 extern JS_PUBLIC_API void JobQueueIsEmpty(JSContext* cx);
313
314 /**
315 * Inform the runtime that job queue is no longer empty. The runtime can now no
316 * longer skip creating promise jobs for asynchronous execution, because
317 * pending jobs in the job queue must be executed first to preserve the FIFO
318 * (first in - first out) property of the queue. This effectively undoes
319 * JobQueueIsEmpty and re-enables the standard job queuing behavior.
320 *
321 * This function must be called whenever enqueuing a job to the job queue when
322 * JobQueueIsEmpty was called previously.
323 */
324 extern JS_PUBLIC_API void JobQueueMayNotBeEmpty(JSContext* cx);
325
326 /**
327 * Returns a new instance of the Promise builtin class in the current
328 * compartment, with the right slot layout.
329 *
330 * The `executor` can be a `nullptr`. In that case, the only way to resolve or
331 * reject the returned promise is via the `JS::ResolvePromise` and
332 * `JS::RejectPromise` JSAPI functions.
333 */
334 extern JS_PUBLIC_API JSObject* NewPromiseObject(JSContext* cx,
335 JS::HandleObject executor);
336
337 /**
338 * Returns true if the given object is an unwrapped PromiseObject, false
339 * otherwise.
340 */
341 extern JS_PUBLIC_API bool IsPromiseObject(JS::HandleObject obj);
342
343 /**
344 * Returns the current compartment's original Promise constructor.
345 */
346 extern JS_PUBLIC_API JSObject* GetPromiseConstructor(JSContext* cx);
347
348 /**
349 * Returns the current compartment's original Promise.prototype.
350 */
351 extern JS_PUBLIC_API JSObject* GetPromisePrototype(JSContext* cx);
352
353 // Keep this in sync with the PROMISE_STATE defines in SelfHostingDefines.h.
354 enum class PromiseState { Pending, Fulfilled, Rejected };
355
356 /**
357 * Returns the given Promise's state as a JS::PromiseState enum value.
358 *
359 * Returns JS::PromiseState::Pending if the given object is a wrapper that
360 * can't safely be unwrapped.
361 */
362 extern JS_PUBLIC_API PromiseState GetPromiseState(JS::HandleObject promise);
363
364 /**
365 * Returns the given Promise's process-unique ID.
366 */
367 JS_PUBLIC_API uint64_t GetPromiseID(JS::HandleObject promise);
368
369 /**
370 * Returns the given Promise's result: either the resolution value for
371 * fulfilled promises, or the rejection reason for rejected ones.
372 */
373 extern JS_PUBLIC_API JS::Value GetPromiseResult(JS::HandleObject promise);
374
375 /**
376 * Returns whether the given promise's rejection is already handled or not.
377 *
378 * The caller must check the given promise is rejected before checking it's
379 * handled or not.
380 */
381 extern JS_PUBLIC_API bool GetPromiseIsHandled(JS::HandleObject promise);
382
383 /*
384 * Given a settled (i.e. fulfilled or rejected, not pending) promise, sets
385 * |promise.[[PromiseIsHandled]]| to true and removes it from the list of
386 * unhandled rejected promises.
387 */
388 extern JS_PUBLIC_API bool SetSettledPromiseIsHandled(JSContext* cx,
389 JS::HandleObject promise);
390
391 /*
392 * Given a promise (settled or not), sets |promise.[[PromiseIsHandled]]| to true
393 * and removes it from the list of unhandled rejected promises if it's settled.
394 */
395 [[nodiscard]] extern JS_PUBLIC_API bool SetAnyPromiseIsHandled(
396 JSContext* cx, JS::HandleObject promise);
397
398 /**
399 * Returns a js::SavedFrame linked list of the stack that lead to the given
400 * Promise's allocation.
401 */
402 extern JS_PUBLIC_API JSObject* GetPromiseAllocationSite(
403 JS::HandleObject promise);
404
405 extern JS_PUBLIC_API JSObject* GetPromiseResolutionSite(
406 JS::HandleObject promise);
407
408 #ifdef DEBUG
409 extern JS_PUBLIC_API void DumpPromiseAllocationSite(JSContext* cx,
410 JS::HandleObject promise);
411
412 extern JS_PUBLIC_API void DumpPromiseResolutionSite(JSContext* cx,
413 JS::HandleObject promise);
414 #endif
415
416 /**
417 * Calls the current compartment's original Promise.resolve on the original
418 * Promise constructor, with `resolutionValue` passed as an argument.
419 */
420 extern JS_PUBLIC_API JSObject* CallOriginalPromiseResolve(
421 JSContext* cx, JS::HandleValue resolutionValue);
422
423 /**
424 * Calls the current compartment's original Promise.reject on the original
425 * Promise constructor, with `resolutionValue` passed as an argument.
426 */
427 extern JS_PUBLIC_API JSObject* CallOriginalPromiseReject(
428 JSContext* cx, JS::HandleValue rejectionValue);
429
430 /**
431 * Resolves the given Promise with the given `resolutionValue`.
432 *
433 * Calls the `resolve` function that was passed to the executor function when
434 * the Promise was created.
435 */
436 extern JS_PUBLIC_API bool ResolvePromise(JSContext* cx,
437 JS::HandleObject promiseObj,
438 JS::HandleValue resolutionValue);
439
440 /**
441 * Rejects the given `promise` with the given `rejectionValue`.
442 *
443 * Calls the `reject` function that was passed to the executor function when
444 * the Promise was created.
445 */
446 extern JS_PUBLIC_API bool RejectPromise(JSContext* cx,
447 JS::HandleObject promiseObj,
448 JS::HandleValue rejectionValue);
449
450 /**
451 * Create a Promise with the given fulfill/reject handlers, that will be
452 * fulfilled/rejected with the value/reason that the promise `promise` is
453 * fulfilled/rejected with.
454 *
455 * This function basically acts like `promise.then(onFulfilled, onRejected)`,
456 * except that its behavior is unaffected by changes to `Promise`,
457 * `Promise[Symbol.species]`, `Promise.prototype.then`, `promise.constructor`,
458 * `promise.then`, and so on.
459 *
460 * This function throws if `promise` is not a Promise from this or another
461 * realm.
462 *
463 * This function will assert if `onFulfilled` or `onRejected` is non-null and
464 * also not IsCallable.
465 */
466 extern JS_PUBLIC_API JSObject* CallOriginalPromiseThen(
467 JSContext* cx, JS::HandleObject promise, JS::HandleObject onFulfilled,
468 JS::HandleObject onRejected);
469
470 /**
471 * Unforgeable, optimized version of the JS builtin Promise.prototype.then.
472 *
473 * Takes a Promise instance and nullable `onFulfilled`/`onRejected` callables to
474 * enqueue as reactions for that promise. In contrast to Promise.prototype.then,
475 * this doesn't create and return a new Promise instance.
476 *
477 * Throws a TypeError if `promise` isn't a Promise (or possibly a different
478 * error if it's a security wrapper or dead object proxy).
479 */
480 extern JS_PUBLIC_API bool AddPromiseReactions(JSContext* cx,
481 JS::HandleObject promise,
482 JS::HandleObject onFulfilled,
483 JS::HandleObject onRejected);
484
485 /**
486 * Unforgeable, optimized version of the JS builtin Promise.prototype.then.
487 *
488 * Takes a Promise instance and nullable `onFulfilled`/`onRejected` callables to
489 * enqueue as reactions for that promise. In contrast to Promise.prototype.then,
490 * this doesn't create and return a new Promise instance.
491 *
492 * Throws a TypeError if `promise` isn't a Promise (or possibly a different
493 * error if it's a security wrapper or dead object proxy).
494 *
495 * If `onRejected` is null and `promise` is rejected, this function -- unlike
496 * the function above -- will not report an unhandled rejection.
497 */
498 extern JS_PUBLIC_API bool AddPromiseReactionsIgnoringUnhandledRejection(
499 JSContext* cx, JS::HandleObject promise, JS::HandleObject onFulfilled,
500 JS::HandleObject onRejected);
501
502 // This enum specifies whether a promise is expected to keep track of
503 // information that is useful for embedders to implement user activation
504 // behavior handling as specified in the HTML spec:
505 // https://html.spec.whatwg.org/multipage/interaction.html#triggered-by-user-activation
506 // By default, promises created by SpiderMonkey do not make any attempt to keep
507 // track of information about whether an activation behavior was being processed
508 // when the original promise in a promise chain was created. If the embedder
509 // sets either of the HadUserInteractionAtCreation or
510 // DidntHaveUserInteractionAtCreation flags on a promise after creating it,
511 // SpiderMonkey will propagate that flag to newly created promises when
512 // processing Promise#then and will make it possible to query this flag off of a
513 // promise further down the chain later using the
514 // GetPromiseUserInputEventHandlingState() API.
515 enum class PromiseUserInputEventHandlingState {
516 // Don't keep track of this state (default for all promises)
517 DontCare,
518 // Keep track of this state, the original promise in the chain was created
519 // while an activation behavior was being processed.
520 HadUserInteractionAtCreation,
521 // Keep track of this state, the original promise in the chain was created
522 // while an activation behavior was not being processed.
523 DidntHaveUserInteractionAtCreation
524 };
525
526 /**
527 * Returns the given Promise's activation behavior state flag per above as a
528 * JS::PromiseUserInputEventHandlingState value. All promises are created with
529 * the DontCare state by default.
530 *
531 * Returns JS::PromiseUserInputEventHandlingState::DontCare if the given object
532 * is a wrapper that can't safely be unwrapped.
533 */
534 extern JS_PUBLIC_API PromiseUserInputEventHandlingState
535 GetPromiseUserInputEventHandlingState(JS::HandleObject promise);
536
537 /**
538 * Sets the given Promise's activation behavior state flag per above as a
539 * JS::PromiseUserInputEventHandlingState value.
540 *
541 * Returns false if the given object is a wrapper that can't safely be
542 * unwrapped.
543 */
544 extern JS_PUBLIC_API bool SetPromiseUserInputEventHandlingState(
545 JS::HandleObject promise, JS::PromiseUserInputEventHandlingState state);
546
547 /**
548 * Unforgeable version of the JS builtin Promise.all.
549 *
550 * Takes a HandleObjectVector of Promise objects and returns a promise that's
551 * resolved with an array of resolution values when all those promises have
552 * been resolved, or rejected with the rejection value of the first rejected
553 * promise.
554 *
555 * Asserts that all objects in the `promises` vector are, maybe wrapped,
556 * instances of `Promise` or a subclass of `Promise`.
557 */
558 extern JS_PUBLIC_API JSObject* GetWaitForAllPromise(
559 JSContext* cx, JS::HandleObjectVector promises);
560
561 /**
562 * The Dispatchable interface allows the embedding to call SpiderMonkey
563 * on a JSContext thread when requested via DispatchToEventLoopCallback.
564 */
565 class JS_PUBLIC_API Dispatchable {
566 public:
567 // Destruction of Dispatchables is public in order to be used with
568 // UniquePtrs. Their destruction by SpiderMonkey is enforced by
569 // ReleaseFailedTask.
570 virtual ~Dispatchable() = default;
571
572 // ShuttingDown indicates that SpiderMonkey should abort async tasks to
573 // expedite shutdown.
574 enum MaybeShuttingDown { NotShuttingDown, ShuttingDown };
575
576 // Called by the embedding after DispatchToEventLoopCallback succeeds.
577 // Used to correctly release the unique ptr and call the run task.
578 static void Run(JSContext* cx, js::UniquePtr<Dispatchable>&& task,
579 MaybeShuttingDown maybeShuttingDown);
580
581 // Used to correctly release the unique ptr. Relies on the
582 // OffThreadRuntimePromiseState to handle cleanup via iteration over the
583 // live() set.
584 static void ReleaseFailedTask(js::UniquePtr<Dispatchable>&& task);
585
586 protected:
587 // Dispatchables are created exclusively by SpiderMonkey.
588 Dispatchable() = default;
589
590 // These two methods must be implemented in order to correctly handle
591 // success and failure cases for the task.
592
593 // Used to execute the task, run on the owning thread.
594 // A subclass should override this method to
595 // 1) execute the task as necessary and
596 // 2) delete the task.
597 virtual void run(JSContext* cx, MaybeShuttingDown maybeShuttingDown) = 0;
598
599 // Used to transfer the task back to the runtime if the embedding, upon
600 // taking ownership of the task, fails to dispatch and run it. This allows
601 // the runtime to delete the task during shutdown. This method can be called
602 // from any thread.
603 // Typically, this will be used with a UniquePtr like so:
604 // auto task = myTask.release();
605 // task->transferToRuntime();
606 virtual void transferToRuntime() = 0;
607 };
608
609 /**
610 * Callbacks to dispatch a JS::Dispatchable to a JSContext's thread's event
611 * loop.
612 *
613 * The DispatchToEventLoopCallback set on a particular JSContext must accept
614 * JS::Dispatchable instances and arrange for their `run` methods to be called
615 * eventually on the JSContext's thread. This is used for cross-thread dispatch,
616 * so the callback itself must be safe to call from any thread. It cannot
617 * trigger a GC.
618 *
619 * The DelayedDispatchToEventLoopCallback in addition takes a delay, and it
620 * must accept JS::Dispatchable instances and arrange for their `run` methods
621 * to be called after the delay on the JSContext's thread.
622 * The embeddings must have its own timeout manager to handle the delay.
623 * If a timeout manager is not available for given context, it should return
624 * false, optionally with a warning message printed.
625 *
626 * If the callback returns `true`, it must eventually run the given
627 * Dispatchable; otherwise, SpiderMonkey may leak memory or hang.
628 *
629 * The callback may return `false` to indicate that the JSContext's thread is
630 * shutting down and is no longer accepting runnables. Shutting down is a
631 * one-way transition: once the callback has rejected a runnable, it must reject
632 * all subsequently submitted runnables as well.
633 *
634 * To establish a DispatchToEventLoopCallback, the embedding may either call
635 * InitDispatchsToEventLoop to provide its own, or call js::UseInternalJobQueues
636 * to select a default implementation built into SpiderMonkey. This latter
637 * depends on the embedding to call js::RunJobs on the JavaScript thread to
638 * process queued Dispatchables at appropriate times.
639 */
640
641 typedef bool (*DispatchToEventLoopCallback)(
642 void* closure, js::UniquePtr<Dispatchable>&& dispatchable);
643
644 typedef bool (*DelayedDispatchToEventLoopCallback)(
645 void* closure, js::UniquePtr<Dispatchable>&& dispatchable, uint32_t delay);
646
647 extern JS_PUBLIC_API void InitDispatchsToEventLoop(
648 JSContext* cx, DispatchToEventLoopCallback callback,
649 DelayedDispatchToEventLoopCallback delayedCallback, void* closure);
650
651 /**
652 * When a JSRuntime is destroyed it implicitly cancels all async tasks in
653 * progress, releasing any roots held by the task. However, this is not soon
654 * enough for cycle collection, which needs to have roots dropped earlier so
655 * that the cycle collector can transitively remove roots for a future GC. For
656 * these and other cases, the set of pending async tasks can be canceled
657 * with this call earlier than JSRuntime destruction.
658 */
659
660 extern JS_PUBLIC_API void ShutdownAsyncTasks(JSContext* cx);
661
662 } // namespace JS
663
664 #endif // js_Promise_h