Skip to content

Commit

Permalink
lib: implement AbortSignal.any()
Browse files Browse the repository at this point in the history
  • Loading branch information
atlowChemi committed May 2, 2023
1 parent ab434d2 commit 413e398
Show file tree
Hide file tree
Showing 7 changed files with 287 additions and 13 deletions.
13 changes: 13 additions & 0 deletions doc/api/globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,18 @@ added:

Returns a new `AbortSignal` which will be aborted in `delay` milliseconds.

#### Static method: `AbortSignal.any(signals)`

<!-- YAML
added: REPLACEME
-->

* `signals` {Array} The `AbortSignal`s of which to compose a new `AbortSignal`.

Returns a new `AbortSignal` which will be aborted if any of the provided
signals are aborted. Its [`abortSignal.reason`][] will be set to whichever
one of the `signals` caused it to be aborted.

#### Event: `'abort'`

<!-- YAML
Expand Down Expand Up @@ -1043,3 +1055,4 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][].
[timers]: timers.md
[webassembly-mdn]: https://developer.mozilla.org/en-US/docs/WebAssembly
[webassembly-org]: https://webassembly.org
[`abortSignal.reason`]: #abortSignal.reason
73 changes: 64 additions & 9 deletions lib/internal/abort_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ const {
} = require('internal/errors');

const {
validateAbortSignal,
validateAbortSignalArray,
validateObject,
validateUint32,
} = require('internal/validators');
Expand All @@ -54,6 +54,7 @@ const {
clearTimeout,
setTimeout,
} = require('timers');
const assert = require('internal/assert');

const {
messaging_deserialize_symbol: kDeserialize,
Expand All @@ -80,13 +81,16 @@ function lazyMakeTransferable(obj) {
}

const clearTimeoutRegistry = new SafeFinalizationRegistry(clearTimeout);
const timeOutSignals = new SafeSet();
const gcPersistentSignals = new SafeSet();

const kAborted = Symbol('kAborted');
const kReason = Symbol('kReason');
const kCloneData = Symbol('kCloneData');
const kTimeout = Symbol('kTimeout');
const kMakeTransferable = Symbol('kMakeTransferable');
const kComposite = Symbol('kComposite');
const kSourceSignals = Symbol('kSourceSignals');
const kDependantSignals = Symbol('kDependantSignals');

function customInspect(self, obj, depth, options) {
if (depth < 0)
Expand Down Expand Up @@ -116,7 +120,7 @@ function setWeakAbortSignalTimeout(weakRef, delay) {
const timeout = setTimeout(() => {
const signal = weakRef.deref();
if (signal !== undefined) {
timeOutSignals.delete(signal);
gcPersistentSignals.delete(signal);
abortSignal(
signal,
new DOMException(
Expand Down Expand Up @@ -185,25 +189,68 @@ class AbortSignal extends EventTarget {
return signal;
}

/**
* @param {AbortSignal[]} signals
* @returns {AbortSignal}
*/
static any(signals) {
validateAbortSignalArray(signals, 'signals');
const resultSignal = createAbortSignal({ composite: true });
const resultSignalWeakRef = new WeakRef(resultSignal);
for (const signal of signals) {
if (signal.aborted) {
abortSignal(resultSignal, signal.reason);
return resultSignal;
}
resultSignal[kSourceSignals] ??= new SafeSet();
signal[kDependantSignals] ??= new SafeSet();
if (!signal[kComposite]) {
resultSignal[kSourceSignals].add(new WeakRef(signal));
signal[kDependantSignals].add(resultSignalWeakRef);
} else {
if (!signal[kSourceSignals]) {
continue;
}
for (const sourceSignal of signal[kSourceSignals]) {
const sourceSignalRef = sourceSignal.deref();
if (!sourceSignalRef) {
continue;
}
assert(!sourceSignalRef.aborted);
assert(!sourceSignalRef[kComposite]);

if (resultSignal[kSourceSignals].has(sourceSignal)) {
continue;
}
resultSignal[kSourceSignals].add(sourceSignal);
sourceSignalRef[kDependantSignals].add(resultSignalWeakRef);
}
}
}
return resultSignal;
}

[kNewListener](size, type, listener, once, capture, passive, weak) {
super[kNewListener](size, type, listener, once, capture, passive, weak);
if (this[kTimeout] &&
const isTimeoutOrNonEmptyCompositeSignal = this[kTimeout] || (this[kComposite] && this[kSourceSignals]?.size);
if (isTimeoutOrNonEmptyCompositeSignal &&
type === 'abort' &&
!this.aborted &&
!weak &&
size === 1) {
// If this is a timeout signal, and we're adding a non-weak abort
// If this is a timeout signal, or a non-empty composite signal, and we're adding a non-weak abort
// listener, then we don't want it to be gc'd while the listener
// is attached and the timer still hasn't fired. So, we retain a
// strong ref that is held for as long as the listener is registered.
timeOutSignals.add(this);
gcPersistentSignals.add(this);
}
}

[kRemoveListener](size, type, listener, capture) {
super[kRemoveListener](size, type, listener, capture);
if (this[kTimeout] && type === 'abort' && size === 0) {
timeOutSignals.delete(this);
const isTimeoutOrNonEmptyCompositeSignal = this[kTimeout] || (this[kComposite] && this[kSourceSignals]?.size);
if (isTimeoutOrNonEmptyCompositeSignal && type === 'abort' && size === 0) {
gcPersistentSignals.delete(this);
}
}

Expand Down Expand Up @@ -287,7 +334,8 @@ defineEventHandler(AbortSignal.prototype, 'abort');
* @param {{
* aborted? : boolean,
* reason? : any,
* transferable? : boolean
* transferable? : boolean,
* composite? : boolean,
* }} [init]
* @returns {AbortSignal}
*/
Expand All @@ -296,11 +344,13 @@ function createAbortSignal(init = kEmptyObject) {
aborted = false,
reason = undefined,
transferable = false,
composite = false,
} = init;
const signal = new EventTarget();
ObjectSetPrototypeOf(signal, AbortSignal.prototype);
signal[kAborted] = aborted;
signal[kReason] = reason;
signal[kComposite] = composite;
return transferable ? lazyMakeTransferable(signal) : signal;
}

Expand All @@ -312,6 +362,11 @@ function abortSignal(signal, reason) {
[kTrustEvent]: true,
});
signal.dispatchEvent(event);
signal[kDependantSignals]?.forEach(s => {
const signalRef = s.deref();
if (!signalRef) return;
abortSignal(signalRef, reason);
});
}

class AbortController {
Expand Down
21 changes: 19 additions & 2 deletions lib/internal/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,21 @@ function validateBooleanArray(value, name) {
}
}

/**
* @callback validateAbortSignalArray
* @param {*} value
* @param {string} name
* @returns {asserts value is AbortSignal[]}
*/

/** @type {validateAbortSignalArray} */
function validateAbortSignalArray(value, name) {
validateArray(value, name);
for (let i = 0; i < value.length; i++) {
validateAbortSignal(value[i], `${name}[${i}]`, false);
}
}

/**
* @param {*} signal
* @param {string} [name='signal']
Expand Down Expand Up @@ -395,11 +410,12 @@ function validatePort(port, name = 'Port', allowZero = true) {
* @callback validateAbortSignal
* @param {*} signal
* @param {string} name
* @param {boolean} [acceptUndefined=true]
*/

/** @type {validateAbortSignal} */
const validateAbortSignal = hideStackFrames((signal, name) => {
if (signal !== undefined &&
const validateAbortSignal = hideStackFrames((signal, name, acceptUndefined = true) => {
if ((!acceptUndefined || signal !== undefined) &&
(signal === null ||
typeof signal !== 'object' ||
!('aborted' in signal))) {
Expand Down Expand Up @@ -534,6 +550,7 @@ module.exports = {
validateArray,
validateStringArray,
validateBooleanArray,
validateAbortSignalArray,
validateBoolean,
validateBuffer,
validateDictionary,
Expand Down
2 changes: 1 addition & 1 deletion test/fixtures/wpt/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Last update:

- common: https://github.com/web-platform-tests/wpt/tree/dbd648158d/common
- console: https://github.com/web-platform-tests/wpt/tree/767ae35464/console
- dom/abort: https://github.com/web-platform-tests/wpt/tree/8fadb38120/dom/abort
- dom/abort: https://github.com/web-platform-tests/wpt/tree/d1f1ecbd52/dom/abort
- dom/events: https://github.com/web-platform-tests/wpt/tree/ab8999891c/dom/events
- encoding: https://github.com/web-platform-tests/wpt/tree/0c1b9d1622/encoding
- fetch/data-urls/resources: https://github.com/web-platform-tests/wpt/tree/7c79d998ff/fetch/data-urls/resources
Expand Down
4 changes: 4 additions & 0 deletions test/fixtures/wpt/dom/abort/abort-signal-any.any.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// META: script=./resources/abort-signal-any-tests.js

abortSignalAnySignalOnlyTests(AbortSignal);
abortSignalAnyTests(AbortSignal, AbortController);
Loading

0 comments on commit 413e398

Please sign in to comment.