-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
92 lines (78 loc) · 2.23 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
'use strict'
const { HttpLogger } = require('zipkin-transport-http')
const {
Tracer,
BatchRecorder,
jsonEncoder: { JSON_V2 }
} = require('zipkin')
const assert = require('node:assert')
const CLSContext = require('zipkin-context-cls')
const fp = require('fastify-plugin')
const url = require('node:url')
const zipkin = require('zipkin')
const Some = zipkin.option.Some
const None = zipkin.option.None
const Instrumentation = zipkin.Instrumentation
function fastifyZipkin (fastify, opts, next) {
assert(opts.serviceName, 'serviceName option should not be empty')
assert(opts.httpReporterUrl, 'httpReporterUrl option should not be empty')
const ctxImpl = new CLSContext('zipkin')
const recorder = opts.recorder || new BatchRecorder({
logger: new HttpLogger({
endpoint: opts.httpReporterUrl,
jsonEncoder: JSON_V2
})
})
const tracer = opts.tracer || new Tracer({
ctxImpl,
recorder,
localServiceName: opts.serviceName
})
const instrumentation = new Instrumentation.HttpServer({
tracer,
serviceName: opts.serviceName,
port: opts.servicePort || 0
})
try {
// we must register a custom error handler
// otherwise all the 404 requests
// will not be catched by our hooks
fastify.setNotFoundHandler(basic404)
} catch {
// a custom error handler is already present
}
fastify.addHook('onRequest', onRequest)
fastify.addHook('onResponse', onResponse)
function onRequest (req, res, done) {
tracer.scoped(() => {
const id = instrumentation.recordRequest(
req.raw.method,
url.format(req.raw.url),
readHeader.bind(req.headers)
)
res._zipkinId = id
done()
})
}
function onResponse (_req, reply, done) {
tracer.scoped(() => {
instrumentation.recordResponse(reply._zipkinId, reply.raw.statusCode)
})
done()
}
function readHeader (header) {
const val = this[header.toLowerCase()]
if (val != null) return new Some(val)
return None
}
next()
}
function basic404 (_req, reply) {
reply.code(404).send(new Error('Not found'))
}
module.exports = fp(fastifyZipkin, {
fastify: '>=5.x',
name: '@fastify/zipkin'
})
module.exports.default = fastifyZipkin
module.exports.fastifyZipkin = fastifyZipkin