diff --git a/benchmark/diagnostics_channel/publish-bypass.js b/benchmark/diagnostics_channel/publish-bypass.js new file mode 100644 index 000000000000..1ed1cdfec9e8 --- /dev/null +++ b/benchmark/diagnostics_channel/publish-bypass.js @@ -0,0 +1,47 @@ +'use strict'; +const common = require('../common.js'); +const dc = require('node:diagnostics_channel'); + +// This benchmark requires a binary supporting bypassId and cannot run on main. + +const bench = common.createBenchmark(main, { + mode: ['normal', 'bypass-idle', 'bypass-active'], + n: [1e7], + subscribers: [1, 10], +}); + +function noop() {} + +function main({ mode, n, subscribers }) { + const channel = dc.channel('test'); + const key = Symbol('key'); + const data = {}; + + for (let i = 0; i < subscribers; i++) { + if (mode === 'normal') { + channel.subscribe(noop); + } else { + channel.subscribe(noop, { bypassId: key }); + } + } + + const publish = () => { + bench.start(); + for (let i = 0; i < n; i++) { + channel.publish(data); + } + bench.end(n); + }; + + switch (mode) { + case 'normal': + case 'bypass-idle': + publish(); + break; + case 'bypass-active': + dc.bypass(key, publish); + break; + default: + throw new Error(`Unsupported mode: ${mode}`); + } +} diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 25e544ccf27b..78d0547c9782 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -231,6 +231,154 @@ diagnostics_channel.subscribe('my-channel', onMessage); diagnostics_channel.unsubscribe('my-channel', onMessage); ``` +#### `diagnostics_channel.bypass(key, fn[, thisArg[, ...args]])` + + + +> Stability: 1.1 - Active development + +* `key` {symbol|Object} The bypass identity token. Subscribers and + stores registered with the same `bypassId` value will be skipped + while this function executes. +* `fn` {Function} The function to run with bypass active. +* `thisArg` {any} The receiver to use for the function call. +* `...args` {any} Optional arguments to pass to the function. +* Returns: {any} The return value of `fn`. + +Calls `fn` and skips any channel subscribers or bound stores that +were registered with a matching `bypassId` key. The skip behavior +also applies to any async continuations (Promises, timers, +microtasks) within `fn`. + +Subscribers and stores registered with `bypassId` run after all +regular subscribers and stores on the same channel, regardless of +registration order. This applies to both `publish()` and `runStores()`. + +```mjs +import diagnostics_channel from 'node:diagnostics_channel'; +import { request } from 'node:http'; + +const { channel, bypass } = diagnostics_channel; + +// A unique token identifying this APM tool +const kMyTracer = Symbol('my-tracer'); + +// Subscribe to HTTP requests, but opt into bypass +channel('http.client.request.start').subscribe((message) => { + console.log('HTTP request:', message.url); +}, { bypassId: kMyTracer }); + +// When exporting traces internally, use bypass() so the +// above subscriber is NOT triggered for this internal request +function exportTraces(data) { + bypass(kMyTracer, () => { + // This HTTP request will NOT trigger the subscriber above + const req = request('https://my-apm-backend.example.com/traces', { + method: 'POST', + }); + req.end(); + }); +} +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); +const { request } = require('node:http'); + +const { channel, bypass } = diagnostics_channel; + +// A unique token identifying this APM tool +const kMyTracer = Symbol('my-tracer'); + +// Subscribe to HTTP requests, but opt into bypass +channel('http.client.request.start').subscribe((message) => { + console.log('HTTP request:', message.url); +}, { bypassId: kMyTracer }); + +// When exporting traces internally, use bypass() so the +// above subscriber is NOT triggered for this internal request +function exportTraces(data) { + bypass(kMyTracer, () => { + // This HTTP request will NOT trigger the subscriber above + const req = request('https://my-apm-backend.example.com/traces', { + method: 'POST', + }); + req.end(); + }); +} +``` + +Without `bypass()`, the internal `exportTraces()` HTTP request +would trigger the subscriber, which would try to export a trace +of the export, causing infinite recursion. + +The bypass context propagates across async boundaries: + +```mjs +// bypass() works across Promise boundaries +await bypass(kMyTracer, async () => { + await someAsyncOperation(); // still bypassed + channel('http.client.request.start').publish({}); // subscriber skipped +}); + +// And across timers +bypass(kMyTracer, () => { + setImmediate(() => { + // Still bypassed here + channel('http.client.request.start').publish({}); + }); +}); +``` + +```cjs +(async () => { + await bypass(kMyTracer, async () => { + await someAsyncOperation(); + channel('http.client.request.start').publish({}); + }); + bypass(kMyTracer, () => { + setImmediate(() => { + channel('http.client.request.start').publish({}); + }); + }); +})(); +``` + +Multiple tools can each use their own `bypassId` without +interfering with each other: + +```mjs +const kToolA = Symbol('tool-a'); +const kToolB = Symbol('tool-b'); + +channel('http.client.request.start').subscribe(handlerA, { bypassId: kToolA }); +channel('http.client.request.start').subscribe(handlerB, { bypassId: kToolB }); + +// Only handlerA is skipped, handlerB still fires +bypass(kToolA, () => { + channel('http.client.request.start').publish({}); +}); +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); + +const { channel, bypass } = diagnostics_channel; + +const kToolA = Symbol('tool-a'); +const kToolB = Symbol('tool-b'); + +channel('http.client.request.start').subscribe(handlerA, { bypassId: kToolA }); +channel('http.client.request.start').subscribe(handlerB, { bypassId: kToolB }); + +// Only handlerA is skipped, handlerB still fires +bypass(kToolA, () => { + channel('http.client.request.start').publish({}); +}); +``` + #### `diagnostics_channel.tracingChannel(nameOrChannels)` > Stability: 1 - Experimental * `store` {AsyncLocalStorage} The store to which to bind the context data * `transform` {Function} Transform context data before setting the store context +* `options` {Object} + * `bypassId` {symbol|Object} An optional identity token. When + provided, this bound store will be skipped while + [`diagnostics_channel.bypass()`][] is active with the same key. + Stores registered with `bypassId` run after all regular stores + on the same channel, regardless of registration order. When [`channel.runStores(context, ...)`][] is called, the given context data will be applied to any store bound to the channel. If the store has already been bound the previous `transform` function will be replaced with the new one. +Rebinding a store with or without `bypassId` moves it between the regular and +bypass groups. The `transform` function may be omitted to set the given context data as the context directly. @@ -569,6 +740,8 @@ channel.bindStore(store, (data) => { }); ``` +See [`diagnostics_channel.bypass()`][] for usage with `bypassId`. + #### `channel.unbindStore(store)` * `subscribers` {Object} Set of [TracingChannel Channels][] subscribers @@ -778,6 +955,11 @@ added: * `asyncStart` {Function} The [`asyncStart` event][] subscriber * `asyncEnd` {Function} The [`asyncEnd` event][] subscriber * `error` {Function} The [`error` event][] subscriber +* `options` {Object} + * `bypassId` {symbol|Object} An optional identity token. When + provided, ALL handlers (start, end, asyncStart, asyncEnd, error) + will be skipped while [`diagnostics_channel.bypass()`][] is + active with the same key. Helper to subscribe a collection of functions to the corresponding channels. This is the same as calling [`channel.subscribe(onMessage)`][] on each channel @@ -831,6 +1013,52 @@ channels.subscribe({ }); ``` +To opt all TracingChannel handlers into bypass behavior: + +```mjs +import diagnostics_channel from 'node:diagnostics_channel'; + +const { tracingChannel, bypass } = diagnostics_channel; +const kMyTool = Symbol('my-tool'); +const tc = tracingChannel('my-operation'); + +// All TracingChannel events skipped when bypass(kMyTool) is active +tc.subscribe({ + start(message) { /* ... */ }, + end(message) { /* ... */ }, + asyncStart(message) { /* ... */ }, + asyncEnd(message) { /* ... */ }, +}, { bypassId: kMyTool }); + +bypass(kMyTool, () => { + tc.traceSync(() => { + // Start and end handlers are NOT called + }); +}); +``` + +```cjs +const diagnostics_channel = require('node:diagnostics_channel'); + +const { tracingChannel, bypass } = diagnostics_channel; +const kMyTool = Symbol('my-tool'); +const tc = tracingChannel('my-operation'); + +// All TracingChannel events skipped when bypass(kMyTool) is active +tc.subscribe({ + start(message) { /* ... */ }, + end(message) { /* ... */ }, + asyncStart(message) { /* ... */ }, + asyncEnd(message) { /* ... */ }, +}, { bypassId: kMyTool }); + +bypass(kMyTool, () => { + tc.traceSync(() => { + // Start and end handlers are NOT called + }); +}); +``` + #### `tracingChannel.unsubscribe(subscribers)` * `handlers` {Object} Set of channel subscribers * `start` {Function} The start event subscriber * `end` {Function} The end event subscriber +* `options` {Object} + * `bypassId` {symbol|Object} An optional identity token. When + provided, this subscriber will be skipped while + [`diagnostics_channel.bypass()`][] is active with the same key. + Subscribers registered with `bypassId` run after all regular + subscribers on the same channel, regardless of registration order. Subscribe to the bounded channel events. This is equivalent to calling [`channel.subscribe(onMessage)`][] on each channel individually. @@ -2059,6 +2297,7 @@ statement, since both are still in use while the event is being delivered; see [`channel.withStoreScope(data)`]: #channelwithstorescopedata [`child_process.spawn()`]: child_process.md#child_processspawncommand-args-options [`database.close()`]: sqlite.md#databaseclose +[`diagnostics_channel.bypass()`]: #diagnostics_channelbypasskey-fn-thisarg-args [`diagnostics_channel.channel(name)`]: #diagnostics_channelchannelname [`diagnostics_channel.subscribe(name, onMessage)`]: #diagnostics_channelsubscribename-onmessage [`diagnostics_channel.tracingChannel()`]: #diagnostics_channeltracingchannelnameorchannels diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index bb0c7d66050c..4c6d3ef20b7e 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -7,6 +7,9 @@ const { ArrayPrototypePushApply, ArrayPrototypeSlice, ArrayPrototypeSplice, + DisposableStack, + DisposableStackPrototypeMove, + DisposableStackPrototypeUse, ObjectDefineProperty, ObjectGetPrototypeOf, ObjectSetPrototypeOf, @@ -15,12 +18,12 @@ const { ReflectApply, SafeFinalizationRegistry, SafeMap, + SafeSet, SymbolDispose, SymbolHasInstance, } = primordials; const { - aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, }, @@ -38,6 +41,33 @@ const dc_binding = internalBinding('diagnostics_channel'); const { WeakReference, kEmptyObject } = require('internal/util'); const { isPromise } = require('internal/util/types'); +let bypassStorage; + +function getBypassStorage() { + if (bypassStorage === undefined) { + const { AsyncLocalStorage } = require('async_hooks'); + bypassStorage = new AsyncLocalStorage(); + } + return bypassStorage; +} + +function withBypassContext(set, fn, thisArg, args) { + return getBypassStorage().run( + set, + () => ReflectApply(fn, thisArg, args), + ); +} + +function validateBypassKey(value, name) { + if (value == null) { + throw new ERR_INVALID_ARG_TYPE(name, ['object', 'symbol'], value); + } + const type = typeof value; + if (type !== 'object' && type !== 'symbol') { + throw new ERR_INVALID_ARG_TYPE(name, ['object', 'symbol'], value); + } +} + // 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. class WeakRefMap extends SafeMap { @@ -73,7 +103,9 @@ function markActive(channel) { // eslint-disable-next-line no-use-before-define ObjectSetPrototypeOf(channel, ActiveChannel.prototype); channel._subscribers = []; + channel._bypassSubscribers = null; channel._stores = new SafeMap(); + channel._bypassStores = null; // Notify native modules that this channel just got its first subscriber. if (channel._index !== undefined) @@ -82,7 +114,10 @@ function markActive(channel) { function maybeMarkInactive(channel) { // When there are no more active subscribers or bound, restore to fast prototype. - if (!channel._subscribers.length && !channel._stores.size) { + if (!channel._subscribers.length && + !channel._stores.size && + !channel._bypassSubscribers?.length && + !channel._bypassStores?.size) { // Notify native modules that this channel just lost its last subscriber. if (channel._index !== undefined) dc_binding.notifyChannelInactive(channel._index); @@ -91,35 +126,22 @@ function maybeMarkInactive(channel) { ObjectSetPrototypeOf(channel, Channel.prototype); channel._subscribers = undefined; channel._stores = undefined; + channel._bypassSubscribers = undefined; + channel._bypassStores = undefined; } } -function disposeStoreScopes(stack, error, hasError = false) { - for (let i = stack.length - 1; i >= 0; i--) { - try { - stack[i][SymbolDispose](); - } catch (err) { - error = hasError ? aggregateTwoErrors(err, error) : err; - hasError = true; - } - } - - if (hasError) throw error; -} - class RunStoresScope { #stack; constructor(activeChannel, data) { - // TODO: use native DisposableStack once supported in core - const stack = []; + using stack = new DisposableStack(); - // Enter stores using withScope + // Normal stores, unchanged from before. if (activeChannel._stores) { for (const entry of activeChannel._stores.entries()) { const store = entry[0]; const transform = entry[1]; - let newContext = data; if (transform) { try { @@ -131,12 +153,29 @@ class RunStoresScope { continue; } } + DisposableStackPrototypeUse(stack, store.withScope(newContext)); + } + } - try { - ArrayPrototypePush(stack, store.withScope(newContext)); - } catch (err) { - disposeStoreScopes(stack, err, true); + // Bypass stores, only checked when bypass stores exist. + if (activeChannel._bypassStores) { + const activeKeys = getBypassStorage().getStore(); + for (const entry of activeChannel._bypassStores.entries()) { + const store = entry[0]; + const { transform, bypassId } = entry[1]; + if (activeKeys?.has(bypassId)) continue; + let newContext = data; + if (transform) { + try { + newContext = transform(data); + } catch (err) { + process.nextTick(() => { + triggerUncaughtException(err, false); + }); + continue; + } } + DisposableStackPrototypeUse(stack, store.withScope(newContext)); } } @@ -144,67 +183,130 @@ class RunStoresScope { activeChannel.publish(data); // Transfer ownership of the stack - // TODO: Restore stack.move() when DisposableStack is restored in core to avoid broken behavior. - this.#stack = stack; + this.#stack = DisposableStackPrototypeMove(stack); } [SymbolDispose]() { - if (this.#stack !== undefined) { - const stack = this.#stack; - this.#stack = undefined; - - disposeStoreScopes(stack); - } + this.#stack[SymbolDispose](); } } // TODO(qard): should there be a C++ channel interface? class ActiveChannel { - subscribe(subscription) { + subscribe(subscription, options = kEmptyObject) { validateFunction(subscription, 'subscription'); - this._subscribers = ArrayPrototypeSlice(this._subscribers); - ArrayPrototypePush(this._subscribers, subscription); + const bypassId = options?.bypassId; + + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + // Bypass path, lazy separate array only allocated when needed. + if (this._bypassSubscribers === null) { + this._bypassSubscribers = []; + } + this._bypassSubscribers = ArrayPrototypeSlice(this._bypassSubscribers); + ArrayPrototypePush(this._bypassSubscribers, { handler: subscription, bypassId }); + } else { + // Normal path, plain function call with no extra overhead. + this._subscribers = ArrayPrototypeSlice(this._subscribers); + ArrayPrototypePush(this._subscribers, subscription); + } + channels.incRef(this.name); if (this._index !== undefined) dc_binding.subscribers[this._index]++; } unsubscribe(subscription) { const index = ArrayPrototypeIndexOf(this._subscribers, subscription); - if (index === -1) return false; - - const before = ArrayPrototypeSlice(this._subscribers, 0, index); - const after = ArrayPrototypeSlice(this._subscribers, index + 1); - this._subscribers = before; - ArrayPrototypePushApply(this._subscribers, after); + if (index !== -1) { + const before = ArrayPrototypeSlice(this._subscribers, 0, index); + const after = ArrayPrototypeSlice(this._subscribers, index + 1); + this._subscribers = before; + ArrayPrototypePushApply(this._subscribers, after); + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); + return true; + } + + // Check bypass subscribers + if (this._bypassSubscribers != null) { + let bypassIndex = -1; + for (let i = 0; i < this._bypassSubscribers.length; i++) { + if (this._bypassSubscribers[i].handler === subscription) { + bypassIndex = i; + break; + } + } + if (bypassIndex !== -1) { + const before = ArrayPrototypeSlice(this._bypassSubscribers, 0, bypassIndex); + const after = ArrayPrototypeSlice(this._bypassSubscribers, bypassIndex + 1); + this._bypassSubscribers = before; + ArrayPrototypePushApply(this._bypassSubscribers, after); + if (this._bypassSubscribers.length === 0) { + this._bypassSubscribers = null; + } + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); + return true; + } + } + return false; + } - channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; - maybeMarkInactive(this); + bindStore(store, transform, options = kEmptyObject) { + const bypassId = options?.bypassId; - return true; - } + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + } - bindStore(store, transform) { - const replacing = this._stores.has(store); + const replacing = this._stores.has(store) || this._bypassStores?.has(store); if (!replacing) { channels.incRef(this.name); if (this._index !== undefined) dc_binding.subscribers[this._index]++; } - this._stores.set(store, transform); + + if (bypassId !== undefined) { + this._stores.delete(store); + // Bypass path, lazy separate SafeMap only allocated when needed. + if (this._bypassStores === null) { + this._bypassStores = new SafeMap(); + } + this._bypassStores.set(store, { transform, bypassId }); + } else { + // No bypassId provided: store as a plain transform function, + // matching the pre-bypass-feature behavior exactly. + if (this._bypassStores?.has(store)) { + this._bypassStores.delete(store); + if (this._bypassStores.size === 0) { + this._bypassStores = null; + } + } + this._stores.set(store, transform); + } } unbindStore(store) { - if (!this._stores.has(store)) { - return false; + if (this._stores.has(store)) { + this._stores.delete(store); + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); + return true; + } + + if (this._bypassStores?.has(store)) { + this._bypassStores.delete(store); + if (this._bypassStores.size === 0) { + this._bypassStores = null; + } + channels.decRef(this.name); + if (this._index !== undefined) dc_binding.subscribers[this._index]--; + maybeMarkInactive(this); + return true; } - - this._stores.delete(store); - - channels.decRef(this.name); - if (this._index !== undefined) dc_binding.subscribers[this._index]--; - maybeMarkInactive(this); - - return true; + return false; } get hasSubscribers() { @@ -212,17 +314,34 @@ class ActiveChannel { } publish(data) { + // Normal path, no ALS lookup, plain function call, zero overhead. const subscribers = this._subscribers; - for (let i = 0; i < (subscribers?.length || 0); i++) { + for (let i = 0; i < subscribers.length; i++) { try { - const onMessage = subscribers[i]; - onMessage(data, this.name); + subscribers[i](data, this.name); } catch (err) { process.nextTick(() => { triggerUncaughtException(err, false); }); } } + + // Bypass path, only entered if bypass subscribers exist. + if (this._bypassSubscribers != null) { + const activeKeys = getBypassStorage().getStore(); + const bypassSubscribers = this._bypassSubscribers; + for (let i = 0; i < bypassSubscribers.length; i++) { + try { + const { handler, bypassId } = bypassSubscribers[i]; + if (activeKeys?.has(bypassId)) continue; + handler(data, this.name); + } catch (err) { + process.nextTick(() => { + triggerUncaughtException(err, false); + }); + } + } + } } withStoreScope(data) { @@ -243,6 +362,8 @@ class Channel { constructor(name) { this._subscribers = undefined; this._stores = undefined; + this._bypassSubscribers = undefined; + this._bypassStores = undefined; this.name = name; this._index = undefined; @@ -255,19 +376,27 @@ class Channel { prototype === ActiveChannel.prototype; } - subscribe(subscription) { + subscribe(subscription, options) { validateFunction(subscription, 'subscription'); + const bypassId = options?.bypassId; + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + } markActive(this); - this.subscribe(subscription); + this.subscribe(subscription, options); } unsubscribe() { return false; } - bindStore(store, transform) { + bindStore(store, transform, options) { + const bypassId = options?.bypassId; + if (bypassId !== undefined) { + validateBypassKey(bypassId, 'bypassId'); + } markActive(this); - this.bindStore(store, transform); + this.bindStore(store, transform, options); } unbindStore() { @@ -401,12 +530,12 @@ class BoundedChannel { this.end?.hasSubscribers; } - subscribe(handlers) { + subscribe(handlers, options) { for (let i = 0; i < boundedEvents.length; ++i) { const name = boundedEvents[i]; if (!handlers[name]) continue; - this[name]?.subscribe(handlers[name]); + this[name]?.subscribe(handlers[name], options); } } @@ -496,13 +625,13 @@ class TracingChannel { this.error?.hasSubscribers; } - subscribe(handlers) { + subscribe(handlers, options) { // Subscribe to call window (start/end) if (handlers.start || handlers.end) { this.#callWindow.subscribe({ start: handlers.start, end: handlers.end, - }); + }, options); } // Subscribe to continuation window (asyncStart/asyncEnd) @@ -510,12 +639,12 @@ class TracingChannel { this.#continuationWindow.subscribe({ start: handlers.asyncStart, end: handlers.asyncEnd, - }); + }, options); } // Subscribe to error channel if (handlers.error) { - this.error.subscribe(handlers.error); + this.error.subscribe(handlers.error, options); } } @@ -704,14 +833,28 @@ dc_binding.linkNativeChannel((name, index) => { linkedChannel._index = index; dc_binding.subscribers[index] = (linkedChannel._subscribers?.length || 0) + - (linkedChannel._stores?.size || 0); + (linkedChannel._stores?.size || 0) + + (linkedChannel._bypassSubscribers?.length || 0) + + (linkedChannel._bypassStores?.size || 0); return linkedChannel; }); +function bypass(key, fn, thisArg, ...args) { + validateFunction(fn, 'fn'); + + validateBypassKey(key, 'key'); + + const currentSet = getBypassStorage().getStore(); + const next = currentSet ? new SafeSet(currentSet) : new SafeSet(); + next.add(key); + return withBypassContext(next, fn, thisArg, args); +} + module.exports = { channel, hasSubscribers, subscribe, + bypass, tracingChannel, unsubscribe, boundedChannel, diff --git a/test/parallel/test-diagnostics-channel-bypass.js b/test/parallel/test-diagnostics-channel-bypass.js new file mode 100644 index 000000000000..de5af39d3979 --- /dev/null +++ b/test/parallel/test-diagnostics-channel-bypass.js @@ -0,0 +1,565 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { channel, bypass } = require('node:diagnostics_channel'); +const { AsyncLocalStorage } = require('async_hooks'); + +// Test 1: Basic bypass - subscriber with bypassId is skipped inside bypass() +{ + const key = Symbol('tracer'); + const ch = channel('test-bypass-basic'); + const handler = common.mustNotCall(); + ch.subscribe(handler, { bypassId: key }); + + bypass(key, common.mustCall(() => { + ch.publish({}); + })); + + ch.unsubscribe(handler); +} + +// Test 2: Non-opted subscriber fires even inside bypass() scope +{ + const key = Symbol('tracer2'); + const ch = channel('test-bypass-nonopted'); + const optedHandler = common.mustNotCall(); + const regularHandler = common.mustCall(); + ch.subscribe(optedHandler, { bypassId: key }); + ch.subscribe(regularHandler); // no bypass + + bypass(key, common.mustCall(() => { + ch.publish({}); + })); + + ch.unsubscribe(optedHandler); + ch.unsubscribe(regularHandler); +} + +// Test 3: Two APMs with different keys don't bypass each other +{ + const k1 = Symbol('k1'); + const k2 = Symbol('k2'); + const ch = channel('test-bypass-two-keys'); + let h1Calls = 0; + let h2Calls = 0; + const h1 = common.mustCall(() => { h1Calls++; }, 1); + const h2 = common.mustCall(() => { h2Calls++; }, 1); + ch.subscribe(h1, { bypassId: k1 }); + ch.subscribe(h2, { bypassId: k2 }); + + bypass(k1, common.mustCall(() => { + ch.publish({}); + })); + + assert.strictEqual(h1Calls, 0); + assert.strictEqual(h2Calls, 1); + + bypass(k2, common.mustCall(() => { + ch.publish({}); + })); + + assert.strictEqual(h1Calls, 1); + assert.strictEqual(h2Calls, 1); + + ch.unsubscribe(h1); + ch.unsubscribe(h2); +} + +// Test 4: Nested bypass() calls (same key, different keys) +{ + const k1 = Symbol('nested1'); + const k2 = Symbol('nested2'); + const ch = channel('test-bypass-nested'); + const h1 = common.mustNotCall(); + let h2Calls = 0; + const h2 = common.mustCall(() => { h2Calls++; }, 2); + ch.subscribe(h1, { bypassId: k1 }); + ch.subscribe(h2, { bypassId: k2 }); + + bypass(k1, common.mustCall(() => { + // Inside k1, h1 skipped, h2 runs + ch.publish({}); + assert.strictEqual(h2Calls, 1); + + bypass(k2, common.mustCall(() => { + // Inside both, both skipped + ch.publish({}); + assert.strictEqual(h2Calls, 1); + })); + + // Back to only k1 + ch.publish({}); + assert.strictEqual(h2Calls, 2); + })); + + ch.unsubscribe(h1); + ch.unsubscribe(h2); +} + +// Test 5: bypass() across a Promise boundary +{ + const key = Symbol('promise'); + const ch = channel('test-bypass-promise'); + const handler = common.mustNotCall(); + ch.subscribe(handler, { bypassId: key }); + const done = common.mustCall(); + + bypass(key, common.mustCall(async () => { + await Promise.resolve(); + ch.publish({}); + })).then(common.mustCall(() => { + ch.unsubscribe(handler); + done(); + })); +} + +// Test 6: bypass() across setImmediate and queueMicrotask +{ + const key = Symbol('timers'); + const ch = channel('test-bypass-timers'); + const handler = common.mustNotCall(); + ch.subscribe(handler, { bypassId: key }); + const done = common.mustCall(); + + bypass(key, common.mustCall(async () => { + await new Promise((resolve) => { + setImmediate(common.mustCall(() => { + ch.publish({}); + + queueMicrotask(common.mustCall(() => { + ch.publish({}); + resolve(); + })); + })); + }); + })).then(common.mustCall(() => { + ch.unsubscribe(handler); + done(); + })); +} + +// Test 7: unsubscribe() works correctly after using bypassId +{ + const key = Symbol('unsub'); + const ch = channel('test-bypass-unsubscribe'); + const handler = common.mustNotCall(); + ch.subscribe(handler, { bypassId: key }); + ch.unsubscribe(handler); + + // Should not throw and should not be called + bypass(key, common.mustCall(() => { + ch.publish({}); + })); +} + +// Test 8: bindStore with bypassId is skipped inside bypass() +{ + const key = Symbol('store'); + const ch = channel('test-bypass-store'); + const als = new AsyncLocalStorage(); + const normalAls = new AsyncLocalStorage(); + + // Normal store, no bypassId, must always be entered. + ch.bindStore(normalAls, common.mustCall((data) => ({ value: data.value }))); + + // Bypass store, must NOT be entered inside bypass(). + ch.bindStore(als, common.mustNotCall(), { bypassId: key }); + + bypass(key, common.mustCall(() => { + ch.runStores({ value: 42 }, common.mustCall(() => { + // Assertions inside runStores where store context exists + assert.strictEqual(normalAls.getStore()?.value, 42); + assert.strictEqual(als.getStore(), undefined); + })); + })); + + ch.unbindStore(als); + ch.unbindStore(normalAls); +} + +// Test 9: Wrong type for bypassId throws ERR_INVALID_ARG_TYPE +{ + const ch = channel('test-bypass-wrong-type'); + const bad = 'not-allowed'; + assert.throws(() => ch.subscribe(() => {}, { bypassId: bad }), { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + }); + const als = new AsyncLocalStorage(); + assert.throws(() => ch.bindStore(als, (d) => d, { bypassId: bad }), { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + }); + assert.throws(() => bypass(bad, () => {}), { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + }); +} + +// Test 10: bypass() return value passes through fn's return value +{ + const key = Symbol('return'); + const receiver = { value: 41 }; + const result = bypass(key, common.mustCall(function(a, b) { + assert.strictEqual(this, receiver); + assert.strictEqual(a, 'a'); + assert.strictEqual(b, 'b'); + return this.value + 1; + }), receiver, 'a', 'b'); + assert.strictEqual(result, 42); +} + +// Test 11: TracingChannel traceSync respects bypass +{ + const { tracingChannel } = require('node:diagnostics_channel'); + const key = Symbol('tracing-sync'); + const tc = tracingChannel('test-bypass-tracing-sync'); + const startHandler = common.mustNotCall(); + const endHandler = common.mustNotCall(); + const errorHandler = common.mustNotCall(); + + tc.subscribe({ + start: startHandler, + end: endHandler, + error: errorHandler, + }, { bypassId: key }); + + bypass(key, common.mustCall(() => { + tc.traceSync(common.mustCall(), {}); + })); + + tc.unsubscribe({ + start: startHandler, + end: endHandler, + error: errorHandler, + }); +} + +// Test 12: TracingChannel tracePromise respects bypass +{ + const { tracingChannel } = require('node:diagnostics_channel'); + const key = Symbol('tracing-promise'); + const tc = tracingChannel('test-bypass-tracing-promise'); + const startHandler = common.mustNotCall(); + const endHandler = common.mustNotCall(); + const asyncStartHandler = common.mustNotCall(); + const asyncEndHandler = common.mustNotCall(); + const done = common.mustCall(); + + tc.subscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }, { bypassId: key }); + + bypass(key, common.mustCall(() => { + return tc.tracePromise(common.mustCall(() => Promise.resolve(42)), {}); + })).then(common.mustCall(() => { + tc.unsubscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }); + done(); + })); +} + +// Test 13: TracingChannel traceCallback respects bypass +{ + const { tracingChannel } = require('node:diagnostics_channel'); + const key = Symbol('tracing-callback'); + const tc = tracingChannel('test-bypass-tracing-callback'); + const startHandler = common.mustNotCall(); + const endHandler = common.mustNotCall(); + const asyncStartHandler = common.mustNotCall(); + const asyncEndHandler = common.mustNotCall(); + const done = common.mustCall(); + + tc.subscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }, { bypassId: key }); + + bypass(key, common.mustCall(() => { + tc.traceCallback( + common.mustCall((cb) => setImmediate(cb, null, 'result')), + -1, + {}, + null, + common.mustCall((err, res) => { + assert.strictEqual(err, null); + assert.strictEqual(res, 'result'); + tc.unsubscribe({ + start: startHandler, + end: endHandler, + asyncStart: asyncStartHandler, + asyncEnd: asyncEndHandler, + }); + done(); + }) + ); + })); +} + +// Test 14: Bind normally, rebind with bypassId, unbindStore once marks channel inactive +{ + const key = Symbol('rebind-normal-to-bypass'); + const ch = channel('test-bypass-rebind-normal-to-bypass'); + const als = new AsyncLocalStorage(); + + ch.bindStore(als, (data) => data); + assert.strictEqual(ch.hasSubscribers, true); + + // Rebind with bypassId + ch.bindStore(als, (data) => data, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + // Outside bypass(key), the store is entered + ch.runStores({ value: 1 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 1 }); + })); + + // Inside bypass(key), the store is skipped + bypass(key, common.mustCall(() => { + ch.runStores({ value: 1 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + })); + + // Unbind once: must completely remove store and make channel inactive + const unbound = ch.unbindStore(als); + assert.strictEqual(unbound, true); + assert.strictEqual(ch.hasSubscribers, false); + + // Store is no longer entered + ch.runStores({ value: 1 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + + // Unbinding again returns false + assert.strictEqual(ch.unbindStore(als), false); +} + +// Test 15: Bind with bypassId, rebind normally, unbindStore once marks channel inactive +{ + const key = Symbol('rebind-bypass-to-normal'); + const ch = channel('test-bypass-rebind-bypass-to-normal'); + const als = new AsyncLocalStorage(); + + ch.bindStore(als, (data) => data, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + // Rebind without bypassId (normal) + ch.bindStore(als, (data) => data); + assert.strictEqual(ch.hasSubscribers, true); + + // Inside bypass(key), normal store should now fire (it was rebound to normal) + bypass(key, common.mustCall(() => { + ch.runStores({ value: 2 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 2 }); + })); + })); + + // Outside bypass(key), normal store fires + ch.runStores({ value: 2 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 2 }); + })); + + // Unbind once: must completely remove store and make channel inactive + const unbound = ch.unbindStore(als); + assert.strictEqual(unbound, true); + assert.strictEqual(ch.hasSubscribers, false); + + // Store is no longer entered + ch.runStores({ value: 3 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + + // Unbinding again returns false + assert.strictEqual(ch.unbindStore(als), false); +} + +// Test 16: Store is entered exactly once per runStores() after rebind and transform calls verified +{ + const key = Symbol('rebind-single-entry'); + const ch = channel('test-bypass-rebind-single-entry'); + const als = new AsyncLocalStorage(); + + let transformCalls = 0; + ch.bindStore(als, (data) => { + transformCalls++; + return data; + }); + + // Rebind with bypassId + let transformCallsRebound = 0; + ch.bindStore(als, (data) => { + transformCallsRebound++; + return data; + }, { bypassId: key }); + + ch.runStores({ value: 42 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 42 }); + })); + + // The original transform must not be called; the rebound transform called exactly once + assert.strictEqual(transformCalls, 0); + assert.strictEqual(transformCallsRebound, 1); + + // Rebind back to normal + let transformCallsRebound2 = 0; + ch.bindStore(als, (data) => { + transformCallsRebound2++; + return data; + }); + + ch.runStores({ value: 43 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 43 }); + })); + + assert.strictEqual(transformCalls, 0); + assert.strictEqual(transformCallsRebound, 1); + assert.strictEqual(transformCallsRebound2, 1); + + ch.unbindStore(als); + assert.strictEqual(ch.hasSubscribers, false); +} + +// Test 17: Invalid bypassId on rebind throws ERR_INVALID_ARG_TYPE and preserves earlier binding and refcount +{ + const bad = 'invalid-string-key'; + + // 1. Earlier binding is normal + { + const ch = channel('test-bypass-rebind-invalid-normal'); + const als = new AsyncLocalStorage(); + + ch.bindStore(als, (data) => data); + assert.strictEqual(ch.hasSubscribers, true); + + assert.throws( + () => ch.bindStore(als, (data) => ({ modified: data }), { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + + // Channel still active, earlier binding intact and entered + assert.strictEqual(ch.hasSubscribers, true); + ch.runStores({ value: 100 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 100 }); + })); + + // Unbinding once still properly decrements refcount and marks inactive + assert.strictEqual(ch.unbindStore(als), true); + assert.strictEqual(ch.hasSubscribers, false); + } + + // 2. Earlier binding is bypass + { + const ch = channel('test-bypass-rebind-invalid-bypass'); + const als = new AsyncLocalStorage(); + const key = Symbol('valid-key'); + + ch.bindStore(als, (data) => data, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + assert.throws( + () => ch.bindStore(als, (data) => ({ modified: data }), { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + + // Channel still active, earlier bypass binding intact + assert.strictEqual(ch.hasSubscribers, true); + + // Outside bypass, store is entered + ch.runStores({ value: 200 }, common.mustCall(() => { + assert.deepStrictEqual(als.getStore(), { value: 200 }); + })); + + // Inside bypass with valid key, store is skipped + bypass(key, common.mustCall(() => { + ch.runStores({ value: 200 }, common.mustCall(() => { + assert.strictEqual(als.getStore(), undefined); + })); + })); + + // Unbinding once still properly decrements refcount and marks inactive + assert.strictEqual(ch.unbindStore(als), true); + assert.strictEqual(ch.hasSubscribers, false); + } +} + +// Test 18: Invalid bypassId on fresh inactive channel leaves channel inactive +{ + const bad = 'invalid-string-key'; + + // 1. Invalid bypassId passed to subscribe() on fresh inactive channel + { + const ch = channel('test-bypass-fresh-invalid-subscribe'); + assert.strictEqual(ch.hasSubscribers, false); + + assert.throws( + () => ch.subscribe(() => {}, { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + assert.strictEqual(ch.hasSubscribers, false); + + const key = Symbol('valid-subscribe'); + const handler = common.mustCall(); + ch.subscribe(handler, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + ch.publish({}); + + assert.strictEqual(ch.unsubscribe(handler), true); + assert.strictEqual(ch.hasSubscribers, false); + + const plainHandler = common.mustCall(); + ch.subscribe(plainHandler); + assert.strictEqual(ch.hasSubscribers, true); + + ch.publish({}); + + assert.strictEqual(ch.unsubscribe(plainHandler), true); + assert.strictEqual(ch.hasSubscribers, false); + } + + // 2. Invalid bypassId passed to bindStore() on fresh inactive channel + { + const ch = channel('test-bypass-fresh-invalid-bind-store'); + const als = new AsyncLocalStorage(); + assert.strictEqual(ch.hasSubscribers, false); + + assert.throws( + () => ch.bindStore(als, (data) => data, { bypassId: bad }), + { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + } + ); + assert.strictEqual(ch.hasSubscribers, false); + + const key = Symbol('valid-bind-store'); + const handler = common.mustCall(); + ch.subscribe(handler, { bypassId: key }); + assert.strictEqual(ch.hasSubscribers, true); + + ch.publish({}); + + assert.strictEqual(ch.unsubscribe(handler), true); + assert.strictEqual(ch.hasSubscribers, false); + } +}