-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathbunserver.ts
293 lines (264 loc) · 8.46 KB
/
bunserver.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
import type { ServeOptions } from 'bun';
import type { IntegrationFn, RequestEventData, SpanAttributes } from '@sentry/core';
import {
SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
captureException,
isURLObjectRelative,
setHttpStatus,
defineIntegration,
continueTrace,
startSpan,
withIsolationScope,
parseStringToURLObject,
} from '@sentry/core';
const INTEGRATION_NAME = 'BunServer';
const _bunServerIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
instrumentBunServe();
},
};
}) satisfies IntegrationFn;
/**
* Instruments `Bun.serve` to automatically create transactions and capture errors.
*
* Does not support instrumenting static routes.
*
* Enabled by default in the Bun SDK.
*
* ```js
* Sentry.init({
* integrations: [
* Sentry.bunServerIntegration(),
* ],
* })
* ```
*/
export const bunServerIntegration = defineIntegration(_bunServerIntegration);
let hasPatchedBunServe = false;
/**
* Instruments Bun.serve by patching it's options.
*
* Only exported for tests.
*/
export function instrumentBunServe(): void {
if (hasPatchedBunServe) {
return;
}
Bun.serve = new Proxy(Bun.serve, {
apply(serveTarget, serveThisArg, serveArgs: Parameters<typeof Bun.serve>) {
instrumentBunServeOptions(serveArgs[0]);
const server: ReturnType<typeof Bun.serve> = serveTarget.apply(serveThisArg, serveArgs);
// A Bun server can be reloaded, re-wrap any fetch function passed to it
// We can't use a Proxy for this as Bun does `instanceof` checks internally that fail if we
// wrap the Server instance.
const originalReload: typeof server.reload = server.reload.bind(server);
server.reload = (serveOptions: ServeOptions) => {
instrumentBunServeOptions(serveOptions);
return originalReload(serveOptions);
};
return server;
},
});
hasPatchedBunServe = true;
}
/**
* Instruments Bun.serve options.
*
* @param serveOptions - The options for the Bun.serve function.
*/
function instrumentBunServeOptions(serveOptions: Parameters<typeof Bun.serve>[0]): void {
// First handle fetch
instrumentBunServeOptionFetch(serveOptions);
// then handle routes
instrumentBunServeOptionRoutes(serveOptions);
}
/**
* Instruments the `fetch` option of Bun.serve.
*
* @param serveOptions - The options for the Bun.serve function.
*/
function instrumentBunServeOptionFetch(serveOptions: Parameters<typeof Bun.serve>[0]): void {
if (typeof serveOptions.fetch !== 'function') {
return;
}
serveOptions.fetch = new Proxy(serveOptions.fetch, {
apply(fetchTarget, fetchThisArg, fetchArgs: Parameters<typeof serveOptions.fetch>) {
return wrapRequestHandler(fetchTarget, fetchThisArg, fetchArgs);
},
});
}
/**
* Instruments the `routes` option of Bun.serve.
*
* @param serveOptions - The options for the Bun.serve function.
*/
function instrumentBunServeOptionRoutes(serveOptions: Parameters<typeof Bun.serve>[0]): void {
if (!serveOptions.routes) {
return;
}
if (typeof serveOptions.routes !== 'object') {
return;
}
Object.keys(serveOptions.routes).forEach(route => {
const routeHandler = serveOptions.routes[route];
// Handle route handlers that are an object
if (typeof routeHandler === 'function') {
serveOptions.routes[route] = new Proxy(routeHandler, {
apply: (routeHandlerTarget, routeHandlerThisArg, routeHandlerArgs: Parameters<typeof routeHandler>) => {
return wrapRequestHandler(routeHandlerTarget, routeHandlerThisArg, routeHandlerArgs, route);
},
});
}
// Static routes are not instrumented
if (routeHandler instanceof Response) {
return;
}
// Handle the route handlers that are an object. This means they define a route handler for each method.
if (typeof routeHandler === 'object') {
Object.entries(routeHandler).forEach(([routeHandlerObjectHandlerKey, routeHandlerObjectHandler]) => {
if (typeof routeHandlerObjectHandler === 'function') {
(serveOptions.routes[route] as Record<string, RouteHandler>)[routeHandlerObjectHandlerKey] = new Proxy(
routeHandlerObjectHandler,
{
apply: (
routeHandlerObjectHandlerTarget,
routeHandlerObjectHandlerThisArg,
routeHandlerObjectHandlerArgs: Parameters<typeof routeHandlerObjectHandler>,
) => {
return wrapRequestHandler(
routeHandlerObjectHandlerTarget,
routeHandlerObjectHandlerThisArg,
routeHandlerObjectHandlerArgs,
route,
);
},
},
);
}
});
}
});
}
type RouteHandler = Extract<
NonNullable<Parameters<typeof Bun.serve>[0]['routes']>[string],
// eslint-disable-next-line @typescript-eslint/ban-types
Function
>;
function wrapRequestHandler<T extends RouteHandler = RouteHandler>(
target: T,
thisArg: unknown,
args: Parameters<T>,
route?: string,
): ReturnType<T> {
return withIsolationScope(isolationScope => {
const request = args[0];
const upperCaseMethod = request.method.toUpperCase();
if (upperCaseMethod === 'OPTIONS' || upperCaseMethod === 'HEAD') {
return target.apply(thisArg, args);
}
const parsedUrl = parseStringToURLObject(request.url);
const attributes = getSpanAttributesFromParsedUrl(parsedUrl, request);
let routeName = parsedUrl?.pathname || '/';
if (request.params) {
Object.keys(request.params).forEach(key => {
attributes[`url.path.parameter.${key}`] = (request.params as Record<string, string>)[key];
});
// If a route has parameters, it's a parameterized route
if (route) {
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes['url.template'] = route;
routeName = route;
}
}
// Handle wildcard routes
if (route?.endsWith('/*')) {
attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';
attributes['url.template'] = route;
routeName = route;
}
isolationScope.setSDKProcessingMetadata({
normalizedRequest: {
url: request.url,
method: request.method,
headers: request.headers.toJSON(),
query_string: parsedUrl?.search,
} satisfies RequestEventData,
});
return continueTrace(
{
sentryTrace: request.headers.get('sentry-trace') ?? '',
baggage: request.headers.get('baggage'),
},
() =>
startSpan(
{
attributes,
op: 'http.server',
name: `${request.method} ${routeName}`,
},
async span => {
try {
const response = (await target.apply(thisArg, args)) as Response | undefined;
if (response?.status) {
setHttpStatus(span, response.status);
isolationScope.setContext('response', {
headers: response.headers.toJSON(),
status_code: response.status,
});
}
return response;
} catch (e) {
captureException(e, {
mechanism: {
type: 'bun',
handled: false,
data: {
function: 'serve',
},
},
});
throw e;
}
},
),
);
});
}
function getSpanAttributesFromParsedUrl(
parsedUrl: ReturnType<typeof parseStringToURLObject>,
request: Request,
): SpanAttributes {
const attributes: SpanAttributes = {
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.bun.serve',
[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD]: request.method || 'GET',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
};
if (parsedUrl) {
if (parsedUrl.search) {
attributes['url.query'] = parsedUrl.search;
}
if (parsedUrl.hash) {
attributes['url.fragment'] = parsedUrl.hash;
}
if (parsedUrl.pathname) {
attributes['url.path'] = parsedUrl.pathname;
}
if (!isURLObjectRelative(parsedUrl)) {
attributes['url.full'] = parsedUrl.href;
if (parsedUrl.port) {
attributes['url.port'] = parsedUrl.port;
}
if (parsedUrl.protocol) {
attributes['url.scheme'] = parsedUrl.protocol;
}
if (parsedUrl.hostname) {
attributes['url.domain'] = parsedUrl.hostname;
}
}
}
return attributes;
}