-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
390 lines (342 loc) · 13.1 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
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
'use strict'
const { context, trace, SpanStatusCode } = require('@opentelemetry/api')
const { getRPCMetadata, RPCType } = require('@opentelemetry/core')
const {
ATTR_HTTP_ROUTE,
ATTR_HTTP_RESPONSE_STATUS_CODE,
ATTR_HTTP_REQUEST_METHOD,
ATTR_SERVICE_NAME
} = require('@opentelemetry/semantic-conventions')
const { InstrumentationBase } = require('@opentelemetry/instrumentation')
const {
version: PACKAGE_VERSION,
name: PACKAGE_NAME
} = require('./package.json')
// Constants
const SUPPORTED_VERSIONS = '>=4.0.0 <6'
const FASTIFY_HOOKS = [
'onRequest',
'preParsing',
'preValidation',
'preHandler',
'preSerialization',
'onSend',
'onResponse',
'onError'
]
const ATTRIBUTE_NAMES = {
HOOK_NAME: 'hook.name',
FASTIFY_TYPE: 'fastify.type',
HOOK_CALLBACK_NAME: 'hook.callback.name',
ROOT: 'fastify.root'
}
const HOOK_TYPES = {
ROUTE: 'route-hook',
INSTANCE: 'hook',
HANDLER: 'request-handler'
}
const ANONYMOUS_FUNCTION_NAME = 'anonymous'
// Symbols
const kInstrumentation = Symbol('fastify otel instance')
const kRequestSpan = Symbol('fastify otel request spans')
const kRequestContext = Symbol('fastify otel request context')
const kAddHookOriginal = Symbol('fastify otel addhook original')
const kSetNotFoundOriginal = Symbol('fastify otel setnotfound original')
class FastifyOtelInstrumentation extends InstrumentationBase {
static FastifyOtelInstrumentation = FastifyOtelInstrumentation
static default = FastifyOtelInstrumentation
servername = ''
constructor (config) {
super(PACKAGE_NAME, PACKAGE_VERSION, config)
this.servername = config?.servername ?? process.env.OTEL_SERVICE_NAME ?? 'fastify'
}
// We do not do patching in this instrumentation
init () {
return []
}
plugin () {
const instrumentation = this
FastifyInstrumentationPlugin[Symbol.for('skip-override')] = true
FastifyInstrumentationPlugin[Symbol.for('fastify.display-name')] = '@fastify/otel'
FastifyInstrumentationPlugin[Symbol.for('plugin-meta')] = {
fastify: SUPPORTED_VERSIONS,
name: '@fastify/otel',
}
return FastifyInstrumentationPlugin
function FastifyInstrumentationPlugin (instance, opts, done) {
instance.decorate(kInstrumentation, instrumentation)
// addHook and notfoundHandler are essentially inherited from the prototype
// what is important is to bound it to the right instance
instance.decorate(kAddHookOriginal, instance.addHook)
instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler)
instance.decorateRequest(kRequestSpan, null)
instance.decorateRequest(kRequestContext, null)
instance.addHook('onRoute', function (routeOptions) {
for (const hook of FASTIFY_HOOKS) {
if (routeOptions[hook] != null) {
const handlerLike = routeOptions[hook]
if (typeof handlerLike === 'function') {
routeOptions[hook] = handlerWrapper(handlerLike, {
[ATTR_SERVICE_NAME]:
instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route -> ${hook}`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.ROUTE,
[ATTR_HTTP_ROUTE]: routeOptions.url,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
handlerLike.name?.length > 0
? handlerLike.name
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
})
} else if (Array.isArray(handlerLike)) {
const wrappedHandlers = []
for (const handler of handlerLike) {
wrappedHandlers.push(
handlerWrapper(handler, {
[ATTR_SERVICE_NAME]:
instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route -> ${hook}`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.ROUTE,
[ATTR_HTTP_ROUTE]: routeOptions.url,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
handler.name?.length > 0
? handler.name
: ANONYMOUS_FUNCTION_NAME
})
)
}
routeOptions[hook] = wrappedHandlers
}
}
}
// We always want to add the onSend hook to the route to be executed last
if (routeOptions.onSend != null) {
routeOptions.onSend = Array.isArray(routeOptions.onSend)
? [...routeOptions.onSend, onSendHook]
: [routeOptions.onSend, onSendHook]
} else {
routeOptions.onSend = onSendHook
}
// We always want to add the onError hook to the route to be executed last
if (routeOptions.onError != null) {
routeOptions.onError = Array.isArray(routeOptions.onError)
? [...routeOptions.onError, onErrorHook]
: [routeOptions.onError, onErrorHook]
} else {
routeOptions.onError = onErrorHook
}
routeOptions.handler = handlerWrapper(routeOptions.handler, {
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route-handler`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.HANDLER,
[ATTR_HTTP_ROUTE]: routeOptions.url,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
routeOptions.handler.name.length > 0
? routeOptions.handler.name
: ANONYMOUS_FUNCTION_NAME
})
})
instance.addHook('onRequest', function (request, _reply, hookDone) {
if (this[kInstrumentation].isEnabled() === true) {
const rpcMetadata = getRPCMetadata(context.active())
if (
request.routeOptions.url != null &&
rpcMetadata?.type === RPCType.HTTP
) {
rpcMetadata.route = request.routeOptions.url
}
/** @type {Span} */
const span = this[kInstrumentation].tracer.startSpan('request', {
attributes: {
[ATTR_SERVICE_NAME]:
instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.ROOT]: '@fastify/otel',
[ATTR_HTTP_ROUTE]: request.url,
[ATTR_HTTP_REQUEST_METHOD]: request.method
}
})
request[kRequestContext] = trace.setSpan(context.active(), span)
request[kRequestSpan] = span
}
hookDone()
})
// onResponse is the last hook to be executed, only added for 404 handlers
instance.addHook('onResponse', function (request, reply, hookDone) {
const span = request[kRequestSpan]
if (span != null) {
span.setStatus({
code: SpanStatusCode.OK,
message: 'OK'
})
span.setAttributes({
[ATTR_HTTP_RESPONSE_STATUS_CODE]: 404
})
span.end()
}
request[kRequestSpan] = null
hookDone()
})
instance.addHook = addHookPatched
instance.setNotFoundHandler = setNotFoundHandlerPatched
done()
function onSendHook (request, reply, payload, hookDone) {
/** @type {import('@opentelemetry/api').Span} */
const span = request[kRequestSpan]
if (span != null) {
if (reply.statusCode < 500) {
span.setStatus({
code: SpanStatusCode.OK,
message: 'OK'
})
}
span.setAttributes({
[ATTR_HTTP_RESPONSE_STATUS_CODE]: reply.statusCode
})
span.end()
}
request[kRequestSpan] = null
hookDone(null, payload)
}
function onErrorHook (request, reply, error, hookDone) {
/** @type {Span} */
const span = request[kRequestSpan]
if (span != null) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
})
span.recordException(error)
}
hookDone()
}
function addHookPatched (name, hook) {
const addHookOriginal = this[kAddHookOriginal]
if (FASTIFY_HOOKS.includes(name)) {
addHookOriginal.call(
this,
name,
handlerWrapper(hook, {
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - ${name}`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
hook.name?.length > 0
? hook.name
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
})
)
} else {
addHookOriginal.call(this, name, hook)
}
}
function setNotFoundHandlerPatched (hooks, handler) {
const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal]
if (typeof hooks === 'function') {
handler = handlerWrapper(hooks, {
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
hooks.name?.length > 0
? hooks.name
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
})
setNotFoundHandlerOriginal.call(this, handler)
} else {
if (hooks.preValidation != null) {
hooks.preValidation = handlerWrapper(hooks.preValidation, {
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
hooks.preValidation.name?.length > 0
? hooks.preValidation.name
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
})
}
if (hooks.preHandler != null) {
hooks.preHandler = handlerWrapper(hooks.preHandler, {
[ATTR_SERVICE_NAME]:
instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
hooks.preHandler.name?.length > 0
? hooks.preHandler.name
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
})
}
handler = handlerWrapper(handler, {
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler`,
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
handler.name?.length > 0
? handler.name
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
})
setNotFoundHandlerOriginal.call(this, hooks, handler)
}
}
function handlerWrapper (handler, spanAttributes = {}) {
return function handlerWrapped (...args) {
/** @type {FastifyOtelInstrumentation} */
const instrumentation = this[kInstrumentation]
const [request] = args
if (instrumentation.isEnabled() === false) {
return handler.call(this, ...args)
}
const ctx = request[kRequestContext]
const span = instrumentation.tracer.startSpan(
`handler - ${
handler.name?.length > 0
? handler.name
: this.pluginName /* c8 ignore next */ ??
ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
}`,
{
attributes: spanAttributes
},
ctx
)
return context.with(
trace.setSpan(ctx, span),
function () {
try {
const res = handler.call(this, ...args)
if (typeof res?.then === 'function') {
return res.then(
result => {
span.end()
return result
},
error => {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
})
span.recordException(error)
span.end()
return Promise.reject(error)
}
)
}
span.end()
return res
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
})
span.recordException(error)
span.end()
throw error
}
},
this
)
}
}
}
}
}
module.exports = FastifyOtelInstrumentation