Skip to content

Commit 34e370e

Browse files
ShogunPandaaduh95
authored andcommitted
worker: add diagnostic channel 'worker_threads.main.registry'
Signed-off-by: Paolo Insogna <paolo@cowtech.it> Assisted-By: OpenAI:GPT-6.1 Sol <openai/gpt-6.1-sol> PR-URL: #67311 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 636d9c9 commit 34e370e

3 files changed

Lines changed: 118 additions & 0 deletions

File tree

‎doc/api/diagnostics_channel.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2021,6 +2021,20 @@ added: v16.18.0
20212021

20222022
Emitted when a new thread is created.
20232023

2024+
##### Event: `'worker_threads.main.registry'`
2025+
2026+
* `threadIds` {number\[]} A snapshot of the registered worker thread IDs.
2027+
2028+
Emitted only on the main thread whenever the worker thread registry changes,
2029+
including workers created by other workers. Each event contains a snapshot of
2030+
the registered worker thread IDs. The main thread's ID (`0`) is not included.
2031+
2032+
The registry tracks workers through their internal messaging ports. Registration
2033+
can occur before a worker is online. Removal occurs when the parent thread
2034+
processes the worker's exit and can be delayed if the parent thread is blocked.
2035+
Consequently, a snapshot does not guarantee that every listed worker is ready or
2036+
still running.
2037+
20242038
#### SQLite
20252039

20262040
<!-- YAML

‎lib/internal/worker/messaging.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
'use strict';
22

33
const {
4+
ArrayFrom,
45
AtomicsNotify,
56
AtomicsStore,
67
AtomicsWaitAsync,
@@ -30,6 +31,8 @@ const { MessageChannel } = require('internal/worker/io');
3031

3132
const { validateNumber } = require('internal/validators');
3233

34+
const registryChannel = require('diagnostics_channel').channel('worker_threads.main.registry');
35+
3336
const messageTypes = {
3437
REGISTER_MAIN_THREAD_PORT: 'registerMainThreadPort',
3538
UNREGISTER_MAIN_THREAD_PORT: 'unregisterMainThreadPort',
@@ -72,12 +75,26 @@ function handleMessageFromThread(message) {
7275

7376
// Never block the thread on this port
7477
port.unref();
78+
79+
if (registryChannel.hasSubscribers) {
80+
registryChannel.publish({
81+
__proto__: null,
82+
threadIds: ArrayFrom(threadsPorts.keys()),
83+
});
84+
}
7585
}
7686

7787
break;
7888
case messageTypes.UNREGISTER_MAIN_THREAD_PORT:
7989
threadsPorts.get(message.threadId).close();
8090
threadsPorts.delete(message.threadId);
91+
92+
if (registryChannel.hasSubscribers) {
93+
registryChannel.publish({
94+
__proto__: null,
95+
threadIds: ArrayFrom(threadsPorts.keys()),
96+
});
97+
}
8198
break;
8299
case messageTypes.SEND_MESSAGE_TO_WORKER:
83100
{
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { once } = require('events');
5+
const dc = require('diagnostics_channel');
6+
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
7+
8+
// Only the main thread publishes registry updates; allow the test's own workers.
9+
if (!isMainThread && workerData !== 'parent' && workerData !== 'child') {
10+
common.skip('This test must be started on the main thread');
11+
}
12+
13+
const channelName = 'worker_threads.main.registry';
14+
15+
if (isMainThread) {
16+
// Expect one snapshot for each registration and removal in the worker tree.
17+
const snapshots = [];
18+
const childRegistered = Promise.withResolvers();
19+
const childRemoved = Promise.withResolvers();
20+
21+
dc.subscribe(channelName, common.mustCall((message) => {
22+
assert.strictEqual(Object.getPrototypeOf(message), null);
23+
assert.deepStrictEqual(Object.keys(message), ['threadIds']);
24+
snapshots.push(message.threadIds);
25+
26+
if (snapshots.length === 2) {
27+
childRegistered.resolve();
28+
}
29+
if (snapshots.length === 3) {
30+
childRemoved.resolve();
31+
}
32+
}, 4));
33+
34+
async function test() {
35+
const worker = new Worker(__filename, { workerData: 'parent' });
36+
const threadId = worker.threadId;
37+
38+
// The child ID and its registry update arrive on independent channels.
39+
const [[childId]] = await Promise.all([
40+
once(worker, 'message'),
41+
once(worker, 'online'),
42+
childRegistered.promise,
43+
]);
44+
45+
assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId]]);
46+
47+
// Remove the nested worker first, keeping its parent alive for the update.
48+
worker.postMessage('stop');
49+
await childRemoved.promise;
50+
51+
assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId], [threadId]]);
52+
53+
// Let the parent exit naturally, then check that earlier snapshots are intact.
54+
const exited = once(worker, 'exit');
55+
worker.postMessage('finish');
56+
const [code] = await exited;
57+
58+
assert.strictEqual(code, 0);
59+
assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId], [threadId], []]);
60+
}
61+
62+
test().then(common.mustCall());
63+
} else {
64+
// Neither the parent worker nor its child should publish this channel locally.
65+
dc.subscribe(channelName, common.mustNotCall());
66+
67+
if (workerData === 'child') {
68+
// Keep the child alive until its parent explicitly terminates it.
69+
parentPort.on('message', common.mustNotCall());
70+
} else {
71+
async function run() {
72+
const worker = new Worker(__filename, { workerData: 'child' });
73+
await once(worker, 'online');
74+
parentPort.postMessage(worker.threadId);
75+
76+
// The main thread requests termination after observing both registrations.
77+
await once(parentPort, 'message');
78+
assert.strictEqual(await worker.terminate(), 1);
79+
80+
// Wait until the main thread observes the child's removal before exiting.
81+
await once(parentPort, 'message');
82+
parentPort.close();
83+
}
84+
85+
run().then(common.mustCall());
86+
}
87+
}

0 commit comments

Comments
 (0)