@sentry/node-cpu-profiler 2.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +10 -0
  3. package/binding.gyp +20 -0
  4. package/bindings/cpu_profiler.cc +1222 -0
  5. package/lib/index.d.ts +14 -0
  6. package/lib/index.d.ts.map +1 -0
  7. package/lib/index.js +217 -0
  8. package/lib/sentry_cpu_profiler-darwin-arm64-108.node +0 -0
  9. package/lib/sentry_cpu_profiler-darwin-arm64-115.node +0 -0
  10. package/lib/sentry_cpu_profiler-darwin-arm64-127.node +0 -0
  11. package/lib/sentry_cpu_profiler-darwin-arm64-137.node +0 -0
  12. package/lib/sentry_cpu_profiler-darwin-arm64-147.node +0 -0
  13. package/lib/sentry_cpu_profiler-darwin-x64-108.node +0 -0
  14. package/lib/sentry_cpu_profiler-darwin-x64-115.node +0 -0
  15. package/lib/sentry_cpu_profiler-darwin-x64-127.node +0 -0
  16. package/lib/sentry_cpu_profiler-darwin-x64-137.node +0 -0
  17. package/lib/sentry_cpu_profiler-darwin-x64-147.node +0 -0
  18. package/lib/sentry_cpu_profiler-linux-arm64-glibc-108.node +0 -0
  19. package/lib/sentry_cpu_profiler-linux-arm64-glibc-115.node +0 -0
  20. package/lib/sentry_cpu_profiler-linux-arm64-glibc-127.node +0 -0
  21. package/lib/sentry_cpu_profiler-linux-arm64-glibc-137.node +0 -0
  22. package/lib/sentry_cpu_profiler-linux-arm64-glibc-147.node +0 -0
  23. package/lib/sentry_cpu_profiler-linux-arm64-musl-108.node +0 -0
  24. package/lib/sentry_cpu_profiler-linux-arm64-musl-115.node +0 -0
  25. package/lib/sentry_cpu_profiler-linux-arm64-musl-127.node +0 -0
  26. package/lib/sentry_cpu_profiler-linux-arm64-musl-137.node +0 -0
  27. package/lib/sentry_cpu_profiler-linux-arm64-musl-147.node +0 -0
  28. package/lib/sentry_cpu_profiler-linux-x64-glibc-108.node +0 -0
  29. package/lib/sentry_cpu_profiler-linux-x64-glibc-115.node +0 -0
  30. package/lib/sentry_cpu_profiler-linux-x64-glibc-127.node +0 -0
  31. package/lib/sentry_cpu_profiler-linux-x64-glibc-137.node +0 -0
  32. package/lib/sentry_cpu_profiler-linux-x64-glibc-147.node +0 -0
  33. package/lib/sentry_cpu_profiler-linux-x64-musl-108.node +0 -0
  34. package/lib/sentry_cpu_profiler-linux-x64-musl-115.node +0 -0
  35. package/lib/sentry_cpu_profiler-linux-x64-musl-127.node +0 -0
  36. package/lib/sentry_cpu_profiler-linux-x64-musl-137.node +0 -0
  37. package/lib/sentry_cpu_profiler-linux-x64-musl-147.node +0 -0
  38. package/lib/sentry_cpu_profiler-win32-x64-108.node +0 -0
  39. package/lib/sentry_cpu_profiler-win32-x64-115.node +0 -0
  40. package/lib/sentry_cpu_profiler-win32-x64-127.node +0 -0
  41. package/lib/sentry_cpu_profiler-win32-x64-137.node +0 -0
  42. package/lib/sentry_cpu_profiler-win32-x64-147.node +0 -0
  43. package/lib/types.d.ts +53 -0
  44. package/lib/types.d.ts.map +1 -0
  45. package/lib/types.js +8 -0
  46. package/package.json +68 -0
  47. package/scripts/binaries.js +27 -0
  48. package/scripts/check-build.js +57 -0
  49. package/scripts/copy-target.js +28 -0
@@ -0,0 +1,1222 @@
1
+ #ifndef NOMINMAX
2
+ #define NOMINMAX
3
+ #endif
4
+
5
+ #include <assert.h>
6
+ #include <math.h>
7
+ #include <node_api.h>
8
+ #include <string.h>
9
+ #include <uv.h>
10
+ #include <v8-profiler.h>
11
+ #include <v8.h>
12
+
13
+ #include <chrono>
14
+ #include <functional>
15
+ #include <string>
16
+ #include <unordered_map>
17
+
18
+ static const uint8_t kMaxStackDepth(128);
19
+ static const uint16_t kMaxMeasurementSamples(300);
20
+ static const float kSamplingFrequency(99.0); // 99 to avoid lockstep sampling
21
+ static const float kSamplingHz(1 / kSamplingFrequency);
22
+ static const int kSamplingInterval(kSamplingHz * 1e6);
23
+ static const v8::CpuProfilingNamingMode
24
+ kNamingMode(v8::CpuProfilingNamingMode::kDebugNaming);
25
+ static const v8::CpuProfilingLoggingMode
26
+ kDefaultLoggingMode(v8::CpuProfilingLoggingMode::kEagerLogging);
27
+
28
+ enum ProfileFormat {
29
+ kFormatThread = 0,
30
+ kFormatChunk = 1,
31
+ };
32
+
33
+ // Allow users to override the default logging mode via env variable. This is
34
+ // useful because sometimes the flow of the profiled program can be to execute
35
+ // many sequential transaction - in that case, it may be preferable to set eager
36
+ // logging to avoid paying the high cost of profiling for each individual
37
+ // transaction (one example for this are jest tests when run with --runInBand
38
+ // option).
39
+ static const char *kEagerLoggingMode = "eager";
40
+ static const char *kLazyLoggingMode = "lazy";
41
+
42
+ v8::CpuProfilingLoggingMode GetLoggingMode() {
43
+ static const char *logging_mode(getenv("SENTRY_PROFILER_LOGGING_MODE"));
44
+
45
+ // most times this wont be set so just bail early
46
+ if (!logging_mode) {
47
+ return kDefaultLoggingMode;
48
+ }
49
+
50
+ // other times it'll likely be set to lazy as eager is the default
51
+ if (strcmp(logging_mode, kLazyLoggingMode) == 0) {
52
+ return v8::CpuProfilingLoggingMode::kLazyLogging;
53
+ } else if (strcmp(logging_mode, kEagerLoggingMode) == 0) {
54
+ return v8::CpuProfilingLoggingMode::kEagerLogging;
55
+ }
56
+
57
+ return kDefaultLoggingMode;
58
+ }
59
+
60
+ uint64_t timestamp_milliseconds() {
61
+ return std::chrono::duration_cast<std::chrono::milliseconds>(
62
+ std::chrono::system_clock::now().time_since_epoch())
63
+ .count();
64
+ }
65
+
66
+ class SentryProfile;
67
+ class Profiler;
68
+
69
+ enum class ProfileStatus {
70
+ kNotStarted,
71
+ kStarted,
72
+ kStopped,
73
+ };
74
+
75
+ class MeasurementsTicker {
76
+ private:
77
+ uv_timer_t *timer;
78
+ uint64_t period_ms;
79
+ std::unordered_map<std::string,
80
+ const std::function<bool(uint64_t, v8::HeapStatistics &)>>
81
+ heap_listeners;
82
+ std::unordered_map<std::string, const std::function<bool(uint64_t, double)>>
83
+ cpu_listeners;
84
+ v8::Isolate *isolate;
85
+ v8::HeapStatistics heap_stats;
86
+ uv_cpu_info_t cpu_stats;
87
+
88
+ public:
89
+ MeasurementsTicker(uv_loop_t *loop)
90
+ : period_ms(100), isolate(v8::Isolate::GetCurrent()) {
91
+ timer = new uv_timer_t;
92
+ uv_timer_init(loop, timer);
93
+ uv_handle_set_data((uv_handle_t *)timer, this);
94
+ uv_ref((uv_handle_t *)timer);
95
+ }
96
+
97
+ static void ticker(uv_timer_t *);
98
+ // Memory listeners
99
+ void heap_callback();
100
+ void add_heap_listener(
101
+ std::string &profile_id,
102
+ const std::function<bool(uint64_t, v8::HeapStatistics &)> cb);
103
+ void remove_heap_listener(
104
+ std::string &profile_id,
105
+ const std::function<bool(uint64_t, v8::HeapStatistics &)> &cb);
106
+
107
+ // CPU listeners
108
+ void cpu_callback();
109
+ void add_cpu_listener(std::string &profile_id,
110
+ const std::function<bool(uint64_t, double)> cb);
111
+ void remove_cpu_listener(std::string &profile_id,
112
+ const std::function<bool(uint64_t, double)> &cb);
113
+
114
+ size_t listener_count();
115
+
116
+ ~MeasurementsTicker() {
117
+ uv_handle_t *handle = (uv_handle_t *)timer;
118
+
119
+ uv_timer_stop(timer);
120
+ uv_unref(handle);
121
+
122
+ if (!uv_is_closing(handle)) {
123
+ uv_close(handle, [](uv_handle_t *handle) { delete handle; });
124
+ }
125
+ }
126
+ };
127
+
128
+ size_t MeasurementsTicker::listener_count() {
129
+ return heap_listeners.size() + cpu_listeners.size();
130
+ }
131
+
132
+ // Heap tickers
133
+ void MeasurementsTicker::heap_callback() {
134
+ isolate->GetHeapStatistics(&heap_stats);
135
+ uint64_t ts = uv_hrtime();
136
+
137
+ for (auto cb : heap_listeners) {
138
+ cb.second(ts, heap_stats);
139
+ }
140
+ }
141
+
142
+ void MeasurementsTicker::add_heap_listener(
143
+ std::string &profile_id,
144
+ const std::function<bool(uint64_t, v8::HeapStatistics &)> cb) {
145
+ heap_listeners.emplace(profile_id, cb);
146
+
147
+ if (listener_count() == 1) {
148
+ uv_timer_set_repeat(timer, period_ms);
149
+ uv_timer_start(timer, ticker, 0, period_ms);
150
+ }
151
+ }
152
+
153
+ void MeasurementsTicker::remove_heap_listener(
154
+ std::string &profile_id,
155
+ const std::function<bool(uint64_t, v8::HeapStatistics &)> &cb) {
156
+ heap_listeners.erase(profile_id);
157
+
158
+ if (listener_count() == 0) {
159
+ uv_timer_stop(timer);
160
+ }
161
+ };
162
+
163
+ // CPU tickers
164
+ void MeasurementsTicker::cpu_callback() {
165
+ uv_cpu_info_t *cpu = &cpu_stats;
166
+ int count;
167
+ int err = uv_cpu_info(&cpu, &count);
168
+
169
+ if (err) {
170
+ return;
171
+ }
172
+
173
+ if (count < 1) {
174
+ return;
175
+ }
176
+
177
+ uint64_t ts = uv_hrtime();
178
+ uint64_t total = 0;
179
+ uint64_t idle_total = 0;
180
+
181
+ for (int i = 0; i < count; i++) {
182
+ uv_cpu_info_t *core = cpu + i;
183
+
184
+ total += core->cpu_times.user;
185
+ total += core->cpu_times.nice;
186
+ total += core->cpu_times.sys;
187
+ total += core->cpu_times.idle;
188
+ total += core->cpu_times.irq;
189
+
190
+ idle_total += core->cpu_times.idle;
191
+ }
192
+
193
+ double idle_avg = static_cast<double>(idle_total) / count;
194
+ double total_avg = static_cast<double>(total) / count;
195
+ double rate = 1.0 - idle_avg / total_avg;
196
+
197
+ if (rate < 0.0 || isinf(rate) || isnan(rate)) {
198
+ rate = 0.0;
199
+ }
200
+
201
+ auto it = cpu_listeners.begin();
202
+ while (it != cpu_listeners.end()) {
203
+ if (it->second(ts, rate)) {
204
+ it = cpu_listeners.erase(it);
205
+ } else {
206
+ ++it;
207
+ }
208
+ };
209
+
210
+ uv_free_cpu_info(cpu, count);
211
+ };
212
+
213
+ void MeasurementsTicker::ticker(uv_timer_t *handle) {
214
+ if (handle == nullptr) {
215
+ return;
216
+ }
217
+
218
+ MeasurementsTicker *self = static_cast<MeasurementsTicker *>(handle->data);
219
+ self->heap_callback();
220
+ self->cpu_callback();
221
+ }
222
+
223
+ void MeasurementsTicker::add_cpu_listener(
224
+ std::string &profile_id, const std::function<bool(uint64_t, double)> cb) {
225
+ cpu_listeners.emplace(profile_id, cb);
226
+
227
+ if (listener_count() == 1) {
228
+ uv_timer_set_repeat(timer, period_ms);
229
+ uv_timer_start(timer, ticker, 0, period_ms);
230
+ }
231
+ }
232
+
233
+ void MeasurementsTicker::remove_cpu_listener(
234
+ std::string &profile_id, const std::function<bool(uint64_t, double)> &cb) {
235
+ cpu_listeners.erase(profile_id);
236
+
237
+ if (listener_count() == 0) {
238
+ uv_timer_stop(timer);
239
+ }
240
+ };
241
+
242
+ class Profiler {
243
+ public:
244
+ std::unordered_map<std::string, SentryProfile *> active_profiles;
245
+
246
+ MeasurementsTicker measurements_ticker;
247
+ v8::CpuProfiler *cpu_profiler;
248
+
249
+ explicit Profiler(napi_env env, v8::Isolate *isolate)
250
+ : measurements_ticker(uv_default_loop()),
251
+ cpu_profiler(
252
+ v8::CpuProfiler::New(isolate, kNamingMode, GetLoggingMode())) {}
253
+ };
254
+
255
+ class SentryProfile {
256
+ private:
257
+ uint64_t started_at;
258
+ uint64_t timestamp;
259
+ uint16_t heap_write_index = 0;
260
+ uint16_t cpu_write_index = 0;
261
+
262
+ std::vector<uint64_t> heap_stats_ts;
263
+ std::vector<uint64_t> heap_stats_usage;
264
+
265
+ std::vector<uint64_t> cpu_stats_ts;
266
+ std::vector<double> cpu_stats_usage;
267
+
268
+ const std::function<bool(uint64_t, v8::HeapStatistics &)> memory_sampler_cb;
269
+ const std::function<bool(uint64_t, double)> cpu_sampler_cb;
270
+
271
+ ProfileStatus status = ProfileStatus::kNotStarted;
272
+ std::string id;
273
+
274
+ public:
275
+ explicit SentryProfile(const char *id)
276
+ : started_at(uv_hrtime()), timestamp(timestamp_milliseconds()),
277
+ memory_sampler_cb([this](uint64_t ts, v8::HeapStatistics &stats) {
278
+ if (heap_write_index >= kMaxMeasurementSamples) {
279
+ return true;
280
+ }
281
+
282
+ heap_stats_ts.push_back(ts - started_at);
283
+ heap_stats_usage.push_back(
284
+ static_cast<uint64_t>(stats.used_heap_size()));
285
+ ++heap_write_index;
286
+
287
+ return false;
288
+ }),
289
+
290
+ cpu_sampler_cb([this](uint64_t ts, double rate) {
291
+ if (cpu_write_index >= kMaxMeasurementSamples) {
292
+ return true;
293
+ }
294
+ cpu_stats_ts.push_back(ts - started_at);
295
+ cpu_stats_usage.push_back(rate);
296
+ ++cpu_write_index;
297
+ return false;
298
+ }),
299
+
300
+ status(ProfileStatus::kNotStarted), id(id) {
301
+ heap_stats_ts.reserve(kMaxMeasurementSamples);
302
+ heap_stats_usage.reserve(kMaxMeasurementSamples);
303
+ cpu_stats_ts.reserve(kMaxMeasurementSamples);
304
+ cpu_stats_usage.reserve(kMaxMeasurementSamples);
305
+ }
306
+
307
+ const std::vector<uint64_t> &heap_usage_timestamps() const;
308
+ const std::vector<uint64_t> &heap_usage_values() const;
309
+ const uint16_t &heap_usage_write_index() const;
310
+
311
+ const std::vector<uint64_t> &cpu_usage_timestamps() const;
312
+ const std::vector<double> &cpu_usage_values() const;
313
+ const uint16_t &cpu_usage_write_index() const;
314
+ const uint64_t &profile_start_timestamp() const;
315
+
316
+ void Start(Profiler *profiler);
317
+ v8::CpuProfile *Stop(Profiler *profiler);
318
+ };
319
+
320
+ void SentryProfile::Start(Profiler *profiler) {
321
+ v8::Local<v8::String> profile_title =
322
+ v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), id.c_str(),
323
+ v8::NewStringType::kNormal)
324
+ .ToLocalChecked();
325
+
326
+ started_at = uv_hrtime();
327
+ timestamp = timestamp_milliseconds();
328
+
329
+ // Initialize the CPU Profiler
330
+ profiler->cpu_profiler->StartProfiling(
331
+ profile_title, v8::CpuProfilingMode::kCallerLineNumbers, true,
332
+ v8::CpuProfilingOptions::kNoSampleLimit);
333
+
334
+ // listen for memory sample ticks
335
+ profiler->measurements_ticker.add_cpu_listener(id, cpu_sampler_cb);
336
+ profiler->measurements_ticker.add_heap_listener(id, memory_sampler_cb);
337
+
338
+ status = ProfileStatus::kStarted;
339
+ }
340
+
341
+ v8::CpuProfile *SentryProfile::Stop(Profiler *profiler) {
342
+ if (status != ProfileStatus::kStarted) {
343
+ return nullptr;
344
+ }
345
+
346
+ // Stop the CPU Profiler
347
+ v8::CpuProfile *profile = profiler->cpu_profiler->StopProfiling(
348
+ v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), id.c_str(),
349
+ v8::NewStringType::kNormal)
350
+ .ToLocalChecked());
351
+
352
+ // Remove the memory sampler
353
+ profiler->measurements_ticker.remove_heap_listener(id, memory_sampler_cb);
354
+ profiler->measurements_ticker.remove_cpu_listener(id, cpu_sampler_cb);
355
+ // If for some reason stopProfiling was called with an invalid profile title
356
+ // or if that title had somehow been stopped already, profile will be null.
357
+ status = ProfileStatus::kStopped;
358
+ return profile;
359
+ }
360
+
361
+ // Memory getters
362
+ const std::vector<uint64_t> &SentryProfile::heap_usage_timestamps() const {
363
+ return heap_stats_ts;
364
+ };
365
+
366
+ const std::vector<uint64_t> &SentryProfile::heap_usage_values() const {
367
+ return heap_stats_usage;
368
+ };
369
+
370
+ const uint16_t &SentryProfile::heap_usage_write_index() const {
371
+ return heap_write_index;
372
+ };
373
+
374
+ // CPU getters
375
+ const std::vector<uint64_t> &SentryProfile::cpu_usage_timestamps() const {
376
+ return cpu_stats_ts;
377
+ };
378
+
379
+ const std::vector<double> &SentryProfile::cpu_usage_values() const {
380
+ return cpu_stats_usage;
381
+ };
382
+ const uint16_t &SentryProfile::cpu_usage_write_index() const {
383
+ return cpu_write_index;
384
+ };
385
+ const uint64_t &SentryProfile::profile_start_timestamp() const {
386
+ return timestamp;
387
+ }
388
+
389
+ static void CleanupSentryProfile(Profiler *profiler,
390
+ SentryProfile *sentry_profile,
391
+ const std::string &profile_id) {
392
+ if (sentry_profile == nullptr) {
393
+ return;
394
+ }
395
+
396
+ sentry_profile->Stop(profiler);
397
+ profiler->active_profiles.erase(profile_id);
398
+ delete sentry_profile;
399
+ };
400
+
401
+ #ifdef _WIN32
402
+ static const char kPlatformSeparator = '\\';
403
+ static const char kWinDiskPrefix = ':';
404
+ #else
405
+ static const char kPlatformSeparator = '/';
406
+ #endif
407
+
408
+ static const char kSentryPathDelimiter = '.';
409
+ static const char kSentryFileDelimiter = ':';
410
+ static const std::string kNodeModulesPath =
411
+ std::string("node_modules") + kPlatformSeparator;
412
+
413
+ static void GetFrameModule(const std::string &abs_path, std::string &module) {
414
+ if (abs_path.empty()) {
415
+ return;
416
+ }
417
+
418
+ module = abs_path;
419
+
420
+ // Drop .js extension
421
+ size_t module_len = module.length();
422
+ if (module.compare(module_len - 3, 3, ".js") == 0) {
423
+ module = module.substr(0, module_len - 3);
424
+ }
425
+
426
+ // Drop anything before and including node_modules/
427
+ size_t node_modules_pos = module.rfind(kNodeModulesPath);
428
+ if (node_modules_pos != std::string::npos) {
429
+ module = module.substr(node_modules_pos + 13);
430
+ }
431
+
432
+ // Replace all path separators with dots except the last one, that one is
433
+ // replaced with a colon
434
+ int match_count = 0;
435
+ for (int pos = module.length() - 1; pos >= 0; pos--) {
436
+ // if there is a match and it's not the first character, replace it
437
+ if (module[pos] == kPlatformSeparator) {
438
+ module[pos] =
439
+ match_count == 0 ? kSentryFileDelimiter : kSentryPathDelimiter;
440
+ match_count++;
441
+ }
442
+ }
443
+
444
+ #ifdef _WIN32
445
+ // Strip out C: prefix. On Windows, the drive letter is not part of the module
446
+ // name
447
+ if (module[1] == kWinDiskPrefix) {
448
+ // We will try and strip our the disk prefix.
449
+ module = module.substr(2, std::string::npos);
450
+ }
451
+ #endif
452
+
453
+ if (module[0] == '.') {
454
+ module = module.substr(1, std::string::npos);
455
+ }
456
+ }
457
+
458
+ static napi_value GetFrameModuleWrapped(napi_env env, napi_callback_info info) {
459
+ size_t argc = 2;
460
+ napi_value argv[2];
461
+ napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
462
+
463
+ size_t len;
464
+ assert(napi_get_value_string_utf8(env, argv[0], NULL, 0, &len) == napi_ok);
465
+
466
+ std::string abs_path(len, '\0');
467
+ assert(napi_get_value_string_utf8(env, argv[0], &abs_path[0], len + 1,
468
+ &len) == napi_ok);
469
+
470
+ std::string module;
471
+ napi_value napi_module;
472
+
473
+ GetFrameModule(abs_path, module);
474
+
475
+ assert(napi_create_string_utf8(env, module.c_str(), NAPI_AUTO_LENGTH,
476
+ &napi_module) == napi_ok);
477
+ return napi_module;
478
+ }
479
+
480
+ napi_value
481
+ CreateFrameNode(napi_env env, const v8::CpuProfileNode &node,
482
+ std::unordered_map<std::string, std::string> &module_cache,
483
+ napi_value &resources) {
484
+ napi_value js_node;
485
+ napi_create_object(env, &js_node);
486
+
487
+ napi_value lineno_prop;
488
+ napi_create_int32(env, node.GetLineNumber(), &lineno_prop);
489
+ napi_set_named_property(env, js_node, "lineno", lineno_prop);
490
+
491
+ napi_value colno_prop;
492
+ napi_create_int32(env, node.GetColumnNumber(), &colno_prop);
493
+ napi_set_named_property(env, js_node, "colno", colno_prop);
494
+
495
+ if (node.GetSourceType() != v8::CpuProfileNode::SourceType::kScript) {
496
+ napi_value system_frame_prop;
497
+ napi_get_boolean(env, false, &system_frame_prop);
498
+ napi_set_named_property(env, js_node, "in_app", system_frame_prop);
499
+ }
500
+
501
+ napi_value function;
502
+ napi_create_string_utf8(env, node.GetFunctionNameStr(), NAPI_AUTO_LENGTH,
503
+ &function);
504
+ napi_set_named_property(env, js_node, "function", function);
505
+
506
+ const char *resource = node.GetScriptResourceNameStr();
507
+
508
+ if (resource != nullptr) {
509
+ // resource is absolute path, set it on the abs_path property
510
+ napi_value abs_path_prop;
511
+ napi_create_string_utf8(env, resource, NAPI_AUTO_LENGTH, &abs_path_prop);
512
+ napi_set_named_property(env, js_node, "abs_path", abs_path_prop);
513
+ // Error stack traces are not relative to root dir, doing our own path
514
+ // normalization breaks people's code mapping configs so we need to leave it
515
+ // as is.
516
+ napi_set_named_property(env, js_node, "filename", abs_path_prop);
517
+
518
+ std::string module;
519
+ std::string resource_str = std::string(resource);
520
+
521
+ if (resource_str.empty()) {
522
+ return js_node;
523
+ }
524
+
525
+ if (module_cache.find(resource_str) != module_cache.end()) {
526
+ module = module_cache[resource_str];
527
+ } else {
528
+ napi_value resource;
529
+ napi_create_string_utf8(env, resource_str.c_str(), NAPI_AUTO_LENGTH,
530
+ &resource);
531
+ napi_set_element(env, resources, module_cache.size(), resource);
532
+
533
+ GetFrameModule(resource_str, module);
534
+ module_cache.emplace(resource_str, module);
535
+ }
536
+
537
+ if (!module.empty()) {
538
+ napi_value filename_prop;
539
+ napi_create_string_utf8(env, module.c_str(), NAPI_AUTO_LENGTH,
540
+ &filename_prop);
541
+ napi_set_named_property(env, js_node, "module", filename_prop);
542
+ }
543
+ }
544
+
545
+ return js_node;
546
+ };
547
+
548
+ napi_value CreateSample(napi_env env, const enum ProfileFormat format,
549
+ const uint32_t stack_id,
550
+ const int64_t sample_timestamp_ns,
551
+ const double chunk_timestamp,
552
+ const uint32_t thread_id) {
553
+ napi_value js_node;
554
+ napi_create_object(env, &js_node);
555
+
556
+ napi_value stack_id_prop;
557
+ napi_create_uint32(env, stack_id, &stack_id_prop);
558
+ napi_set_named_property(env, js_node, "stack_id", stack_id_prop);
559
+
560
+ napi_value thread_id_prop;
561
+ napi_create_string_utf8(env, std::to_string(thread_id).c_str(),
562
+ NAPI_AUTO_LENGTH, &thread_id_prop);
563
+ napi_set_named_property(env, js_node, "thread_id", thread_id_prop);
564
+
565
+ switch (format) {
566
+ case ProfileFormat::kFormatThread: {
567
+ napi_value timestamp;
568
+ napi_create_string_utf8(env, std::to_string(sample_timestamp_ns).c_str(),
569
+ NAPI_AUTO_LENGTH, &timestamp);
570
+ napi_set_named_property(env, js_node, "elapsed_since_start_ns", timestamp);
571
+ } break;
572
+ case ProfileFormat::kFormatChunk: {
573
+ napi_value timestamp;
574
+ napi_create_double(env, chunk_timestamp, &timestamp);
575
+ napi_set_named_property(env, js_node, "timestamp", timestamp);
576
+ } break;
577
+ default:
578
+ break;
579
+ }
580
+
581
+ return js_node;
582
+ };
583
+
584
+ std::string kDelimiter = std::string(";");
585
+ std::string hashCpuProfilerNodeByPath(const v8::CpuProfileNode *node,
586
+ std::string &path) {
587
+ path.clear();
588
+
589
+ while (node != nullptr) {
590
+ path.append(std::to_string(node->GetNodeId()));
591
+ node = node->GetParent();
592
+ }
593
+
594
+ return path;
595
+ }
596
+
597
+ static void GetSamples(napi_env env, const v8::CpuProfile *profile,
598
+ ProfileFormat format,
599
+ const uint64_t profile_start_timestamp_ms,
600
+ const uint32_t thread_id, napi_value &samples,
601
+ napi_value &stacks, napi_value &frames,
602
+ napi_value &resources) {
603
+ const int64_t profile_start_time_us = profile->GetStartTime();
604
+ const int64_t sampleCount = profile->GetSamplesCount();
605
+
606
+ uint32_t unique_stack_id = 0;
607
+ uint32_t unique_frame_id = 0;
608
+
609
+ // Initialize the lookup tables for stacks and frames, both of these are
610
+ // indexed in the sample format we are using to optimize for size.
611
+ std::unordered_map<uint32_t, uint32_t> frame_lookup_table;
612
+ std::unordered_map<std::string, uint32_t> stack_lookup_table;
613
+ std::unordered_map<std::string, std::string> module_cache;
614
+
615
+ // At worst, all stacks are unique so reserve the maximum amount of space
616
+ stack_lookup_table.reserve(sampleCount);
617
+
618
+ std::string node_hash = "";
619
+
620
+ for (int i = 0; i < sampleCount; i++) {
621
+ uint32_t stack_index = unique_stack_id;
622
+
623
+ const v8::CpuProfileNode *node = profile->GetSample(i);
624
+ const int64_t sample_timestamp_us = profile->GetSampleTimestamp(i);
625
+
626
+ // If a node was only on top of the stack once, then it will only ever
627
+ // be inserted once and there is no need for hashing.
628
+ if (node->GetHitCount() > 1) {
629
+ hashCpuProfilerNodeByPath(node, node_hash);
630
+
631
+ std::unordered_map<std::string, uint32_t>::iterator
632
+ stack_index_cache_hit = stack_lookup_table.find(node_hash);
633
+
634
+ // If we have a hit, update the stack index, otherwise
635
+ // insert it into the hash table and continue.
636
+ if (stack_index_cache_hit == stack_lookup_table.end()) {
637
+ stack_lookup_table.emplace(node_hash, stack_index);
638
+ } else {
639
+ stack_index = stack_index_cache_hit->second;
640
+ }
641
+ }
642
+
643
+ uint64_t sample_delta_us = sample_timestamp_us - profile_start_time_us;
644
+ uint64_t sample_timestamp_ns = sample_delta_us * 1000;
645
+ uint64_t sample_offset_from_profile_start_ms = sample_delta_us / 1000;
646
+ double seconds_since_start =
647
+ (profile_start_timestamp_ms + sample_offset_from_profile_start_ms) *
648
+ 1e-3;
649
+
650
+ napi_value sample = nullptr;
651
+ sample = CreateSample(env, format, stack_index, sample_timestamp_ns,
652
+ seconds_since_start, thread_id);
653
+
654
+ if (stack_index != unique_stack_id) {
655
+ napi_value index;
656
+ napi_create_uint32(env, i, &index);
657
+ napi_set_property(env, samples, index, sample);
658
+ continue;
659
+ }
660
+
661
+ // A stack is a list of frames ordered from outermost (top) to innermost
662
+ // frame (bottom)
663
+ napi_value stack;
664
+ napi_create_array(env, &stack);
665
+
666
+ uint32_t stack_depth = 0;
667
+
668
+ while (node != nullptr && stack_depth < kMaxStackDepth) {
669
+ auto nodeId = node->GetNodeId();
670
+ auto frame_index = frame_lookup_table.find(nodeId);
671
+
672
+ // If the frame does not exist in the index
673
+ if (frame_index == frame_lookup_table.end()) {
674
+ frame_lookup_table.emplace(nodeId, unique_frame_id);
675
+
676
+ napi_value frame_id;
677
+ napi_create_uint32(env, unique_frame_id, &frame_id);
678
+
679
+ napi_value depth;
680
+ napi_create_uint32(env, stack_depth, &depth);
681
+ napi_set_property(env, stack, depth, frame_id);
682
+ napi_set_property(env, frames, frame_id,
683
+ CreateFrameNode(env, *node, module_cache, resources));
684
+
685
+ unique_frame_id++;
686
+ } else {
687
+ // If it was already indexed, just add it's id to the stack
688
+ napi_value depth;
689
+ napi_create_uint32(env, stack_depth, &depth);
690
+
691
+ napi_value frame;
692
+ napi_create_uint32(env, frame_index->second, &frame);
693
+ napi_set_property(env, stack, depth, frame);
694
+ };
695
+
696
+ // Continue walking down the stack
697
+ node = node->GetParent();
698
+ stack_depth++;
699
+ }
700
+
701
+ napi_value napi_sample_index;
702
+ napi_value napi_stack_index;
703
+
704
+ napi_create_uint32(env, i, &napi_sample_index);
705
+ napi_set_property(env, samples, napi_sample_index, sample);
706
+ napi_create_uint32(env, stack_index, &napi_stack_index);
707
+ napi_set_property(env, stacks, napi_stack_index, stack);
708
+
709
+ unique_stack_id++;
710
+ }
711
+ }
712
+
713
+ static napi_value TranslateMeasurementsDouble(
714
+ napi_env env, const enum ProfileFormat format, const char *unit,
715
+ const uint64_t profile_start_timestamp_ms, const uint16_t size,
716
+ const std::vector<double> &values,
717
+ const std::vector<uint64_t> &timestamps_ns) {
718
+ if (size > values.size() || size > timestamps_ns.size()) {
719
+ napi_throw_range_error(env, "NAPI_ERROR",
720
+ "CPU measurement size is larger than the number of "
721
+ "values or timestamps");
722
+ return nullptr;
723
+ }
724
+
725
+ if (values.size() != timestamps_ns.size()) {
726
+ napi_throw_range_error(env, "NAPI_ERROR",
727
+ "CPU measurement entries are corrupt, expected "
728
+ "values and timestamps to be of equal length");
729
+ return nullptr;
730
+ }
731
+
732
+ napi_value measurement;
733
+ napi_create_object(env, &measurement);
734
+
735
+ napi_value unit_string;
736
+ napi_create_string_utf8(env, unit, NAPI_AUTO_LENGTH, &unit_string);
737
+ napi_set_named_property(env, measurement, "unit", unit_string);
738
+
739
+ napi_value values_array;
740
+ napi_create_array(env, &values_array);
741
+
742
+ uint16_t idx = size;
743
+
744
+ for (size_t i = 0; i < idx; i++) {
745
+ napi_value entry;
746
+ napi_create_object(env, &entry);
747
+
748
+ napi_value value;
749
+ if (napi_create_double(env, values[i], &value) != napi_ok) {
750
+ if (napi_create_double(env, 0.0, &value) != napi_ok) {
751
+ continue;
752
+ }
753
+ }
754
+
755
+ napi_set_named_property(env, entry, "value", value);
756
+
757
+ if (format == ProfileFormat::kFormatThread) {
758
+ napi_value ts;
759
+ napi_create_int64(env, timestamps_ns[i], &ts);
760
+ napi_set_named_property(env, entry, "elapsed_since_start_ns", ts);
761
+ } else if (format == ProfileFormat::kFormatChunk) {
762
+ napi_value ts;
763
+ napi_create_double(
764
+ env, profile_start_timestamp_ms + (timestamps_ns[i] * 1e-9), &ts);
765
+ napi_set_named_property(env, entry, "timestamp", ts);
766
+ }
767
+
768
+ napi_set_element(env, values_array, i, entry);
769
+ }
770
+
771
+ napi_set_named_property(env, measurement, "values", values_array);
772
+
773
+ return measurement;
774
+ }
775
+
776
+ static napi_value
777
+ TranslateMeasurements(napi_env env, const enum ProfileFormat format,
778
+ const char *unit,
779
+ const uint64_t profile_start_timestamp_ms,
780
+ const uint16_t size, const std::vector<uint64_t> &values,
781
+ const std::vector<uint64_t> &timestamps_ns) {
782
+ if (size > values.size() || size > timestamps_ns.size()) {
783
+ napi_throw_range_error(env, "NAPI_ERROR",
784
+ "Memory measurement size is larger than the number "
785
+ "of values or timestamps");
786
+ return nullptr;
787
+ }
788
+
789
+ if (values.size() != timestamps_ns.size()) {
790
+ napi_throw_range_error(env, "NAPI_ERROR",
791
+ "Memory measurement entries are corrupt, expected "
792
+ "values and timestamps to be of equal length");
793
+ return nullptr;
794
+ }
795
+
796
+ napi_value measurement;
797
+ napi_create_object(env, &measurement);
798
+
799
+ napi_value unit_string;
800
+ napi_create_string_utf8(env, unit, NAPI_AUTO_LENGTH, &unit_string);
801
+ napi_set_named_property(env, measurement, "unit", unit_string);
802
+
803
+ napi_value values_array;
804
+ napi_create_array(env, &values_array);
805
+
806
+ for (size_t i = 0; i < size; i++) {
807
+ napi_value entry;
808
+ napi_create_object(env, &entry);
809
+
810
+ napi_value value;
811
+ napi_create_int64(env, values[i], &value);
812
+
813
+ napi_set_named_property(env, entry, "value", value);
814
+ switch (format) {
815
+ case ProfileFormat::kFormatThread: {
816
+ napi_value ts;
817
+ napi_create_int64(env, timestamps_ns[i], &ts);
818
+ napi_set_named_property(env, entry, "elapsed_since_start_ns", ts);
819
+ } break;
820
+ case ProfileFormat::kFormatChunk: {
821
+ napi_value ts;
822
+ napi_create_double(
823
+ env, profile_start_timestamp_ms + (timestamps_ns[i] * 1e-9), &ts);
824
+ napi_set_named_property(env, entry, "timestamp", ts);
825
+ } break;
826
+ default:
827
+ break;
828
+ }
829
+ napi_set_element(env, values_array, i, entry);
830
+ }
831
+
832
+ napi_set_named_property(env, measurement, "values", values_array);
833
+
834
+ return measurement;
835
+ }
836
+
837
+ static napi_value TranslateProfile(napi_env env, const v8::CpuProfile *profile,
838
+ const enum ProfileFormat format,
839
+ const uint64_t profile_start_timestamp_ms,
840
+ const uint32_t thread_id,
841
+ bool collect_resources) {
842
+ napi_value js_profile;
843
+
844
+ napi_create_object(env, &js_profile);
845
+
846
+ napi_value logging_mode;
847
+ napi_value samples;
848
+ napi_value stacks;
849
+ napi_value frames;
850
+ napi_value resources;
851
+
852
+ napi_create_string_utf8(
853
+ env,
854
+ GetLoggingMode() == v8::CpuProfilingLoggingMode::kEagerLogging ? "eager"
855
+ : "lazy",
856
+ NAPI_AUTO_LENGTH, &logging_mode);
857
+
858
+ napi_create_array(env, &samples);
859
+ napi_create_array(env, &stacks);
860
+ napi_create_array(env, &frames);
861
+ napi_create_array(env, &resources);
862
+
863
+ napi_set_named_property(env, js_profile, "samples", samples);
864
+ napi_set_named_property(env, js_profile, "stacks", stacks);
865
+ napi_set_named_property(env, js_profile, "frames", frames);
866
+ napi_set_named_property(env, js_profile, "profiler_logging_mode",
867
+ logging_mode);
868
+
869
+ GetSamples(env, profile, format, profile_start_timestamp_ms, thread_id,
870
+ samples, stacks, frames, resources);
871
+
872
+ if (collect_resources) {
873
+ napi_set_named_property(env, js_profile, "resources", resources);
874
+ } else {
875
+ napi_create_array(env, &resources);
876
+ napi_set_named_property(env, js_profile, "resources", resources);
877
+ }
878
+
879
+ return js_profile;
880
+ }
881
+
882
+ static napi_value StartProfiling(napi_env env, napi_callback_info info) {
883
+ size_t argc = 1;
884
+ napi_value argv[1];
885
+
886
+ assert(napi_get_cb_info(env, info, &argc, argv, NULL, NULL) == napi_ok);
887
+
888
+ napi_valuetype callbacktype0;
889
+ assert(napi_typeof(env, argv[0], &callbacktype0) == napi_ok);
890
+
891
+ if (callbacktype0 != napi_string) {
892
+ napi_throw_error(
893
+ env, "NAPI_ERROR",
894
+ "TypeError: StartProfiling expects a string as first argument.");
895
+ napi_value napi_null;
896
+ assert(napi_get_null(env, &napi_null) == napi_ok);
897
+
898
+ return napi_null;
899
+ }
900
+
901
+ size_t len;
902
+ assert(napi_get_value_string_utf8(env, argv[0], NULL, 0, &len) == napi_ok);
903
+
904
+ std::string title(len, '\0');
905
+ assert(napi_get_value_string_utf8(env, argv[0], &title[0], len + 1, &len) ==
906
+ napi_ok);
907
+
908
+ if (len < 1) {
909
+ napi_throw_error(env, "NAPI_ERROR",
910
+ "StartProfiling expects a non-empty string as first "
911
+ "argument, got an empty string.");
912
+
913
+ napi_value napi_null;
914
+ assert(napi_get_null(env, &napi_null) == napi_ok);
915
+
916
+ return napi_null;
917
+ }
918
+
919
+ v8::Isolate *isolate = v8::Isolate::GetCurrent();
920
+ assert(isolate != 0);
921
+
922
+ Profiler *profiler;
923
+ assert(napi_get_instance_data(env, (void **)&profiler) == napi_ok);
924
+
925
+ if (!profiler) {
926
+ napi_throw_error(env, "NAPI_ERROR",
927
+ "StartProfiling: Profiler is not initialized.");
928
+
929
+ napi_value napi_null;
930
+ assert(napi_get_null(env, &napi_null) == napi_ok);
931
+
932
+ return napi_null;
933
+ }
934
+
935
+ // In case we have a collision, cleanup the old profile first
936
+ auto existing_profile = profiler->active_profiles.find(title);
937
+ if (existing_profile != profiler->active_profiles.end()) {
938
+ existing_profile->second->Stop(profiler);
939
+ CleanupSentryProfile(profiler, existing_profile->second, title);
940
+ }
941
+
942
+ SentryProfile *sentry_profile = new SentryProfile(title.c_str());
943
+ sentry_profile->Start(profiler);
944
+
945
+ profiler->active_profiles.emplace(title, sentry_profile);
946
+
947
+ napi_value napi_null;
948
+ assert(napi_get_null(env, &napi_null) == napi_ok);
949
+
950
+ return napi_null;
951
+ }
952
+
953
+ // StopProfiling(string title)
954
+ // https://v8docs.nodesource.com/node-18.2/d2/d34/classv8_1_1_cpu_profiler.html#a40ca4c8a8aa4c9233aa2a2706457cc80
955
+ static napi_value StopProfiling(napi_env env, napi_callback_info info) {
956
+ size_t argc = 4;
957
+ napi_value argv[4];
958
+
959
+ assert(napi_get_cb_info(env, info, &argc, argv, NULL, NULL) == napi_ok);
960
+
961
+ if (argc < 3) {
962
+ napi_throw_error(env, "NAPI_ERROR",
963
+ "StopProfiling expects at least three arguments.");
964
+
965
+ napi_value napi_null;
966
+ assert(napi_get_null(env, &napi_null) == napi_ok);
967
+
968
+ return napi_null;
969
+ }
970
+
971
+ // Verify the first argument is a string
972
+ napi_valuetype callbacktype0;
973
+ assert(napi_typeof(env, argv[0], &callbacktype0) == napi_ok);
974
+
975
+ if (callbacktype0 != napi_string) {
976
+ napi_throw_error(env, "NAPI_ERROR",
977
+ "StopProfiling expects a string as first argument.");
978
+
979
+ napi_value napi_null;
980
+ assert(napi_get_null(env, &napi_null) == napi_ok);
981
+
982
+ return napi_null;
983
+ }
984
+
985
+ size_t len;
986
+ assert(napi_get_value_string_utf8(env, argv[0], NULL, 0, &len) == napi_ok);
987
+
988
+ std::string title(len, '\0');
989
+ assert(napi_get_value_string_utf8(env, argv[0], &title[0], len + 1, &len) ==
990
+ napi_ok);
991
+
992
+ if (len < 1) {
993
+ napi_throw_error(
994
+ env, "NAPI_ERROR",
995
+ "StopProfiling expects a non empty string as first argument.");
996
+
997
+ napi_value napi_null;
998
+ assert(napi_get_null(env, &napi_null) == napi_ok);
999
+
1000
+ return napi_null;
1001
+ }
1002
+
1003
+ // Verify the second argument is a number
1004
+ napi_valuetype callbacktype1;
1005
+ assert(napi_typeof(env, argv[1], &callbacktype1) == napi_ok);
1006
+
1007
+ if (callbacktype1 != napi_number) {
1008
+ napi_throw_error(env, "NAPI_ERROR",
1009
+ "StopProfiling expects a format type as second argument.");
1010
+
1011
+ napi_value napi_null;
1012
+ assert(napi_get_null(env, &napi_null) == napi_ok);
1013
+
1014
+ return napi_null;
1015
+ }
1016
+
1017
+ // Verify the third argument is a number
1018
+ napi_valuetype callbacktype2;
1019
+ assert(napi_typeof(env, argv[2], &callbacktype2) == napi_ok);
1020
+
1021
+ if (callbacktype2 != napi_number) {
1022
+ napi_throw_error(
1023
+ env, "NAPI_ERROR",
1024
+ "StopProfiling expects a thread_id integer as third argument.");
1025
+
1026
+ napi_value napi_null;
1027
+ assert(napi_get_null(env, &napi_null) == napi_ok);
1028
+ return napi_null;
1029
+ }
1030
+
1031
+ int32_t format;
1032
+ assert(napi_get_value_int32(env, argv[1], &format) == napi_ok);
1033
+
1034
+ int64_t thread_id;
1035
+ assert(napi_get_value_int64(env, argv[2], &thread_id) == napi_ok);
1036
+
1037
+ // Get profiler from instance data
1038
+ Profiler *profiler;
1039
+ assert(napi_get_instance_data(env, (void **)&profiler) == napi_ok);
1040
+
1041
+ if (!profiler) {
1042
+ napi_throw_error(env, "NAPI_ERROR",
1043
+ "StopProfiling: Profiler is not initialized.");
1044
+
1045
+ napi_value napi_null;
1046
+ assert(napi_get_null(env, &napi_null) == napi_ok);
1047
+ return napi_null;
1048
+ }
1049
+
1050
+ auto profile = profiler->active_profiles.find(title);
1051
+
1052
+ // If the profile was never started, silently ignore the call and return null
1053
+ if (profile == profiler->active_profiles.end()) {
1054
+ napi_value napi_null;
1055
+ assert(napi_get_null(env, &napi_null) == napi_ok);
1056
+ return napi_null;
1057
+ }
1058
+
1059
+ v8::CpuProfile *cpu_profile = profile->second->Stop(profiler);
1060
+
1061
+ // If for some reason stopProfiling was called with an invalid profile title
1062
+ // or if that title had somehow been stopped already, profile will be null.
1063
+ if (!cpu_profile) {
1064
+ CleanupSentryProfile(profiler, profile->second, title);
1065
+
1066
+ napi_value napi_null;
1067
+ assert(napi_get_null(env, &napi_null) == napi_ok);
1068
+ return napi_null;
1069
+ };
1070
+
1071
+ napi_valuetype callbacktype3;
1072
+ assert(napi_typeof(env, argv[3], &callbacktype3) == napi_ok);
1073
+
1074
+ bool collect_resources;
1075
+ napi_get_value_bool(env, argv[3], &collect_resources);
1076
+
1077
+ const ProfileFormat format_type = static_cast<ProfileFormat>(format);
1078
+
1079
+ if (format_type != ProfileFormat::kFormatThread &&
1080
+ format_type != ProfileFormat::kFormatChunk) {
1081
+ napi_throw_error(
1082
+ env, "NAPI_ERROR",
1083
+ "StopProfiling expects a valid format type as second argument.");
1084
+
1085
+ napi_value napi_null;
1086
+ assert(napi_get_null(env, &napi_null) == napi_ok);
1087
+ return napi_null;
1088
+ }
1089
+
1090
+ napi_value js_profile = TranslateProfile(
1091
+ env, cpu_profile, format_type, profile->second->profile_start_timestamp(),
1092
+ thread_id, collect_resources);
1093
+
1094
+ napi_value measurements;
1095
+ napi_create_object(env, &measurements);
1096
+
1097
+ if (profile->second->heap_usage_write_index() > 0) {
1098
+ static const char *memory_unit = "byte";
1099
+ napi_value heap_usage_measurements =
1100
+ TranslateMeasurements(env, format_type, memory_unit,
1101
+ profile->second->profile_start_timestamp(),
1102
+ profile->second->heap_usage_write_index(),
1103
+ profile->second->heap_usage_values(),
1104
+ profile->second->heap_usage_timestamps());
1105
+
1106
+ if (heap_usage_measurements != nullptr) {
1107
+ napi_set_named_property(env, measurements, "memory_footprint",
1108
+ heap_usage_measurements);
1109
+ };
1110
+ };
1111
+
1112
+ if (profile->second->cpu_usage_write_index() > 0) {
1113
+ static const char *cpu_unit = "percent";
1114
+ napi_value cpu_usage_measurements = TranslateMeasurementsDouble(
1115
+ env, format_type, cpu_unit, profile->second->profile_start_timestamp(),
1116
+ profile->second->cpu_usage_write_index(),
1117
+ profile->second->cpu_usage_values(),
1118
+ profile->second->cpu_usage_timestamps());
1119
+
1120
+ if (cpu_usage_measurements != nullptr) {
1121
+ napi_set_named_property(env, measurements, "cpu_usage",
1122
+ cpu_usage_measurements);
1123
+ };
1124
+ };
1125
+
1126
+ napi_set_named_property(env, js_profile, "measurements", measurements);
1127
+
1128
+ CleanupSentryProfile(profiler, profile->second, title);
1129
+ cpu_profile->Delete();
1130
+
1131
+ return js_profile;
1132
+ };
1133
+
1134
+ void FreeAddonData(napi_env env, void *data, void *hint) {
1135
+ Profiler *profiler = static_cast<Profiler *>(data);
1136
+
1137
+ if (profiler == nullptr) {
1138
+ return;
1139
+ }
1140
+
1141
+ for (auto &profile : profiler->active_profiles) {
1142
+ if (profile.second != nullptr) {
1143
+ profile.second->Stop(profiler);
1144
+ delete profile.second;
1145
+ }
1146
+ }
1147
+ profiler->active_profiles.clear();
1148
+
1149
+ if (profiler->cpu_profiler != nullptr) {
1150
+ profiler->cpu_profiler->Dispose();
1151
+ profiler->cpu_profiler = nullptr;
1152
+ }
1153
+
1154
+ delete profiler;
1155
+ }
1156
+
1157
+ napi_value Init(napi_env env, napi_value exports) {
1158
+ v8::Isolate *isolate = v8::Isolate::GetCurrent();
1159
+
1160
+ if (isolate == nullptr) {
1161
+ napi_throw_error(env, nullptr,
1162
+ "Failed to initialize Sentry profiler: isolate is null.");
1163
+ return NULL;
1164
+ }
1165
+
1166
+ Profiler *profiler = new Profiler(env, isolate);
1167
+ profiler->cpu_profiler->SetSamplingInterval(kSamplingInterval);
1168
+
1169
+ if (napi_set_instance_data(env, profiler, FreeAddonData, NULL) != napi_ok) {
1170
+ napi_throw_error(env, nullptr, "Failed to set instance data for profiler.");
1171
+ return NULL;
1172
+ }
1173
+
1174
+ napi_value start_profiling;
1175
+ if (napi_create_function(env, "startProfiling", NAPI_AUTO_LENGTH,
1176
+ StartProfiling, exports,
1177
+ &start_profiling) != napi_ok) {
1178
+ napi_throw_error(env, nullptr, "Failed to create startProfiling function.");
1179
+ return NULL;
1180
+ }
1181
+
1182
+ if (napi_set_named_property(env, exports, "startProfiling",
1183
+ start_profiling) != napi_ok) {
1184
+ napi_throw_error(env, nullptr,
1185
+ "Failed to set startProfiling property on exports.");
1186
+ return NULL;
1187
+ }
1188
+
1189
+ napi_value stop_profiling;
1190
+ if (napi_create_function(env, "stopProfiling", NAPI_AUTO_LENGTH,
1191
+ StopProfiling, exports,
1192
+ &stop_profiling) != napi_ok) {
1193
+ napi_throw_error(env, nullptr, "Failed to create stopProfiling function.");
1194
+ return NULL;
1195
+ }
1196
+
1197
+ if (napi_set_named_property(env, exports, "stopProfiling", stop_profiling) !=
1198
+ napi_ok) {
1199
+ napi_throw_error(env, nullptr,
1200
+ "Failed to set stopProfiling property on exports.");
1201
+ return NULL;
1202
+ }
1203
+
1204
+ napi_value get_frame_module;
1205
+ if (napi_create_function(env, "getFrameModule", NAPI_AUTO_LENGTH,
1206
+ GetFrameModuleWrapped, exports,
1207
+ &get_frame_module) != napi_ok) {
1208
+ napi_throw_error(env, nullptr, "Failed to create getFrameModule function.");
1209
+ return NULL;
1210
+ }
1211
+
1212
+ if (napi_set_named_property(env, exports, "getFrameModule",
1213
+ get_frame_module) != napi_ok) {
1214
+ napi_throw_error(env, nullptr,
1215
+ "Failed to set getFrameModule property on exports.");
1216
+ return NULL;
1217
+ }
1218
+
1219
+ return exports;
1220
+ }
1221
+
1222
+ NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)