forked from pinpoint-apm/pinpoint-node-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
koa-router.js
89 lines (77 loc) · 2.91 KB
/
koa-router.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
/**
* Pinpoint Node.js Agent
* Copyright 2020-present NAVER Corp.
* Apache License v2.0
*/
'use strict'
const semver = require('semver')
const shimmer = require('shimmer')
const ServiceTypeCode = require('../../constant/service-type').ServiceTypeCode
const log = require('../../utils/logger')
const layerPatchedSymbol = Symbol('PinpointKoaLayerPatched')
const { makeMethodDescriptorBuilder } = require('../../context/make-method-descriptor-builder')
const KoaMethodDescriptorBuilder = require('../../context/koa-method-descriptor-builder')
const apiMetaService = require('../../context/api-meta-service')
module.exports = function (agent, version, router) {
if (!semver.satisfies(version, '>=5.2.0 <8')) {
log.debug('koa-router version %s not supported - aborting...', version)
return router
}
shimmer.wrap(router.prototype, 'register', function (original) {
return function (path, methods, middleware, opts) {
const layer = original.apply(this, arguments)
if (layer[layerPatchedSymbol]) {
return layer
}
layer[layerPatchedSymbol] = true
if (!Array.isArray(layer.stack) || layer.stack.length < 1) {
return layer
}
const handlerIndex = layer.stack.length - 1
const fn = layer.stack[handlerIndex]
if (typeof fn !== 'function') {
return layer
}
const builder = KoaMethodDescriptorBuilder.make(makeMethodDescriptorBuilder('koa', 2, 3))
const methodDescriptor = apiMetaService.cacheApiWithBuilder(builder)
layer.stack[handlerIndex] = async function (ctx, next) {
const name = fn.name || 'AnonymousFunction'
const trace = agent.traceContext.currentTraceObject()
let spanEventRecorder = null
let result
try {
if (trace) {
spanEventRecorder = trace.traceBlockBegin()
spanEventRecorder.recordServiceType(ServiceTypeCode.koa)
recordAPI(methodDescriptor, path, spanEventRecorder, ctx, name)
}
result = await fn.apply(this, arguments)
} catch (e) {
if (!e._pinpointCheck) {
e._pinpointCheck = true
spanEventRecorder.recordServiceType(ServiceTypeCode.koa)
recordAPI(methodDescriptor, path, spanEventRecorder, ctx, name)
spanEventRecorder.recordException(e, true)
}
throw e
} finally {
if (trace) {
trace.traceBlockEnd(spanEventRecorder)
}
}
return result
}
return layer
}
})
return router
}
function recordAPI(methodDescriptor, path, spanEventRecorder, ctx, name) {
if (methodDescriptor && typeof path === 'string') {
spanEventRecorder.recordApiWithParameters(methodDescriptor, [path])
} else if (methodDescriptor) {
spanEventRecorder.recordApi(methodDescriptor)
} else {
spanEventRecorder.recordApiDesc(`koa.router.${ctx.method.toLocaleLowerCase()} [${name}]`)
}
}