Commit 6a536f95f70 for nodejs
commit 6a536f95f706d222883e0134472449162e93c8e8
Author: Ilyas Shabi <ilyasshabi94@gmail.com>
Date: Tue Nov 17 10:00:19 2026 +0100
diagnostics_channel: add threadpool work event
Signed-off-by: ishabi <ilyasshabi94@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65982
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Bryan English <bryan@bryanenglish.com>
diff --git a/benchmark/diagnostics_channel/threadpool-work.js b/benchmark/diagnostics_channel/threadpool-work.js
new file mode 100644
index 00000000000..2674729023e
--- /dev/null
+++ b/benchmark/diagnostics_channel/threadpool-work.js
@@ -0,0 +1,69 @@
+'use strict';
+
+const assert = require('node:assert');
+const crypto = require('node:crypto');
+const dc = require('node:diagnostics_channel');
+const fs = require('node:fs');
+const zlib = require('node:zlib');
+const common = require('../common.js');
+const tmpdir = require('../../test/common/tmpdir');
+
+const bench = common.createBenchmark(main, {
+ n: [1e3, 1e4],
+ mode: ['subscribed', 'unsubscribed'],
+ operation: ['crypto', 'zlib', 'readFile', 'writeFile'],
+});
+
+function main({ n, mode, operation }) {
+ const subscriber = () => {};
+ const type = {
+ crypto: 'crypto',
+ zlib: 'zlib',
+ readFile: 'fs.readfile',
+ writeFile: 'fs.writefile',
+ }[operation];
+ assert(type);
+ const channel = `uv.threadpool.work.${type}`;
+ if (mode === 'subscribed') {
+ dc.subscribe(channel, subscriber);
+ } else if (mode === 'unsubscribed') {
+ dc.subscribe(channel, subscriber);
+ dc.unsubscribe(channel, subscriber);
+ }
+
+ tmpdir.refresh();
+ const file = tmpdir.resolve('file');
+ const data = Buffer.alloc(1024, 'x');
+ fs.writeFileSync(file, data);
+
+ const operations = {
+ crypto(callback) {
+ crypto.pbkdf2('secret', 'salt', 1, 32, 'sha256', callback);
+ },
+ zlib(callback) {
+ zlib.gzip(data, callback);
+ },
+ readFile(callback) {
+ fs.readFile(file, callback);
+ },
+ writeFile(callback) {
+ fs.writeFile(file, data, callback);
+ },
+ };
+
+ let completed = 0;
+ bench.start();
+ run();
+
+ function run() {
+ operations[operation]((err) => {
+ assert.ifError(err);
+ if (++completed < n) return run();
+
+ bench.end(n);
+ if (mode === 'subscribed') {
+ dc.unsubscribe(channel, subscriber);
+ }
+ });
+ }
+}
diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md
index 25e544ccf27..61b5068e207 100644
--- a/doc/api/diagnostics_channel.md
+++ b/doc/api/diagnostics_channel.md
@@ -2040,6 +2040,53 @@ statement is garbage collected. Subscribers must not close the database or the
statement, since both are still in use while the event is being delivered; see
[`database.close()`][] and [`statement.close()`][].
+#### libuv Thread Pool
+
+<!-- YAML
+added: REPLACEME
+-->
+
+> Stability: 1 - Experimental
+
+##### Event: `'uv.threadpool.work.<type>'`
+
+Each kind of work submitted to the [libuv thread pool][] has a separate channel
+named by appending its `type` to `'uv.threadpool.work.'`.
+
+Supported values for `<type>` are:
+
+* `'crypto'`
+
+* `'fs.cp'`
+
+* `'fs.readfile'`
+
+* `'fs.writefile'`
+
+* `'glob'`
+
+* `'histogram.qrde'`
+
+* `'node_api'`
+
+* `'readdir_recursive'`
+
+* `'node_sqlite3.BackupJob'`
+
+* `'zlib'`
+
+Messages contain:
+
+* `enqueued` {number} When the work was submitted to the pool.
+
+* `started` {number|null} When execution started, or `null` if cancelled.
+
+* `ended` {number|null} When execution ended, or `null` if cancelled.
+
+Emitted after the work finishes and before its completion callback. Timestamps
+use the [`performance.now()`][] timeline. `started - enqueued` is queue time;
+`ended - started` is execution time.
+
[BoundedChannel Channels]: #boundedchannel-channels
[Test instrumentation and OpenTelemetry]: test.md#test-instrumentation-and-opentelemetry
[TracingChannel Channels]: #tracingchannel-channels
@@ -2066,9 +2113,11 @@ statement, since both are still in use while the event is being delivered; see
[`error` event]: #errorevent
[`locks.request()`]: worker_threads.md#locksrequestname-options-callback
[`net.Server.listen()`]: net.md#serverlisten
+[`performance.now()`]: perf_hooks.md#performancenow
[`process.execve()`]: process.md#processexecvefile-args-env
[`start` event]: #startevent
[`statement.close()`]: sqlite.md#statementclose
[`worker_threads.locks`]: worker_threads.md#worker_threadslocks
[context loss]: async_context.md#troubleshooting-context-loss
+[libuv thread pool]: https://docs.libuv.org/en/v1.x/threadpool.html
[thenable object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables
diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h
index 816ca62f65e..95980b1250f 100644
--- a/src/crypto/crypto_util.h
+++ b/src/crypto/crypto_util.h
@@ -346,7 +346,7 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork {
CryptoJobMode mode,
AdditionalParams&& params)
: AsyncWrap(env, object, type),
- ThreadPoolWork(env, "crypto"),
+ ThreadPoolWork(env, ThreadPoolWorkType::kCrypto),
mode_(mode),
params_(std::move(params)) {
// If the CryptoJob is async, then the instance will be
diff --git a/src/env.cc b/src/env.cc
index c54ce749825..0e2baa810d0 100644
--- a/src/env.cc
+++ b/src/env.cc
@@ -8,6 +8,7 @@
#include "node_buffer.h"
#include "node_context_data.h"
#include "node_contextify.h"
+#include "node_diagnostics_channel.h"
#include "node_dotenv.h"
#include "node_errors.h"
#include "node_file_utils.h"
@@ -1320,6 +1321,30 @@ Environment::~Environment() {
isolate_data_->RemoveEnvironment();
}
+void Environment::InitializeThreadPoolWorkChannels() {
+ if (isolate_data()->is_building_snapshot()) return;
+
+ auto* binding =
+ principal_realm()->GetBindingData<diagnostics_channel::BindingData>();
+ CHECK_NOT_NULL(binding);
+ for (size_t i = 0; i < threadpool_work_channels_.size(); i++) {
+ ThreadPoolWorkChannel* entry = &threadpool_work_channels_[i];
+ if (entry->channel.get() != nullptr) continue;
+
+ std::string name = "uv.threadpool.work.";
+ name += kThreadPoolWorkNames[i];
+ BaseObjectPtr<diagnostics_channel::Channel> channel =
+ diagnostics_channel::Channel::Get(this, name);
+ if (!channel) continue;
+
+ binding->SetChannelStatusCallback(
+ channel->index(), [entry](bool active) { entry->active = active; });
+ entry->channel =
+ BaseObjectWeakPtr<diagnostics_channel::Channel>(channel.get());
+ entry->active = channel->HasSubscribers();
+ }
+}
+
void Environment::InitializeLibuv() {
HandleScope handle_scope(isolate());
Context::Scope context_scope(context());
diff --git a/src/env.h b/src/env.h
index b8c48352e91..b3e6ec46713 100644
--- a/src/env.h
+++ b/src/env.h
@@ -63,6 +63,7 @@
#include <ostream>
#include <set>
#include <string>
+#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <variant>
@@ -83,6 +84,42 @@ void FreeRootCertStore(RootCertStore* root_certs);
} // namespace crypto
#endif // HAVE_OPENSSL
+namespace diagnostics_channel {
+class Channel;
+}
+
+struct ThreadPoolWorkChannel {
+ BaseObjectWeakPtr<diagnostics_channel::Channel> channel;
+ bool active = false;
+};
+
+enum class ThreadPoolWorkType : uint8_t {
+ kCrypto,
+ kFsCp,
+ kFsReadFile,
+ kFsWriteFile,
+ kGlob,
+ kHistogramQrde,
+ kNodeApi,
+ kReadDirRecursive,
+ kSQLiteBackup,
+ kZlib,
+ kCount,
+};
+
+inline constexpr std::array<std::string_view,
+ static_cast<size_t>(ThreadPoolWorkType::kCount)>
+ kThreadPoolWorkNames = {"crypto",
+ "fs.cp",
+ "fs.readfile",
+ "fs.writefile",
+ "glob",
+ "histogram.qrde",
+ "node_api",
+ "readdir_recursive",
+ "node_sqlite3.BackupJob",
+ "zlib"};
+
namespace shadow_realm {
class ShadowRealm;
}
@@ -745,6 +782,11 @@ class Environment final : public MemoryRetainer {
void RunDeserializeRequests();
// Should be called before InitializeInspector()
void InitializeDiagnostics();
+ void InitializeThreadPoolWorkChannels();
+ inline ThreadPoolWorkChannel* threadpool_work_channel(
+ ThreadPoolWorkType type) {
+ return &threadpool_work_channels_[static_cast<size_t>(type)];
+ }
#if HAVE_INSPECTOR
// If the environment is created for a worker, pass parent_handle and
@@ -1291,6 +1333,9 @@ class Environment final : public MemoryRetainer {
AliasedInt32Array timeout_info_;
TickInfo tick_info_;
permission::Permission permission_;
+ std::array<ThreadPoolWorkChannel,
+ static_cast<size_t>(ThreadPoolWorkType::kCount)>
+ threadpool_work_channels_;
const uint64_t timer_base_;
std::shared_ptr<KVStore> env_vars_;
int ipc_channel_fd_ = -1;
diff --git a/src/env_properties.h b/src/env_properties.h
index c7a26ce3a58..3c52ea87498 100644
--- a/src/env_properties.h
+++ b/src/env_properties.h
@@ -465,6 +465,7 @@
V(srv_record_template, v8::DictionaryTemplate) \
V(streambaseoutputstream_constructor_template, v8::ObjectTemplate) \
V(tcp_constructor_template, v8::FunctionTemplate) \
+ V(threadpool_work_template, v8::DictionaryTemplate) \
V(tlsa_record_template, v8::DictionaryTemplate) \
V(tty_constructor_template, v8::FunctionTemplate) \
V(txt_record_template, v8::DictionaryTemplate) \
diff --git a/src/glob/node_glob.cc b/src/glob/node_glob.cc
index 9337775c79d..0e8b1e86ea6 100644
--- a/src/glob/node_glob.cc
+++ b/src/glob/node_glob.cc
@@ -431,7 +431,7 @@ GlobRequest::GlobRequest(Environment* env,
const std::vector<CompiledPatternPtr>& excludes,
std::unique_ptr<JsExcludeFilter> filter)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_GLOBREQUEST),
- ThreadPoolWork(env, "glob"),
+ ThreadPoolWork(env, ThreadPoolWorkType::kGlob),
filter_(std::move(filter)),
walk_(env, options, includes, excludes),
with_file_types_(options.with_file_types) {
diff --git a/src/histogram.cc b/src/histogram.cc
index 6efe2d6985c..2b91bb7f6a6 100644
--- a/src/histogram.cc
+++ b/src/histogram.cc
@@ -970,7 +970,7 @@ class QrdeJob final : public ThreadPoolWork {
Histogram::RecordedSnapshotSource snapshot_source,
std::vector<double> probabilities,
QrdeDequantization dequantization)
- : ThreadPoolWork(env, "histogram.qrde"),
+ : ThreadPoolWork(env, ThreadPoolWorkType::kHistogramQrde),
histogram_(std::move(histogram)),
snapshot_source_(std::move(snapshot_source)),
probabilities_(std::move(probabilities)),
diff --git a/src/node_api.cc b/src/node_api.cc
index b7854c2fe42..64d26a7a502 100644
--- a/src/node_api.cc
+++ b/src/node_api.cc
@@ -1219,7 +1219,7 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork {
env->isolate,
async_resource,
node::Utf8Value(env->isolate, async_resource_name).ToStringView()),
- ThreadPoolWork(env->node_env(), "node_api"),
+ ThreadPoolWork(env->node_env(), node::ThreadPoolWorkType::kNodeApi),
_env(env),
_data(data),
_execute(execute),
diff --git a/src/node_diagnostics_channel.cc b/src/node_diagnostics_channel.cc
index 2cc3309542f..c9d8a6de062 100644
--- a/src/node_diagnostics_channel.cc
+++ b/src/node_diagnostics_channel.cc
@@ -3,6 +3,7 @@
#include "base_object-inl.h"
#include "env-inl.h"
#include "node_external_reference.h"
+#include "node_internals.h"
#include "util-inl.h"
#include "v8.h"
@@ -109,6 +110,7 @@ void BindingData::LinkNativeChannel(const FunctionCallbackInfo<Value>& args) {
}
}
}
+ realm->env()->InitializeThreadPoolWorkChannels();
}
bool BindingData::PrepareForSerialization(Local<Context> context,
@@ -117,6 +119,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context,
internal_field_info_ = InternalFieldInfoBase::New<InternalFieldInfo>(type());
internal_field_info_->subscribers = subscribers_.Serialize(context, creator);
internal_field_info_->subscribers_capacity = subscribers_.Length();
+ channel_status_callbacks_.clear();
link_callback_.Reset();
channel_wrap_template_.Reset();
DetachChannels();
diff --git a/src/node_diagnostics_channel.h b/src/node_diagnostics_channel.h
index b1da5fcee3d..596ee7fe168 100644
--- a/src/node_diagnostics_channel.h
+++ b/src/node_diagnostics_channel.h
@@ -90,6 +90,8 @@ class Channel : public BaseObject {
static BaseObjectPtr<Channel> Get(Environment* env, std::string_view name);
+ uint32_t index() const { return index_; }
+
inline bool HasSubscribers() const {
return binding_data_ != nullptr && binding_data_->subscribers_[index_] > 0;
}
diff --git a/src/node_file.cc b/src/node_file.cc
index b96771217b8..795d796e2bc 100644
--- a/src/node_file.cc
+++ b/src/node_file.cc
@@ -2743,7 +2743,7 @@ class ReadDirRecursiveWork final : public ThreadPoolWork {
public:
ReadDirRecursiveWork(Environment* env,
std::shared_ptr<ReadDirRecursiveRequest> request)
- : ThreadPoolWork(env, "readdir_recursive"),
+ : ThreadPoolWork(env, ThreadPoolWorkType::kReadDirRecursive),
request_(std::move(request)) {}
void DoThreadPoolWork() override { request_->walk()->Run(); }
@@ -3791,7 +3791,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
uint64_t limit,
bool track_fd)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
- ThreadPoolWork(env, "fs.readfile"),
+ ThreadPoolWork(env, ThreadPoolWorkType::kFsReadFile),
path_(std::move(path)),
limit_(limit),
flags_(flags),
@@ -3979,7 +3979,7 @@ class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
- ThreadPoolWork(env, "fs.writefile"),
+ ThreadPoolWork(env, ThreadPoolWorkType::kFsWriteFile),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
@@ -5381,7 +5381,7 @@ class CpDirJob final : public AsyncWrap, public ThreadPoolWork {
std::string&& dest_display,
CpDirOptions options)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
- ThreadPoolWork(env, "fs.cp"),
+ ThreadPoolWork(env, ThreadPoolWorkType::kFsCp),
src_(std::move(src)),
dest_(std::move(dest)),
dest_display_(std::move(dest_display)),
diff --git a/src/node_internals.h b/src/node_internals.h
index 87c2efabf99..6fc29ac89e4 100644
--- a/src/node_internals.h
+++ b/src/node_internals.h
@@ -46,6 +46,10 @@ struct sockaddr;
namespace node {
+namespace diagnostics_channel {
+class Channel;
+}
+
namespace builtins {
class BuiltinLoader;
}
@@ -312,8 +316,10 @@ class DebugSealHandleScope {
class ThreadPoolWork {
public:
- explicit inline ThreadPoolWork(Environment* env, const char* type)
- : env_(env), type_(type) {
+ explicit inline ThreadPoolWork(Environment* env, ThreadPoolWorkType type)
+ : env_(env),
+ type_(kThreadPoolWorkNames[static_cast<size_t>(type)].data()),
+ channel_(env->threadpool_work_channel(type)) {
CHECK_NOT_NULL(env);
}
inline virtual ~ThreadPoolWork() = default;
@@ -327,9 +333,19 @@ class ThreadPoolWork {
Environment* env() const { return env_; }
private:
+ inline bool IsObserved() const { return enqueued_at_ != 0; }
+
+ inline void PublishDiagnostics(diagnostics_channel::Channel& channel);
+
Environment* env_;
uv_work_t work_req_;
const char* type_;
+ ThreadPoolWorkChannel* channel_ = nullptr;
+
+ // libuv synchronizes these marks between the loop and worker threads.
+ uint64_t enqueued_at_ = 0;
+ uint64_t work_start_ = 0;
+ uint64_t work_end_ = 0;
};
// Functions defined in node.cc that are exposed via the bootstrapper object
diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc
index 8341b27a4fa..58ae9410340 100644
--- a/src/node_sqlite.cc
+++ b/src/node_sqlite.cc
@@ -622,7 +622,7 @@ class BackupJob : public ThreadPoolWork {
std::string dest_db,
int pages,
Local<Function> progressFunc)
- : ThreadPoolWork(env, "node_sqlite3.BackupJob"),
+ : ThreadPoolWork(env, ThreadPoolWorkType::kSQLiteBackup),
env_(env),
source_(source),
pages_(pages),
diff --git a/src/node_zlib.cc b/src/node_zlib.cc
index c87703800fd..72947b8b783 100644
--- a/src/node_zlib.cc
+++ b/src/node_zlib.cc
@@ -501,7 +501,7 @@ class CompressionStream : public AsyncWrap,
CompressionStream(Environment* env, Local<Object> wrap)
: AsyncWrap(env, wrap, AsyncWrap::PROVIDER_ZLIB),
- ThreadPoolWork(env, "zlib"),
+ ThreadPoolWork(env, ThreadPoolWorkType::kZlib),
write_result_(nullptr) {
MakeWeak();
}
diff --git a/src/threadpoolwork-inl.h b/src/threadpoolwork-inl.h
index 729e3de8eea..3bbe9b4c9ed 100644
--- a/src/threadpoolwork-inl.h
+++ b/src/threadpoolwork-inl.h
@@ -24,6 +24,9 @@
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
+#include <string_view>
+#include "env-inl.h"
+#include "node_diagnostics_channel.h"
#include "node_internals.h"
#include "tracing/trace_event.h"
#include "util-inl.h"
@@ -34,14 +37,26 @@ void ThreadPoolWork::ScheduleWork() {
env_->IncreaseWaitingRequestCounter();
TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
TRACING_CATEGORY_NODE2(threadpoolwork, async), type_, this);
+
+ // Some ThreadPoolWork instances are submitted more than once.
+ enqueued_at_ = 0;
+ work_start_ = 0;
+ work_end_ = 0;
+
+ if (channel_ != nullptr && channel_->active) [[unlikely]] {
+ enqueued_at_ = uv_hrtime();
+ }
+
int status = uv_queue_work(
env_->event_loop(),
&work_req_,
[](uv_work_t* req) {
ThreadPoolWork* self = ContainerOf(&ThreadPoolWork::work_req_, req);
+ if (self->IsObserved()) self->work_start_ = uv_hrtime();
TRACE_EVENT_BEGIN0(TRACING_CATEGORY_NODE2(threadpoolwork, sync),
self->type_);
self->DoThreadPoolWork();
+ if (self->IsObserved()) self->work_end_ = uv_hrtime();
TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(threadpoolwork, sync),
self->type_);
},
@@ -54,11 +69,51 @@ void ThreadPoolWork::ScheduleWork() {
self,
"result",
status);
+ // AfterThreadPoolWork() may unsubscribe or delete `self`.
+ if (self->IsObserved()) {
+ auto* channel = self->channel_ == nullptr
+ ? nullptr
+ : self->channel_->channel.get();
+ if (channel != nullptr) self->PublishDiagnostics(*channel);
+ }
self->AfterThreadPoolWork(status);
});
CHECK_EQ(status, 0);
}
+void ThreadPoolWork::PublishDiagnostics(diagnostics_channel::Channel& channel) {
+ if (!env_->can_call_into_js() || !channel.HasSubscribers()) return;
+
+ v8::Isolate* isolate = env_->isolate();
+ v8::HandleScope handle_scope(isolate);
+ v8::Local<v8::Context> context = env_->context();
+
+ // Match performance.now() without losing precision.
+ auto to_milliseconds = [isolate, origin = env_->time_origin()](
+ uint64_t mark) -> v8::Local<v8::Value> {
+ if (mark == 0) return v8::Null(isolate);
+ return v8::Number::New(isolate, static_cast<double>(mark - origin) / 1e6);
+ };
+
+ v8::Local<v8::DictionaryTemplate> tmpl = env_->threadpool_work_template();
+ if (tmpl.IsEmpty()) {
+ static constexpr std::string_view names[] = {
+ "enqueued", "started", "ended"};
+ tmpl = v8::DictionaryTemplate::New(isolate, names);
+ env_->set_threadpool_work_template(tmpl);
+ }
+
+ v8::MaybeLocal<v8::Value> values[] = {
+ to_milliseconds(enqueued_at_),
+ to_milliseconds(work_start_),
+ to_milliseconds(work_end_),
+ };
+
+ v8::Local<v8::Object> message;
+ if (!NewDictionaryInstance(context, tmpl, values).ToLocal(&message)) return;
+ channel.Publish(env_, message);
+}
+
int ThreadPoolWork::CancelWork() {
return uv_cancel(reinterpret_cast<uv_req_t*>(&work_req_));
}
diff --git a/test/node-api/test_async/test-loop.js b/test/node-api/test_async/test-loop.js
index 1b05cbad4a5..221063e8a36 100644
--- a/test/node-api/test_async/test-loop.js
+++ b/test/node-api/test_async/test-loop.js
@@ -1,14 +1,23 @@
'use strict';
const common = require('../../common');
const assert = require('assert');
+const dc = require('diagnostics_channel');
const test_async = require(`./build/${common.buildType}/test_async`);
const iterations = 500;
let x = 0;
+const events = [];
+const onThreadPoolWork = (event) => events.push(event);
const workDone = common.mustCall((status) => {
assert.strictEqual(status, 0);
+ if (x === 0) assert.strictEqual(events.length, 0);
if (++x < iterations) {
setImmediate(() => test_async.DoRepeatedWork(workDone));
+ } else {
+ dc.unsubscribe('uv.threadpool.work.node_api', onThreadPoolWork);
+ assert.strictEqual(events.length, iterations - 1);
}
}, iterations);
+// Subscribe after submission to verify subscription latching.
test_async.DoRepeatedWork(workDone);
+dc.subscribe('uv.threadpool.work.node_api', onThreadPoolWork);
diff --git a/test/node-api/test_async/test.js b/test/node-api/test_async/test.js
index 34ecae08e67..03e02fcd509 100644
--- a/test/node-api/test_async/test.js
+++ b/test/node-api/test_async/test.js
@@ -2,6 +2,7 @@
const common = require('../../common');
const assert = require('assert');
const child_process = require('child_process');
+const dc = require('diagnostics_channel');
const test_async = require(`./build/${common.buildType}/test_async`);
const testException = 'test_async_cb_exception';
@@ -27,4 +28,12 @@ test_async.Test(5, {}, common.mustCall(function(err, val) {
}));
// Async work item cancellation with callback.
-test_async.TestCancel(common.mustCall());
+const events = [];
+const onThreadPoolWork = (event) => events.push(event);
+dc.subscribe('uv.threadpool.work.node_api', onThreadPoolWork);
+test_async.TestCancel(common.mustCall(() => {
+ dc.unsubscribe('uv.threadpool.work.node_api', onThreadPoolWork);
+ const event = events.find(({ started, ended }) =>
+ started === null && ended === null);
+ assert.ok(event);
+}));
diff --git a/test/parallel/test-diagnostics-channel-threadpool-work.js b/test/parallel/test-diagnostics-channel-threadpool-work.js
new file mode 100644
index 00000000000..5111a4fb2b5
--- /dev/null
+++ b/test/parallel/test-diagnostics-channel-threadpool-work.js
@@ -0,0 +1,100 @@
+'use strict';
+
+const common = require('../common');
+
+const assert = require('node:assert');
+const crypto = common.hasCrypto ? require('node:crypto') : null;
+const dc = require('node:diagnostics_channel');
+const fs = require('node:fs');
+const {
+ cp,
+ glob,
+ readFile,
+ readdir,
+ writeFile,
+} = require('node:fs/promises');
+const { createHistogram } = require('node:perf_hooks');
+const { it } = require('node:test');
+const zlib = require('node:zlib');
+
+const tmpdir = require('../common/tmpdir');
+
+tmpdir.refresh();
+const sourceDir = tmpdir.resolve('source');
+const sourceFile = `${sourceDir}/file.js`;
+fs.mkdirSync(`${sourceDir}/nested`, { recursive: true });
+fs.writeFileSync(sourceFile, 'data');
+
+async function assertPublishes(t, type, trigger) {
+ const channel = `uv.threadpool.work.${type}`;
+ let published = false;
+ const handler = () => { published = true; };
+ dc.subscribe(channel, handler);
+ t.after(() => dc.unsubscribe(channel, handler));
+
+ await trigger();
+
+ assert.ok(published);
+}
+
+it('publishes for crypto work', { skip: !common.hasCrypto }, (t) => {
+ return assertPublishes(t, 'crypto', () => new Promise((resolve, reject) => {
+ crypto.pbkdf2('password', '0123456789abcdef', 1000, 16, 'sha256',
+ (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ }));
+});
+
+it('publishes for fs.cp work', (t) => {
+ return assertPublishes(t, 'fs.cp', () =>
+ cp(sourceDir, tmpdir.resolve('copy'), { recursive: true }));
+});
+
+it('publishes for fs.readfile work', (t) => {
+ return assertPublishes(t, 'fs.readfile', () => readFile(sourceFile));
+});
+
+it('publishes for fs.writefile work', (t) => {
+ return assertPublishes(t, 'fs.writefile', () =>
+ writeFile(tmpdir.resolve('written'), 'data'));
+});
+
+it('publishes for glob work', (t) => {
+ return assertPublishes(t, 'glob', () =>
+ Array.fromAsync(glob('**', { cwd: sourceDir })));
+});
+
+it('publishes for histogram.qrde work', (t) => {
+ return assertPublishes(t, 'histogram.qrde', () => {
+ const histogram = createHistogram();
+ histogram.record(1);
+ return histogram.qrde({ bins: 1 });
+ });
+});
+
+it('publishes for readdir_recursive work', (t) => {
+ return assertPublishes(t, 'readdir_recursive', () =>
+ readdir(sourceDir, { recursive: true }));
+});
+
+it('publishes for node_sqlite3.BackupJob work', {
+ skip: !common.hasSQLite,
+}, (t) => {
+ return assertPublishes(t, 'node_sqlite3.BackupJob', async () => {
+ const { backup, DatabaseSync } = require('node:sqlite');
+ const database = new DatabaseSync(':memory:');
+ t.after(() => database.close());
+ await backup(database, tmpdir.resolve('backup.db'));
+ });
+});
+
+it('publishes for zlib work', (t) => {
+ return assertPublishes(t, 'zlib', () => new Promise((resolve, reject) => {
+ zlib.gzip('data', (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ }));
+});