-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat(bun): Instrument Bun.serve #9080
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
import { captureException, getCurrentHub, runWithAsyncContext, startSpan, Transaction } from '@sentry/core'; | ||
import type { Integration } from '@sentry/types'; | ||
import { addExceptionMechanism, getSanitizedUrlString, parseUrl, tracingContextFromHeaders } from '@sentry/utils'; | ||
|
||
function sendErrorToSentry(e: unknown): unknown { | ||
captureException(e, scope => { | ||
scope.addEventProcessor(event => { | ||
addExceptionMechanism(event, { | ||
type: 'bun', | ||
handled: false, | ||
data: { | ||
function: 'serve', | ||
}, | ||
}); | ||
return event; | ||
}); | ||
|
||
return scope; | ||
}); | ||
|
||
return e; | ||
} | ||
|
||
/** | ||
* Instruments `Bun.serve` to automatically create transactions and capture errors. | ||
*/ | ||
export class BunServer implements Integration { | ||
/** | ||
* @inheritDoc | ||
*/ | ||
public static id: string = 'BunServer'; | ||
|
||
/** | ||
* @inheritDoc | ||
*/ | ||
public name: string = BunServer.id; | ||
|
||
/** | ||
* @inheritDoc | ||
*/ | ||
public setupOnce(): void { | ||
instrumentBunServe(); | ||
} | ||
} | ||
|
||
/** | ||
* Instruments Bun.serve by patching it's options. | ||
*/ | ||
export function instrumentBunServe(): void { | ||
Bun.serve = new Proxy(Bun.serve, { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. dayum we're lucky this is just a field on a global - let's pray this never changes 🙏 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think they'll break this for a while, but let's see. |
||
apply(serveTarget, serveThisArg, serveArgs: Parameters<typeof Bun.serve>) { | ||
instrumentBunServeOptions(serveArgs[0]); | ||
return serveTarget.apply(serveThisArg, serveArgs); | ||
}, | ||
}); | ||
} | ||
|
||
/** | ||
* Instruments Bun.serve `fetch` option to automatically create spans and capture errors. | ||
*/ | ||
function instrumentBunServeOptions(serveOptions: Parameters<typeof Bun.serve>[0]): void { | ||
serveOptions.fetch = new Proxy(serveOptions.fetch, { | ||
apply(fetchTarget, fetchThisArg, fetchArgs: Parameters<typeof serveOptions.fetch>) { | ||
return runWithAsyncContext(() => { | ||
const hub = getCurrentHub(); | ||
|
||
const request = fetchArgs[0]; | ||
const upperCaseMethod = request.method.toUpperCase(); | ||
if (upperCaseMethod === 'OPTIONS' || upperCaseMethod === 'HEAD') { | ||
return fetchTarget.apply(fetchThisArg, fetchArgs); | ||
} | ||
|
||
const sentryTrace = request.headers.get('sentry-trace') || ''; | ||
const baggage = request.headers.get('baggage'); | ||
const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders( | ||
sentryTrace, | ||
baggage, | ||
); | ||
hub.getScope().setPropagationContext(propagationContext); | ||
|
||
const parsedUrl = parseUrl(request.url); | ||
const data: Record<string, unknown> = { | ||
'http.request.method': request.method || 'GET', | ||
}; | ||
if (parsedUrl.search) { | ||
data['http.query'] = parsedUrl.search; | ||
} | ||
|
||
const url = getSanitizedUrlString(parsedUrl); | ||
return startSpan( | ||
{ | ||
op: 'http.server', | ||
name: `${request.method} ${parsedUrl.path || '/'}`, | ||
origin: 'auto.http.bun.serve', | ||
...traceparentData, | ||
data, | ||
metadata: { | ||
source: 'url', | ||
dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext, | ||
request: { | ||
url, | ||
method: request.method, | ||
headers: request.headers.toJSON(), | ||
}, | ||
}, | ||
}, | ||
async span => { | ||
try { | ||
const response = await (fetchTarget.apply(fetchThisArg, fetchArgs) as ReturnType< | ||
typeof serveOptions.fetch | ||
>); | ||
if (response && response.status) { | ||
span?.setHttpStatus(response.status); | ||
span?.setData('http.response.status_code', response.status); | ||
if (span instanceof Transaction) { | ||
span.setContext('response', { | ||
headers: response.headers.toJSON(), | ||
status_code: response.status, | ||
}); | ||
} | ||
} | ||
return response; | ||
} catch (e) { | ||
sendErrorToSentry(e); | ||
throw e; | ||
} | ||
}, | ||
); | ||
}); | ||
}, | ||
}); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { BunServer } from './bunserver'; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
import { createTransport } from '@sentry/core'; | ||
import { resolvedSyncPromise } from '@sentry/utils'; | ||
|
||
import type { BunClientOptions } from '../src/types'; | ||
|
||
export function getDefaultBunClientOptions(options: Partial<BunClientOptions> = {}): BunClientOptions { | ||
return { | ||
integrations: [], | ||
transport: () => createTransport({ recordDroppedEvent: () => undefined }, _ => resolvedSyncPromise({})), | ||
stackParser: () => [], | ||
instrumenter: 'sentry', | ||
...options, | ||
}; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
import { Hub, makeMain } from '@sentry/core'; | ||
// eslint-disable-next-line import/no-unresolved | ||
import { beforeAll, beforeEach, describe, expect, test } from 'bun:test'; | ||
|
||
import { BunClient } from '../../src/client'; | ||
import { instrumentBunServe } from '../../src/integrations/bunserver'; | ||
import { getDefaultBunClientOptions } from '../helpers'; | ||
|
||
// Fun fact: Bun = 2 21 14 :) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. :) |
||
const DEFAULT_PORT = 22114; | ||
|
||
describe('Bun Serve Integration', () => { | ||
let hub: Hub; | ||
let client: BunClient; | ||
|
||
beforeAll(() => { | ||
instrumentBunServe(); | ||
}); | ||
|
||
beforeEach(() => { | ||
const options = getDefaultBunClientOptions({ tracesSampleRate: 1, debug: true }); | ||
client = new BunClient(options); | ||
hub = new Hub(client); | ||
makeMain(hub); | ||
}); | ||
|
||
test('generates a transaction around a request', async () => { | ||
client.on('finishTransaction', transaction => { | ||
expect(transaction.status).toBe('ok'); | ||
expect(transaction.tags).toEqual({ | ||
'http.status_code': '200', | ||
}); | ||
expect(transaction.op).toEqual('http.server'); | ||
expect(transaction.name).toEqual('GET /'); | ||
}); | ||
|
||
const server = Bun.serve({ | ||
async fetch(_req) { | ||
return new Response('Bun!'); | ||
}, | ||
port: DEFAULT_PORT, | ||
}); | ||
|
||
await fetch('http://localhost:22114/'); | ||
|
||
server.stop(); | ||
}); | ||
|
||
test('generates a post transaction', async () => { | ||
client.on('finishTransaction', transaction => { | ||
expect(transaction.status).toBe('ok'); | ||
expect(transaction.tags).toEqual({ | ||
'http.status_code': '200', | ||
}); | ||
expect(transaction.op).toEqual('http.server'); | ||
expect(transaction.name).toEqual('POST /'); | ||
}); | ||
|
||
const server = Bun.serve({ | ||
async fetch(_req) { | ||
return new Response('Bun!'); | ||
}, | ||
port: DEFAULT_PORT, | ||
}); | ||
|
||
await fetch('http://localhost:22114/', { | ||
method: 'POST', | ||
}); | ||
|
||
server.stop(); | ||
}); | ||
|
||
test('continues a trace', async () => { | ||
const TRACE_ID = '12312012123120121231201212312012'; | ||
const PARENT_SPAN_ID = '1121201211212012'; | ||
const PARENT_SAMPLED = '1'; | ||
|
||
const SENTRY_TRACE_HEADER = `${TRACE_ID}-${PARENT_SPAN_ID}-${PARENT_SAMPLED}`; | ||
const SENTRY_BAGGAGE_HEADER = 'sentry-version=1.0,sentry-environment=production'; | ||
|
||
client.on('finishTransaction', transaction => { | ||
expect(transaction.traceId).toBe(TRACE_ID); | ||
expect(transaction.parentSpanId).toBe(PARENT_SPAN_ID); | ||
expect(transaction.sampled).toBe(true); | ||
|
||
expect(transaction.metadata?.dynamicSamplingContext).toStrictEqual({ version: '1.0', environment: 'production' }); | ||
}); | ||
|
||
const server = Bun.serve({ | ||
async fetch(_req) { | ||
return new Response('Bun!'); | ||
}, | ||
port: DEFAULT_PORT, | ||
}); | ||
|
||
await fetch('http://localhost:22114/', { | ||
headers: { 'sentry-trace': SENTRY_TRACE_HEADER, baggage: SENTRY_BAGGAGE_HEADER }, | ||
}); | ||
|
||
server.stop(); | ||
}); | ||
|
||
test('does not create transactions for OPTIONS or HEAD requests', async () => { | ||
client.on('finishTransaction', () => { | ||
// This will never run, but we want to make sure it doesn't run. | ||
expect(false).toEqual(true); | ||
}); | ||
|
||
const server = Bun.serve({ | ||
async fetch(_req) { | ||
return new Response('Bun!'); | ||
}, | ||
port: DEFAULT_PORT, | ||
}); | ||
|
||
await fetch('http://localhost:22114/', { | ||
method: 'OPTIONS', | ||
}); | ||
|
||
await fetch('http://localhost:22114/', { | ||
method: 'HEAD', | ||
}); | ||
|
||
server.stop(); | ||
}); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wasn't sure if
serve
orfetch
is more correct but w/eThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yeah debated this too, will stick with serve for now, but we can always adjust later.