Skip to content

Commit 94e1e1d

Browse files
IlyasShabiaduh95
authored andcommitted
diagnostics_channel: add threadpool work event
Signed-off-by: ishabi <ilyasshabi94@gmail.com> PR-URL: #65982 Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Bryan English <bryan@bryanenglish.com>
1 parent 645be14 commit 94e1e1d

19 files changed

Lines changed: 396 additions & 13 deletions
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
'use strict';
2+
3+
const assert = require('node:assert');
4+
const crypto = require('node:crypto');
5+
const dc = require('node:diagnostics_channel');
6+
const fs = require('node:fs');
7+
const zlib = require('node:zlib');
8+
const common = require('../common.js');
9+
const tmpdir = require('../../test/common/tmpdir');
10+
11+
const bench = common.createBenchmark(main, {
12+
n: [1e3, 1e4],
13+
mode: ['subscribed', 'unsubscribed'],
14+
operation: ['crypto', 'zlib', 'readFile', 'writeFile'],
15+
});
16+
17+
function main({ n, mode, operation }) {
18+
const subscriber = () => {};
19+
const type = {
20+
crypto: 'crypto',
21+
zlib: 'zlib',
22+
readFile: 'fs.readfile',
23+
writeFile: 'fs.writefile',
24+
}[operation];
25+
assert(type);
26+
const channel = `uv.threadpool.work.${type}`;
27+
if (mode === 'subscribed') {
28+
dc.subscribe(channel, subscriber);
29+
} else if (mode === 'unsubscribed') {
30+
dc.subscribe(channel, subscriber);
31+
dc.unsubscribe(channel, subscriber);
32+
}
33+
34+
tmpdir.refresh();
35+
const file = tmpdir.resolve('file');
36+
const data = Buffer.alloc(1024, 'x');
37+
fs.writeFileSync(file, data);
38+
39+
const operations = {
40+
crypto(callback) {
41+
crypto.pbkdf2('secret', 'salt', 1, 32, 'sha256', callback);
42+
},
43+
zlib(callback) {
44+
zlib.gzip(data, callback);
45+
},
46+
readFile(callback) {
47+
fs.readFile(file, callback);
48+
},
49+
writeFile(callback) {
50+
fs.writeFile(file, data, callback);
51+
},
52+
};
53+
54+
let completed = 0;
55+
bench.start();
56+
run();
57+
58+
function run() {
59+
operations[operation]((err) => {
60+
assert.ifError(err);
61+
if (++completed < n) return run();
62+
63+
bench.end(n);
64+
if (mode === 'subscribed') {
65+
dc.unsubscribe(channel, subscriber);
66+
}
67+
});
68+
}
69+
}

‎doc/api/diagnostics_channel.md‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2040,6 +2040,53 @@ statement is garbage collected. Subscribers must not close the database or the
20402040
statement, since both are still in use while the event is being delivered; see
20412041
[`database.close()`][] and [`statement.close()`][].
20422042

2043+
#### libuv Thread Pool
2044+
2045+
<!-- YAML
2046+
added: REPLACEME
2047+
-->
2048+
2049+
> Stability: 1 - Experimental
2050+
2051+
##### Event: `'uv.threadpool.work.<type>'`
2052+
2053+
Each kind of work submitted to the [libuv thread pool][] has a separate channel
2054+
named by appending its `type` to `'uv.threadpool.work.'`.
2055+
2056+
Supported values for `<type>` are:
2057+
2058+
* `'crypto'`
2059+
2060+
* `'fs.cp'`
2061+
2062+
* `'fs.readfile'`
2063+
2064+
* `'fs.writefile'`
2065+
2066+
* `'glob'`
2067+
2068+
* `'histogram.qrde'`
2069+
2070+
* `'node_api'`
2071+
2072+
* `'readdir_recursive'`
2073+
2074+
* `'node_sqlite3.BackupJob'`
2075+
2076+
* `'zlib'`
2077+
2078+
Messages contain:
2079+
2080+
* `enqueued` {number} When the work was submitted to the pool.
2081+
2082+
* `started` {number|null} When execution started, or `null` if cancelled.
2083+
2084+
* `ended` {number|null} When execution ended, or `null` if cancelled.
2085+
2086+
Emitted after the work finishes and before its completion callback. Timestamps
2087+
use the [`performance.now()`][] timeline. `started - enqueued` is queue time;
2088+
`ended - started` is execution time.
2089+
20432090
[BoundedChannel Channels]: #boundedchannel-channels
20442091
[Test instrumentation and OpenTelemetry]: test.md#test-instrumentation-and-opentelemetry
20452092
[TracingChannel Channels]: #tracingchannel-channels
@@ -2066,9 +2113,11 @@ statement, since both are still in use while the event is being delivered; see
20662113
[`error` event]: #errorevent
20672114
[`locks.request()`]: worker_threads.md#locksrequestname-options-callback
20682115
[`net.Server.listen()`]: net.md#serverlisten
2116+
[`performance.now()`]: perf_hooks.md#performancenow
20692117
[`process.execve()`]: process.md#processexecvefile-args-env
20702118
[`start` event]: #startevent
20712119
[`statement.close()`]: sqlite.md#statementclose
20722120
[`worker_threads.locks`]: worker_threads.md#worker_threadslocks
20732121
[context loss]: async_context.md#troubleshooting-context-loss
2122+
[libuv thread pool]: https://docs.libuv.org/en/v1.x/threadpool.html
20742123
[thenable object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables

‎src/crypto/crypto_util.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork {
346346
CryptoJobMode mode,
347347
AdditionalParams&& params)
348348
: AsyncWrap(env, object, type),
349-
ThreadPoolWork(env, "crypto"),
349+
ThreadPoolWork(env, ThreadPoolWorkType::kCrypto),
350350
mode_(mode),
351351
params_(std::move(params)) {
352352
// If the CryptoJob is async, then the instance will be

‎src/env.cc‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include "node_buffer.h"
99
#include "node_context_data.h"
1010
#include "node_contextify.h"
11+
#include "node_diagnostics_channel.h"
1112
#include "node_dotenv.h"
1213
#include "node_errors.h"
1314
#include "node_file_utils.h"
@@ -1322,6 +1323,30 @@ Environment::~Environment() {
13221323
isolate_data_->RemoveEnvironment();
13231324
}
13241325

1326+
void Environment::InitializeThreadPoolWorkChannels() {
1327+
if (isolate_data()->is_building_snapshot()) return;
1328+
1329+
auto* binding =
1330+
principal_realm()->GetBindingData<diagnostics_channel::BindingData>();
1331+
CHECK_NOT_NULL(binding);
1332+
for (size_t i = 0; i < threadpool_work_channels_.size(); i++) {
1333+
ThreadPoolWorkChannel* entry = &threadpool_work_channels_[i];
1334+
if (entry->channel.get() != nullptr) continue;
1335+
1336+
std::string name = "uv.threadpool.work.";
1337+
name += kThreadPoolWorkNames[i];
1338+
BaseObjectPtr<diagnostics_channel::Channel> channel =
1339+
diagnostics_channel::Channel::Get(this, name);
1340+
if (!channel) continue;
1341+
1342+
binding->SetChannelStatusCallback(
1343+
channel->index(), [entry](bool active) { entry->active = active; });
1344+
entry->channel =
1345+
BaseObjectWeakPtr<diagnostics_channel::Channel>(channel.get());
1346+
entry->active = channel->HasSubscribers();
1347+
}
1348+
}
1349+
13251350
void Environment::InitializeLibuv() {
13261351
HandleScope handle_scope(isolate());
13271352
Context::Scope context_scope(context());

‎src/env.h‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@
6363
#include <ostream>
6464
#include <set>
6565
#include <string>
66+
#include <string_view>
6667
#include <unordered_map>
6768
#include <unordered_set>
6869
#include <variant>
@@ -83,6 +84,42 @@ void FreeRootCertStore(RootCertStore* root_certs);
8384
} // namespace crypto
8485
#endif // HAVE_OPENSSL
8586

87+
namespace diagnostics_channel {
88+
class Channel;
89+
}
90+
91+
struct ThreadPoolWorkChannel {
92+
BaseObjectWeakPtr<diagnostics_channel::Channel> channel;
93+
bool active = false;
94+
};
95+
96+
enum class ThreadPoolWorkType : uint8_t {
97+
kCrypto,
98+
kFsCp,
99+
kFsReadFile,
100+
kFsWriteFile,
101+
kGlob,
102+
kHistogramQrde,
103+
kNodeApi,
104+
kReadDirRecursive,
105+
kSQLiteBackup,
106+
kZlib,
107+
kCount,
108+
};
109+
110+
inline constexpr std::array<std::string_view,
111+
static_cast<size_t>(ThreadPoolWorkType::kCount)>
112+
kThreadPoolWorkNames = {"crypto",
113+
"fs.cp",
114+
"fs.readfile",
115+
"fs.writefile",
116+
"glob",
117+
"histogram.qrde",
118+
"node_api",
119+
"readdir_recursive",
120+
"node_sqlite3.BackupJob",
121+
"zlib"};
122+
86123
namespace shadow_realm {
87124
class ShadowRealm;
88125
}
@@ -745,6 +782,11 @@ class Environment final : public MemoryRetainer {
745782
void RunDeserializeRequests();
746783
// Should be called before InitializeInspector()
747784
void InitializeDiagnostics();
785+
void InitializeThreadPoolWorkChannels();
786+
inline ThreadPoolWorkChannel* threadpool_work_channel(
787+
ThreadPoolWorkType type) {
788+
return &threadpool_work_channels_[static_cast<size_t>(type)];
789+
}
748790

749791
#if HAVE_INSPECTOR
750792
// If the environment is created for a worker, pass parent_handle and
@@ -1291,6 +1333,9 @@ class Environment final : public MemoryRetainer {
12911333
AliasedInt32Array timeout_info_;
12921334
TickInfo tick_info_;
12931335
permission::Permission permission_;
1336+
std::array<ThreadPoolWorkChannel,
1337+
static_cast<size_t>(ThreadPoolWorkType::kCount)>
1338+
threadpool_work_channels_;
12941339
const uint64_t timer_base_;
12951340
std::shared_ptr<KVStore> env_vars_;
12961341
int ipc_channel_fd_ = -1;

‎src/env_properties.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,7 @@
465465
V(srv_record_template, v8::DictionaryTemplate) \
466466
V(streambaseoutputstream_constructor_template, v8::ObjectTemplate) \
467467
V(tcp_constructor_template, v8::FunctionTemplate) \
468+
V(threadpool_work_template, v8::DictionaryTemplate) \
468469
V(tlsa_record_template, v8::DictionaryTemplate) \
469470
V(tty_constructor_template, v8::FunctionTemplate) \
470471
V(txt_record_template, v8::DictionaryTemplate) \

‎src/glob/node_glob.cc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ GlobRequest::GlobRequest(Environment* env,
431431
const std::vector<CompiledPatternPtr>& excludes,
432432
std::unique_ptr<JsExcludeFilter> filter)
433433
: AsyncWrap(env, object, AsyncWrap::PROVIDER_GLOBREQUEST),
434-
ThreadPoolWork(env, "glob"),
434+
ThreadPoolWork(env, ThreadPoolWorkType::kGlob),
435435
filter_(std::move(filter)),
436436
walk_(env, options, includes, excludes),
437437
with_file_types_(options.with_file_types) {

‎src/histogram.cc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -970,7 +970,7 @@ class QrdeJob final : public ThreadPoolWork {
970970
Histogram::RecordedSnapshotSource snapshot_source,
971971
std::vector<double> probabilities,
972972
QrdeDequantization dequantization)
973-
: ThreadPoolWork(env, "histogram.qrde"),
973+
: ThreadPoolWork(env, ThreadPoolWorkType::kHistogramQrde),
974974
histogram_(std::move(histogram)),
975975
snapshot_source_(std::move(snapshot_source)),
976976
probabilities_(std::move(probabilities)),

‎src/node_api.cc‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1219,7 +1219,7 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork {
12191219
env->isolate,
12201220
async_resource,
12211221
node::Utf8Value(env->isolate, async_resource_name).ToStringView()),
1222-
ThreadPoolWork(env->node_env(), "node_api"),
1222+
ThreadPoolWork(env->node_env(), node::ThreadPoolWorkType::kNodeApi),
12231223
_env(env),
12241224
_data(data),
12251225
_execute(execute),

‎src/node_diagnostics_channel.cc‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "base_object-inl.h"
44
#include "env-inl.h"
55
#include "node_external_reference.h"
6+
#include "node_internals.h"
67
#include "util-inl.h"
78
#include "v8.h"
89

@@ -109,6 +110,7 @@ void BindingData::LinkNativeChannel(const FunctionCallbackInfo<Value>& args) {
109110
}
110111
}
111112
}
113+
realm->env()->InitializeThreadPoolWorkChannels();
112114
}
113115

114116
bool BindingData::PrepareForSerialization(Local<Context> context,
@@ -117,6 +119,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context,
117119
internal_field_info_ = InternalFieldInfoBase::New<InternalFieldInfo>(type());
118120
internal_field_info_->subscribers = subscribers_.Serialize(context, creator);
119121
internal_field_info_->subscribers_capacity = subscribers_.Length();
122+
channel_status_callbacks_.clear();
120123
link_callback_.Reset();
121124
channel_wrap_template_.Reset();
122125
DetachChannels();

0 commit comments

Comments
 (0)