Skip to content

Commit a4e78d8

Browse files
[debug] pretty print async context tree when extending a stack trace
1 parent c234c3a commit a4e78d8

2 files changed

Lines changed: 51 additions & 2 deletions

File tree

debug.js

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,54 @@ function debug(msg) {
66
fs.writeSync(1, 'trace.js DEBUG ' + msg + '\n');
77
}
88

9+
function printRootTraces(traces) {
10+
const rootAsyncIds = findRootAsyncIds(traces);
11+
for (const asyncId of rootAsyncIds) {
12+
printTree(traces, traces.get(asyncId));
13+
}
14+
}
15+
16+
function findRootAsyncIds(traces) {
17+
const asyncIds = new Set(traces.keys());
18+
for (const trace of traces.values()) {
19+
for (const notRootTrace of trace.relatedTraces) {
20+
asyncIds.delete(notRootTrace.asyncId);
21+
}
22+
}
23+
return asyncIds;
24+
}
25+
26+
function printTree(traces, trace, indent='', isLast=true, visited=new Set()) {
27+
let line = indent + '\\-' + trace.asyncId;
28+
29+
if (isLast) {
30+
indent += ' ';
31+
} else {
32+
indent += '| ';
33+
}
34+
35+
if (!traces.get(trace.asyncId)) {
36+
line += ' (not-root)';
37+
}
38+
39+
if (visited.has(trace.asyncId)) {
40+
line += ' (cycle)';
41+
}
42+
43+
fs.writeSync(1, line + '\n');
44+
45+
if (visited.has(trace.asyncId)) {
46+
return;
47+
}
48+
visited.add(trace.asyncId);
49+
50+
for (let i = 0; i < trace.relatedTraces.length; ++i) {
51+
const isLast = i === trace.relatedTraces.length - 1;
52+
printTree(traces, trace.relatedTraces[i], indent, isLast, visited);
53+
}
54+
}
55+
956
module.exports = {
10-
debug
57+
debug,
58+
printRootTraces
1159
};

trace.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use strict';
22

33
const DEBUG = false;
4-
const {debug} = DEBUG ? require('./debug') : {};
4+
const {printRootTraces, debug} = DEBUG ? require('./debug') : {};
55

66
// Arbitrarily limit ourselves so we don't use up all memory on storing stack traces
77
const MAX_RELATED_TRACES = 10;
@@ -53,6 +53,7 @@ function extendFrames(error, frames) {
5353

5454
if (DEBUG) {
5555
debug(`extending: ${asyncId} with ${trace.stacks.map(({asyncId}) => asyncId)}`);
56+
printRootTraces(traces);
5657
}
5758

5859
for (const stack of trace.stacks) {

0 commit comments

Comments
 (0)