Bug 1838365 add some DecodedStream finished logging r=pehrsons,media-playback-reviewe...
[gecko.git] / toolkit / modules / DeferredTask.sys.mjs
blob9f112a54d0d2b3923bc6225ecb3a6106bbee7211
1 /* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
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 const lazy = {};
9 /**
10  * Sets up a function or an asynchronous task whose execution can be triggered
11  * after a defined delay.  Multiple attempts to run the task before the delay
12  * has passed are coalesced.  The task cannot be re-entered while running, but
13  * can be executed again after a previous run finished.
14  *
15  * A common use case occurs when a data structure should be saved into a file
16  * every time the data changes, using asynchronous calls, and multiple changes
17  * to the data may happen within a short time:
18  *
19  *   let saveDeferredTask = new DeferredTask(async function() {
20  *     await OS.File.writeAtomic(...);
21  *     // Any uncaught exception will be reported.
22  *   }, 2000);
23  *
24  *   // The task is ready, but will not be executed until requested.
25  *
26  * The "arm" method can be used to start the internal timer that will result in
27  * the eventual execution of the task.  Multiple attempts to arm the timer don't
28  * introduce further delays:
29  *
30  *   saveDeferredTask.arm();
31  *
32  *   // The task will be executed in 2 seconds from now.
33  *
34  *   await waitOneSecond();
35  *   saveDeferredTask.arm();
36  *
37  *   // The task will be executed in 1 second from now.
38  *
39  * The timer can be disarmed to reset the delay, or just to cancel execution:
40  *
41  *   saveDeferredTask.disarm();
42  *   saveDeferredTask.arm();
43  *
44  *   // The task will be executed in 2 seconds from now.
45  *
46  * When the internal timer fires and the execution of the task starts, the task
47  * cannot be canceled anymore.  It is however possible to arm the timer again
48  * during the execution of the task, in which case the task will need to finish
49  * before the timer is started again, thus guaranteeing a time of inactivity
50  * between executions that is at least equal to the provided delay.
51  *
52  * The "finalize" method can be used to ensure that the task terminates
53  * properly.  The promise it returns is resolved only after the last execution
54  * of the task is finished.  To guarantee that the task is executed for the
55  * last time, the method prevents any attempt to arm the timer again.
56  *
57  * If the timer is already armed when the "finalize" method is called, then the
58  * task is executed immediately.  If the task was already running at this point,
59  * then one last execution from start to finish will happen again, immediately
60  * after the current execution terminates.  If the timer is not armed, the
61  * "finalize" method only ensures that any running task terminates.
62  *
63  * For example, during shutdown, you may want to ensure that any pending write
64  * is processed, using the latest version of the data if the timer is armed:
65  *
66  *   AsyncShutdown.profileBeforeChange.addBlocker(
67  *     "Example service: shutting down",
68  *     () => saveDeferredTask.finalize()
69  *   );
70  *
71  * Instead, if you are going to delete the saved data from disk anyways, you
72  * might as well prevent any pending write from starting, while still ensuring
73  * that any write that is currently in progress terminates, so that the file is
74  * not in use anymore:
75  *
76  *   saveDeferredTask.disarm();
77  *   saveDeferredTask.finalize().then(() => OS.File.remove(...))
78  *                              .then(null, Components.utils.reportError);
79  */
81 // Globals
83 ChromeUtils.defineESModuleGetters(lazy, {
84   PromiseUtils: "resource://gre/modules/PromiseUtils.sys.mjs",
85 });
87 const Timer = Components.Constructor(
88   "@mozilla.org/timer;1",
89   "nsITimer",
90   "initWithCallback"
93 // DeferredTask
95 /**
96  * Sets up a task whose execution can be triggered after a delay.
97  *
98  * @param aTaskFn
99  *        Function to execute.  If the function returns a promise, the task is
100  *        not considered complete until that promise resolves.  This
101  *        task is never re-entered while running.
102  * @param aDelayMs
103  *        Time between executions, in milliseconds.  Multiple attempts to run
104  *        the task before the delay has passed are coalesced.  This time of
105  *        inactivity is guaranteed to pass between multiple executions of the
106  *        task, except on finalization, when the task may restart immediately
107  *        after the previous execution finished.
108  * @param aIdleTimeoutMs
109  *        The maximum time to wait for an idle slot on the main thread after
110  *        aDelayMs have elapsed. If omitted, waits indefinitely for an idle
111  *        callback.
112  */
113 export var DeferredTask = function (aTaskFn, aDelayMs, aIdleTimeoutMs) {
114   this._taskFn = aTaskFn;
115   this._delayMs = aDelayMs;
116   this._timeoutMs = aIdleTimeoutMs;
117   this._caller = new Error().stack.split("\n", 2)[1];
118   let markerString = `delay: ${aDelayMs}ms`;
119   if (aIdleTimeoutMs) {
120     markerString += `, idle timeout: ${aIdleTimeoutMs}`;
121   }
122   ChromeUtils.addProfilerMarker(
123     "DeferredTask",
124     { captureStack: true },
125     markerString
126   );
129 DeferredTask.prototype = {
130   /**
131    * Function to execute.
132    */
133   _taskFn: null,
135   /**
136    * Time between executions, in milliseconds.
137    */
138   _delayMs: null,
140   /**
141    * Indicates whether the task is currently requested to start again later,
142    * regardless of whether it is currently running.
143    */
144   get isArmed() {
145     return this._armed;
146   },
147   _armed: false,
149   /**
150    * Indicates whether the task is currently running.  This is always true when
151    * read from code inside the task function, but can also be true when read
152    * from external code, in case the task is an asynchronous function.
153    */
154   get isRunning() {
155     return !!this._runningPromise;
156   },
158   /**
159    * Promise resolved when the current execution of the task terminates, or null
160    * if the task is not currently running.
161    */
162   _runningPromise: null,
164   /**
165    * nsITimer used for triggering the task after a delay, or null in case the
166    * task is running or there is no task scheduled for execution.
167    */
168   _timer: null,
170   /**
171    * Actually starts the timer with the delay specified on construction.
172    */
173   _startTimer() {
174     let callback, timer;
175     if (this._timeoutMs === 0) {
176       callback = () => this._timerCallback();
177     } else {
178       callback = () => {
179         this._startIdleDispatch(() => {
180           // _timer could have changed by now:
181           // - to null if disarm() or finalize() has been called.
182           // - to a new nsITimer if disarm() was called, followed by arm().
183           // In either case, don't invoke _timerCallback any more.
184           if (this._timer === timer) {
185             this._timerCallback();
186           }
187         }, this._timeoutMs);
188       };
189     }
190     timer = new Timer(callback, this._delayMs, Ci.nsITimer.TYPE_ONE_SHOT);
191     this._timer = timer;
192   },
194   /**
195    * Dispatches idle task. Can be overridden for testing by test_DeferredTask.
196    */
197   _startIdleDispatch(callback, timeout) {
198     ChromeUtils.idleDispatch(callback, { timeout });
199   },
201   /**
202    * Requests the execution of the task after the delay specified on
203    * construction.  Multiple calls don't introduce further delays.  If the task
204    * is running, the delay will start when the current execution finishes.
205    *
206    * The task will always be executed on a different tick of the event loop,
207    * even if the delay specified on construction is zero.  Multiple "arm" calls
208    * within the same tick of the event loop are guaranteed to result in a single
209    * execution of the task.
210    *
211    * @note By design, this method doesn't provide a way for the caller to detect
212    *       when the next execution terminates, or collect a result.  In fact,
213    *       doing that would often result in duplicate processing or logging.  If
214    *       a special operation or error logging is needed on completion, it can
215    *       be better handled from within the task itself, for example using a
216    *       try/catch/finally clause in the task.  The "finalize" method can be
217    *       used in the common case of waiting for completion on shutdown.
218    */
219   arm() {
220     if (this._finalized) {
221       throw new Error("Unable to arm timer, the object has been finalized.");
222     }
224     this._armed = true;
226     // In case the timer callback is running, do not create the timer now,
227     // because this will be handled by the timer callback itself.  Also, the
228     // timer is not restarted in case it is already running.
229     if (!this._runningPromise && !this._timer) {
230       this._startTimer();
231     }
232   },
234   /**
235    * Cancels any request for a delayed the execution of the task, though the
236    * task itself cannot be canceled in case it is already running.
237    *
238    * This method stops any currently running timer, thus the delay will restart
239    * from its original value in case the "arm" method is called again.
240    */
241   disarm() {
242     this._armed = false;
243     if (this._timer) {
244       // Calling the "cancel" method and discarding the timer reference makes
245       // sure that the timer callback will not be called later, even if the
246       // timer thread has already posted the timer event on the main thread.
247       this._timer.cancel();
248       this._timer = null;
249     }
250   },
252   /**
253    * Ensures that any pending task is executed from start to finish, while
254    * preventing any attempt to arm the timer again.
255    *
256    * - If the task is running and the timer is armed, then one last execution
257    *   from start to finish will happen again, immediately after the current
258    *   execution terminates, then the returned promise will be resolved.
259    * - If the task is running and the timer is not armed, the returned promise
260    *   will be resolved when the current execution terminates.
261    * - If the task is not running and the timer is armed, then the task is
262    *   started immediately, and the returned promise resolves when the new
263    *   execution terminates.
264    * - If the task is not running and the timer is not armed, the method returns
265    *   a resolved promise.
266    *
267    * @return {Promise}
268    * @resolves After the last execution of the task is finished.
269    * @rejects Never.
270    */
271   finalize() {
272     if (this._finalized) {
273       throw new Error("The object has been already finalized.");
274     }
275     this._finalized = true;
277     // If the timer is armed, it means that the task is not running but it is
278     // scheduled for execution.  Cancel the timer and run the task immediately,
279     // so we don't risk blocking async shutdown longer than necessary.
280     if (this._timer) {
281       this.disarm();
282       this._timerCallback();
283     }
285     // Wait for the operation to be completed, or resolve immediately.
286     if (this._runningPromise) {
287       return this._runningPromise;
288     }
289     return Promise.resolve();
290   },
291   _finalized: false,
293   /**
294    * Whether the DeferredTask has been finalized, and it cannot be armed anymore.
295    */
296   get isFinalized() {
297     return this._finalized;
298   },
300   /**
301    * Timer callback used to run the delayed task.
302    */
303   _timerCallback() {
304     let runningDeferred = lazy.PromiseUtils.defer();
306     // All these state changes must occur at the same time directly inside the
307     // timer callback, to prevent race conditions and to ensure that all the
308     // methods behave consistently even if called from inside the task.  This
309     // means that the assignment of "this._runningPromise" must complete before
310     // the task gets a chance to start.
311     this._timer = null;
312     this._armed = false;
313     this._runningPromise = runningDeferred.promise;
315     runningDeferred.resolve(
316       (async () => {
317         // Execute the provided function asynchronously.
318         await this._runTask();
320         // Now that the task has finished, we check the state of the object to
321         // determine if we should restart the task again.
322         if (this._armed) {
323           if (!this._finalized) {
324             this._startTimer();
325           } else {
326             // Execute the task again immediately, for the last time.  The isArmed
327             // property should return false while the task is running, and should
328             // remain false after the last execution terminates.
329             this._armed = false;
330             await this._runTask();
331           }
332         }
334         // Indicate that the execution of the task has finished.  This happens
335         // synchronously with the previous state changes in the function.
336         this._runningPromise = null;
337       })().catch(console.error)
338     );
339   },
341   /**
342    * Executes the associated task and catches exceptions.
343    */
344   async _runTask() {
345     let startTime = Cu.now();
346     try {
347       await this._taskFn();
348     } catch (ex) {
349       console.error(ex);
350     } finally {
351       ChromeUtils.addProfilerMarker(
352         "DeferredTask",
353         { startTime },
354         this._caller
355       );
356     }
357   },