|
| 1 | +import { errorMonitor } from 'node:events'; |
| 2 | +import http from 'node:http'; |
| 3 | +import https from 'node:https'; |
| 4 | +import type { HttpIncomingMessage, HttpServerResponse, IntegrationFn, Span } from '@sentry/core'; |
| 5 | +import { defineIntegration, getHttpServerSubscriptions, HTTP_ON_SERVER_REQUEST } from '@sentry/core'; |
| 6 | + |
| 7 | +const INTEGRATION_NAME = 'BunHttpServer' as const; |
| 8 | + |
| 9 | +interface BunHttpServerOptions { |
| 10 | + /** |
| 11 | + * Whether to create `http.server` spans for incoming requests. |
| 12 | + * |
| 13 | + * Set this to `false` when another layer already emits incoming-request spans |
| 14 | + * (e.g. Next.js running on Bun, which creates its own OpenTelemetry spans). |
| 15 | + * The integration then only isolates each request and resets its trace, without |
| 16 | + * creating duplicate transactions. |
| 17 | + * |
| 18 | + * @default true |
| 19 | + */ |
| 20 | + spans?: boolean; |
| 21 | + |
| 22 | + /** |
| 23 | + * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests. |
| 24 | + * |
| 25 | + * @default true |
| 26 | + */ |
| 27 | + sessions?: boolean; |
| 28 | + |
| 29 | + /** |
| 30 | + * Number of milliseconds until sessions are flushed as a session aggregate. |
| 31 | + * |
| 32 | + * @default 60000 |
| 33 | + */ |
| 34 | + sessionFlushingDelayMS?: number; |
| 35 | + |
| 36 | + /** |
| 37 | + * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`. |
| 38 | + */ |
| 39 | + ignoreRequestBody?: (url: string, request: http.RequestOptions) => boolean; |
| 40 | + |
| 41 | + /** |
| 42 | + * Controls the maximum size of incoming HTTP request bodies attached to events. |
| 43 | + * |
| 44 | + * @default 'medium' |
| 45 | + */ |
| 46 | + maxRequestBodySize?: 'none' | 'small' | 'medium' | 'always'; |
| 47 | + |
| 48 | + /** |
| 49 | + * Do not capture spans for incoming HTTP requests to URLs where the given callback returns `true`. |
| 50 | + * |
| 51 | + * The `urlPath` param consists of the URL path and query string (if any) of the incoming request. |
| 52 | + */ |
| 53 | + ignoreIncomingRequests?: (urlPath: string, request: HttpIncomingMessage) => boolean; |
| 54 | + |
| 55 | + /** |
| 56 | + * Whether to automatically ignore common static asset requests like favicon.ico, robots.txt, etc. |
| 57 | + * |
| 58 | + * @default true |
| 59 | + */ |
| 60 | + ignoreStaticAssets?: boolean; |
| 61 | + |
| 62 | + /** |
| 63 | + * A hook that can be used to mutate the span for incoming requests. |
| 64 | + * This is triggered after the span is created, but before it is recorded. |
| 65 | + */ |
| 66 | + onSpanCreated?: (span: Span, request: HttpIncomingMessage, response: HttpServerResponse) => void; |
| 67 | + |
| 68 | + /** |
| 69 | + * A hook that can be used to mutate the span one last time when the response is finished. |
| 70 | + */ |
| 71 | + onSpanEnd?: (span: Span, request: HttpIncomingMessage, response: HttpServerResponse) => void; |
| 72 | +} |
| 73 | + |
| 74 | +let hasPatched = false; |
| 75 | + |
| 76 | +const _bunHttpServerIntegration = ((options: BunHttpServerOptions = {}) => { |
| 77 | + return { |
| 78 | + name: INTEGRATION_NAME, |
| 79 | + setupOnce() { |
| 80 | + instrumentBunHttpServer(options); |
| 81 | + }, |
| 82 | + }; |
| 83 | +}) satisfies IntegrationFn; |
| 84 | + |
| 85 | +/** |
| 86 | + * Instruments incoming `node:http`/`node:https` server requests under the Bun runtime. |
| 87 | + * |
| 88 | + * Unlike Node.js, Bun does not emit the `http.server.request.start` diagnostics channel that the |
| 89 | + * Node SDK relies on to isolate each incoming request. As a result, servers built on `node:http` |
| 90 | + * (such as Next.js running via `bun --bun`) do not get a fresh isolation scope and trace per request, |
| 91 | + * so unrelated requests can end up sharing one trace. |
| 92 | + * |
| 93 | + * This closes that gap by patching `http.Server.prototype.emit` and, on the first `'request'` event |
| 94 | + * of each server, handing that server to the same core instrumentation the Node SDK uses |
| 95 | + * (`getHttpServerSubscriptions` → `instrumentServer`). We patch the prototype (not `createServer`) |
| 96 | + * because the server is typically created before Sentry is initialized — e.g. Next.js creates and |
| 97 | + * `listen()`s its server before running the `instrumentation.ts` `register()` hook that loads the |
| 98 | + * Sentry config. |
| 99 | + * |
| 100 | + * This is intended for `node:http`-based servers. For `Bun.serve`, use {@link bunServerIntegration}. |
| 101 | + * |
| 102 | + * ```js |
| 103 | + * Sentry.init({ |
| 104 | + * integrations: [ |
| 105 | + * Sentry.bunHttpServerIntegration(), |
| 106 | + * ], |
| 107 | + * }) |
| 108 | + * ``` |
| 109 | + */ |
| 110 | +export const bunHttpServerIntegration = defineIntegration(_bunHttpServerIntegration); |
| 111 | + |
| 112 | +/** |
| 113 | + * Patches `http.Server.prototype.emit` so each server's incoming requests are isolated using the |
| 114 | + * same core instrumentation the Node SDK uses. |
| 115 | + * |
| 116 | + * Only exported for tests. |
| 117 | + */ |
| 118 | +export function instrumentBunHttpServer(options: BunHttpServerOptions = {}): void { |
| 119 | + // This only makes sense under Bun; on Node the diagnostics channel already handles this. |
| 120 | + if (!process.versions.bun || hasPatched) { |
| 121 | + return; |
| 122 | + } |
| 123 | + |
| 124 | + const { [HTTP_ON_SERVER_REQUEST]: onServerRequest } = getHttpServerSubscriptions({ |
| 125 | + ...options, |
| 126 | + // Pass the real `errorMonitor` symbol so core observes `'error'` events without consuming |
| 127 | + // them — otherwise it would swallow errors before they reach user-supplied `'error'` handlers. |
| 128 | + errorMonitor, |
| 129 | + }); |
| 130 | + |
| 131 | + // Track which servers we have already handed to core, so we instrument each server exactly once. |
| 132 | + // After core instruments a server it installs its own `emit` on the instance, which shadows this |
| 133 | + // prototype patch for all subsequent requests to that server. |
| 134 | + const instrumented = new WeakSet<object>(); |
| 135 | + |
| 136 | + const patchEmitOn = (ServerClass: typeof http.Server): void => { |
| 137 | + // oxlint-disable-next-line typescript/unbound-method |
| 138 | + const originalEmit = ServerClass.prototype.emit; |
| 139 | + ServerClass.prototype.emit = function (this: http.Server, event: string, ...args: unknown[]): boolean { |
| 140 | + if (event === 'request' && !instrumented.has(this)) { |
| 141 | + instrumented.add(this); |
| 142 | + // Hand the server to core, which patches this instance's `emit` to isolate requests. |
| 143 | + onServerRequest({ server: this }, HTTP_ON_SERVER_REQUEST); |
| 144 | + // Re-dispatch the in-flight request through the instance emit core just installed. |
| 145 | + return this.emit(event, ...args); |
| 146 | + } |
| 147 | + return originalEmit.call(this, event, ...args) as boolean; |
| 148 | + } as typeof originalEmit; |
| 149 | + }; |
| 150 | + |
| 151 | + patchEmitOn(http.Server); |
| 152 | + // In Bun `https.Server` reuses `http.Server`, but patch it explicitly in case that ever diverges. |
| 153 | + if (https.Server !== http.Server) { |
| 154 | + patchEmitOn(https.Server); |
| 155 | + } |
| 156 | + |
| 157 | + hasPatched = true; |
| 158 | +} |
0 commit comments