-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
102 lines (83 loc) · 2.37 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
98
99
100
101
102
'use strict'
const assert = require('assert')
const fp = require('fastify-plugin')
const { initTracer, opentracing } = require('jaeger-client')
const url = require('url')
const { Tags, FORMAT_HTTP_HEADERS } = opentracing
function jaegerPlugin (fastify, opts, next) {
assert(opts.serviceName, 'Jaeger Plugin requires serviceName option')
const { state = {}, initTracerOpts = {}, ...tracerConfig } = opts
const exposeAPI = opts.exposeAPI !== false
const defaultConfig = {
sampler: {
type: 'const',
param: 1
},
reporter: {
logSpans: false
}
}
const defaultOptions = {
logger: fastify.log
}
const tracer = initTracer(
{ ...defaultConfig, ...tracerConfig },
{ ...defaultOptions, ...initTracerOpts }
)
const tracerMap = new WeakMap()
function api () {
const req = this
return {
get span () {
return tracerMap.get(req)
},
tags: Tags
}
}
if (exposeAPI) {
fastify.decorateRequest('jaeger', api)
}
function filterObject (obj) {
const ret = {}
Object.keys(obj)
.filter((key) => obj[key] != null)
.forEach((key) => { ret[key] = obj[key] })
return ret
}
function setContext (headers) {
return filterObject({ ...headers, ...state })
}
function onRequest (req, res, done) {
const parentSpanContext = tracer.extract(FORMAT_HTTP_HEADERS, setContext(req.raw.headers))
const span = tracer.startSpan(`${req.raw.method} - ${url.format(req.raw.url)}`, {
childOf: parentSpanContext,
tags: { [Tags.SPAN_KIND]: Tags.SPAN_KIND_RPC_SERVER, [Tags.HTTP_METHOD]: req.raw.method, [Tags.HTTP_URL]: url.format(req.raw.url) }
})
tracerMap.set(req, span)
done()
}
function onResponse (req, reply, done) {
const span = tracerMap.get(req)
span.setTag(Tags.HTTP_STATUS_CODE, reply.res.statusCode)
span.finish()
done()
}
function onError (req, reply, error, done) {
const span = tracerMap.get(req)
span.setTag(Tags.ERROR, {
'error.object': error,
message: error.message,
stack: error.stack
})
done()
}
function onClose (instance, done) {
tracer.close(done)
}
fastify.addHook('onRequest', onRequest)
fastify.addHook('onResponse', onResponse)
fastify.addHook('onError', onError)
fastify.addHook('onClose', onClose)
next()
}
module.exports = fp(jaegerPlugin, { name: 'fastify-jaeger' })