diagnostics_channel: add BoundedChannel and scopes

PR-URL: https://github.com/nodejs/node/pull/61680
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Stephen Belanger authored and GitHub committed 2026-03-31 19:04:24 +00:00
1 parent cd391b5f11
commit cb78a7f484
12 files changed
+1863 -107

No files matched your search

+397
View File
@@ -282,6 +282,53 @@ const channelsByCollection = diagnostics_channel.tracingChannel({
});
```
#### `diagnostics_channel.boundedChannel(nameOrChannels)`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
* `nameOrChannels` {string|BoundedChannel} Channel name or
object containing all the [BoundedChannel Channels][]
* Returns: {BoundedChannel} Collection of channels to trace with
Creates a [`BoundedChannel`][] wrapper for the given channels. If a name is
given, the corresponding channels will be created in the form of
`tracing:${name}:${eventType}` where `eventType` is `start` or `end`.
A `BoundedChannel` is a simplified version of [`TracingChannel`][] that only
traces synchronous operations. It only has `start` and `end` events, without
`asyncStart`, `asyncEnd`, or `error` events, making it suitable for tracing
operations that don't involve asynchronous continuations or error handling.
```mjs
import { boundedChannel, channel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
// or...
const wc2 = boundedChannel({
start: channel('tracing:my-operation:start'),
end: channel('tracing:my-operation:end'),
});
```
```cjs
const { boundedChannel, channel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
// or...
const wc2 = boundedChannel({
start: channel('tracing:my-operation:start'),
end: channel('tracing:my-operation:end'),
});
```
### Class: `Channel`
<!-- YAML
@@ -620,6 +667,77 @@ channel.runStores({ some: 'message' }, () => {
});
```
#### `channel.withStoreScope(data)`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
* `data` {any} Message to bind to stores
* Returns: {RunStoresScope} Disposable scope object
Creates a disposable scope that binds the given data to any AsyncLocalStorage
instances bound to the channel and publishes it to subscribers. The scope
automatically restores the previous storage contexts when disposed.
This method enables the use of JavaScript's explicit resource management
(`using` syntax with `Symbol.dispose`) to manage store contexts without
closure wrapping.
```mjs
import { channel } from 'node:diagnostics_channel';
import { AsyncLocalStorage } from 'node:async_hooks';
const store = new AsyncLocalStorage();
const ch = channel('my-channel');
ch.bindStore(store, (message) => {
return { ...message, timestamp: Date.now() };
});
{
using scope = ch.withStoreScope({ request: 'data' });
// Store is entered, data is published
console.log(store.getStore()); // { request: 'data', timestamp: ... }
}
// Store is automatically restored on scope exit
```
```cjs
const { channel } = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
const store = new AsyncLocalStorage();
const ch = channel('my-channel');
ch.bindStore(store, (message) => {
return { ...message, timestamp: Date.now() };
});
{
using scope = ch.withStoreScope({ request: 'data' });
// Store is entered, data is published
console.log(store.getStore()); // { request: 'data', timestamp: ... }
}
// Store is automatically restored on scope exit
```
### Class: `RunStoresScope`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
The class `RunStoresScope` represents a disposable scope created by
[`channel.withStoreScope(data)`][]. It manages the lifecycle of store
contexts and ensures they are properly restored when the scope exits.
The scope must be used with the `using` syntax to ensure proper disposal.
### Class: `TracingChannel`
<!-- YAML
@@ -1026,6 +1144,281 @@ if (channels.hasSubscribers) {
}
```
### Class: `BoundedChannel`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
The class `BoundedChannel` is a simplified version of [`TracingChannel`][] that
only traces synchronous operations. It consists of two channels (`start` and
`end`) instead of five, omitting the `asyncStart`, `asyncEnd`, and `error`
events. This makes it suitable for tracing operations that don't involve
asynchronous continuations or error handling.
Like `TracingChannel`, it is recommended to create and reuse a single
`BoundedChannel` at the top-level of the file rather than creating them
dynamically.
#### `boundedChannel.hasSubscribers`
<!-- YAML
added: REPLACEME
-->
* Returns: {boolean} `true` if any of the individual channels has a subscriber,
`false` if not.
Check if any of the `start` or `end` channels have subscribers.
```mjs
import { boundedChannel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
if (wc.hasSubscribers) {
// There are subscribers, perform traced operation
}
```
```cjs
const { boundedChannel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
if (wc.hasSubscribers) {
// There are subscribers, perform traced operation
}
```
#### `boundedChannel.subscribe(handlers)`
<!-- YAML
added: REPLACEME
-->
* `handlers` {Object} Set of channel subscribers
* `start` {Function} The start event subscriber
* `end` {Function} The end event subscriber
Subscribe to the bounded channel events. This is equivalent to calling
[`channel.subscribe(onMessage)`][] on each channel individually.
```mjs
import { boundedChannel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
wc.subscribe({
start(message) {
// Handle start
},
end(message) {
// Handle end
},
});
```
```cjs
const { boundedChannel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
wc.subscribe({
start(message) {
// Handle start
},
end(message) {
// Handle end
},
});
```
#### `boundedChannel.unsubscribe(handlers)`
<!-- YAML
added: REPLACEME
-->
* `handlers` {Object} Set of channel subscribers
* `start` {Function} The start event subscriber
* `end` {Function} The end event subscriber
* Returns: {boolean} `true` if all handlers were successfully unsubscribed,
`false` otherwise.
Unsubscribe from the bounded channel events. This is equivalent to calling
[`channel.unsubscribe(onMessage)`][] on each channel individually.
```mjs
import { boundedChannel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
const handlers = {
start(message) {},
end(message) {},
};
wc.subscribe(handlers);
wc.unsubscribe(handlers);
```
```cjs
const { boundedChannel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
const handlers = {
start(message) {},
end(message) {},
};
wc.subscribe(handlers);
wc.unsubscribe(handlers);
```
#### `boundedChannel.run(context, fn[, thisArg[, ...args]])`
<!-- YAML
added: REPLACEME
-->
* `context` {Object} Shared object to correlate events through
* `fn` {Function} Function to wrap a trace around
* `thisArg` {any} The receiver to be used for the function call
* `...args` {any} Optional arguments to pass to the function
* Returns: {any} The return value of the given function
Trace a synchronous function call. This will produce a `start` event and `end`
event around the execution. This runs the given function using
[`channel.runStores(context, ...)`][] on the `start` channel which ensures all
events have any bound stores set to match this trace context.
```mjs
import { boundedChannel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
const result = wc.run({ operationId: '123' }, () => {
// Perform operation
return 42;
});
```
```cjs
const { boundedChannel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
const result = wc.run({ operationId: '123' }, () => {
// Perform operation
return 42;
});
```
#### `boundedChannel.withScope([context])`
<!-- YAML
added: REPLACEME
-->
* `context` {Object} Shared object to correlate events through
* Returns: {BoundedChannelScope} Disposable scope object
Create a disposable scope for tracing a synchronous operation using JavaScript's
explicit resource management (`using` syntax). The scope automatically publishes
`start` and `end` events, enters bound stores, and handles cleanup when disposed.
```mjs
import { boundedChannel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
const context = { operationId: '123' };
{
using scope = wc.withScope(context);
// Stores are entered, start event is published
// Perform work and set result on context
context.result = 42;
}
// End event is published, stores are restored automatically
```
```cjs
const { boundedChannel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
const context = { operationId: '123' };
{
using scope = wc.withScope(context);
// Stores are entered, start event is published
// Perform work and set result on context
context.result = 42;
}
// End event is published, stores are restored automatically
```
### Class: `BoundedChannelScope`
<!-- YAML
added: REPLACEME
-->
> Stability: 1 - Experimental
The class `BoundedChannelScope` represents a disposable scope created by
[`boundedChannel.withScope(context)`][]. It manages the lifecycle of a traced
operation, automatically publishing events and managing store contexts.
The scope must be used with the `using` syntax to ensure proper disposal.
```mjs
import { boundedChannel } from 'node:diagnostics_channel';
const wc = boundedChannel('my-operation');
const context = {};
{
using scope = wc.withScope(context);
// Start event is published, stores are entered
context.result = performOperation();
// End event is automatically published at end of block
}
```
```cjs
const { boundedChannel } = require('node:diagnostics_channel');
const wc = boundedChannel('my-operation');
const context = {};
{
using scope = wc.withScope(context);
// Start event is published, stores are entered
context.result = performOperation();
// End event is automatically published at end of block
}
```
### BoundedChannel Channels
A `BoundedChannel` consists of two diagnostics channels representing the
lifecycle of a scope created with the `using` syntax:
* `tracing:${name}:start` - Published when the `using` statement executes (scope creation)
* `tracing:${name}:end` - Published when exiting the block (scope disposal)
When using the `using` syntax with \[`boundedChannel.withScope([context])`]\[], the `start`
event is published immediately when the statement executes, and the `end` event
is automatically published when disposal occurs at the end of the block. All
events share the same context object, which can be extended with additional
properties like `result` during scope execution.
### TracingChannel Channels
A TracingChannel is a collection of several diagnostics\_channels representing
@@ -1518,15 +1911,19 @@ added: v16.18.0
Emitted when a new thread is created.
[BoundedChannel Channels]: #boundedchannel-channels
[TracingChannel Channels]: #tracingchannel-channels
[`'uncaughtException'`]: process.md#event-uncaughtexception
[`BoundedChannel`]: #class-boundedchannel
[`TracingChannel`]: #class-tracingchannel
[`asyncEnd` event]: #asyncendevent
[`asyncStart` event]: #asyncstartevent
[`boundedChannel.withScope(context)`]: #boundedchannelwithscopecontext
[`channel.bindStore(store)`]: #channelbindstorestore-transform
[`channel.runStores(context, ...)`]: #channelrunstorescontext-fn-thisarg-args
[`channel.subscribe(onMessage)`]: #channelsubscribeonmessage
[`channel.unsubscribe(onMessage)`]: #channelunsubscribeonmessage
[`channel.withStoreScope(data)`]: #channelwithstorescopedata
[`child_process.spawn()`]: child_process.md#child_processspawncommand-args-options
[`diagnostics_channel.channel(name)`]: #diagnostics_channelchannelname
[`diagnostics_channel.subscribe(name, onMessage)`]: #diagnostics_channelsubscribename-onmessage
+285 -106
View File
@@ -10,9 +10,12 @@ const {
ObjectDefineProperty,
ObjectGetPrototypeOf,
ObjectSetPrototypeOf,
PromisePrototypeThen,
PromiseReject,
ReflectApply,
SafeFinalizationRegistry,
SafeMap,
SymbolDispose,
SymbolHasInstance,
} = primordials;
@@ -31,6 +34,7 @@ const dc_binding = internalBinding('diagnostics_channel');
const { subscribers: subscriberCounts } = dc_binding;
const { WeakReference } = require('internal/util');
const { isPromise } = require('internal/util/types');
// Can't delete when weakref count reaches 0 as it could increment again.
// Only GC can be used as a valid time to clean up the channels map.
@@ -80,24 +84,45 @@ function maybeMarkInactive(channel) {
}
}
function defaultTransform(data) {
return data;
}
class RunStoresScope {
#stack;
function wrapStoreRun(store, data, next, transform = defaultTransform) {
return () => {
let context;
try {
context = transform(data);
} catch (err) {
process.nextTick(() => {
triggerUncaughtException(err, false);
});
return next();
constructor(activeChannel, data) {
// eslint-disable-next-line no-restricted-globals
using stack = new DisposableStack();
// Enter stores using withScope
if (activeChannel._stores) {
for (const entry of activeChannel._stores.entries()) {
const store = entry[0];
const transform = entry[1];
let newContext = data;
if (transform) {
try {
newContext = transform(data);
} catch (err) {
process.nextTick(() => {
triggerUncaughtException(err, false);
});
continue;
}
}
stack.use(store.withScope(newContext));
}
}
return store.run(context, next);
};
// Publish data
activeChannel.publish(data);
// Transfer ownership of the stack
this.#stack = stack.move();
}
[SymbolDispose]() {
this.#stack[SymbolDispose]();
}
}
// TODO(qard): should there be a C++ channel interface?
@@ -167,19 +192,14 @@ class ActiveChannel {
}
}
withStoreScope(data) {
return new RunStoresScope(this, data);
}
runStores(data, fn, thisArg, ...args) {
let run = () => {
this.publish(data);
return ReflectApply(fn, thisArg, args);
};
for (const entry of this._stores.entries()) {
const store = entry[0];
const transform = entry[1];
run = wrapStoreRun(store, data, run, transform);
}
return run();
// eslint-disable-next-line no-unused-vars
using scope = this.withStoreScope(data);
return ReflectApply(fn, thisArg, args);
}
}
@@ -228,6 +248,13 @@ class Channel {
runStores(data, fn, thisArg, ...args) {
return ReflectApply(fn, thisArg, args);
}
withStoreScope() {
// Return no-op disposable for inactive channels
return {
[SymbolDispose]() {},
};
}
}
const channels = new WeakRefMap();
@@ -258,12 +285,9 @@ function hasSubscribers(name) {
return channel.hasSubscribers;
}
const traceEvents = [
const boundedEvents = [
'start',
'end',
'asyncStart',
'asyncEnd',
'error',
];
function assertChannel(value, name) {
@@ -272,7 +296,12 @@ function assertChannel(value, name) {
}
}
function tracingChannelFrom(nameOrChannels, name) {
function emitNonThenableWarning(fn) {
process.emitWarning(`tracePromise was called with the function '${fn.name || '<anonymous>'}', ` +
'which returned a non-thenable.');
}
function channelFromMap(nameOrChannels, name, className) {
if (typeof nameOrChannels === 'string') {
return channel(`tracing:${nameOrChannels}:${name}`);
}
@@ -284,37 +313,62 @@ function tracingChannelFrom(nameOrChannels, name) {
}
throw new ERR_INVALID_ARG_TYPE('nameOrChannels',
['string', 'object', 'TracingChannel'],
['string', 'object', className],
nameOrChannels);
}
function emitNonThenableWarning(fn) {
process.emitWarning(`tracePromise was called with the function '${fn.name || '<anonymous>'}', ` +
'which returned a non-thenable.');
class BoundedChannelScope {
#context;
#end;
#scope;
constructor(boundedChannel, context) {
// Only proceed if there are subscribers
if (!boundedChannel.hasSubscribers) {
return;
}
const { start, end } = boundedChannel;
this.#context = context;
this.#end = end;
// Use RunStoresScope for the start channel
this.#scope = new RunStoresScope(start, context);
}
[SymbolDispose]() {
if (!this.#scope) {
return;
}
// Publish end event
this.#end.publish(this.#context);
// Dispose the start scope to restore stores
this.#scope[SymbolDispose]();
this.#scope = undefined;
}
}
class TracingChannel {
class BoundedChannel {
constructor(nameOrChannels) {
for (let i = 0; i < traceEvents.length; ++i) {
const eventName = traceEvents[i];
for (let i = 0; i < boundedEvents.length; ++i) {
const eventName = boundedEvents[i];
ObjectDefineProperty(this, eventName, {
__proto__: null,
value: tracingChannelFrom(nameOrChannels, eventName),
value: channelFromMap(nameOrChannels, eventName, 'BoundedChannel'),
});
}
}
get hasSubscribers() {
return this.start?.hasSubscribers ||
this.end?.hasSubscribers ||
this.asyncStart?.hasSubscribers ||
this.asyncEnd?.hasSubscribers ||
this.error?.hasSubscribers;
this.end?.hasSubscribers;
}
subscribe(handlers) {
for (let i = 0; i < traceEvents.length; ++i) {
const name = traceEvents[i];
for (let i = 0; i < boundedEvents.length; ++i) {
const name = boundedEvents[i];
if (!handlers[name]) continue;
this[name]?.subscribe(handlers[name]);
@@ -324,8 +378,8 @@ class TracingChannel {
unsubscribe(handlers) {
let done = true;
for (let i = 0; i < traceEvents.length; ++i) {
const name = traceEvents[i];
for (let i = 0; i < boundedEvents.length; ++i) {
const name = boundedEvents[i];
if (!handlers[name]) continue;
if (!this[name]?.unsubscribe(handlers[name])) {
@@ -336,26 +390,148 @@ class TracingChannel {
return done;
}
withScope(context = {}) {
return new BoundedChannelScope(this, context);
}
run(context, fn, thisArg, ...args) {
context ??= {};
// eslint-disable-next-line no-unused-vars
using scope = this.withScope(context);
return ReflectApply(fn, thisArg, args);
}
}
function boundedChannel(nameOrChannels) {
return new BoundedChannel(nameOrChannels);
}
class TracingChannel {
#callWindow;
#continuationWindow;
constructor(nameOrChannels) {
// Create a BoundedChannel for start/end (call window)
if (typeof nameOrChannels === 'string') {
this.#callWindow = new BoundedChannel(nameOrChannels);
this.#continuationWindow = new BoundedChannel({
start: channel(`tracing:${nameOrChannels}:asyncStart`),
end: channel(`tracing:${nameOrChannels}:asyncEnd`),
});
} else if (typeof nameOrChannels === 'object') {
this.#callWindow = new BoundedChannel({
start: nameOrChannels.start,
end: nameOrChannels.end,
});
this.#continuationWindow = new BoundedChannel({
start: nameOrChannels.asyncStart,
end: nameOrChannels.asyncEnd,
});
}
// Create individual channel for error
ObjectDefineProperty(this, 'error', {
__proto__: null,
value: channelFromMap(nameOrChannels, 'error', 'TracingChannel'),
});
}
get start() {
return this.#callWindow.start;
}
get end() {
return this.#callWindow.end;
}
get asyncStart() {
return this.#continuationWindow.start;
}
get asyncEnd() {
return this.#continuationWindow.end;
}
get hasSubscribers() {
return this.#callWindow.hasSubscribers ||
this.#continuationWindow.hasSubscribers ||
this.error?.hasSubscribers;
}
subscribe(handlers) {
// Subscribe to call window (start/end)
if (handlers.start || handlers.end) {
this.#callWindow.subscribe({
start: handlers.start,
end: handlers.end,
});
}
// Subscribe to continuation window (asyncStart/asyncEnd)
if (handlers.asyncStart || handlers.asyncEnd) {
this.#continuationWindow.subscribe({
start: handlers.asyncStart,
end: handlers.asyncEnd,
});
}
// Subscribe to error channel
if (handlers.error) {
this.error.subscribe(handlers.error);
}
}
unsubscribe(handlers) {
let done = true;
// Unsubscribe from call window
if (handlers.start || handlers.end) {
if (!this.#callWindow.unsubscribe({
start: handlers.start,
end: handlers.end,
})) {
done = false;
}
}
// Unsubscribe from continuation window
if (handlers.asyncStart || handlers.asyncEnd) {
if (!this.#continuationWindow.unsubscribe({
start: handlers.asyncStart,
end: handlers.asyncEnd,
})) {
done = false;
}
}
// Unsubscribe from error channel
if (handlers.error) {
if (!this.error.unsubscribe(handlers.error)) {
done = false;
}
}
return done;
}
traceSync(fn, context = {}, thisArg, ...args) {
if (!this.hasSubscribers) {
return ReflectApply(fn, thisArg, args);
}
const { start, end, error } = this;
const { error } = this;
return start.runStores(context, () => {
try {
const result = ReflectApply(fn, thisArg, args);
context.result = result;
return result;
} catch (err) {
context.error = err;
error.publish(context);
throw err;
} finally {
end.publish(context);
}
});
// eslint-disable-next-line no-unused-vars
using scope = this.#callWindow.withScope(context);
try {
const result = ReflectApply(fn, thisArg, args);
context.result = result;
return result;
} catch (err) {
context.error = err;
error.publish(context);
throw err;
}
}
tracePromise(fn, context = {}, thisArg, ...args) {
@@ -367,44 +543,50 @@ class TracingChannel {
return result;
}
const { start, end, asyncStart, asyncEnd, error } = this;
const { error } = this;
const continuationWindow = this.#continuationWindow;
function reject(err) {
context.error = err;
error.publish(context);
asyncStart.publish(context);
// Use continuation window for asyncStart/asyncEnd
// eslint-disable-next-line no-unused-vars
using scope = continuationWindow.withScope(context);
// TODO: Is there a way to have asyncEnd _after_ the continuation?
asyncEnd.publish(context);
throw err;
return PromiseReject(err);
}
function resolve(result) {
context.result = result;
asyncStart.publish(context);
// Use continuation window for asyncStart/asyncEnd
// eslint-disable-next-line no-unused-vars
using scope = continuationWindow.withScope(context);
// TODO: Is there a way to have asyncEnd _after_ the continuation?
asyncEnd.publish(context);
return result;
}
return start.runStores(context, () => {
try {
const result = ReflectApply(fn, thisArg, args);
// If the return value is not a thenable, then return it with a warning.
// Do not publish to asyncStart/asyncEnd.
if (typeof result?.then !== 'function') {
emitNonThenableWarning(fn);
context.result = result;
return result;
}
return result.then(resolve, reject);
} catch (err) {
context.error = err;
error.publish(context);
throw err;
} finally {
end.publish(context);
// eslint-disable-next-line no-unused-vars
using scope = this.#callWindow.withScope(context);
try {
const result = ReflectApply(fn, thisArg, args);
// If the return value is not a thenable, return it directly with a warning.
// Do not publish to asyncStart/asyncEnd.
if (typeof result?.then !== 'function') {
emitNonThenableWarning(fn);
context.result = result;
return result;
}
});
// For native Promises use PromisePrototypeThen to avoid user overrides.
if (isPromise(result)) {
return PromisePrototypeThen(result, resolve, reject);
}
// For custom thenables, call .then() directly to preserve the thenable type.
return result.then(resolve, reject);
} catch (err) {
context.error = err;
error.publish(context);
throw err;
}
}
traceCallback(fn, position = -1, context = {}, thisArg, ...args) {
@@ -412,7 +594,8 @@ class TracingChannel {
return ReflectApply(fn, thisArg, args);
}
const { start, end, asyncStart, asyncEnd, error } = this;
const { error } = this;
const continuationWindow = this.#continuationWindow;
function wrappedCallback(err, res) {
if (err) {
@@ -422,31 +605,25 @@ class TracingChannel {
context.result = res;
}
// Using runStores here enables manual context failure recovery
asyncStart.runStores(context, () => {
try {
return ReflectApply(callback, this, arguments);
} finally {
asyncEnd.publish(context);
}
});
// Use continuation window for asyncStart/asyncEnd around callback
// eslint-disable-next-line no-unused-vars
using scope = continuationWindow.withScope(context);
return ReflectApply(callback, this, arguments);
}
const callback = ArrayPrototypeAt(args, position);
validateFunction(callback, 'callback');
ArrayPrototypeSplice(args, position, 1, wrappedCallback);
return start.runStores(context, () => {
try {
return ReflectApply(fn, thisArg, args);
} catch (err) {
context.error = err;
error.publish(context);
throw err;
} finally {
end.publish(context);
}
});
// eslint-disable-next-line no-unused-vars
using scope = this.#callWindow.withScope(context);
try {
return ReflectApply(fn, thisArg, args);
} catch (err) {
context.error = err;
error.publish(context);
throw err;
}
}
}
@@ -462,5 +639,7 @@ module.exports = {
subscribe,
tracingChannel,
unsubscribe,
boundedChannel,
Channel,
BoundedChannel,
};
@@ -0,0 +1,66 @@
'use strict';
const common = require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test BoundedChannel.run() with store transform error
// Transform errors are scheduled via process.nextTick(triggerUncaughtException)
const boundedChannel = dc.boundedChannel('test-run-transform-error');
const store = new AsyncLocalStorage();
const events = [];
const transformError = new Error('transform failed');
// Set up uncaughtException handler to catch the transform error
process.on('uncaughtException', common.mustCall((err) => {
assert.strictEqual(err, transformError);
events.push('uncaughtException');
}));
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
// Bind store with a transform that throws
boundedChannel.start.bindStore(store, () => {
throw transformError;
});
// Store should remain undefined since transform will fail
assert.strictEqual(store.getStore(), undefined);
const result = boundedChannel.run({ operationId: '123' }, common.mustCall(() => {
// Store should still be undefined because transform threw
assert.strictEqual(store.getStore(), undefined);
events.push('inside-run');
return 42;
}));
// Should still return the result despite transform error
assert.strictEqual(result, 42);
// Store should still be undefined after run
assert.strictEqual(store.getStore(), undefined);
// Start and end events should still be published despite transform error
assert.strictEqual(events.length, 3);
assert.strictEqual(events[0].type, 'start');
assert.strictEqual(events[0].data.operationId, '123');
assert.strictEqual(events[1], 'inside-run');
assert.strictEqual(events[2].type, 'end');
assert.strictEqual(events[2].data.operationId, '123');
// Validate uncaughtException was triggered via nextTick
process.on('beforeExit', common.mustCall(() => {
assert.strictEqual(events.length, 4);
assert.strictEqual(events[3], 'uncaughtException');
}));
@@ -0,0 +1,125 @@
'use strict';
require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test basic run functionality
{
const boundedChannel = dc.boundedChannel('test-run-basic');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
const context = { id: 123 };
const result = boundedChannel.run(context, () => {
return 'success';
});
assert.strictEqual(result, 'success');
assert.strictEqual(events.length, 2);
assert.deepStrictEqual(events, [
{ type: 'start', data: { id: 123 } },
{ type: 'end', data: { id: 123 } },
]);
}
// Test run with error
{
const boundedChannel = dc.boundedChannel('test-run-error');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
const context = { id: 456 };
const testError = new Error('test error');
assert.throws(() => {
boundedChannel.run(context, () => {
throw testError;
});
}, testError);
// BoundedChannel does not handle errors - they just propagate
// Only start and end events are published
assert.strictEqual(events.length, 2);
assert.deepStrictEqual(events, [
{ type: 'start', data: { id: 456 } },
{ type: 'end', data: { id: 456 } },
]);
}
// Test run with thisArg and args
{
const boundedChannel = dc.boundedChannel('test-run-args');
const obj = { value: 10 };
const result = boundedChannel.run({}, function(a, b) {
return this.value + a + b;
}, obj, 5, 15);
assert.strictEqual(result, 30);
}
// Test run with AsyncLocalStorage
{
const boundedChannel = dc.boundedChannel('test-run-store');
const store = new AsyncLocalStorage();
const events = [];
boundedChannel.start.bindStore(store, (context) => {
return { traceId: context.traceId };
});
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', store: store.getStore() });
},
end(message) {
events.push({ type: 'end', store: store.getStore() });
},
});
const result = boundedChannel.run({ traceId: 'abc123' }, () => {
events.push({ type: 'inside', store: store.getStore() });
return 'result';
});
assert.strictEqual(result, 'result');
assert.strictEqual(events.length, 3);
// Innert events should have store set
assert.deepStrictEqual(events, [
{ type: 'start', store: { traceId: 'abc123' } },
{ type: 'inside', store: { traceId: 'abc123' } },
{ type: 'end', store: { traceId: 'abc123' } },
]);
// Store should be undefined outside
assert.strictEqual(store.getStore(), undefined);
}
// Test run without subscribers
{
const boundedChannel = dc.boundedChannel('test-run-no-subs');
const result = boundedChannel.run({}, () => {
return 'fast path';
});
assert.strictEqual(result, 'fast path');
}
@@ -0,0 +1,90 @@
/* eslint-disable no-unused-vars */
'use strict';
require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test scope with thrown error
{
const boundedChannel = dc.boundedChannel('test-scope-throw');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
const context = { id: 1 };
const testError = new Error('thrown error');
assert.throws(() => {
using scope = boundedChannel.withScope(context);
context.result = 'partial';
throw testError;
}, testError);
// End event should still be published
assert.strictEqual(events.length, 2);
assert.strictEqual(events[0].type, 'start');
assert.strictEqual(events[1].type, 'end');
// Context should have partial result but no error from throw
assert.strictEqual(context.result, 'partial');
assert.strictEqual(context.error, undefined);
}
// Test store restoration on error
{
const boundedChannel = dc.boundedChannel('test-scope-store-error');
const store = new AsyncLocalStorage();
boundedChannel.start.bindStore(store, (context) => context.value);
boundedChannel.subscribe({
start() {},
end() {},
});
store.enterWith('before');
assert.strictEqual(store.getStore(), 'before');
const testError = new Error('test');
assert.throws(() => {
using scope = boundedChannel.withScope({ value: 'during' });
assert.strictEqual(store.getStore(), 'during');
throw testError;
}, testError);
// Store should be restored even after error
assert.strictEqual(store.getStore(), 'before');
}
// Test dispose during exception handling
{
const boundedChannel = dc.boundedChannel('test-scope-dispose-exception');
const events = [];
boundedChannel.subscribe({
start() {
events.push('start');
},
end() {
events.push('end');
},
});
// Dispose should complete even when exception is thrown
assert.throws(() => {
using scope = boundedChannel.withScope({});
throw new Error('original error');
}, /original error/);
// End event should have been called
assert.deepStrictEqual(events, ['start', 'end']);
}
@@ -0,0 +1,257 @@
/* eslint-disable no-unused-vars */
'use strict';
require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test nested scopes
{
const boundedChannel = dc.boundedChannel('test-nested-basic');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', id: message.id });
},
end(message) {
events.push({ type: 'end', id: message.id });
},
});
{
using outer = boundedChannel.withScope({ id: 'outer' });
events.push({ type: 'work', id: 'outer' });
{
using inner = boundedChannel.withScope({ id: 'inner' });
events.push({ type: 'work', id: 'inner' });
}
events.push({ type: 'work', id: 'outer-after' });
}
assert.strictEqual(events.length, 7);
assert.deepStrictEqual(events[0], { type: 'start', id: 'outer' });
assert.deepStrictEqual(events[1], { type: 'work', id: 'outer' });
assert.deepStrictEqual(events[2], { type: 'start', id: 'inner' });
assert.deepStrictEqual(events[3], { type: 'work', id: 'inner' });
assert.deepStrictEqual(events[4], { type: 'end', id: 'inner' });
assert.deepStrictEqual(events[5], { type: 'work', id: 'outer-after' });
assert.deepStrictEqual(events[6], { type: 'end', id: 'outer' });
}
// Test nested scopes with stores
{
const boundedChannel = dc.boundedChannel('test-nested-stores');
const store = new AsyncLocalStorage();
const storeValues = [];
boundedChannel.start.bindStore(store, (context) => context.id);
boundedChannel.subscribe({
start() {},
end() {},
});
assert.strictEqual(store.getStore(), undefined);
{
using outer = boundedChannel.withScope({ id: 'outer' });
storeValues.push(store.getStore());
{
using inner = boundedChannel.withScope({ id: 'inner' });
storeValues.push(store.getStore());
}
// Should restore to outer
storeValues.push(store.getStore());
}
// Should restore to undefined
storeValues.push(store.getStore());
assert.deepStrictEqual(storeValues, ['outer', 'inner', 'outer', undefined]);
}
// Test nested scopes with different channels
{
const channel1 = dc.boundedChannel('test-nested-chan1');
const channel2 = dc.boundedChannel('test-nested-chan2');
const events = [];
channel1.subscribe({
start({ ...data }) {
events.push({ channel: 1, type: 'start', data });
},
end({ ...data }) {
events.push({ channel: 1, type: 'end', data });
},
});
channel2.subscribe({
start({ ...data }) {
events.push({ channel: 2, type: 'start', data });
},
end({ ...data }) {
events.push({ channel: 2, type: 'end', data });
},
});
const contextA = { id: 'A' };
const contextB = { id: 'B' };
{
using scope1 = channel1.withScope(contextA);
{
using scope2 = channel2.withScope(contextB);
contextB.result = 'B-result';
}
contextA.result = 'A-result';
}
assert.strictEqual(events.length, 4);
assert.deepStrictEqual(events, [
{ channel: 1, type: 'start', data: { id: 'A' } },
{ channel: 2, type: 'start', data: { id: 'B' } },
{ channel: 2, type: 'end', data: { id: 'B', result: 'B-result' } },
{ channel: 1, type: 'end', data: { id: 'A', result: 'A-result' } },
]);
}
// Test nested scopes with shared store
{
const channel1 = dc.boundedChannel('test-nested-shared1');
const channel2 = dc.boundedChannel('test-nested-shared2');
const store = new AsyncLocalStorage();
const storeValues = [];
channel1.start.bindStore(store, (context) => ({ from: 'channel1', ...context }));
channel2.start.bindStore(store, (context) => ({ from: 'channel2', ...context }));
channel1.subscribe({ start() {}, end() {} });
channel2.subscribe({ start() {}, end() {} });
{
using scope1 = channel1.withScope({ id: 1 });
storeValues.push({ ...store.getStore() });
{
using scope2 = channel2.withScope({ id: 2 });
storeValues.push({ ...store.getStore() });
}
// Should restore to channel1's store value
storeValues.push({ ...store.getStore() });
}
assert.strictEqual(storeValues.length, 3);
assert.deepStrictEqual(storeValues[0], { from: 'channel1', id: 1 });
assert.deepStrictEqual(storeValues[1], { from: 'channel2', id: 2 });
assert.deepStrictEqual(storeValues[2], { from: 'channel1', id: 1 });
}
// Test deeply nested scopes
{
const boundedChannel = dc.boundedChannel('test-nested-deep');
const store = new AsyncLocalStorage();
const depths = [];
boundedChannel.start.bindStore(store, (context) => context.depth);
boundedChannel.subscribe({
start() {},
end() {},
});
{
using s1 = boundedChannel.withScope({ depth: 1 });
depths.push(store.getStore());
{
using s2 = boundedChannel.withScope({ depth: 2 });
depths.push(store.getStore());
{
using s3 = boundedChannel.withScope({ depth: 3 });
depths.push(store.getStore());
{
using s4 = boundedChannel.withScope({ depth: 4 });
depths.push(store.getStore());
}
depths.push(store.getStore());
}
depths.push(store.getStore());
}
depths.push(store.getStore());
}
depths.push(store.getStore());
assert.deepStrictEqual(depths, [1, 2, 3, 4, 3, 2, 1, undefined]);
}
// Test nested scopes with errors
{
const boundedChannel = dc.boundedChannel('test-nested-error');
const store = new AsyncLocalStorage();
const events = [];
boundedChannel.start.bindStore(store, (context) => context.id);
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', id: message.id });
},
end(message) {
events.push({ type: 'end', id: message.id });
},
});
const testError = new Error('inner error');
assert.throws(() => {
using outer = boundedChannel.withScope({ id: 'outer' });
events.push({ type: 'store', value: store.getStore() });
assert.throws(() => {
using inner = boundedChannel.withScope({ id: 'inner' });
events.push({ type: 'store', value: store.getStore() });
throw testError;
}, testError);
// After inner error, should be back to outer store
events.push({ type: 'store', value: store.getStore() });
throw new Error('outer error');
}, /outer error/);
// Both start and end events should have been published for both scopes
assert.strictEqual(events[0].type, 'start');
assert.strictEqual(events[0].id, 'outer');
assert.strictEqual(events[1].type, 'store');
assert.strictEqual(events[1].value, 'outer');
assert.strictEqual(events[2].type, 'start');
assert.strictEqual(events[2].id, 'inner');
assert.strictEqual(events[3].type, 'store');
assert.strictEqual(events[3].value, 'inner');
assert.strictEqual(events[4].type, 'end');
assert.strictEqual(events[4].id, 'inner');
assert.strictEqual(events[5].type, 'store');
assert.strictEqual(events[5].value, 'outer');
assert.strictEqual(events[6].type, 'end');
assert.strictEqual(events[6].id, 'outer');
// Store should be restored
assert.strictEqual(store.getStore(), undefined);
}
@@ -0,0 +1,66 @@
'use strict';
const common = require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test BoundedChannelScope with transform error
// Transform errors are scheduled via process.nextTick(triggerUncaughtException)
const boundedChannel = dc.boundedChannel('test-transform-error');
const store = new AsyncLocalStorage();
const events = [];
const transformError = new Error('transform failed');
// Set up uncaughtException handler to catch the transform error
process.on('uncaughtException', common.mustCall((err) => {
assert.strictEqual(err, transformError);
events.push('uncaughtException');
}));
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
// Bind store with a transform that throws
boundedChannel.start.bindStore(store, () => {
throw transformError;
});
// Store should remain undefined since transform will fail
assert.strictEqual(store.getStore(), undefined);
const context = { id: 123 };
{
// eslint-disable-next-line no-unused-vars
using scope = boundedChannel.withScope(context);
// Store should still be undefined because transform threw
assert.strictEqual(store.getStore(), undefined);
events.push('inside-scope');
context.result = 42;
}
// Store should still be undefined after scope exit
assert.strictEqual(store.getStore(), undefined);
// Start and end events should still be published despite transform error
assert.strictEqual(events.length, 3);
assert.strictEqual(events[0].type, 'start');
assert.strictEqual(events[0].data.id, 123);
assert.strictEqual(events[1], 'inside-scope');
assert.strictEqual(events[2].type, 'end');
assert.strictEqual(events[2].data.result, 42);
// Validate uncaughtException was triggered via nextTick
process.on('beforeExit', common.mustCall(() => {
assert.strictEqual(events.length, 4);
assert.strictEqual(events[3], 'uncaughtException');
}));
@@ -0,0 +1,206 @@
/* eslint-disable no-unused-vars */
'use strict';
require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test basic scope with using
{
const boundedChannel = dc.boundedChannel('test-scope-basic');
const events = [];
boundedChannel.subscribe({
start({ ...data }) {
events.push({ type: 'start', data });
},
end({ ...data }) {
events.push({ type: 'end', data });
},
});
const context = { id: 123 };
{
using scope = boundedChannel.withScope(context);
assert.ok(scope);
context.value = 'inside';
}
assert.strictEqual(events.length, 2);
assert.deepStrictEqual(events, [
{
type: 'start',
data: { id: 123 }
},
{
type: 'end',
data: {
id: 123,
value: 'inside'
}
},
]);
}
// Test scope with result setter
{
const boundedChannel = dc.boundedChannel('test-scope-result');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
const context = {};
{
using scope = boundedChannel.withScope(context);
context.result = 42;
}
assert.strictEqual(context.result, 42);
assert.strictEqual(events.length, 2);
assert.strictEqual(events[1].data.result, 42);
}
// Test scope with error setter
{
const boundedChannel = dc.boundedChannel('test-scope-error-setter');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', data: message });
},
end(message) {
events.push({ type: 'end', data: message });
},
});
const context = {};
{
using scope = boundedChannel.withScope(context);
context.result = 'test result';
}
// BoundedChannel does not handle errors - only start and end
assert.strictEqual(context.result, 'test result');
assert.strictEqual(events.length, 2);
assert.strictEqual(events[0].type, 'start');
assert.strictEqual(events[1].type, 'end');
}
// Test scope with AsyncLocalStorage
{
const boundedChannel = dc.boundedChannel('test-scope-store');
const store = new AsyncLocalStorage();
const events = [];
boundedChannel.start.bindStore(store, (context) => {
return { traceId: context.traceId };
});
boundedChannel.subscribe({
start(message) {
events.push({ type: 'start', store: store.getStore() });
},
end(message) {
events.push({ type: 'end', store: store.getStore() });
},
});
assert.strictEqual(store.getStore(), undefined);
{
using scope = boundedChannel.withScope({ traceId: 'xyz789' });
// Store should be set inside scope
assert.deepStrictEqual(store.getStore(), { traceId: 'xyz789' });
events.push({ type: 'inside', store: store.getStore() });
}
// Store should be restored after scope
assert.strictEqual(store.getStore(), undefined);
assert.strictEqual(events.length, 3);
assert.strictEqual(events[0].type, 'start');
assert.deepStrictEqual(events[0].store, { traceId: 'xyz789' });
assert.strictEqual(events[1].type, 'inside');
assert.deepStrictEqual(events[1].store, { traceId: 'xyz789' });
assert.strictEqual(events[2].type, 'end');
assert.deepStrictEqual(events[2].store, { traceId: 'xyz789' });
}
// Test scope without subscribers (no-op)
{
const boundedChannel = dc.boundedChannel('test-scope-no-subs');
const context = {};
{
using scope = boundedChannel.withScope(context);
context.result = 'value';
}
// Context should still be updated even without subscribers
assert.strictEqual(context.result, 'value');
}
// Test manual dispose via Symbol.dispose
{
const boundedChannel = dc.boundedChannel('test-scope-manual');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push('start');
},
end(message) {
events.push('end');
},
});
const scope = boundedChannel.withScope({});
assert.strictEqual(events.length, 1);
assert.strictEqual(events[0], 'start');
scope[Symbol.dispose]();
assert.strictEqual(events.length, 2);
assert.strictEqual(events[1], 'end');
// Double dispose should be idempotent
scope[Symbol.dispose]();
assert.strictEqual(events.length, 2);
}
// Test scope with store restore to previous value
{
const boundedChannel = dc.boundedChannel('test-scope-restore');
const store = new AsyncLocalStorage();
boundedChannel.start.bindStore(store, (context) => context.value);
boundedChannel.subscribe({
start() {},
end() {},
});
store.enterWith('initial');
assert.strictEqual(store.getStore(), 'initial');
{
using scope = boundedChannel.withScope({ value: 'scoped' });
assert.strictEqual(store.getStore(), 'scoped');
}
// Should restore to previous value
assert.strictEqual(store.getStore(), 'initial');
}
@@ -0,0 +1,105 @@
'use strict';
require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
// Test BoundedChannel exports
{
assert.strictEqual(typeof dc.boundedChannel, 'function');
assert.strictEqual(typeof dc.BoundedChannel, 'function');
const wc = dc.boundedChannel('test-export');
assert.ok(wc instanceof dc.BoundedChannel);
}
// Test basic BoundedChannel creation and properties
{
const boundedChannel = dc.boundedChannel('test-window-basic');
assert.ok(boundedChannel.start);
assert.ok(boundedChannel.end);
assert.strictEqual(boundedChannel.start.name, 'tracing:test-window-basic:start');
assert.strictEqual(boundedChannel.end.name, 'tracing:test-window-basic:end');
assert.strictEqual(boundedChannel.hasSubscribers, false);
assert.strictEqual(typeof boundedChannel.subscribe, 'function');
assert.strictEqual(typeof boundedChannel.unsubscribe, 'function');
assert.strictEqual(typeof boundedChannel.run, 'function');
assert.strictEqual(typeof boundedChannel.withScope, 'function');
}
// Test BoundedChannel with channel objects
{
const startChannel = dc.channel('custom:start');
const endChannel = dc.channel('custom:end');
const boundedChannel = dc.boundedChannel({
start: startChannel,
end: endChannel,
});
assert.strictEqual(boundedChannel.start, startChannel);
assert.strictEqual(boundedChannel.end, endChannel);
}
// Test subscribe/unsubscribe
{
const boundedChannel = dc.boundedChannel('test-window-subscribe');
const events = [];
const handlers = {
start(message) {
events.push({ type: 'start', message });
},
end(message) {
events.push({ type: 'end', message });
},
};
assert.strictEqual(boundedChannel.hasSubscribers, false);
boundedChannel.subscribe(handlers);
assert.strictEqual(boundedChannel.hasSubscribers, true);
// Test that events are received
boundedChannel.start.publish({ test: 'start' });
boundedChannel.end.publish({ test: 'end' });
assert.strictEqual(events.length, 2);
assert.strictEqual(events[0].type, 'start');
assert.strictEqual(events[0].message.test, 'start');
assert.strictEqual(events[1].type, 'end');
assert.strictEqual(events[1].message.test, 'end');
// Test unsubscribe
const result = boundedChannel.unsubscribe(handlers);
assert.strictEqual(result, true);
assert.strictEqual(boundedChannel.hasSubscribers, false);
// Test unsubscribe when not subscribed
const result2 = boundedChannel.unsubscribe(handlers);
assert.strictEqual(result2, false);
}
// Test partial subscription
{
const boundedChannel = dc.boundedChannel('test-window-partial');
const events = [];
boundedChannel.subscribe({
start(message) {
events.push('start');
},
});
assert.strictEqual(boundedChannel.hasSubscribers, true);
boundedChannel.start.publish({});
boundedChannel.end.publish({});
assert.strictEqual(events.length, 1);
assert.strictEqual(events[0], 'start');
}
@@ -0,0 +1,57 @@
'use strict';
const common = require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test RunStoresScope with transform error
// Transform errors are scheduled via process.nextTick(triggerUncaughtException)
const channel = dc.channel('test-transform-error');
const store = new AsyncLocalStorage();
const events = [];
const transformError = new Error('transform failed');
// Set up uncaughtException handler to catch the transform error
process.on('uncaughtException', common.mustCall((err) => {
assert.strictEqual(err, transformError);
events.push('uncaughtException');
}));
channel.subscribe((message) => {
events.push({ type: 'message', data: message });
});
// Bind store with a transform that throws
channel.bindStore(store, () => {
throw transformError;
});
// Store should remain undefined since transform failed
assert.strictEqual(store.getStore(), undefined);
{
// eslint-disable-next-line no-unused-vars
using scope = channel.withStoreScope({ value: 'test' });
// Store should still be undefined because transform threw
assert.strictEqual(store.getStore(), undefined);
events.push('inside-scope');
}
// Store should still be undefined after scope exit
assert.strictEqual(store.getStore(), undefined);
// Message should still be published despite transform error
assert.strictEqual(events.length, 2);
assert.strictEqual(events[0].type, 'message');
assert.strictEqual(events[0].data.value, 'test');
assert.strictEqual(events[1], 'inside-scope');
// Validate uncaughtException was triggered via nextTick
process.on('beforeExit', common.mustCall(() => {
assert.strictEqual(events.length, 3);
assert.strictEqual(events[2], 'uncaughtException');
}));
@@ -0,0 +1,206 @@
/* eslint-disable no-unused-vars */
'use strict';
require('../common');
const assert = require('node:assert');
const dc = require('node:diagnostics_channel');
const { AsyncLocalStorage } = require('node:async_hooks');
// Test basic RunStoresScope with active channel
{
const channel = dc.channel('test-run-stores-scope-basic');
const store = new AsyncLocalStorage();
const events = [];
channel.subscribe((message) => {
events.push({ type: 'message', data: message, store: store.getStore() });
});
channel.bindStore(store, (data) => {
return { transformed: data.value };
});
assert.strictEqual(store.getStore(), undefined);
{
using scope = channel.withStoreScope({ value: 'test' });
// Store should be set
assert.deepStrictEqual(store.getStore(), { transformed: 'test' });
events.push({ type: 'inside', store: store.getStore() });
}
// Store should be restored
assert.strictEqual(store.getStore(), undefined);
assert.strictEqual(events.length, 2);
assert.strictEqual(events[0].type, 'message');
assert.strictEqual(events[0].data.value, 'test');
assert.deepStrictEqual(events[0].store, { transformed: 'test' });
assert.strictEqual(events[1].type, 'inside');
assert.deepStrictEqual(events[1].store, { transformed: 'test' });
}
// Test RunStoresScope with inactive channel (no-op)
{
const channel = dc.channel('test-run-stores-scope-inactive');
// No subscribers, channel is inactive
{
using scope = channel.withStoreScope({ value: 'test' });
assert.ok(scope);
}
// Should not throw
}
// Test RunStoresScope restores previous store value
{
const channel = dc.channel('test-run-stores-scope-restore');
const store = new AsyncLocalStorage();
channel.subscribe(() => {});
channel.bindStore(store, (data) => data);
store.enterWith('initial');
assert.strictEqual(store.getStore(), 'initial');
{
using scope = channel.withStoreScope('scoped');
assert.strictEqual(store.getStore(), 'scoped');
}
// Should restore to previous value
assert.strictEqual(store.getStore(), 'initial');
}
// Test RunStoresScope with multiple stores
{
const channel = dc.channel('test-run-stores-scope-multi');
const store1 = new AsyncLocalStorage();
const store2 = new AsyncLocalStorage();
const store3 = new AsyncLocalStorage();
channel.subscribe(() => {});
channel.bindStore(store1, (data) => `${data}-1`);
channel.bindStore(store2, (data) => `${data}-2`);
channel.bindStore(store3, (data) => `${data}-3`);
{
using scope = channel.withStoreScope('test');
assert.strictEqual(store1.getStore(), 'test-1');
assert.strictEqual(store2.getStore(), 'test-2');
assert.strictEqual(store3.getStore(), 'test-3');
}
assert.strictEqual(store1.getStore(), undefined);
assert.strictEqual(store2.getStore(), undefined);
assert.strictEqual(store3.getStore(), undefined);
}
// Test manual dispose via Symbol.dispose
{
const channel = dc.channel('test-run-stores-scope-manual');
const store = new AsyncLocalStorage();
const events = [];
channel.subscribe((message) => {
events.push(message);
});
channel.bindStore(store, (data) => data);
const scope = channel.withStoreScope('test');
assert.strictEqual(events.length, 1);
assert.strictEqual(store.getStore(), 'test');
scope[Symbol.dispose]();
// Store should be restored
assert.strictEqual(store.getStore(), undefined);
// Double dispose should be idempotent
scope[Symbol.dispose]();
assert.strictEqual(store.getStore(), undefined);
}
// Test nested RunStoresScope
{
const channel = dc.channel('test-run-stores-scope-nested');
const store = new AsyncLocalStorage();
const storeValues = [];
channel.subscribe(() => {});
channel.bindStore(store, (data) => data);
{
using outer = channel.withStoreScope('outer');
storeValues.push(store.getStore());
{
using inner = channel.withStoreScope('inner');
storeValues.push(store.getStore());
}
// Should restore to outer
storeValues.push(store.getStore());
}
// Should restore to undefined
storeValues.push(store.getStore());
assert.deepStrictEqual(storeValues, ['outer', 'inner', 'outer', undefined]);
}
// Test RunStoresScope with error during usage
{
const channel = dc.channel('test-run-stores-scope-error');
const store = new AsyncLocalStorage();
channel.subscribe(() => {});
channel.bindStore(store, (data) => data);
store.enterWith('before');
const testError = new Error('test');
assert.throws(() => {
using scope = channel.withStoreScope('during');
assert.strictEqual(store.getStore(), 'during');
throw testError;
}, testError);
// Store should be restored even after error
assert.strictEqual(store.getStore(), 'before');
}
// Test RunStoresScope with inactive channel (no stores or subscribers)
{
const channel = dc.channel('test-run-stores-scope-inactive');
// Channel is inactive (no subscribers or bound stores)
{
using scope = channel.withStoreScope('test');
// No-op disposable, nothing happens
assert.ok(scope);
}
}
// Test RunStoresScope with Symbol.dispose
{
const channel = dc.channel('test-run-stores-scope-symbol');
const store = new AsyncLocalStorage();
channel.subscribe(() => {});
channel.bindStore(store, (data) => data);
const scope = channel.withStoreScope('test');
assert.strictEqual(store.getStore(), 'test');
// Call Symbol.dispose directly
scope[Symbol.dispose]();
assert.strictEqual(store.getStore(), undefined);
}
@@ -16,7 +16,7 @@ channel.start.bindStore(store, common.mustCall(() => {
return firstContext;
}));
channel.asyncStart.bindStore(store, common.mustNotCall(() => {
channel.asyncStart.bindStore(store, common.mustCall(() => {
return secondContext;
}));
@@ -27,5 +27,7 @@ channel.tracePromise(common.mustCall(async () => {
// Should _not_ switch to second context as promises don't have an "after"
// point at which to do a runStores.
assert.deepStrictEqual(store.getStore(), firstContext);
})).then(common.mustCall(() => {
assert.strictEqual(store.getStore(), undefined);
}));
assert.strictEqual(store.getStore(), undefined);