-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathinstrumentServer.ts
460 lines (397 loc) · 15.2 KB
/
instrumentServer.ts
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
/* eslint-disable max-lines */
import type { RequestEventData, Span, TransactionSource, WrappedFunction } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
continueTrace,
fill,
getActiveSpan,
getClient,
getRootSpan,
getTraceData,
hasTracingEnabled,
isNodeEnv,
loadModule,
logger,
setHttpStatus,
spanToJSON,
startSpan,
winterCGRequestToRequestData,
withIsolationScope,
} from '@sentry/core';
import { DEBUG_BUILD } from './debug-build';
import { captureRemixServerException, errorHandleDataFunction, errorHandleDocumentRequestFunction } from './errors';
import { getFutureFlagsServer, getRemixVersionFromBuild } from './futureFlags';
import type { RemixOptions } from './remixOptions';
import { createRoutes, getTransactionName } from './utils';
import { extractData, isDeferredData, isResponse, isRouteErrorResponse, json } from './vendor/response';
import type {
AppData,
AppLoadContext,
CreateRequestHandlerFunction,
DataFunction,
DataFunctionArgs,
EntryContext,
FutureConfig,
HandleDocumentRequestFunction,
RemixRequest,
RequestHandler,
ServerBuild,
ServerRoute,
ServerRouteManifest,
} from './vendor/types';
let FUTURE_FLAGS: FutureConfig | undefined;
const redirectStatusCodes = new Set([301, 302, 303, 307, 308]);
function isRedirectResponse(response: Response): boolean {
return redirectStatusCodes.has(response.status);
}
function isCatchResponse(response: Response): boolean {
return response.headers.get('X-Remix-Catch') != null;
}
/**
* Sentry utility to be used in place of `handleError` function of Remix v2
* Remix Docs: https://remix.run/docs/en/main/file-conventions/entry.server#handleerror
*
* Should be used in `entry.server` like:
*
* export const handleError = Sentry.sentryHandleError
*/
export function sentryHandleError(err: unknown, { request }: DataFunctionArgs): void {
// We are skipping thrown responses here as they are handled by
// `captureRemixServerException` at loader / action level
// We don't want to capture them twice.
// This function is only for capturing unhandled server-side exceptions.
// https://remix.run/docs/en/main/file-conventions/entry.server#thrown-responses
// https://remix.run/docs/en/v1/api/conventions#throwing-responses-in-loaders
if (isResponse(err) || isRouteErrorResponse(err)) {
return;
}
captureRemixServerException(err, 'remix.server.handleError', request).then(null, e => {
DEBUG_BUILD && logger.warn('Failed to capture Remix Server exception.', e);
});
}
/**
* @deprecated Use `sentryHandleError` instead.
*/
export const wrapRemixHandleError = sentryHandleError;
/**
* Sentry wrapper for Remix's `handleError` function.
* Remix Docs: https://remix.run/docs/en/main/file-conventions/entry.server#handleerror
*/
export function wrapHandleErrorWithSentry(
origHandleError: (err: unknown, args: { request: unknown }) => void,
): (err: unknown, args: { request: unknown }) => void {
return function (this: unknown, err: unknown, args: { request: unknown }): void {
// This is expected to be void but just in case it changes in the future.
const res = origHandleError.call(this, err, args);
sentryHandleError(err, args as DataFunctionArgs);
return res;
};
}
function makeWrappedDocumentRequestFunction(autoInstrumentRemix?: boolean, remixVersion?: number) {
return function (origDocumentRequestFunction: HandleDocumentRequestFunction): HandleDocumentRequestFunction {
return async function (
this: unknown,
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
context: EntryContext,
loadContext?: Record<string, unknown>,
): Promise<Response> {
const documentRequestContext = {
request,
responseStatusCode,
responseHeaders,
context,
loadContext,
};
const isRemixV2 = FUTURE_FLAGS?.v2_errorBoundary || remixVersion === 2;
if (!autoInstrumentRemix) {
const activeSpan = getActiveSpan();
const rootSpan = activeSpan && getRootSpan(activeSpan);
const name = rootSpan ? spanToJSON(rootSpan).description : undefined;
return startSpan(
{
// If we don't have a root span, `onlyIfParent` will lead to the span not being created anyhow
// So we don't need to care too much about the fallback name, it's just for typing purposes....
name: name || '<unknown>',
onlyIfParent: true,
attributes: {
method: request.method,
url: request.url,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.function.remix',
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'function.remix.document_request',
},
},
() => {
return errorHandleDocumentRequestFunction.call(
this,
origDocumentRequestFunction,
documentRequestContext,
isRemixV2,
);
},
);
} else {
return errorHandleDocumentRequestFunction.call(
this,
origDocumentRequestFunction,
documentRequestContext,
isRemixV2,
);
}
};
};
}
function makeWrappedDataFunction(
origFn: DataFunction,
id: string,
name: 'action' | 'loader',
remixVersion: number,
autoInstrumentRemix?: boolean,
): DataFunction {
return async function (this: unknown, args: DataFunctionArgs): Promise<Response | AppData> {
const isRemixV2 = FUTURE_FLAGS?.v2_errorBoundary || remixVersion === 2;
if (!autoInstrumentRemix) {
return startSpan(
{
op: `function.remix.${name}`,
name: id,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.remix',
name,
},
},
(span: Span) => {
return errorHandleDataFunction.call(this, origFn, name, args, isRemixV2, span);
},
);
} else {
return errorHandleDataFunction.call(this, origFn, name, args, isRemixV2);
}
};
}
const makeWrappedAction =
(id: string, remixVersion: number, autoInstrumentRemix?: boolean) =>
(origAction: DataFunction): DataFunction => {
return makeWrappedDataFunction(origAction, id, 'action', remixVersion, autoInstrumentRemix);
};
const makeWrappedLoader =
(id: string, remixVersion: number, autoInstrumentRemix?: boolean) =>
(origLoader: DataFunction): DataFunction => {
return makeWrappedDataFunction(origLoader, id, 'loader', remixVersion, autoInstrumentRemix);
};
function getTraceAndBaggage(): {
sentryTrace?: string;
sentryBaggage?: string;
} {
if (isNodeEnv()) {
const traceData = getTraceData();
return {
sentryTrace: traceData['sentry-trace'],
sentryBaggage: traceData.baggage,
};
}
return {};
}
function makeWrappedRootLoader(remixVersion: number) {
return function (origLoader: DataFunction): DataFunction {
return async function (this: unknown, args: DataFunctionArgs): Promise<Response | AppData> {
const res = await origLoader.call(this, args);
const traceAndBaggage = getTraceAndBaggage();
if (isDeferredData(res)) {
res.data['sentryTrace'] = traceAndBaggage.sentryTrace;
res.data['sentryBaggage'] = traceAndBaggage.sentryBaggage;
res.data['remixVersion'] = remixVersion;
return res;
}
if (isResponse(res)) {
// Note: `redirect` and `catch` responses do not have bodies to extract.
// We skip injection of trace and baggage in those cases.
// For `redirect`, a valid internal redirection target will have the trace and baggage injected.
if (isRedirectResponse(res) || isCatchResponse(res)) {
DEBUG_BUILD && logger.warn('Skipping injection of trace and baggage as the response does not have a body');
return res;
} else {
const data = await extractData(res);
if (typeof data === 'object') {
return json(
{ ...data, ...traceAndBaggage, remixVersion },
{
headers: res.headers,
statusText: res.statusText,
status: res.status,
},
);
} else {
DEBUG_BUILD && logger.warn('Skipping injection of trace and baggage as the response body is not an object');
return res;
}
}
}
return { ...res, ...traceAndBaggage, remixVersion };
};
};
}
function wrapRequestHandler(
origRequestHandler: RequestHandler,
build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>),
autoInstrumentRemix: boolean,
): RequestHandler {
let resolvedBuild: ServerBuild;
let routes: ServerRoute[];
let name: string;
let source: TransactionSource;
return async function (this: unknown, request: RemixRequest, loadContext?: AppLoadContext): Promise<Response> {
const upperCaseMethod = request.method.toUpperCase();
// We don't want to wrap OPTIONS and HEAD requests
if (upperCaseMethod === 'OPTIONS' || upperCaseMethod === 'HEAD') {
return origRequestHandler.call(this, request, loadContext);
}
if (!autoInstrumentRemix) {
if (typeof build === 'function') {
resolvedBuild = await build();
} else {
resolvedBuild = build;
}
routes = createRoutes(resolvedBuild.routes);
}
return withIsolationScope(async isolationScope => {
const options = getClient()?.getOptions();
let normalizedRequest: RequestEventData = {};
try {
normalizedRequest = winterCGRequestToRequestData(request);
} catch (e) {
DEBUG_BUILD && logger.warn('Failed to normalize Remix request');
}
if (!autoInstrumentRemix) {
const url = new URL(request.url);
[name, source] = getTransactionName(routes, url);
isolationScope.setTransactionName(name);
}
isolationScope.setSDKProcessingMetadata({ normalizedRequest });
if (!options || !hasTracingEnabled(options)) {
return origRequestHandler.call(this, request, loadContext);
}
return continueTrace(
{
sentryTrace: request.headers.get('sentry-trace') || '',
baggage: request.headers.get('baggage') || '',
},
async () => {
if (!autoInstrumentRemix) {
return startSpan(
{
name,
attributes: {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.remix',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
method: request.method,
},
},
async span => {
const res = (await origRequestHandler.call(this, request, loadContext)) as Response;
if (isResponse(res)) {
setHttpStatus(span, res.status);
}
return res;
},
);
}
return (await origRequestHandler.call(this, request, loadContext)) as Response;
},
);
});
};
}
function instrumentBuildCallback(build: ServerBuild, autoInstrumentRemix: boolean): ServerBuild {
const routes: ServerRouteManifest = {};
const remixVersion = getRemixVersionFromBuild(build);
const wrappedEntry = { ...build.entry, module: { ...build.entry.module } };
// Not keeping boolean flags like it's done for `requestHandler` functions,
// Because the build can change between build and runtime.
// So if there is a new `loader` or`action` or `documentRequest` after build.
// We should be able to wrap them, as they may not be wrapped before.
const defaultExport = wrappedEntry.module.default as undefined | WrappedFunction;
if (defaultExport && !defaultExport.__sentry_original__) {
fill(wrappedEntry.module, 'default', makeWrappedDocumentRequestFunction(autoInstrumentRemix, remixVersion));
}
for (const [id, route] of Object.entries(build.routes)) {
const wrappedRoute = { ...route, module: { ...route.module } };
const routeAction = wrappedRoute.module.action as undefined | WrappedFunction;
if (routeAction && !routeAction.__sentry_original__) {
fill(wrappedRoute.module, 'action', makeWrappedAction(id, remixVersion, autoInstrumentRemix));
}
const routeLoader = wrappedRoute.module.loader as undefined | WrappedFunction;
if (routeLoader && !routeLoader.__sentry_original__) {
fill(wrappedRoute.module, 'loader', makeWrappedLoader(id, remixVersion, autoInstrumentRemix));
}
// Entry module should have a loader function to provide `sentry-trace` and `baggage`
// They will be available for the root `meta` function as `data.sentryTrace` and `data.sentryBaggage`
if (!wrappedRoute.parentId) {
if (!wrappedRoute.module.loader) {
wrappedRoute.module.loader = () => ({});
}
// We want to wrap the root loader regardless of whether it's already wrapped before.
fill(wrappedRoute.module, 'loader', makeWrappedRootLoader(remixVersion));
}
routes[id] = wrappedRoute;
}
return { ...build, routes, entry: wrappedEntry };
}
/**
* Instruments `remix` ServerBuild for performance tracing and error tracking.
*/
export function instrumentBuild(
build: ServerBuild | (() => ServerBuild | Promise<ServerBuild>),
options: RemixOptions,
): ServerBuild | (() => ServerBuild | Promise<ServerBuild>) {
// eslint-disable-next-line deprecation/deprecation
const autoInstrumentRemix = options?.autoInstrumentRemix || false;
if (typeof build === 'function') {
return function () {
const resolvedBuild = build();
if (resolvedBuild instanceof Promise) {
return resolvedBuild.then(build => {
FUTURE_FLAGS = getFutureFlagsServer(build);
return instrumentBuildCallback(build, autoInstrumentRemix);
});
} else {
FUTURE_FLAGS = getFutureFlagsServer(resolvedBuild);
return instrumentBuildCallback(resolvedBuild, autoInstrumentRemix);
}
};
} else {
FUTURE_FLAGS = getFutureFlagsServer(build);
return instrumentBuildCallback(build, autoInstrumentRemix);
}
}
const makeWrappedCreateRequestHandler = (options: RemixOptions) =>
function (origCreateRequestHandler: CreateRequestHandlerFunction): CreateRequestHandlerFunction {
return function (
this: unknown,
build: ServerBuild | (() => Promise<ServerBuild>),
...args: unknown[]
): RequestHandler {
const newBuild = instrumentBuild(build, options);
const requestHandler = origCreateRequestHandler.call(this, newBuild, ...args);
// eslint-disable-next-line deprecation/deprecation
return wrapRequestHandler(requestHandler, newBuild, options.autoInstrumentRemix || false);
};
};
/**
* Monkey-patch Remix's `createRequestHandler` from `@remix-run/server-runtime`
* which Remix Adapters (https://remix.run/docs/en/v1/api/remix) use underneath.
*/
export function instrumentServer(options: RemixOptions): void {
const pkg = loadModule<{
createRequestHandler: CreateRequestHandlerFunction;
}>('@remix-run/server-runtime', module);
if (!pkg) {
DEBUG_BUILD && logger.warn('Remix SDK was unable to require `@remix-run/server-runtime` package.');
return;
}
fill(pkg, 'createRequestHandler', makeWrappedCreateRequestHandler(options));
}