From 616a9bd0589127c63d86092a0b2dff3d64cb314b Mon Sep 17 00:00:00 2001 From: theanarkh Date: Thu, 11 Sep 2025 00:51:08 +0800 Subject: [PATCH] worker: add heap profile API --- doc/api/v8.md | 27 +++ doc/api/worker_threads.md | 43 ++++ lib/internal/worker.js | 42 ++++ src/async_wrap.h | 1 + src/env_properties.h | 1 + src/node_errors.h | 2 + src/node_worker.cc | 183 ++++++++++++++++++ src/node_worker.h | 3 + test/parallel/test-worker-heap-profile.js | 36 ++++ test/sequential/test-async-wrap-getasyncid.js | 1 + tools/doc/type-parser.mjs | 1 + typings/internalBinding/worker.d.ts | 6 + 12 files changed, 346 insertions(+) create mode 100644 test/parallel/test-worker-heap-profile.js diff --git a/doc/api/v8.md b/doc/api/v8.md index 0e18b6b6c59522..d7536490d728b2 100644 --- a/doc/api/v8.md +++ b/doc/api/v8.md @@ -1425,6 +1425,33 @@ added: REPLACEME Stopping collecting the profile and the profile will be discarded. +## Class: `HeapProfileHandle` + + + +### `heapProfileHandle.stop()` + + + +* Returns: {Promise} + +Stopping collecting the profile, then return a Promise that fulfills with an error or the +profile data. + +### `heapProfileHandle[Symbol.asyncDispose]()` + + + +* Returns: {Promise} + +Stopping collecting the profile and the profile will be discarded. + ## `v8.isStringOneByteRepresentation(content)` + +* Returns: {Promise} + +Starting a Heap profile then return a Promise that fulfills with an error +or an `HeapProfileHandle` object. This API supports `await using` syntax. + +```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.startHeapProfile(); + const profile = await handle.stop(); + console.log(profile); + worker.terminate(); +}); +``` + +`await using` example. + +```cjs +const { Worker } = require('node::worker_threads'); + +const w = new Worker(` + const { parentPort } = require('worker_threads'); + parentPort.on('message', () => {}); + `, { eval: true }); + +w.on('online', async () => { + // Stop profile automatically when return and profile will be discarded + await using handle = await w.startHeapProfile(); +}); +``` + ### `worker.stderr`