Skip to content

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Member

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.

{
  using ds = new DisposableStack();
  ds.defer(onDispose);
}


```mjs
{
await using _ = util.disposer(async function disposer() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
await using _ = util.disposer(async function disposer() {
await using _ = util.asyncDisposer(async function disposer() {

// 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
Expand Down
73 changes: 73 additions & 0 deletions lib/internal/util/disposer.js
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,
};
6 changes: 6 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -491,3 +491,9 @@ defineLazyProperties(
'internal/util/diff',
['diff'],
);

defineLazyProperties(
module.exports,
'internal/util/disposer',
['disposer', 'asyncDisposer', 'Disposer', 'AsyncDisposer'],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disposer and AsyncDisposer are not actually exported?

);
81 changes: 81 additions & 0 deletions test/parallel/test-util-asyncdisposer.js
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',
});
});
68 changes: 68 additions & 0 deletions test/parallel/test-util-disposer.js
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]();
});
3 changes: 3 additions & 0 deletions tools/doc/type-parser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const customTypesMap = {
'AsyncHook': 'async_hooks.html#async_hookscreatehookcallbacks',
'AsyncResource': 'async_hooks.html#class-asyncresource',

'AsyncDisposer': 'util.html#class-utilasyncdisposer',
'Disposer': 'util.html#class-utildisposer',

'brotli options': 'zlib.html#class-brotlioptions',

'Buffer': 'buffer.html#class-buffer',
Expand Down
Loading