Skip to content

Commit

Permalink
lib: use private field in AbortController
Browse files Browse the repository at this point in the history
Instead of validating the receiver ourselves, let V8 handle
the validation using the semantics of private fields.

PR-URL: #43820
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Darshan Sen <raisinten@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
joyeecheung authored Jul 16, 2022
1 parent e54ee80 commit 73ba883
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 19 deletions.
19 changes: 3 additions & 16 deletions lib/internal/abort_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,34 +292,21 @@ function abortSignal(signal, reason) {
signal.dispatchEvent(event);
}

// TODO(joyeecheung): use private fields and we'll get invalid access
// validation from V8 instead of throwing ERR_INVALID_THIS ourselves.
const kSignal = Symbol('signal');

function validateAbortController(obj) {
if (obj?.[kSignal] === undefined)
throw new ERR_INVALID_THIS('AbortController');
}

class AbortController {
constructor() {
this[kSignal] = createAbortSignal();
}
#signal = createAbortSignal();

/**
* @type {AbortSignal}
*/
get signal() {
validateAbortController(this);
return this[kSignal];
return this.#signal;
}

/**
* @param {any} reason
*/
abort(reason = new DOMException('This operation was aborted', 'AbortError')) {
validateAbortController(this);
abortSignal(this[kSignal], reason);
abortSignal(this.#signal, reason);
}

[customInspectSymbol](depth, options) {
Expand Down
6 changes: 3 additions & 3 deletions test/parallel/test-abortcontroller.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,11 @@ const { setTimeout: sleep } = require('timers/promises');
for (const badController of badAbortControllers) {
throws(
() => acSignalGet.call(badController),
{ code: 'ERR_INVALID_THIS', name: 'TypeError' }
{ name: 'TypeError' }
);
throws(
() => acAbort.call(badController),
{ code: 'ERR_INVALID_THIS', name: 'TypeError' }
{ name: 'TypeError' }
);
}
}
Expand All @@ -139,7 +139,7 @@ const { setTimeout: sleep } = require('timers/promises');
for (const badSignal of badAbortSignals) {
throws(
() => signalAbortedGet.call(badSignal),
{ code: 'ERR_INVALID_THIS', name: 'TypeError' }
{ name: 'TypeError' }
);
}
}
Expand Down

0 comments on commit 73ba883

Please sign in to comment.