Skip to content

feat(bun): Support new Bun.serve APIs #16035

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/bun/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"@sentry/opentelemetry": "9.12.0"
},
"devDependencies": {
"bun-types": "latest"
"bun-types": "^1.2.9"
},
"scripts": {
"build": "run-p build:transpile build:types",
Expand Down
294 changes: 223 additions & 71 deletions packages/bun/src/integrations/bunserver.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
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,
continueTrace,
defineIntegration,
extractQueryParamsFromUrl,
getSanitizedUrlString,
parseUrl,
isURLObjectRelative,
setHttpStatus,
defineIntegration,
continueTrace,
startSpan,
withIsolationScope,
parseStringToURLObject,
} from '@sentry/core';

const INTEGRATION_NAME = 'BunServer';
Expand All @@ -28,6 +28,8 @@ const _bunServerIntegration = (() => {
/**
* Instruments `Bun.serve` to automatically create transactions and capture errors.
*
* Does not support instrumenting static routes.
*
* Enabled by default in the Bun SDK.
*
* ```js
Expand All @@ -40,10 +42,18 @@ const _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]);
Expand All @@ -53,89 +63,231 @@ export function instrumentBunServe(): void {
// 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: Parameters<typeof Bun.serve>[0]) => {
server.reload = (serveOptions: ServeOptions) => {
instrumentBunServeOptions(serveOptions);
return originalReload(serveOptions);
};

return server;
},
});

hasPatchedBunServe = true;
}

/**
* Instruments Bun.serve `fetch` option to automatically create spans and capture errors.
* 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 withIsolationScope(isolationScope => {
const request = fetchArgs[0];
const upperCaseMethod = request.method.toUpperCase();
if (upperCaseMethod === 'OPTIONS' || upperCaseMethod === 'HEAD') {
return fetchTarget.apply(fetchThisArg, fetchArgs);
}
return wrapRequestHandler(fetchTarget, fetchThisArg, fetchArgs);
},
});
}

const parsedUrl = parseUrl(request.url);
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.search) {
attributes['http.query'] = parsedUrl.search;
}
/**
* 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;
}

const url = getSanitizedUrlString(parsedUrl);

isolationScope.setSDKProcessingMetadata({
normalizedRequest: {
url,
method: request.method,
headers: request.headers.toJSON(),
query_string: extractQueryParamsFromUrl(url),
} satisfies RequestEventData,
});

return continueTrace(
{ sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },
() => {
return startSpan(
{
attributes,
op: 'http.server',
name: `${request.method} ${parsedUrl.path || '/'}`,
},
async span => {
try {
const response = await (fetchTarget.apply(fetchThisArg, fetchArgs) as ReturnType<
typeof serveOptions.fetch
>);
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;
}
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;
}
Loading
Loading