-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
97 lines (89 loc) · 2.28 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const pprof = require('pprof');
const fs = require('fs');
const heapFilePath = '/tmp/heap.pb.gz';
const wallFilePath = '/tmp/wall.pb.gz';
const heapWebPath = '/debug/pprof/heap';
const heapStopPath = '/debug/pprof/heap/stop';
const wallWebPath = '/debug/pprof/wall';
const intervalBytes = 512 * 1024;
const stackDepth = 64;
// Start Heap Profiler
pprof.heap.start(intervalBytes, stackDepth);
/**
* @param {Object} req
* @param {Object} res
* @param {Function} next
*/
const middleware = async (req, res, next) => {
switch (req.path) {
case heapWebPath:
try {
await heap(heapFilePath);
} catch (err) {
return res.status(500).send(err.message);
}
return res.sendFile(heapFilePath);
case wallWebPath:
try {
let millis = 5000;
if (req.query.seconds) {
const secs = parseInt(req.query.seconds, 10);
if (!Number.isNaN(secs) && secs > 0) {
millis = secs * 1000;
}
}
await wall(wallFilePath, millis);
} catch (err) {
return res.status(500).send(err.message);
}
return res.sendFile(wallFilePath);
case heapStopPath:
try {
pprof.heap.stop();
return res.send('');
} catch (err) {
return res.status(500).send(err.message);
}
default:
return next();
}
};
/**
* @param {string} outPath - output path for the heap protobuf output
*/
const heap = async (outPath) => {
try {
pprof.heap.start(intervalBytes, stackDepth);
} catch { }
const profile = await pprof.heap.profile();
const buf = await pprof.encode(profile);
return new Promise((resolve, reject) => {
fs.writeFile(outPath, buf, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
/**
* @param {string} outPath - output path for the heap protobuf output
* @param {number} durationMillis - sampling duration
*/
const wall = async (outPath, durationMillis) => {
const profile = await pprof.time.profile({
durationMillis,
});
const buf = await pprof.encode(profile);
return new Promise((resolve, reject) => {
fs.writeFile(outPath, buf, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
module.exports = middleware;