Files
palemoon27/toolkit/modules/DeferredTask.jsm
T
roytam1 2e02aab9a7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1198458: Webrtc updated to branch 43; pull made 2015-09-29 09:00AM PDT rs=jesup (c45a789c99)
- Bug 1159489: WebRTC bitrate limits for video depend on input resolution and framerate r=pkerr (e3691a247c)
- Bug 1132318: merge SelectSendFrameRate with SelectSendResolution r=bwc (bcc232994c)
- Bug 1182289: Clean up dispatches in WebrtcGmpVideoEncoder/Decoder. r=jesup, a=abillings (b5e2030b07)
- Bug 1167306: Fix preprocessor goof that disabled the load manager and some preference handling. r=jesup (0cc0dee688)
- Bug 1198458: Rollup of changes previously applied to media/webrtc/trunk/webrtc and fixes to those rs=jesup r=froyd,jib,bwc,jesup,gcp,sotaro,pkerr,pehrsons (fe384d5e63)
- Bug 1198458 Unbreak build on BSDs by fixing non-POSIX thread includes/usage. r=jesup (4ad8e88c17)
- Bug 1198458: Fix typo in merges in OMX rs=bustage,kwierso on a CLOSED TREE (211b3b1a3f)
- Bug 1226146: fix sndio audio_device backend after webrtc 43 landing in bug 1198458 r=jesup NPOTB (2b10ba3e86)
- Bug 1231106 - Make BSDs fall-through to ASSERT as well. r=jesup (775d4fedae)
- Bug 1231109 - Drop FreeBSD checks for unsupported versions. r=jld r=jesup (3cd55166fd)
- Bug 1161079: Fix VideoCodecStats to allow for collecting encoder and decoder stats r=jib (1f98af8939)
- add limits to fix gcc12 compile (d78098980f)
- Bug 1193495 - Part 1: Test case. r=mt (add2ded009)
- Bug 1193495 - Part 2: Maintain clones of supported codecs for each level, and do necessary checking to prevent payload-type clashes. r=mt (d45a24dba7)
- Bug 1191301 - Re-enable the use of media.navigator.video.use_tmmbr pref. r=bwc (d2723821d4)
- Bug 1094447 - Use UDP/TLS/RTP/SAVPF for audio/video m-lines. r=drno (e8e1dafd0a)
- Bug 1173599 - a=imageattr support. r=mt (612fc343d7)
- Bug 1173601 - Add a=simulcast support. r=mt (7c5303bacb)
- Bug 1203246 - Factor track negotiation stuff out of JsepSessionImpl, and other simplification. r=mt (b71c809b78)
- Bug 1212907 - a=rid support. r=mt (7479ab6984)
- Bug 1212908 - Update a=simulcast to match new grammar in 03 draft. r=mt (e205d3b0dd)
- Bug 1192390 - Part 1: Lay architectural groundwork for simulcast negotiation. r=mt r=jesup (e75dda3139)
- Bug 1223160 - added SDP parser file reader. r=bwc (6752195791)
- Bug 1192390 - Part 2: Simulcast and RID negotiation. r=mt (51b151ef52)
- fix some warnings stuff (fed8f513a8)
- Bug 1161317: Fix bug where sendonly video RTCP would be treated as outgoing RTP r=jesup (e24371fbe0)
- Bug 1226347: Import cherry-pick of AEC changes from 43->48 (delay-agnostic AEC). r=pkerr (d3a074f4d8)
- Bug 1226347 - Part 2: Allow control of AEC via prefs. r=rjesup (58f142005b)
- Bug 1228788 - Force QT device release to happen on the main thread. r=jesup (885e9d1236)
- Bug 1162218 - Make worker idle thread timeouts more strict, r=baku. (a7d2106987)
- No bug. Remove a stray debugging printf of mine. r=me. (77b84cda62)
- minor (22564a666e)
- Bug 1224237 - Remove the !baseURL check from ServiceWorkerContainer::Register;r=bkelly (8b13c4dc49)
- Bug 1196157 - Marks left by performance marks should print the domain of the application and not the complete URL. r=baku (d133708d8d)
- Bug 1211970 - "Muted errors in workers are not correctly reported to the console". r=bz (42c15275f4)
- Bug 1208559 - Tests. r=bholley (e16a30caa5)
-  Bug 1045891 - Tests for child-src r=ckerschb (90aa832cd0)
- Bug 1223647: CSP erroneously inherited into dedicated workers. r=ckerschb (6fd8d9bfc9)
- Bug 1218433 - Use AsyncOpen2 in dom/workers/ScriptLoader.cpp - part 1, r=sicking (a7e9187e52)
- Bug 1218433 - Use AsyncOpen2 in dom/workers/ScriptLoader.cpp - part 3 - WPT, r=sicking, r=Ms2ger (e5e3c69f6a)
- Bug 1218433 - Use AsyncOpen2 in dom/workers/ScriptLoader.cpp - part 2 - WPT, r=sicking, r=Ms2ger (1dd2d871ec)
- Bug 1211967 - Fix how we report errors when loading a worker from a data url, r=bz (8517368daa)
- nsRefPtr - RefPtr (34bb404530)
- Bug 1231055 - Fix tags usage in PluginProvider. r=dtownsend (870b0e71eb)
- bug 1228792 - remove use of array comprehensions r=mossop (3e31f18e83)
- bug 1228792 - use standard version of catch r=mossop (f306557ca2)
- Bug 1228009. Geolocation code needs to handle failures on its ErrorResults. r=smaug (8778a9e264)
- Bug 1228707. Add a away to call Web IDL callbacks while ignoring any errors from them, and use it in a few places. r=smaug (a414e0d711)
- Bug 1201692. Add a fast path to ExplicitChildIterator::Seek for the common case of seeking an actual DOM child of the parent node. r=wchen (01234ad43a)
- Bug 1202186 - use nsISensitiveInfoHidden for console methods, r=baku (888b4506ad)
- Bug 1223774 - Console API should check if the outer window exists, r=smaug (e0d7f408dc)
- Bug 1200551 - Handle multiple %c formatters without a string between them by using only the last one for styling;r=baku,r=past (463550117a)
- Bug 1213719 - Back out bug 1170314 for duplicate functionality. r=smaug (ae74e0ad52)
- Bug 1154076 followup: Mark ConsoleRunnable::Run() as override. rs=ehsan (337181faab)
- Bug 1127703 - "Support iteration on FormData" r=bz (4ddd461e99)
- Bug 1230509 - BlobImplFile should return false in IsDateUnknown and IsSizeUnknown, r=bz (1079bfe2ab)
- Bug 1198095 - FileReader should dispatch an error if the blob changes size in the meantime the read is executed, r=bz (263993a172)
- Bug 1231094 - patch 1 - nsDOMFileReader to mozilla::dom::FileReader, r=sicking (aa8c3ff373)
- Bug 1231094 - patch 2 - Get rid of FileIOObject, r=sicking (44af1e17dd)
- Bug 1231100 - Get rid of nsIDOMFileReader - patch 1, r=sicking (c909d9d793)
- Bug 1231100 - Get rid of nsIDOMFileReader - patch 2, r=sicking (4d3da1c566)
- Bug 1161183: Don't show the add-on version in the list view. r=dao (002d8f6fb1)
- Bug 1229519: Fix toolkit/modules to pass eslint checks. r=mak (8bbd9c8fe0)
2023-04-06 15:48:27 +08:00

304 lines
11 KiB
JavaScript

/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80 filetype=javascript: */
/* 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/. */
"use strict";
this.EXPORTED_SYMBOLS = [
"DeferredTask",
];
/**
* Sets up a function or an asynchronous task whose execution can be triggered
* after a defined delay. Multiple attempts to run the task before the delay
* has passed are coalesced. The task cannot be re-entered while running, but
* can be executed again after a previous run finished.
*
* A common use case occurs when a data structure should be saved into a file
* every time the data changes, using asynchronous calls, and multiple changes
* to the data may happen within a short time:
*
* let saveDeferredTask = new DeferredTask(function* () {
* yield OS.File.writeAtomic(...);
* // Any uncaught exception will be reported.
* }, 2000);
*
* // The task is ready, but will not be executed until requested.
*
* The "arm" method can be used to start the internal timer that will result in
* the eventual execution of the task. Multiple attempts to arm the timer don't
* introduce further delays:
*
* saveDeferredTask.arm();
*
* // The task will be executed in 2 seconds from now.
*
* yield waitOneSecond();
* saveDeferredTask.arm();
*
* // The task will be executed in 1 second from now.
*
* The timer can be disarmed to reset the delay, or just to cancel execution:
*
* saveDeferredTask.disarm();
* saveDeferredTask.arm();
*
* // The task will be executed in 2 seconds from now.
*
* When the internal timer fires and the execution of the task starts, the task
* cannot be canceled anymore. It is however possible to arm the timer again
* during the execution of the task, in which case the task will need to finish
* before the timer is started again, thus guaranteeing a time of inactivity
* between executions that is at least equal to the provided delay.
*
* The "finalize" method can be used to ensure that the task terminates
* properly. The promise it returns is resolved only after the last execution
* of the task is finished. To guarantee that the task is executed for the
* last time, the method prevents any attempt to arm the timer again.
*
* If the timer is already armed when the "finalize" method is called, then the
* task is executed immediately. If the task was already running at this point,
* then one last execution from start to finish will happen again, immediately
* after the current execution terminates. If the timer is not armed, the
* "finalize" method only ensures that any running task terminates.
*
* For example, during shutdown, you may want to ensure that any pending write
* is processed, using the latest version of the data if the timer is armed:
*
* AsyncShutdown.profileBeforeChange.addBlocker(
* "Example service: shutting down",
* () => saveDeferredTask.finalize()
* );
*
* Instead, if you are going to delete the saved data from disk anyways, you
* might as well prevent any pending write from starting, while still ensuring
* that any write that is currently in progress terminates, so that the file is
* not in use anymore:
*
* saveDeferredTask.disarm();
* saveDeferredTask.finalize().then(() => OS.File.remove(...))
* .then(null, Components.utils.reportError);
*/
////////////////////////////////////////////////////////////////////////////////
//// Globals
const { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Promise",
"resource://gre/modules/Promise.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "Task",
"resource://gre/modules/Task.jsm");
const Timer = Components.Constructor("@mozilla.org/timer;1", "nsITimer",
"initWithCallback");
////////////////////////////////////////////////////////////////////////////////
//// DeferredTask
/**
* Sets up a task whose execution can be triggered after a delay.
*
* @param aTaskFn
* Function or generator function to execute. This argument is passed to
* the "Task.spawn" method every time the task should be executed. This
* task is never re-entered while running.
* @param aDelayMs
* Time between executions, in milliseconds. Multiple attempts to run
* the task before the delay has passed are coalesced. This time of
* inactivity is guaranteed to pass between multiple executions of the
* task, except on finalization, when the task may restart immediately
* after the previous execution finished.
*/
this.DeferredTask = function (aTaskFn, aDelayMs) {
this._taskFn = aTaskFn;
this._delayMs = aDelayMs;
}
this.DeferredTask.prototype = {
/**
* Function or generator function to execute.
*/
_taskFn: null,
/**
* Time between executions, in milliseconds.
*/
_delayMs: null,
/**
* Indicates whether the task is currently requested to start again later,
* regardless of whether it is currently running.
*/
get isArmed() {
return this._armed;
},
_armed: false,
/**
* Indicates whether the task is currently running. This is always true when
* read from code inside the task function, but can also be true when read
* from external code, in case the task is an asynchronous generator function.
*/
get isRunning() {
return !!this._runningPromise;
},
/**
* Promise resolved when the current execution of the task terminates, or null
* if the task is not currently running.
*/
_runningPromise: null,
/**
* nsITimer used for triggering the task after a delay, or null in case the
* task is running or there is no task scheduled for execution.
*/
_timer: null,
/**
* Actually starts the timer with the delay specified on construction.
*/
_startTimer: function ()
{
this._timer = new Timer(this._timerCallback.bind(this), this._delayMs,
Ci.nsITimer.TYPE_ONE_SHOT);
},
/**
* Requests the execution of the task after the delay specified on
* construction. Multiple calls don't introduce further delays. If the task
* is running, the delay will start when the current execution finishes.
*
* The task will always be executed on a different tick of the event loop,
* even if the delay specified on construction is zero. Multiple "arm" calls
* within the same tick of the event loop are guaranteed to result in a single
* execution of the task.
*
* @note By design, this method doesn't provide a way for the caller to detect
* when the next execution terminates, or collect a result. In fact,
* doing that would often result in duplicate processing or logging. If
* a special operation or error logging is needed on completion, it can
* be better handled from within the task itself, for example using a
* try/catch/finally clause in the task. The "finalize" method can be
* used in the common case of waiting for completion on shutdown.
*/
arm: function ()
{
if (this._finalized) {
throw new Error("Unable to arm timer, the object has been finalized.");
}
this._armed = true;
// In case the timer callback is running, do not create the timer now,
// because this will be handled by the timer callback itself. Also, the
// timer is not restarted in case it is already running.
if (!this._runningPromise && !this._timer) {
this._startTimer();
}
},
/**
* Cancels any request for a delayed the execution of the task, though the
* task itself cannot be canceled in case it is already running.
*
* This method stops any currently running timer, thus the delay will restart
* from its original value in case the "arm" method is called again.
*/
disarm: function () {
this._armed = false;
if (this._timer) {
// Calling the "cancel" method and discarding the timer reference makes
// sure that the timer callback will not be called later, even if the
// timer thread has already posted the timer event on the main thread.
this._timer.cancel();
this._timer = null;
}
},
/**
* Ensures that any pending task is executed from start to finish, while
* preventing any attempt to arm the timer again.
*
* - If the task is running and the timer is armed, then one last execution
* from start to finish will happen again, immediately after the current
* execution terminates, then the returned promise will be resolved.
* - If the task is running and the timer is not armed, the returned promise
* will be resolved when the current execution terminates.
* - If the task is not running and the timer is armed, then the task is
* started immediately, and the returned promise resolves when the new
* execution terminates.
* - If the task is not running and the timer is not armed, the method returns
* a resolved promise.
*
* @return {Promise}
* @resolves After the last execution of the task is finished.
* @rejects Never.
*/
finalize: function () {
if (this._finalized) {
throw new Error("The object has been already finalized.");
}
this._finalized = true;
// If the timer is armed, it means that the task is not running but it is
// scheduled for execution. Cancel the timer and run the task immediately.
if (this._timer) {
this.disarm();
this._timerCallback();
}
// Wait for the operation to be completed, or resolve immediately.
if (this._runningPromise) {
return this._runningPromise;
}
return Promise.resolve();
},
_finalized: false,
/**
* Timer callback used to run the delayed task.
*/
_timerCallback: function ()
{
let runningDeferred = Promise.defer();
// All these state changes must occur at the same time directly inside the
// timer callback, to prevent race conditions and to ensure that all the
// methods behave consistently even if called from inside the task. This
// means that the assignment of "this._runningPromise" must complete before
// the task gets a chance to start.
this._timer = null;
this._armed = false;
this._runningPromise = runningDeferred.promise;
runningDeferred.resolve(Task.spawn(function* () {
// Execute the provided function asynchronously.
yield Task.spawn(this._taskFn).then(null, Cu.reportError);
// Now that the task has finished, we check the state of the object to
// determine if we should restart the task again.
if (this._armed) {
if (!this._finalized) {
this._startTimer();
} else {
// Execute the task again immediately, for the last time. The isArmed
// property should return false while the task is running, and should
// remain false after the last execution terminates.
this._armed = false;
yield Task.spawn(this._taskFn).then(null, Cu.reportError);
}
}
// Indicate that the execution of the task has finished. This happens
// synchronously with the previous state changes in the function.
this._runningPromise = null;
}.bind(this)).then(null, Cu.reportError));
},
};