-
-
Notifications
You must be signed in to change notification settings - Fork 32.2k
util: add util.disposer helper to wrap a dispose function #58585
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
legendecas
wants to merge
1
commit into
nodejs:main
Choose a base branch
from
legendecas:util-disposable
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+314
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -3655,6 +3655,89 @@ Returns `true` if the value is a built-in {WeakSet} instance. | |||||
util.types.isWeakSet(new WeakSet()); // Returns true | ||||||
``` | ||||||
|
||||||
## Disposer APIs | ||||||
|
||||||
> Stability: 1 - Experimental | ||||||
|
||||||
### `util.asyncDisposer(onDispose)` | ||||||
|
||||||
<!-- YAML | ||||||
added: REPLACEME | ||||||
--> | ||||||
|
||||||
* `onDispose` {Function} A dispose function returning a promise | ||||||
* Returns: {AsyncDisposer} | ||||||
|
||||||
Create a convenient wrapper on the given async function that can be used | ||||||
with `using` declaration. | ||||||
|
||||||
If an error is thrown in the function, instead of returning a promise, | ||||||
the error will be wrapped in a rejected promise. | ||||||
|
||||||
```mjs | ||||||
{ | ||||||
await using _ = util.disposer(async function disposer() { | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
// Performing async disposing actions... | ||||||
}); | ||||||
|
||||||
// Doing some works... | ||||||
|
||||||
} // When this scope exits, the disposer function is invoked and awaited. | ||||||
``` | ||||||
|
||||||
### `util.disposer(onDispose)` | ||||||
|
||||||
<!-- YAML | ||||||
added: REPLACEME | ||||||
--> | ||||||
|
||||||
* `onDispose` {Function} A dispose function | ||||||
* Returns: {Disposer} | ||||||
|
||||||
Create a convenient wrapper on the given function that can be used with | ||||||
`using` declaration. | ||||||
|
||||||
```js | ||||||
{ | ||||||
using _ = util.disposer(function disposer() { | ||||||
// Performing disposing actions... | ||||||
}); | ||||||
|
||||||
// Doing some works... | ||||||
|
||||||
} // When this scope exits, the disposer function is invoked. | ||||||
``` | ||||||
|
||||||
### Class: `util.AsyncDisposer` | ||||||
|
||||||
<!-- YAML | ||||||
added: REPLACEME | ||||||
--> | ||||||
|
||||||
A convenience wrapper on an async dispose function. | ||||||
|
||||||
#### `asyncDisposer[Symbol.asyncDispose]()` | ||||||
|
||||||
Invokes the function specified in `util.asyncDisposer(onDispose)`. | ||||||
|
||||||
Multiple invocations on this method only result in a single | ||||||
invocation of the `onDispose` function. | ||||||
|
||||||
### Class: `util.Disposer` | ||||||
|
||||||
<!-- YAML | ||||||
added: REPLACEME | ||||||
--> | ||||||
|
||||||
A convenience wrapper on a dispose function. | ||||||
|
||||||
#### `disposer[Symbol.dispose]()` | ||||||
|
||||||
Invokes the function specified in `util.disposer(onDispose)`. | ||||||
|
||||||
Multiple invocations on this method only result in a single | ||||||
invocation of the `onDispose` function. | ||||||
|
||||||
## Deprecated APIs | ||||||
|
||||||
The following APIs are deprecated and should no longer be used. Existing | ||||||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
'use strict'; | ||
|
||
const { | ||
PromiseWithResolvers, | ||
SymbolAsyncDispose, | ||
SymbolDispose, | ||
} = primordials; | ||
const { | ||
validateFunction, | ||
} = require('internal/validators'); | ||
|
||
class Disposer { | ||
#disposed = false; | ||
#onDispose; | ||
constructor(onDispose) { | ||
validateFunction(onDispose, 'disposeFn'); | ||
this.#onDispose = onDispose; | ||
} | ||
|
||
dispose() { | ||
if (this.#disposed) { | ||
return; | ||
} | ||
this.#disposed = true; | ||
this.#onDispose(); | ||
} | ||
|
||
[SymbolDispose]() { | ||
this.dispose(); | ||
} | ||
} | ||
|
||
class AsyncDisposer { | ||
/** | ||
* @type {PromiseWithResolvers<void>} | ||
*/ | ||
#disposeDeferred; | ||
#onDispose; | ||
constructor(onDispose) { | ||
validateFunction(onDispose, 'disposeFn'); | ||
this.#onDispose = onDispose; | ||
} | ||
|
||
dispose() { | ||
if (this.#disposeDeferred === undefined) { | ||
this.#disposeDeferred = PromiseWithResolvers(); | ||
try { | ||
const ret = this.#onDispose(); | ||
this.#disposeDeferred.resolve(ret); | ||
} catch (err) { | ||
this.#disposeDeferred.reject(err); | ||
} | ||
} | ||
return this.#disposeDeferred.promise; | ||
} | ||
|
||
[SymbolAsyncDispose]() { | ||
return this.dispose(); | ||
} | ||
} | ||
|
||
function disposer(disposeFn) { | ||
return new Disposer(disposeFn); | ||
} | ||
|
||
function asyncDisposer(disposeFn) { | ||
return new AsyncDisposer(disposeFn); | ||
} | ||
|
||
module.exports = { | ||
disposer, | ||
asyncDisposer, | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -491,3 +491,9 @@ defineLazyProperties( | |
'internal/util/diff', | ||
['diff'], | ||
); | ||
|
||
defineLazyProperties( | ||
module.exports, | ||
'internal/util/disposer', | ||
['disposer', 'asyncDisposer', 'Disposer', 'AsyncDisposer'], | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
'use strict'; | ||
|
||
// This test checks that the semantics of `util.asyncDisposer` are as described in | ||
// the API docs | ||
|
||
const common = require('../common'); | ||
const assert = require('node:assert'); | ||
const { asyncDisposer } = require('node:util'); | ||
const test = require('node:test'); | ||
|
||
test('util.asyncDisposer should throw on non-function first parameter', () => { | ||
const invalidDisposers = [ | ||
null, | ||
undefined, | ||
42, | ||
'string', | ||
{}, | ||
[], | ||
Symbol('symbol'), | ||
]; | ||
for (const invalidDisposer of invalidDisposers) { | ||
assert.throws(() => { | ||
asyncDisposer(invalidDisposer); | ||
}, { | ||
code: 'ERR_INVALID_ARG_TYPE', | ||
name: 'TypeError', | ||
}); | ||
} | ||
}); | ||
|
||
test('util.asyncDisposer should create a AsyncDisposable object', async () => { | ||
const disposeFn = common.mustCall(); | ||
const disposable = asyncDisposer(disposeFn); | ||
assert.strictEqual(typeof disposable, 'object'); | ||
assert.strictEqual(disposable[Symbol.dispose], undefined); | ||
assert.strictEqual(typeof disposable[Symbol.asyncDispose], 'function'); | ||
|
||
// Multiple calls to asyncDispose should not throw and only invoke the function once. | ||
const p1 = disposable[Symbol.asyncDispose](); | ||
const p2 = disposable[Symbol.asyncDispose](); | ||
assert.strictEqual(p1, p2); | ||
await p1; | ||
}); | ||
|
||
test('AsyncDisposer[Symbol.asyncDispose] must be invoked with an AsyncDisposer', () => { | ||
const disposeFn = common.mustNotCall(); | ||
const disposable = asyncDisposer(disposeFn); | ||
assert.throws(() => { | ||
disposable[Symbol.asyncDispose].call({}); // Call with a non-AsyncDisposer object | ||
}, TypeError); | ||
|
||
assert.throws(() => { | ||
disposable.dispose.call({}); // Call with a non-AsyncDisposer object | ||
}, TypeError); | ||
}); | ||
|
||
test('AsyncDisposer[Symbol.asyncDispose] should reject if the disposerFn throws sync', async () => { | ||
const disposeFn = common.mustCall(() => { | ||
throw new Error('Disposer error'); | ||
}); | ||
const disposable = asyncDisposer(disposeFn); | ||
const promise = disposable[Symbol.asyncDispose](); | ||
|
||
await assert.rejects(promise, { | ||
name: 'Error', | ||
message: 'Disposer error', | ||
}); | ||
}); | ||
|
||
test('Disposer[Symbol.asyncDispose] should reject if the disposerFn rejects', async () => { | ||
const disposeFn = common.mustCall(() => { | ||
return Promise.reject(new Error('Disposer error')); | ||
}); | ||
const disposable = asyncDisposer(disposeFn); | ||
const promise = disposable[Symbol.asyncDispose](); | ||
|
||
await assert.rejects(promise, { | ||
name: 'Error', | ||
message: 'Disposer error', | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
'use strict'; | ||
|
||
// This test checks that the semantics of `util.disposer` are as described in | ||
// the API docs | ||
|
||
const common = require('../common'); | ||
const assert = require('node:assert'); | ||
const { disposer } = require('node:util'); | ||
const test = require('node:test'); | ||
|
||
test('util.disposer should throw on non-function first parameter', () => { | ||
const invalidDisposers = [ | ||
null, | ||
undefined, | ||
42, | ||
'string', | ||
{}, | ||
[], | ||
Symbol('symbol'), | ||
]; | ||
for (const invalidDisposer of invalidDisposers) { | ||
assert.throws(() => { | ||
disposer(invalidDisposer); | ||
}, { | ||
code: 'ERR_INVALID_ARG_TYPE', | ||
name: 'TypeError', | ||
}); | ||
} | ||
}); | ||
|
||
test('util.disposer should create a Disposable object', () => { | ||
const disposeFn = common.mustCall(); | ||
const disposable = disposer(disposeFn); | ||
assert.strictEqual(typeof disposable, 'object'); | ||
assert.strictEqual(typeof disposable[Symbol.dispose], 'function'); | ||
assert.strictEqual(disposable[Symbol.asyncDispose], undefined); | ||
disposable[Symbol.dispose](); | ||
// Multiple calls to dispose should not throw and only invoke the function once. | ||
disposable[Symbol.dispose](); | ||
}); | ||
|
||
test('Disposer[Symbol.dispose] must be invoked with an Disposer', () => { | ||
const disposeFn = common.mustNotCall(); | ||
const disposable = disposer(disposeFn); | ||
assert.throws(() => { | ||
disposable[Symbol.dispose].call({}); // Call with a non-Disposer object | ||
}, TypeError); | ||
|
||
assert.throws(() => { | ||
disposable.dispose.call({}); // Call with a non-Disposer object | ||
}, TypeError); | ||
}); | ||
|
||
test('Disposer[Symbol.dispose] should throw if the disposerFn throws', () => { | ||
const disposeFn = common.mustCall(() => { | ||
throw new Error('Disposer error'); | ||
}); | ||
const disposable = disposer(disposeFn); | ||
assert.throws(() => { | ||
disposable[Symbol.dispose](); | ||
}, { | ||
name: 'Error', | ||
message: 'Disposer error', | ||
}); | ||
|
||
// Multiple calls to dispose should not throw and only invoke the function once. | ||
disposable[Symbol.dispose](); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given that
DisposableStack.defer(...)
exists I'm not super convinced that this is needed or all that useful.