Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-node-packages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ jobs:
# Lay each package out as its rules_js store directory: <name with / as +>@<version>.
version_of() { sed -n "s/^ARG $1=//p" Dockerfile.Packages; }
DIRS=()
for spec in "bcrypt BCRYPT_VERSION" "cld CLD_VERSION" "unix-dgram UNIX_DGRAM_VERSION" "@datadog/pprof PPROF_VERSION"; do
for spec in "bcrypt BCRYPT_VERSION" "cld CLD_VERSION" "unix-dgram UNIX_DGRAM_VERSION" "@datadog/pprof PPROF_VERSION" "@asana/async-stack-sampler ASYNC_STACK_SAMPLER_VERSION"; do
set -- $spec
name=$1
version=$(version_of "$2")
Expand Down
14 changes: 14 additions & 0 deletions Dockerfile.Packages
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,20 @@ RUN node -e " \
COPY asana-pprof-cped-smoke-test.js .
RUN node asana-pprof-cped-smoke-test.js 5 && node --stress-compaction asana-pprof-cped-smoke-test.js 5

# Must match asana-addons/async-stack-sampler/package.json.
ARG ASYNC_STACK_SAMPLER_VERSION=0.1.0
COPY asana-addons/async-stack-sampler /usr/src/async-stack-sampler
WORKDIR /usr/src/async-stack-sampler
RUN test "$(node -p "require('./package.json').version")" = "$ASYNC_STACK_SAMPLER_VERSION" && \
/usr/src/pprof-source/node_modules/.bin/node-gyp rebuild --jobs=max --nodedir="$NODE_DIR" && \
node smoke-test.js && node --stress-compaction smoke-test.js
WORKDIR /usr/src/node
RUN set -e; \
PKG=node_modules/@asana/async-stack-sampler; \
mkdir -p "$PKG/build/Release"; \
cp /usr/src/async-stack-sampler/package.json /usr/src/async-stack-sampler/index.js "$PKG/"; \
cp /usr/src/async-stack-sampler/build/Release/async_stack_sampler.node "$PKG/build/Release/"

RUN ls node_modules

CMD ["bash"]
1 change: 1 addition & 0 deletions asana-addons/async-stack-sampler/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build/
295 changes: 295 additions & 0 deletions asana-addons/async-stack-sampler/async_stack_sampler.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
// Samples the JS thread's stack, including V8's await chain, which CPU profilers don't record.
//
// A timer thread calls Isolate::RequestInterrupt every interval, and V8 runs the interrupt on the
// JS thread at its next stack-guard check. The interrupt captures the stack into a fresh holder
// with v8::Exception::CaptureStackTrace and keeps the holder plus the current AsyncContextFrame.
// V8 stores the raw frames and formats them on the first read of holder.stack, so formatting and
// source mapping happen after the request, not in the interrupt.
//
// Samples land at safepoints, so leaves are biased, and the public API always skips the first
// frame, so the leaf function itself is missing. Pair with a CPU profiler for exact leaves.
//
// RequestInterrupt documents that the callback shouldn't call back into the isolate. This one
// allocates and calls the V8 API, which works because V8 serves interrupts from a runtime call at
// a safepoint, never inside GC; it runs no JS.
#include <node.h>
#include <v8.h>

#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <vector>

namespace {

using v8::Context;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Integer;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

int64_t NowNs() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count();
}

struct Sample {
double requested_us;
double served_us;
double capture_ns;
};

struct Sampler {
Isolate* isolate = nullptr;
std::thread thread;
std::mutex wake_mutex;
std::condition_variable wake;
std::atomic<bool> running{false};
// Set while an interrupt is requested and not yet served, so captures never overlap.
std::atomic<bool> pending{false};
std::atomic<int64_t> requested_ns{0};
int interval_us = 10000;
int64_t late_ns = 0;
int max_frames = 80;
size_t max_samples = 2000;
v8::Global<Object> error_ctor;
v8::Global<String> limit_key;

// Touched only on the JS thread.
std::vector<Sample> samples;
std::vector<v8::Global<Object>> holders;
std::vector<v8::Global<v8::Data>> contexts;
int64_t late = 0;
int64_t dropped = 0;
int64_t failed = 0;
int64_t capture_ns = 0;
};

// Never freed: an interrupt requested before stop() may still be served after it.
Sampler* g_sampler = nullptr;

Local<String> Str(Isolate* isolate, const char* s) {
return String::NewFromUtf8(isolate, s, v8::NewStringType::kInternalized).ToLocalChecked();
}

bool Capture(Sampler* s, Isolate* isolate, Local<Context> context) {
Local<Object> error_ctor = s->error_ctor.Get(isolate);
Local<String> key = s->limit_key.Get(isolate);
Local<Value> previous_limit;
bool restore = error_ctor->Get(context, key).ToLocal(&previous_limit) &&
error_ctor->Set(context, key, Integer::New(isolate, s->max_frames)).FromMaybe(false);
Local<Object> holder = Object::New(isolate);
bool ok = v8::Exception::CaptureStackTrace(context, holder).FromMaybe(false);
if (restore) {
(void)error_ctor->Set(context, key, previous_limit);
}
if (ok) {
s->holders.emplace_back(isolate, holder);
s->contexts.emplace_back(isolate, isolate->GetContinuationPreservedEmbedderDataV2());
}
return ok;
}

void OnInterrupt(Isolate* isolate, void* data) {
auto* s = static_cast<Sampler*>(data);
int64_t start = NowNs();
int64_t requested = s->requested_ns.load();
if (!s->running.load()) {
s->pending.store(false);
return;
}
if (start - requested > s->late_ns) {
s->late++;
} else if (s->holders.size() >= s->max_samples) {
s->dropped++;
} else {
HandleScope scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
v8::TryCatch try_catch(isolate);
if (!context.IsEmpty() && Capture(s, isolate, context)) {
int64_t end = NowNs();
s->samples.push_back({requested / 1e3, start / 1e3, static_cast<double>(end - start)});
s->capture_ns += end - start;
} else {
s->failed++;
}
}
s->pending.store(false);
}

void TimerLoop(Sampler* s) {
while (s->running.load()) {
{
std::unique_lock<std::mutex> lock(s->wake_mutex);
s->wake.wait_for(lock, std::chrono::microseconds(s->interval_us),
[s] { return !s->running.load(); });
}
if (!s->running.load()) {
break;
}
bool expected = false;
if (s->pending.compare_exchange_strong(expected, true)) {
s->requested_ns.store(NowNs());
s->isolate->RequestInterrupt(OnInterrupt, s);
}
}
}

void StopThread(Sampler* s) {
{
std::lock_guard<std::mutex> lock(s->wake_mutex);
s->running.store(false);
}
s->wake.notify_all();
if (s->thread.joinable()) {
s->thread.join();
}
}

// The timer thread must not request interrupts on an isolate that is being torn down.
void OnEnvironmentCleanup(void* data) {
StopThread(static_cast<Sampler*>(data));
}

int IntOption(Isolate* isolate, Local<Context> context, Local<Object> options, const char* name,
int fallback) {
Local<Value> value;
if (!options->Get(context, Str(isolate, name)).ToLocal(&value) || !value->IsNumber()) {
return fallback;
}
return value->Int32Value(context).FromMaybe(fallback);
}

// start({ intervalMicros, maxFrames, maxSamples, lateFactor })
void Start(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
if (g_sampler == nullptr) {
g_sampler = new Sampler();
g_sampler->isolate = isolate;
Local<Value> error_ctor;
if (!context->Global()->Get(context, Str(isolate, "Error")).ToLocal(&error_ctor) ||
!error_ctor->IsObject()) {
isolate->ThrowError("async-stack-sampler: no global Error");
return;
}
g_sampler->error_ctor.Reset(isolate, error_ctor.As<Object>());
g_sampler->limit_key.Reset(isolate, Str(isolate, "stackTraceLimit"));
node::AddEnvironmentCleanupHook(isolate, OnEnvironmentCleanup, g_sampler);
}
Sampler* s = g_sampler;
if (s->isolate != isolate) {
isolate->ThrowError("async-stack-sampler supports only the main thread");
return;
}
if (s->running.load()) {
isolate->ThrowError("async-stack-sampler is already running");
return;
}
Local<Object> options = args.Length() > 0 && args[0]->IsObject() ? args[0].As<Object>()
: Object::New(isolate);
s->interval_us = std::max(100, IntOption(isolate, context, options, "intervalMicros", 10000));
s->max_frames = std::max(1, IntOption(isolate, context, options, "maxFrames", 80));
s->max_samples = std::max(1, IntOption(isolate, context, options, "maxSamples", 2000));
s->late_ns = static_cast<int64_t>(IntOption(isolate, context, options, "lateFactor", 3)) *
s->interval_us * 1000;
s->samples.clear();
s->holders.clear();
s->contexts.clear();
s->late = s->dropped = s->failed = s->capture_ns = 0;
s->samples.reserve(s->max_samples);
s->holders.reserve(s->max_samples);
s->contexts.reserve(s->max_samples);
s->pending.store(false);
s->running.store(true);
s->thread = std::thread(TimerLoop, s);
}

// stop() -> { holders, contexts, times, late, dropped, failed, captureMs }
// times is a Float64Array of [requestedMicros, servedMicros, captureNanos] per sample, on the
// steady clock; holders[i].stack formats sample i; contexts[i] is its AsyncContextFrame.
void Stop(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
Sampler* s = g_sampler;
if (s == nullptr || !s->running.load()) {
isolate->ThrowError("async-stack-sampler is not running");
return;
}
StopThread(s);
size_t n = s->holders.size();
Local<v8::ArrayBuffer> buffer = v8::ArrayBuffer::New(isolate, n * 3 * sizeof(double));
auto* times = static_cast<double*>(buffer->Data());
Local<v8::Array> holders = v8::Array::New(isolate, static_cast<int>(n));
Local<v8::Array> contexts = v8::Array::New(isolate, static_cast<int>(n));
for (size_t i = 0; i < n; i++) {
times[i * 3] = s->samples[i].requested_us;
times[i * 3 + 1] = s->samples[i].served_us;
times[i * 3 + 2] = s->samples[i].capture_ns;
holders->Set(context, static_cast<uint32_t>(i), s->holders[i].Get(isolate)).Check();
Local<v8::Data> frame = s->contexts[i].Get(isolate);
contexts
->Set(context, static_cast<uint32_t>(i),
frame.IsEmpty() || !frame->IsValue() ? Local<Value>(v8::Undefined(isolate))
: frame.As<Value>())
.Check();
}
s->samples.clear();
s->holders.clear();
s->contexts.clear();
Local<Object> out = Object::New(isolate);
auto set = [&](const char* name, Local<Value> value) {
out->Set(context, Str(isolate, name), value).Check();
};
set("holders", holders);
set("contexts", contexts);
set("times", v8::Float64Array::New(buffer, 0, n * 3));
set("late", Number::New(isolate, static_cast<double>(s->late)));
set("dropped", Number::New(isolate, static_cast<double>(s->dropped)));
set("failed", Number::New(isolate, static_cast<double>(s->failed)));
set("captureMs", Number::New(isolate, s->capture_ns / 1e6));
args.GetReturnValue().Set(out);
}

// runInFrame(asyncContextFrame, fn): calls fn with that frame as the current async context, so
// AsyncLocalStorage reads inside fn see the stores that were current when the sample was taken.
void RunInFrame(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.Length() < 2 || !args[1]->IsFunction()) {
isolate->ThrowError("runInFrame(frame, fn)");
return;
}
Local<v8::Data> previous = isolate->GetContinuationPreservedEmbedderDataV2();
isolate->SetContinuationPreservedEmbedderDataV2(args[0]);
v8::MaybeLocal<Value> result = args[1].As<v8::Function>()->Call(
isolate->GetCurrentContext(), v8::Undefined(isolate), 0, nullptr);
isolate->SetContinuationPreservedEmbedderDataV2(previous);
Local<Value> value;
if (result.ToLocal(&value)) {
args.GetReturnValue().Set(value);
}
}

} // namespace

NODE_MODULE_INIT(/* exports, module, context */) {
Isolate* isolate = Isolate::GetCurrent();
auto add = [&](const char* name, v8::FunctionCallback fn) {
exports
->Set(context, Str(isolate, name),
v8::FunctionTemplate::New(isolate, fn)->GetFunction(context).ToLocalChecked())
.Check();
};
add("start", Start);
add("stop", Stop);
add("runInFrame", RunInFrame);
}
10 changes: 10 additions & 0 deletions asana-addons/async-stack-sampler/binding.gyp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"targets": [
{
"target_name": "async_stack_sampler",
"sources": ["async_stack_sampler.cc"],
"cflags_cc": ["-std=c++20", "-O2"],
"cflags_cc!": ["-std=gnu++17", "-std=c++17"]
}
]
}
32 changes: 32 additions & 0 deletions asana-addons/async-stack-sampler/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';

const native = require('./build/Release/async_stack_sampler.node');

/**
* Starts sampling the main thread's stack, await chain included, every `intervalMicros`. Keeps at
* most `maxSamples` samples of `maxFrames` frames; later samples are counted as dropped.
*/
function start({ intervalMicros = 10000, maxFrames = 80, maxSamples = 2000, lateFactor = 3 } = {}) {
native.start({ intervalMicros, maxFrames, maxSamples, lateFactor });
}

/**
* Stops sampling. Each sample's `stack` is V8's formatted stack string, built on first read, and
* `inContext(fn)` runs `fn` in the async context that was current when the sample was taken.
*/
function stop() {
const { holders, contexts, times, late, dropped, failed, captureMs } = native.stop();
const samples = holders.map((holder, i) => ({
holder,
get stack() {
return holder.stack;
},
requestedMicros: times[i * 3],
servedMicros: times[i * 3 + 1],
captureNanos: times[i * 3 + 2],
inContext: fn => native.runInFrame(contexts[i], fn),
}));
return { samples, late, dropped, failed, captureMs };
}

module.exports = { start, stop };
9 changes: 9 additions & 0 deletions asana-addons/async-stack-sampler/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"name": "@asana/async-stack-sampler",
"version": "0.1.0",
"description": "Samples the main thread's stack including V8's await chain, for LunaServer request diagnosis",
"main": "index.js",
"private": true,
"license": "UNLICENSED",
"files": ["index.js", "build/Release/async_stack_sampler.node"]
}
Loading
Loading