-
Notifications
You must be signed in to change notification settings - Fork 242
Expand file tree
/
Copy pathstacktraces.js
More file actions
470 lines (423 loc) · 14.4 KB
/
stacktraces.js
File metadata and controls
470 lines (423 loc) · 14.4 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
* Copyright Elasticsearch B.V. and other contributors where applicable.
* Licensed under the BSD 2-Clause License; you may not use this file except in
* compliance with the BSD 2-Clause License.
*/
'use strict'
// Handling for translating `<Error instance>.stack` to the
// `{error.exception,span}.stacktrace` object passed to APM server.
// https://github.com/elastic/apm-server/blob/master/docs/spec/v2/error.json#L633
//
// A lot of this derived from https://github.com/watson/stackman but was
// moved internal to allow breaking compat for perf work.
var fs = require('fs')
var path = require('path')
const asyncCache = require('async-cache')
const afterAllResults = require('after-all-results')
// avoid loading error-callsites until needed to avoid
// Error.prepareStackTrace side-effects
// https://github.com/elastic/apm-agent-nodejs/issues/2833
let errorCallsites
function initStackTraceCollection () {
errorCallsites = require('error-callsites')
}
const errorStackParser = require('error-stack-parser')
const loadSourceMap = require('./load-source-map')
const LRU = require('lru-cache')
const fileCache = asyncCache({
max: 500, // fileCacheMax
load: function (file, cb) {
fs.readFile(file, { encoding: 'utf8' }, function (err, data) {
if (err) {
cb(err)
return
}
cb(null, data.split(/\r?\n/))
})
}
})
const sourceMapCache = asyncCache({
max: 500, // sourceMapCacheMax
load: function (filename, cb) {
if (!filename) {
cb(null, null)
return
}
loadSourceMap(filename, function onSourceMap (err, sourcemap) {
// Translate sourcemap===undefined to null, because 'async-cache'
// treats `undefined` as a cache miss. Without this there is no
// caching for files that have no sourcemap (the common case).
cb(err, sourcemap || null)
})
},
dispose: function (_filename, sourcemap) {
if (sourcemap) {
sourcemap.destroy()
}
}
})
const frameCache = new LRU({ max: 1000 })
const frameCacheStats = {
hits: 0,
misses: 0
}
let lastCwd = process.cwd()
// ---- internal support functions
// process.cwd() can throw EMFILE if hitting the `ulimit -Hn`. A process's
// cwd should not change regularly, so falling back to the previous one is fine.
// At worst the stacktrace frame.filename values will be relative to an old
// directory.
function getCwd (log) {
let cwd
try {
cwd = process.cwd()
} catch (ex) {
log.trace(ex, 'error getting cwd: fallback back to %s', lastCwd)
return lastCwd
}
lastCwd = cwd
return cwd
}
// If gathering a stacktrace from the structured CallSites fails, this is
// used as a fallback: parsing the `err.stack` *string*.
function stackTraceFromErrStackString (log, err) {
const stacktrace = []
// graphqljs adds the `originalError` property which represents the original
// error thrown within the resolver
err = err.originalError || err
if (err.stack === null) {
return []
}
// frames is an array of StackFrame (https://github.com/stacktracejs/stackframe).
let frames = null
try {
frames = errorStackParser.parse(err)
} catch (parseErr) {
log.debug('could not parse err.stack string: %s', parseErr)
}
if (frames) {
const cwd = getCwd(log)
for (var i = 0; i < frames.length; i++) {
const frame = frames[i]
const filename = frame.getFileName() || ''
stacktrace.push({
filename: getRelativeFileName(filename, cwd),
function: frame.getFunctionName(),
lineno: frame.getLineNumber(),
library_frame: !isStackFrameApp(frame),
abs_path: filename
})
}
}
return stacktrace
}
const NODE_MODULES_PATH_SEG = 'node_modules' + path.sep
// Return true iff the given StackFrame
// (https://github.com/stacktracejs/stackframe) is an application frame.
function isStackFrameApp (stackframe) {
if (isStackFrameNode(stackframe)) {
return false
} else {
const fileName = stackframe.getFileName()
if (!fileName) {
return true
} else if (fileName.indexOf(NODE_MODULES_PATH_SEG) === -1) {
return true
} else {
return false
}
}
}
// Return true iff the given StackFrame
// (https://github.com/stacktracejs/stackframe) is a Node frame.
function isStackFrameNode (stackframe) {
if (stackframe.isNative) {
return true
} else {
const fileName = stackframe.getFileName()
if (!fileName) {
return true
} else {
return (!path.isAbsolute(fileName) && fileName[0] !== '.')
}
}
}
function isCallSiteApp (callsite) {
if (isCallSiteNode(callsite)) {
return false
} else {
const fileName = callsite.getFileName()
if (!fileName) {
return true
} else if (fileName.indexOf(NODE_MODULES_PATH_SEG) === -1) {
return true
} else {
return false
}
}
}
function isCallSiteNode (callsite) {
if (callsite.isNative()) {
return true
} else {
const fileName = callsite.getFileName()
if (!fileName) {
return true
} else {
return (!path.isAbsolute(fileName) && fileName[0] !== '.')
}
}
}
function isValidCallsites (callsites) {
return Array.isArray(callsites) &&
callsites.length > 0 &&
typeof callsites[0] === 'object' &&
typeof callsites[0].getFileName === 'function'
}
// From stackman getTypeNameSafely().
function getCallSiteTypeNameSafely (callsite) {
try {
return callsite.getTypeName()
} catch (e) {
// This seems to happen sometimes when using 'use strict',
// stemming from `getTypeName`.
// [TypeError: Cannot read property 'constructor' of undefined]
return null
}
}
// From stackman getFunctionNameSanitized().
function getCallSiteFunctionNameSanitized (callsite) {
var fnName = callsite.getFunctionName()
if (fnName) return fnName
var typeName = getCallSiteTypeNameSafely(callsite)
if (typeName) return typeName + '.' + (callsite.getMethodName() || '<anonymous>')
return '<anonymous>'
}
function addSourceContextToFrame (frame, lines, lineNum, n) {
var index = lineNum - 1 // lines 1-based -> index 0-based
var nBefore = Math.ceil((n - 1) / 2)
var nAfter = Math.floor((n - 1) / 2)
frame.pre_context = lines.slice(Math.max(0, index - nBefore), index)
frame.context_line = lines[index]
frame.post_context = lines.slice(index + 1, index + 1 + nAfter)
}
// Get the path of `filename` relative to `relTo` -- which should be a directory
// path *without* a trailing path separator.
function getRelativeFileName (filename, relTo) {
if (filename.startsWith(relTo + path.sep)) {
return filename.slice(relTo.length + 1)
} else {
return filename
}
}
function getSourceMapConsumer (callsite, cb) {
if (isCallSiteNode(callsite)) {
process.nextTick(cb, null, null)
} else {
var filename = callsite.getFileName()
if (!filename) {
process.nextTick(cb, null, null)
} else {
sourceMapCache.get(filename, cb)
}
}
}
// Put together an APM stacktrace frame object:
// {
// "filename": "...",
// "lineno": 65,
// "function": "...",
// "library_frame": <bool>,
// "abs_path": "...",
// "pre_context": [ ... ],
// "context_line": "...",
// "post_context": [ ... ],
// },
// from a v8 CallSite object
// (https://v8.dev/docs/stack-trace-api#customizing-stack-traces).
//
// This calls back with `cb(null, frame)` -- the first err arg is always null.
function frameFromCallSite (log, callsite, cwd, sourceLinesAppFrames, sourceLinesLibraryFrames, cb) {
// getFileName can return null, e.g. with a `at Generator.next (<anonymous>)` frame.
const filename = callsite.getFileName() || ''
const lineno = callsite.getLineNumber()
const colno = callsite.getColumnNumber()
// Caching
const cacheKey = [filename, lineno, colno, sourceLinesAppFrames, sourceLinesLibraryFrames].join(':')
const cachedFrame = frameCache.get(cacheKey)
if (cachedFrame !== undefined) {
frameCacheStats.hits++
// Guard against later JSON serialization mistakenly changing duplicate
// frames in a stacktrace (a totally legal thing) into '[Circular]' as a
// guard against serializing an object with circular references.
const clonedFrame = Object.assign({}, cachedFrame)
if (clonedFrame.pre_context) {
clonedFrame.pre_context = clonedFrame.pre_context.slice()
}
if (clonedFrame.post_context) {
clonedFrame.post_context = clonedFrame.post_context.slice()
}
setImmediate(cb, null, clonedFrame)
return
}
function cacheAndCb (frame) {
frameCacheStats.misses++
frameCache.set(cacheKey, frame)
cb(null, frame)
}
// If the file has a sourcemap we use that for: filename, lineno, source
// context.
getSourceMapConsumer(callsite, function onSourceMapConsumer (sourceMapErr, sourceMapConsumer) {
let mappedFilename = null
let absMappedFilename = null
let mappedLineno = null
if (sourceMapErr) {
log.debug({ filename, err: sourceMapErr },
'could not process file source map')
} else if (sourceMapConsumer) {
let pos
try {
pos = sourceMapConsumer.originalPositionFor({
line: lineno,
column: callsite.getColumnNumber()
})
} catch (posErr) {
log.debug({ filename, line: lineno, err: sourceMapErr },
'could not get position from sourcemap')
pos = {
source: null,
line: null,
column: null,
name: null
}
}
if (pos.source !== null) {
mappedFilename = pos.source
absMappedFilename = path.resolve(path.dirname(filename), mappedFilename)
}
if (pos.line !== null) {
mappedLineno = pos.line
}
// TODO: Is `pos.name` relevant for `frame.function` if minifying?
}
const isApp = isCallSiteApp(callsite)
const frame = {
filename: getRelativeFileName(absMappedFilename || filename, cwd),
lineno: mappedLineno || lineno,
function: getCallSiteFunctionNameSanitized(callsite),
library_frame: !isApp
}
if (!Number.isFinite(frame.lineno)) {
// An early comment in stackman suggested this is "sometimes not" an int.
frame.lineno = 0
}
if (filename) {
frame.abs_path = absMappedFilename || filename
}
// Finish early if we do not need to collect source lines of context.
var linesOfContext = (isApp ? sourceLinesAppFrames : sourceLinesLibraryFrames)
if (linesOfContext === 0 || !filename || isCallSiteNode(callsite)) {
cacheAndCb(frame)
return
}
// Attempt to use "sourcesContent" in a sourcemap, if available.
if (sourceMapConsumer && mappedFilename && mappedLineno) {
// To use `sourceMapConsumer.sourceContentFor` we need the filename as
// it is in the "sources" field of the source map. `mappedFilename`,
// from `sourceMapConsume.originalPositionFor` above, was made relative
// to "sourceRoot" -- sourceFilename undoes that.
const sourceFilename = sourceMapConsumer.sourceRoot
? path.relative(sourceMapConsumer.sourceRoot, mappedFilename)
: mappedFilename
var source = sourceMapConsumer.sourceContentFor(sourceFilename, true)
log.trace({
sourceRoot: sourceMapConsumer.sourceRoot,
mappedFilename,
sourceFilename,
haveSourceContent: !!source
}, 'sourcemap sourceContent lookup')
if (source) {
addSourceContextToFrame(frame, source.split(/\r?\n/g), mappedLineno, linesOfContext)
cacheAndCb(frame)
return
}
}
// If the file looks like it minimized (as we didn't have a source-map in
// the processing above), then skip adding source context because it
// is mostly useless and the typically 500-char lines result in over-large
// APM error objects.
if (filename.endsWith('.min.js')) {
cacheAndCb(frame)
return
}
// Otherwise load the file from disk, if available.
fileCache.get(frame.abs_path, function onFileCacheGet (fileErr, lines) {
if (fileErr) {
log.debug({ filename: frame.abs_path, err: fileErr },
'could not read file for source context')
} else {
addSourceContextToFrame(frame, lines, frame.lineno, linesOfContext)
}
cacheAndCb(frame)
})
})
}
// ---- exports
// Gather an APM `stacktrace` object from the given `err`.
// This stacktrace object is used for `error.exception.stacktrace`,
// `error.log.stacktrace`, or `span.stacktrace`.
//
// This is a best effort, so it never fails. It will log.debug any parsing
// failures.
//
// @param {Logger} log
// @param {Error|Object} err - Typically an Error instance, but can also be a
// plain object on which `Error.captureStackTrace(...)` has been called.
// @param {Integer} sourceLinesAppFrames - The number of source lines of
// context to include for frames in application code.
// @param {Integer} sourceLinesLibraryFrames - The number of source lines of
// context to include for frames in library code (i.e. under node_modules/)
// @param {Function} filterCallSite - Optional. A function to filter the
// CallSites to include in the stacktrace.
// @param {Function} cb - `cb(null, stacktrace)`
function gatherStackTrace (log, err, sourceLinesAppFrames, sourceLinesLibraryFrames, filterCallSite, cb) {
// errorCallsites returns an array of v8 CallSite objects.
// https://v8.dev/docs/stack-trace-api#customizing-stack-traces
let callsites = errorCallsites ? errorCallsites(err) : null
const next = afterAllResults(function finish (_err, stacktrace) {
// _err is always null from frameFromCallSite.
// If we are not able to extract callsite information from err, then
// fallback to parsing the err.stack string.
if (stacktrace.length === 0) {
stacktrace = stackTraceFromErrStackString(log, err)
}
cb(null, stacktrace)
})
if (!isValidCallsites(callsites)) {
// When can this happen? Another competing Error.prepareStackTrace breaking
// error-callsites? Also initStackTraceCollection not having been called.
log.debug('could not get valid callsites from error "%s"', err)
} else if (callsites) {
if (filterCallSite) {
callsites = callsites.filter(filterCallSite)
}
const cwd = getCwd(log)
for (let i = 0; i < callsites.length; i++) {
frameFromCallSite(
log,
callsites[i],
cwd,
sourceLinesAppFrames,
sourceLinesLibraryFrames,
next()
)
}
}
}
module.exports = {
gatherStackTrace,
frameCacheStats,
initStackTraceCollection,
// Exported for testing only.
stackTraceFromErrStackString
}