From 4797934e6a50f63dc09579c3ca8d382adfbc82bd Mon Sep 17 00:00:00 2001 From: theanarkh Date: Sun, 10 Aug 2025 15:17:05 +0800 Subject: [PATCH] worker: add cpu profile APIs for worker --- doc/api/errors.md | 30 ++++ doc/api/worker_threads.md | 30 ++++ lib/internal/worker.js | 36 +++++ src/async_wrap.h | 1 + src/env.cc | 36 +++++ src/env.h | 7 + src/env_properties.h | 1 + src/node_errors.h | 3 + src/node_worker.cc | 149 +++++++++++++++++- src/node_worker.h | 2 + src/util.h | 21 +++ test/parallel/test-worker-cpu-profile.js | 73 +++++++++ test/sequential/test-async-wrap-getasyncid.js | 1 + typings/internalBinding/worker.d.ts | 1 + 14 files changed, 390 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-worker-cpu-profile.js diff --git a/doc/api/errors.md b/doc/api/errors.md index 7cd23e05a21701..962e011bea5bd5 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -826,6 +826,36 @@ when an error occurs (and is caught) during the creation of the context, for example, when the allocation fails or the maximum call stack size is reached when the context is created. + + +### `ERR_CPU_PROFILE_ALREADY_STARTED` + + + +The CPU profile with the given name is already started. + + + +### `ERR_CPU_PROFILE_NOT_STARTED` + + + +The CPU profile with the given name is not started. + + + +### `ERR_CPU_PROFILE_TOO_MANY` + + + +There are too many CPU profiles being collected. + ### `ERR_CRYPTO_ARGON2_NOT_SUPPORTED` diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index d287bef25f21f8..f937a2004b7cb8 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -1957,6 +1957,36 @@ this matches its values. If the worker has stopped, the return value is an empty object. +### `worker.startCpuProfile(name)` + + + +* name: {string} +* Returns: {Promise} + +Starting a CPU profile with the given `name`, then return a Promise that fulfills +with an error or an object which has a `stop` method. Calling the `stop` method will +stop collecting the profile, then return a Promise that fulfills with an error or the +profile data. + +```cjs +const { Worker } = require('node:worker_threads'); + +const worker = new Worker(` + const { parentPort } = require('worker_threads'); + parentPort.on('message', () => {}); + `, { eval: true }); + +worker.on('online', async () => { + const handle = await worker.startCpuProfile('demo'); + const profile = await handle.stop(); + console.log(profile); + worker.terminate(); +}); +``` + ### `worker.stderr`