-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathindex.ts
More file actions
267 lines (235 loc) · 9.02 KB
/
index.ts
File metadata and controls
267 lines (235 loc) · 9.02 KB
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
import * as diagnosticsChannel from 'node:diagnostics_channel';
import type { Instrumentation, InstrumentationConfig } from '@opentelemetry/instrumentation';
import type { IntegrationFn, Span } from '@sentry/core';
import {
captureException,
defineIntegration,
getClient,
getIsolationScope,
logger,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
spanToJSON,
} from '@sentry/core';
import { DEBUG_BUILD } from '../../../debug-build';
import { generateInstrumentOnce } from '../../../otel/instrument';
import { FastifyOtelInstrumentation } from './fastify-otel/index';
import type { FastifyInstance, FastifyReply, FastifyRequest } from './types';
import { FastifyInstrumentationV3 } from './v3/instrumentation';
interface FastifyHandlerOptions {
/**
* Callback method deciding whether error should be captured and sent to Sentry
*
* @param error Captured Fastify error
* @param request Fastify request (or any object containing at least method, routeOptions.url, and routerPath)
* @param reply Fastify reply (or any object containing at least statusCode)
*
* @example
*
* ```javascript
* setupFastifyErrorHandler(app, {
* shouldHandleError(_error, _request, reply) {
* return reply.statusCode >= 400;
* },
* });
* ```
*
* If using TypeScript, you can cast the request and reply to get full type safety.
*
* ```typescript
* import type { FastifyRequest, FastifyReply } from 'fastify';
*
* setupFastifyErrorHandler(app, {
* shouldHandleError(error, minimalRequest, minimalReply) {
* const request = minimalRequest as FastifyRequest;
* const reply = minimalReply as FastifyReply;
* return reply.statusCode >= 500;
* },
* });
* ```
*/
shouldHandleError: (error: Error, request: FastifyRequest, reply: FastifyReply) => boolean;
}
const INTEGRATION_NAME = 'Fastify';
const INTEGRATION_NAME_V3 = 'Fastify-V3';
export const instrumentFastifyV3 = generateInstrumentOnce(INTEGRATION_NAME_V3, () => new FastifyInstrumentationV3());
function handleFastifyError(
this: {
diagnosticsChannelExists?: boolean;
},
error: Error,
request: FastifyRequest & { opentelemetry?: () => { span?: Span } },
reply: FastifyReply,
shouldHandleError: (error: Error, request: FastifyRequest, reply: FastifyReply) => boolean,
handlerOrigin: 'diagnostics-channel' | 'onError-hook',
): void {
// Diagnostics channel runs before the onError hook, so we can use it to check if the handler was already registered
if (handlerOrigin === 'diagnostics-channel') {
this.diagnosticsChannelExists = true;
}
if (this.diagnosticsChannelExists && handlerOrigin === 'onError-hook') {
DEBUG_BUILD &&
logger.warn(
'Fastify error handler was already registered via diagnostics channel.',
'You can safely remove `setupFastifyErrorHandler` call.',
);
// If the diagnostics channel already exists, we don't need to handle the error again
return;
}
if (shouldHandleError(error, request, reply)) {
captureException(error);
}
}
export const instrumentFastify = generateInstrumentOnce(INTEGRATION_NAME, () => {
const fastifyOtelInstrumentationInstance = new FastifyOtelInstrumentation();
const plugin = fastifyOtelInstrumentationInstance.plugin();
const options = fastifyOtelInstrumentationInstance.getConfig();
const shouldHandleError = (options as FastifyHandlerOptions)?.shouldHandleError || defaultShouldHandleError;
// This message handler works for Fastify versions 3, 4 and 5
diagnosticsChannel.subscribe('fastify.initialization', message => {
const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;
fastifyInstance?.register(plugin).after(err => {
if (err) {
DEBUG_BUILD && logger.error('Failed to setup Fastify instrumentation', err);
} else {
instrumentClient();
if (fastifyInstance) {
instrumentOnRequest(fastifyInstance);
}
}
});
});
// This diagnostics channel only works on Fastify version 5
// For versions 3 and 4, we use `setupFastifyErrorHandler` instead
diagnosticsChannel.subscribe('tracing:fastify.request.handler:error', message => {
const { error, request, reply } = message as {
error: Error;
request: FastifyRequest & { opentelemetry?: () => { span?: Span } };
reply: FastifyReply;
};
handleFastifyError.call(handleFastifyError, error, request, reply, shouldHandleError, 'diagnostics-channel');
});
// Returning this as unknown not to deal with the internal types of the FastifyOtelInstrumentation
return fastifyOtelInstrumentationInstance as Instrumentation<InstrumentationConfig & FastifyHandlerOptions>;
});
const _fastifyIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
instrumentFastifyV3();
instrumentFastify();
},
};
}) satisfies IntegrationFn;
/**
* Adds Sentry tracing instrumentation for [Fastify](https://fastify.dev/).
*
* If you also want to capture errors, you need to call `setupFastifyErrorHandler(app)` after you set up your Fastify server.
*
* For more information, see the [fastify documentation](https://docs.sentry.io/platforms/javascript/guides/fastify/).
*
* @example
* ```javascript
* const Sentry = require('@sentry/node');
*
* Sentry.init({
* integrations: [Sentry.fastifyIntegration()],
* })
* ```
*/
export const fastifyIntegration = defineIntegration(_fastifyIntegration);
/**
* Default function to determine if an error should be sent to Sentry
*
* 3xx and 4xx errors are not sent by default.
*/
function defaultShouldHandleError(_error: Error, _request: FastifyRequest, reply: FastifyReply): boolean {
const statusCode = reply.statusCode;
// 3xx and 4xx errors are not sent by default.
return statusCode >= 500 || statusCode <= 299;
}
/**
* Add an Fastify error handler to capture errors to Sentry.
*
* @param fastify The Fastify instance to which to add the error handler
* @param options Configuration options for the handler
*
* @example
* ```javascript
* const Sentry = require('@sentry/node');
* const Fastify = require("fastify");
*
* const app = Fastify();
*
* Sentry.setupFastifyErrorHandler(app);
*
* // Add your routes, etc.
*
* app.listen({ port: 3000 });
* ```
*/
export function setupFastifyErrorHandler(fastify: FastifyInstance, options?: Partial<FastifyHandlerOptions>): void {
const shouldHandleError = options?.shouldHandleError || defaultShouldHandleError;
const plugin = Object.assign(
function (fastify: FastifyInstance, _options: unknown, done: () => void): void {
fastify.addHook('onError', async (request, reply, error) => {
handleFastifyError.call(handleFastifyError, error, request, reply, shouldHandleError, 'onError-hook');
});
done();
},
{
[Symbol.for('skip-override')]: true,
[Symbol.for('fastify.display-name')]: 'sentry-fastify-error-handler',
},
);
// eslint-disable-next-line @typescript-eslint/no-floating-promises
fastify.register(plugin);
}
function addFastifySpanAttributes(span: Span): void {
const spanJSON = spanToJSON(span);
const spanName = spanJSON.description;
const attributes = spanJSON.data;
const type = attributes['fastify.type'];
const isHook = type === 'hook';
const isHandler = type === spanName?.startsWith('handler -');
// In @fastify/otel `request-handler` is separated by dash, not underscore
const isRequestHandler = spanName === 'request' || type === 'request-handler';
// If this is already set, or we have no fastify span, no need to process again...
if (attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] || (!isHandler && !isRequestHandler && !isHook)) {
return;
}
const opPrefix = isHook ? 'hook' : isHandler ? 'middleware' : isRequestHandler ? 'request-handler' : '<unknown>';
span.setAttributes({
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.fastify',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: `${opPrefix}.fastify`,
});
const attrName = attributes['fastify.name'] || attributes['plugin.name'] || attributes['hook.name'];
if (typeof attrName === 'string') {
// Try removing `fastify -> ` and `@fastify/otel -> ` prefixes
// This is a bit of a hack, and not always working for all spans
// But it's the best we can do without a proper API
const updatedName = attrName.replace(/^fastify -> /, '').replace(/^@fastify\/otel -> /, '');
span.updateName(updatedName);
}
}
function instrumentClient(): void {
const client = getClient();
if (client) {
client.on('spanStart', (span: Span) => {
addFastifySpanAttributes(span);
});
}
}
function instrumentOnRequest(fastify: FastifyInstance): void {
fastify.addHook('onRequest', async (request: FastifyRequest & { opentelemetry?: () => { span?: Span } }, _reply) => {
if (request.opentelemetry) {
const { span } = request.opentelemetry();
if (span) {
addFastifySpanAttributes(span);
}
}
const routeName = request.routeOptions?.url;
const method = request.method || 'GET';
getIsolationScope().setTransactionName(`${method} ${routeName}`);
});
}