Skip to content
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@

namespace facebook::react::jsinspector_modern {

namespace {

/**
* Threshold for the size Trace Event chunk, that will be flushed out with
* Tracing.dataCollected event.
*/
const uint16_t TRACE_EVENT_CHUNK_SIZE = 1000;

} // namespace

bool TracingAgent::handleRequest(const cdp::PreparsedRequest& req) {
if (req.method == "Tracing.start") {
// @cdp Tracing.start support is experimental.
Expand All @@ -26,31 +36,32 @@ bool TracingAgent::handleRequest(const cdp::PreparsedRequest& req) {
return true;
} else if (req.method == "Tracing.end") {
// @cdp Tracing.end support is experimental.
bool firstChunk = true;
auto id = req.id;
bool wasStopped =
PerformanceTracer::getInstance().stopTracingAndCollectEvents(
[this, firstChunk, id](const folly::dynamic& eventsChunk) {
if (firstChunk) {
frontendChannel_(cdp::jsonResult(id));
}
frontendChannel_(cdp::jsonNotification(
"Tracing.dataCollected",
folly::dynamic::object("value", eventsChunk)));
});

if (!wasStopped) {
bool correctlyStopped = PerformanceTracer::getInstance().stopTracing();

if (!correctlyStopped) {
frontendChannel_(cdp::jsonError(
req.id,
cdp::ErrorCode::InternalError,
"Tracing session not started"));
} else {
frontendChannel_(cdp::jsonNotification(
"Tracing.tracingComplete",
folly::dynamic::object("dataLossOccurred", false)));

return true;
}

// Send response to Tracing.end request.
frontendChannel_(cdp::jsonResult(req.id));

PerformanceTracer::getInstance().collectEvents(
[this](const folly::dynamic& eventsChunk) {
frontendChannel_(cdp::jsonNotification(
"Tracing.dataCollected",
folly::dynamic::object("value", eventsChunk)));
},
TRACE_EVENT_CHUNK_SIZE);

frontendChannel_(cdp::jsonNotification(
"Tracing.tracingComplete",
folly::dynamic::object("dataLossOccurred", false)));

return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,31 @@ bool PerformanceTracer::startTracing() {
if (tracing_) {
return false;
}

tracing_ = true;
return true;
}

bool PerformanceTracer::stopTracingAndCollectEvents(
const std::function<void(const folly::dynamic& eventsChunk)>&
resultCallback) {
bool PerformanceTracer::stopTracing() {
std::lock_guard lock(mutex_);

if (!tracing_) {
return false;
}

performanceMeasureCount_ = 0;
tracing_ = false;
return true;
}

void PerformanceTracer::collectEvents(
const std::function<void(const folly::dynamic& eventsChunk)>&
resultCallback,
uint16_t chunkSize) {
std::lock_guard lock(mutex_);

if (buffer_.empty()) {
customTrackIdMap_.clear();
return true;
return;
}

// Register "Main" process
Expand Down Expand Up @@ -91,24 +99,21 @@ bool PerformanceTracer::stopTracingAndCollectEvents(
}

auto traceEvents = folly::dynamic::array();

for (auto event : buffer_) {
// Emit trace events
traceEvents.push_back(serializeTraceEvent(event));

if (traceEvents.size() >= 1000) {
if (traceEvents.size() == chunkSize) {
resultCallback(traceEvents);
traceEvents = folly::dynamic::array();
}
}
customTrackIdMap_.clear();
buffer_.clear();

if (traceEvents.size() >= 1) {
if (!traceEvents.empty()) {
resultCallback(traceEvents);
}

return true;
customTrackIdMap_.clear();
buffer_.clear();
}

void PerformanceTracer::reportMark(
Expand Down Expand Up @@ -156,20 +161,33 @@ void PerformanceTracer::reportMeasure(
}
}

++performanceMeasureCount_;
buffer_.push_back(TraceEvent{
.id = performanceMeasureCount_,
.name = std::string(name),
.cat = "blink.user_timing",
.ph = 'X',
.ph = 'b',
.ts = start,
.pid = PID, // FIXME: This should be the real process ID.
.tid = threadId, // FIXME: This should be the real thread ID.
.dur = duration,
});
buffer_.push_back(TraceEvent{
.id = performanceMeasureCount_,
.name = std::string(name),
.cat = "blink.user_timing",
.ph = 'e',
.ts = start + duration,
.pid = PID, // FIXME: This should be the real process ID.
.tid = threadId, // FIXME: This should be the real thread ID.
});
}

folly::dynamic PerformanceTracer::serializeTraceEvent(TraceEvent event) const {
folly::dynamic result = folly::dynamic::object;

if (event.id.has_value()) {
result["id"] = folly::sformat("0x{:X}", event.id.value());
}
result["name"] = event.name;
result["cat"] = event.cat;
result["ph"] = std::string(1, event.ph);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#pragma once

#include "CdpTracing.h"
#include "TraceEvent.h"

#include <folly/dynamic.h>

Expand All @@ -21,51 +22,6 @@ namespace facebook::react::jsinspector_modern {
// TODO: Review how this API is integrated into jsinspector_modern (singleton
// design is copied from earlier FuseboxTracer prototype).

namespace {

/**
* A trace event to send to the debugger frontend, as defined by the Trace Event
* Format.
* https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview?pli=1&tab=t.0#heading=h.yr4qxyxotyw
*/
struct TraceEvent {
/** The name of the event, as displayed in the Trace Viewer. */
std::string name;

/**
* A comma separated list of categories for the event, configuring how
* events are shown in the Trace Viewer UI.
*/
std::string cat;

/**
* The event type. This is a single character which changes depending on the
* type of event being output. See
* https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview?pli=1&tab=t.0#heading=h.puwqg050lyuy
*/
char ph;

/** The tracing clock timestamp of the event, in microseconds (µs). */
uint64_t ts;

/** The process ID for the process that output this event. */
uint64_t pid;

/** The thread ID for the process that output this event. */
uint64_t tid;

/** Any arguments provided for the event. */
folly::dynamic args = folly::dynamic::object();

/**
* The duration of the event, in microseconds (µs). Only applicable to
* complete events ("ph": "X").
*/
std::optional<uint64_t> dur;
};

} // namespace

/**
* [Experimental] An interface for logging performance trace events to the
* modern debugger server.
Expand All @@ -80,15 +36,17 @@ class PerformanceTracer {
bool startTracing();

/**
* End tracing, and output chunked CDP trace events using the given
* callback.
*
* Returns `false` if tracing was not started.
* Mark trace session as stopped. Returns `false` if wasn't tracing.
*/
bool stopTracingAndCollectEvents(
const std::function<void(const folly::dynamic& eventsChunk)>&
resultCallback);
bool stopTracing();

/**
* Flush out buffered CDP Trace Events using the given callback.
*/
void collectEvents(
const std::function<void(const folly::dynamic& eventsChunk)>&
resultCallback,
uint16_t chunkSize);
/**
* Record a `Performance.mark()` event - a labelled timestamp. If not
* currently tracing, this is a no-op.
Expand Down Expand Up @@ -118,6 +76,7 @@ class PerformanceTracer {
folly::dynamic serializeTraceEvent(TraceEvent event) const;

bool tracing_{false};
uint32_t performanceMeasureCount_{0};
std::unordered_map<std::string, uint64_t> customTrackIdMap_;
std::vector<TraceEvent> buffer_;
std::mutex mutex_;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#pragma once

#include <folly/dynamic.h>

namespace facebook::react::jsinspector_modern {

namespace {

/**
* A trace event to send to the debugger frontend, as defined by the Trace Event
* Format.
* https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview?pli=1&tab=t.0#heading=h.yr4qxyxotyw
*/
struct TraceEvent {
/**
* Optional. Serialized as a string, usually is hexadecimal number.
* https://github.com/ChromeDevTools/devtools-frontend/blob/99a9104ae974f8caa63927e356800f6762cdbf25/front_end/models/trace/helpers/Trace.ts#L198-L201
*/
std::optional<uint32_t> id;

/** The name of the event, as displayed in the Trace Viewer. */
std::string name;

/**
* A comma separated list of categories for the event, configuring how
* events are shown in the Trace Viewer UI.
*/
std::string cat;

/**
* The event type. This is a single character which changes depending on the
* type of event being output. See
* https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview?pli=1&tab=t.0#heading=h.puwqg050lyuy
*/
char ph;

/** The tracing clock timestamp of the event, in microseconds (µs). */
uint64_t ts;

/** The process ID for the process that output this event. */
uint64_t pid;

/** The thread ID for the process that output this event. */
uint64_t tid;

/** Any arguments provided for the event. */
folly::dynamic args = folly::dynamic::object();

/**
* The duration of the event, in microseconds (µs). Only applicable to
* complete events ("ph": "X").
*/
std::optional<uint64_t> dur;
};

} // namespace

} // namespace facebook::react::jsinspector_modern