forked from pinpoint-apm/pinpoint-node-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
express.js
281 lines (254 loc) · 10.8 KB
/
express.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
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
/**
* Pinpoint Node.js Agent
* Copyright 2020-present NAVER Corp.
* Apache License v2.0
*/
'use strict'
const util = require('util')
const shimmer = require('shimmer')
const ServiceTypeCode = require('../../constant/service-type').ServiceTypeCode
const log = require('../../utils/logger')
const MethodDescriptor = require('../../context/method-descriptor')
const apiMetaService = require('../../context/api-meta-service')
const StringUtils = require('../../utils/string-utils')
const { makeMethodDescriptorBuilder } = require('../../context/make-method-descriptor-builder')
const ExpressMethodDescriptorBuilder = require('../../context/express-method-descriptor-builder')
const semver = require('semver')
const parameterizedLayerPathSymbol = Symbol('PinpointParameterizedLayerPathSymbol')
const layerPatchedSymbol = Symbol('PinpointLayerPatched')
const errorReportedSymbol = Symbol('PinpointErrorReported')
// https://github.com/elastic/apm-agent-nodejs/blob/master/lib/instrumentation/modules/express.js
module.exports = function (agent, version, express) {
try {
if (!semver.satisfies(version, '^4.0.0')) {
log.warn(`express version ${version} not supported.`)
return express
}
} catch (error) {
log.error('Invalid Version error')
return express
}
const MODULE_NAME = 'express'
const methodNames = ['GET', 'POST', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'PATCH', 'ALL']
const names = methodNames.map(method => ['route', method])
const methodDescriptorMap = names.reduce((descMap, [objectName, methodName]) => {
const descriptor = MethodDescriptor.create(MODULE_NAME, objectName, methodName)
apiMetaService.cacheApi(descriptor)
descMap[objectName + methodName] = descriptor
return descMap
}, {})
function getMethodDescriptor(objectPath, methodName, httpMethod) {
const method = objectPath === 'route' ? httpMethod : methodName
return methodDescriptorMap[objectPath + method]
}
function getDescriptionText(objectPath, methodName) {
return MODULE_NAME + '.' + objectPath + '.' + (methodName ? StringUtils.encodeMethodName(methodName) : 'AnonymousFunction')
}
shimmer.wrap(express.Router, 'use', function (original) {
return function () {
const result = original.apply(this, arguments)
const fn = arguments && arguments[1]
if (fn && fn.name !== 'router' && this.stack && this.stack.length) {
const layer = this.stack[this.stack.length - 1]
patchLayer(layer, 'middleware', layer.name)
}
return result
}
})
shimmer.wrap(express.Router, 'route', function (original) {
return function route(path) {
const route = original.apply(this, arguments)
if (this.stack && this.stack.length) {
const layer = this.stack[this.stack.length - 1]
patchLayer(layer, 'route', layer.name, path)
}
return route
}
})
function patchLayer(layer, objectName, layerName, layerPath) {
if (!layer[layerPatchedSymbol]) {
layer[layerPatchedSymbol] = true
let appAllMethodDescriptor
let handlerMethodDescriptor
if (objectName == 'route') {
const appAllbuilder = ExpressMethodDescriptorBuilder.make(makeMethodDescriptorBuilder(MODULE_NAME, 3))
appAllMethodDescriptor = apiMetaService.cacheApiWithBuilder(appAllbuilder)
const handlerBuilder = makeMethodDescriptorBuilder(undefined, 4)
handlerMethodDescriptor = apiMetaService.cacheApiWithBuilder(handlerBuilder)
}
shimmer.wrap(layer, 'handle', function (origin) {
let handle
if (origin.length !== 4) {
handle = function (req, res, next) {
const trace = agent.traceContext.currentTraceObject()
if (!trace) {
return origin.apply(this, arguments)
}
const spanEventRecorder = trace.traceBlockBegin()
spanEventRecorder.recordServiceType(ServiceTypeCode.express)
const methodDescriptor = appAllMethodDescriptor || getMethodDescriptor(objectName, layerName, req.method)
if (methodDescriptor && layerPath) {
spanEventRecorder.recordApiWithParameters(methodDescriptor, [layerPath])
} else if (methodDescriptor) {
spanEventRecorder.recordApi(methodDescriptor)
} else {
spanEventRecorder.recordApiDesc(getDescriptionText(objectName, layerName))
}
let handlerSpanEventRecorder
if (handlerMethodDescriptor) {
handlerSpanEventRecorder = trace.traceBlockBegin()
handlerSpanEventRecorder.recordServiceType(ServiceTypeCode.node_method)
handlerSpanEventRecorder.recordApi(handlerMethodDescriptor)
}
// https://github.com/elastic/apm-agent-nodejs/issues/443#issuecomment-455352070
if (!layer.route && layerPath && typeof next === 'function') {
safePush(req, parameterizedLayerPathSymbol, layerPath)
arguments[2] = function () {
if (!(req.route && arguments[0] instanceof Error)) {
req[parameterizedLayerPathSymbol].pop()
}
return next.apply(this, arguments)
}
}
const result = origin.apply(this, arguments)
if (handlerSpanEventRecorder) {
trace.traceBlockEnd(handlerSpanEventRecorder)
}
trace.traceBlockEnd(spanEventRecorder)
return result
}
} else {
handle = function (err, req, res, next) {
const trace = agent.traceContext.currentTraceObject()
let spanEventRecorder = null
let handlerSpanEventRecorder = null
if (shouldReport(err, trace)) {
spanEventRecorder = trace.traceBlockBegin()
spanEventRecorder.recordServiceType(ServiceTypeCode.express)
spanEventRecorder.recordException(err, true)
const methodDescriptor = getMethodDescriptor(objectName, layerName, req.method)
if (methodDescriptor) {
spanEventRecorder.recordApi(getMethodDescriptor(objectName, layerName, req.method))
} else {
spanEventRecorder.recordApiDesc(getDescriptionText(objectName, layerName, req.method))
}
if (handlerMethodDescriptor) {
handlerSpanEventRecorder = trace.traceBlockBegin()
handlerSpanEventRecorder.recordServiceType(ServiceTypeCode.node_method)
handlerSpanEventRecorder.recordApi(handlerMethodDescriptor)
}
}
const result = origin.apply(this, arguments)
if (trace) {
if (handlerSpanEventRecorder) {
trace.traceBlockEnd(handlerSpanEventRecorder)
}
trace.traceBlockEnd(spanEventRecorder)
}
return result
}
}
// https://github.com/elastic/apm-agent-nodejs/issues/1067
for (const prop in origin) {
if (Object.prototype.hasOwnProperty.call(origin, prop)) {
handle[prop] = origin[prop]
}
}
return handle
})
}
// let appAllMethodDescriptor
// let handlerMethodDescriptor
// if (objectName == 'route') {
// const appAllbuilder = ExpressMethodDescriptorBuilder.make(makeMethodDescriptorBuilder(MODULE_NAME, 3))
// appAllMethodDescriptor = apiMetaService.cacheApiWithBuilder(appAllbuilder)
// const handlerBuilder = makeMethodDescriptorBuilder(undefined, 4)
// handlerMethodDescriptor = apiMetaService.cacheApiWithBuilder(handlerBuilder)
// }
// shimmer.wrap(layer, 'handle', function (original) {
// return (original.length === 4)
// ? recordErrorHandle(original, objectName, layerName)
// : recordHandle(original, objectName, layerName, appAllMethodDescriptor, handlerMethodDescriptor, layerPath)
// })
}
function safePush(obj, prop, value) {
if (!obj[prop]) obj[prop] = []
obj[prop].push(value)
}
function shouldReport(error, trace) {
if (!trace) {
return false
}
if (typeof error === 'string') {
return true
}
if (isError(error) && !error[errorReportedSymbol]) {
error[errorReportedSymbol] = true
return true
}
return false
}
function isError(error) {
if (!util.types) {
return util.isError(error)
}
return util.types.isNativeError(error)
}
function recordHandle(original, objectName, layerName, appAllMethodDescriptor, handlerMethodDescriptor, layerPath) {
return function (req) {
const trace = agent.traceContext.currentTraceObject()
let spanEventRecorder = null
let handlerSpanEventRecorder
if (trace) {
spanEventRecorder = trace.traceBlockBegin()
spanEventRecorder.recordServiceType(ServiceTypeCode.express)
const methodDescriptor = appAllMethodDescriptor || getMethodDescriptor(objectName, layerName, req.method)
if (methodDescriptor && layerPath) {
spanEventRecorder.recordApiWithParameters(methodDescriptor, [layerPath])
} else if (methodDescriptor) {
spanEventRecorder.recordApi(methodDescriptor)
} else {
spanEventRecorder.recordApiDesc(getDescriptionText(objectName, layerName))
}
if (handlerMethodDescriptor) {
handlerSpanEventRecorder = trace.traceBlockBegin()
handlerSpanEventRecorder.recordServiceType(ServiceTypeCode.node_method)
handlerSpanEventRecorder.recordApi(handlerMethodDescriptor)
}
}
const result = original.apply(this, arguments)
if (trace) {
if (handlerSpanEventRecorder) {
trace.traceBlockEnd(handlerSpanEventRecorder)
}
trace.traceBlockEnd(spanEventRecorder)
}
return result
}
}
function recordErrorHandle(original, objectName, layerName) {
return function (err, req, res, next) {
log.debug('recordErrorHandle start', getMethodDescriptor(objectName, layerName, req.method))
const trace = agent.traceContext.currentTraceObject()
let spanEventRecorder = null
if (err && trace) {
spanEventRecorder = trace.traceBlockBegin()
spanEventRecorder.recordServiceType(ServiceTypeCode.express)
spanEventRecorder.recordException(err, true)
const methodDescriptor = getMethodDescriptor(objectName, layerName, req.method)
if (methodDescriptor) {
spanEventRecorder.recordApi(getMethodDescriptor(objectName, layerName, req.method))
} else {
spanEventRecorder.recordApiDesc(getDescriptionText(objectName, layerName, req.method))
}
}
const result = original.apply(this, arguments)
if (trace) {
trace.traceBlockEnd(spanEventRecorder)
}
log.debug('recordErrorHandle end', getMethodDescriptor(objectName, layerName, req.method))
return result
}
}
return express
}