diagnostics_channel ↗ モジュールは、診断用に任意のメッセージデータを報告する名前付きチャネルを作る API です。低オーバーヘッドの診断報告向けに設計された、シンプルなイベントの pub/sub モデルです。
import {
channel,
hasSubscribers,
subscribe,
unsubscribe,
tracingChannel,
} from "node:diagnostics_channel";
// For publishing messages to a channel, acquire a channel object:
const myChannel = channel("my-channel");
// Any JS value can be published to a channel.
myChannel.publish({ foo: "bar" });
// For receiving messages on a channel, use subscribe:
subscribe("my-channel", (message) => {
console.log(message);
});すべての Channel インスタンスは、Isolate / コンテキストごと(同じエントリポイントなど)のシングルトンです。サブスクライバーは常に同期的に、登録順で呼び出されます。EventTarget や Node.js の EventEmitter クラスに近い動きです。
Tail Workers を使うと、任意のチャネルへ公開したメッセージは Tail Worker にも転送されます。Tail Worker 内では、diagnosticsChannelEvents プロパティから診断チャネルのメッセージにアクセスできます。
export default {
async tail(events) {
for (const event of events) {
for (const messageData of event.diagnosticsChannelEvents) {
console.log(
messageData.timestamp,
messageData.channel,
messageData.message,
);
}
}
},
};Tail Worker へ渡すメッセージは structured clone algorithm ↗(structuredClone() ↗ API と同じ仕組み)を通るため、クローンできる値だけが使えます。
Node.js のドキュメントによると、「TracingChannel ↗ は、1 つのトレース可能な操作をまとめて表す [Channels] の集まりです。TracingChannel は、アプリケーションフローのトレース用イベントを出す手順を形式化し、簡単にします。」
import { tracingChannel } from "node:diagnostics_channel";
import { AsyncLocalStorage } from "node:async_hooks";
const channels = tracingChannel("my-channel");
const requestId = new AsyncLocalStorage();
channels.start.bindStore(requestId);
channels.subscribe({
start(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle start message
},
end(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle end message
},
asyncStart(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle asyncStart message
},
asyncEnd(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle asyncEnd message
},
error(message) {
console.log(requestId.getStore()); // { requestId: '123' }
// Handle error message
},
});
// The subscriber handlers will be invoked while tracing the execution of the async
// function passed into `channel.tracePromise`...
channel.tracePromise(
async () => {
// Perform some asynchronous work...
},
{ requestId: "123" },
);詳しくは Node.js の diagnostics_channel ドキュメント ↗ を参照してください。