Skip to content
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
45 changes: 18 additions & 27 deletions dev-packages/bun-integration-tests/node-suites/excludes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,22 +169,18 @@ const FETCH_INTEGRATION_DIFFERS = [
'suites/tracing/requests/fetch-sampled-no-active-span/test.ts',
];

// `@sentry/bun` creates `http.server` spans with `bunHttpServerIntegration`, not `httpIntegration`,
// so the incoming-request options that the scenario passes to `httpIntegration` (for example
// `sessionFlushingDelayMS`, `onSpanCreated`, `ignoreIncomingRequests`, `ignoreStaticAssets`) have
// no effect. Its spans also differ: response headers become attributes, and there is no
// `http.response.status_text`. And a server
// that sets `emit` back to the `emit` it had before its first request gets no spans after that.
// See https://github.com/getsentry/sentry-javascript/issues/26609
const HTTP_SERVER_OPTIONS_IGNORED = [
'suites/sessions/exited-session-aggregate/test.ts',
// `@sentry/bun` creates `http.server` spans with `bunHttpServerIntegration`, not `httpIntegration`.
// Its spans differ: response headers become attributes, there is no `http.response.status_text`,
// and the span name has no route. A server that sets `emit` back to the `emit` it had before its
// first request gets no spans after that. And an error that reaches the server does not mark
// the request session as crashed.
const HTTP_SERVER_SPANS_DIFFER = [
'suites/sessions/server-without-process-session/test.ts',
'suites/tracing/httpIntegration/test.ts',
];

// With `@sentry/bun`, these suites fail only because they need Express spans or route names,
// which `bun run` does not create. The crashed and errored session suites also need
// `sessionFlushingDelayMS` (see above).
// which `bun run` does not create.
// See https://github.com/getsentry/sentry-javascript/issues/23882
const NO_EXPRESS_INSTRUMENTATION = [
'suites/sessions/crashed-session-aggregate/test.ts',
Expand All @@ -211,7 +207,7 @@ const BUN_DROPS_PIPELINED_REQUESTS = ['suites/tunnel/hardening/test.ts'];

export const SENTRY_BUN_EXCLUDE = [
...BUN_DROPS_PIPELINED_REQUESTS,
...HTTP_SERVER_OPTIONS_IGNORED,
...HTTP_SERVER_SPANS_DIFFER,
...NO_EXPRESS_INSTRUMENTATION,
...NO_NATIVE_NODE_FETCH_INTEGRATION,
...FETCH_INTEGRATION_DIFFERS,
Expand All @@ -237,14 +233,10 @@ const BUN_BUILD_NO_HTTP_SERVER_INTEGRATION = ['suites/express/multiple-init/test
// `require is not defined`. See https://github.com/oven-sh/bun/issues/14891
const BUN_BUILD_UNBUNDLEABLE_DEPENDENCY = ['suites/tracing/mistral/test.ts', 'suites/tracing/mongodb/test.ts'];

// Some or all tests fail with the bundled scenarios. The cause is not investigated yet. In
// `express/tracing` only the request data tests fail: they set `httpIntegration` options, and with
// `@sentry/bun` the request body comes from `bunHttpServerIntegration`.
// Some or all tests fail with the bundled scenarios. The cause is not investigated yet.
const BUN_BUILD_NOT_TRIAGED = [
'suites/express/sentry-trace/test.ts',
'suites/express/tracing/routing/test.ts',
'suites/express/tracing/request-data/test.ts',
'suites/express/with-http/**',
'suites/hono-sdk/test.ts',
'suites/tracing/google-genai-v2/test.ts',
'suites/tracing/google-genai-v3/test.ts',
Expand All @@ -269,6 +261,15 @@ const BUN_BUILD_NOT_TRIAGED = [
'suites/tracing/vercelai/v6_v7/**',
];

// Before Bun 1.4, Bun does not publish `http.client.request.created`, and `@sentry/node` picks the
// channel from the Node version that Bun reports. So outgoing `node:http` requests get no
// `sentry-trace` header, and the `/test2` request starts its own trace.
// See https://github.com/getsentry/sentry-javascript/issues/26614
const BUN_1_3_NO_HTTP_CLIENT_CHANNEL = ['suites/express/with-http/base/test.ts'];

// Excluded in `node-suites-bun-build` only before Bun 1.4.
export const BUN_BUILD_BEFORE_1_4_EXCLUDE = [...BUN_1_3_NO_HTTP_CLIENT_CHANNEL];

export const BUN_BUILD_EXCLUDE = [
'**/node_modules/**',
// SQL Server runs in the dedicated Node/x86 CI job.
Expand All @@ -282,15 +283,6 @@ export const BUN_BUILD_EXCLUDE = [
// The `bun run` project (`node-suites-bun-run`) runs the suites of `NO_AUTO_INSTRUMENTATION` with
// `@sentry/bun/import` preloaded, on Bun 1.4.6 or later. These do not run there.

// The scenarios pass the incoming-request options (`maxRequestBodySize`, `ignoreIncomingRequestBody`)
// to `httpIntegration`. With `@sentry/bun`, `bunHttpServerIntegration` creates the `http.server` spans
// and takes these options itself, so the tests that set them fail.
// See https://github.com/getsentry/sentry-javascript/issues/26609
const BUN_RUN_HTTP_INTEGRATION_OPTIONS_IGNORED = [
'suites/express/tracing/request-data/test.ts',
'suites/express/with-http/maxIncomingRequestBodySize/test.ts',
];

// The suite tests `@sentry/hono/node`, which builds on `@sentry/node` and creates no `http.server`
// spans on Bun. `@sentry/hono/bun` takes its options in `sentry(app, options)` instead of a separate
// `init()`, so the scenario cannot use it. `suites/hono-sdk` in this package tests `@sentry/hono/bun`.
Expand All @@ -303,6 +295,5 @@ export const BUN_RUN_EXCLUDE = [
// These fail for the same reasons as with the bundled scenarios.
...BUN_BUILD_EAGER_SUBSCRIPTION,
...BUN_BUILD_NO_HTTP_SERVER_INTEGRATION,
...BUN_RUN_HTTP_INTEGRATION_OPTIONS_IGNORED,
...BUN_RUN_HONO_NODE_SDK,
];
4 changes: 3 additions & 1 deletion dev-packages/bun-integration-tests/vite.config.mts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
import baseConfig from '../../vite/vite.config';
import {
BUN_BUILD_BEFORE_1_4_EXCLUDE,
BUN_BUILD_EXCLUDE,
BUN_RUN_EXCLUDE,
NO_AUTO_INSTRUMENTATION,
Expand All @@ -21,6 +22,7 @@ const [bunMajor = 0, bunMinor = 0, bunPatch = 0] = execFileSync('bun', ['--versi
.trim()
.split(/[.-]/)
.map(Number);
const BUN_BEFORE_1_4 = bunMajor < 1 || (bunMajor === 1 && bunMinor < 4);
const BUN_RUN_INSTRUMENTS = bunMajor > 1 || (bunMajor === 1 && (bunMinor > 4 || (bunMinor === 4 && bunPatch >= 6)));

const AUTO_INSTRUMENTATION_SUITES = NO_AUTO_INSTRUMENTATION.map(glob =>
Expand Down Expand Up @@ -106,7 +108,7 @@ export default defineConfig({
// See https://github.com/getsentry/sentry-javascript/issues/23882
name: 'node-suites-bun-build',
include: AUTO_INSTRUMENTATION_SUITES,
exclude: BUN_BUILD_EXCLUDE,
exclude: [...BUN_BUILD_EXCLUDE, ...(BUN_BEFORE_1_4 ? BUN_BUILD_BEFORE_1_4_EXCLUDE : [])],
env: {
RUNTIME: 'bun',
RUNTIME_PRELOAD: fileURLToPath(new URL('./node-suites/alias-sentry-bun.ts', import.meta.url)),
Expand Down
2 changes: 1 addition & 1 deletion packages/bun/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@
"lint:es-compatibility": "node ../../scripts/es-check.mjs es2022",
"install:bun": "node ./scripts/install-bun.js",
"test": "pnpm run install:bun && pnpm run test:bun",
"test:bun": "bun test",
"test:bun": "bun test --isolate",
"test:watch": "bun test --watch",
"yalc:publish": "pnpm dlx yalc publish --push --sig"
},
Expand Down
38 changes: 35 additions & 3 deletions packages/bun/src/integrations/bunHttpServer.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { errorMonitor } from 'node:events';
import * as http from 'node:http';
import * as https from 'node:https';
import type { IntegrationFn, Span } from '@sentry/core';
import type { Client, Integration, IntegrationFn, Span } from '@sentry/core';
import { defineIntegration } from '@sentry/core';
import type {
AssertTrue,
CheckServerRequestOptions,
HttpIncomingMessage,
HttpServerResponse,
ServerRequestOptions,
} from '@sentry/core/server';
import { getHttpServerSubscriptions, HTTP_ON_SERVER_REQUEST } from '@sentry/core/server';
import { isBun } from '@sentry/server-utils';
Expand Down Expand Up @@ -90,13 +91,44 @@ type _ServerRequestOptionsCheck = AssertTrue<
CheckServerRequestOptions<BunHttpServerOptions, HttpIncomingMessage, HttpServerResponse>
>;

// Every shared option is a required key, so a new one fails to compile
// below until the integration passes it on.
type BunHttpServerRequestOptions = {
[K in keyof Required<ServerRequestOptions<HttpIncomingMessage, HttpServerResponse>>]: BunHttpServerOptions[K];
};

interface HttpIntegration extends Integration {
serverRequestOptions: BunHttpServerRequestOptions;
}

let hasPatched = false;

/**
* Merges the incoming-request options of the client's `httpIntegration`
* under the given options. Bun does not publish
* `http.server.request.start`, so `httpIntegration` never applies them.
*/
function resolveOptions(options: BunHttpServerOptions, client: Client): BunHttpServerRequestOptions {
const httpOptions: Partial<BunHttpServerRequestOptions> =
client.getIntegrationByName<HttpIntegration>('Http')?.serverRequestOptions ?? {};
return {
spans: options.spans ?? httpOptions.spans,
sessions: options.sessions ?? httpOptions.sessions,
sessionFlushingDelayMS: options.sessionFlushingDelayMS ?? httpOptions.sessionFlushingDelayMS,
maxRequestBodySize: options.maxRequestBodySize ?? httpOptions.maxRequestBodySize,
ignoreRequestBody: options.ignoreRequestBody ?? httpOptions.ignoreRequestBody,
ignoreIncomingRequests: options.ignoreIncomingRequests ?? httpOptions.ignoreIncomingRequests,
ignoreStaticAssets: options.ignoreStaticAssets ?? httpOptions.ignoreStaticAssets,
onSpanCreated: options.onSpanCreated ?? httpOptions.onSpanCreated,
onSpanEnd: options.onSpanEnd ?? httpOptions.onSpanEnd,
};
}

const _bunHttpServerIntegration = ((options: BunHttpServerOptions = {}) => {
return {
name: INTEGRATION_NAME,
setupOnce() {
instrumentBunHttpServer(options);
afterAllSetup(client) {
instrumentBunHttpServer(resolveOptions(options, client));
},
};
}) satisfies IntegrationFn;
Expand Down
43 changes: 42 additions & 1 deletion packages/bun/test/integrations/bunHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import http from 'node:http';
import { HTTP_REQUEST_METHOD, SENTRY_OP } from '@sentry/conventions/attributes';
import { getActiveSpan, getCurrentScope, getTraceData, spanToJSON } from '@sentry/core';
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { init } from '../../src';
import { bunHttpServerIntegration, httpIntegration, init } from '../../src';

async function startServer(handler: http.RequestListener): Promise<{ port: number; close: () => Promise<void> }> {
const server = http.createServer(handler);
Expand Down Expand Up @@ -31,6 +31,15 @@ describe('Bun HTTP Server Integration', () => {
tracePropagationTargets: [],
// Avoid sending anything to Sentry
transport: () => ({ send: async () => ({}), flush: async () => true }),
integrations: [
httpIntegration({
ignoreIncomingRequests: urlPath => urlPath.startsWith('/ignored'),
onSpanCreated: span => span.setAttribute('created.by', 'http'),
}),
bunHttpServerIntegration({
onSpanCreated: span => span.setAttribute('created.by', 'bunHttpServer'),
}),
],
});
});

Expand Down Expand Up @@ -125,4 +134,36 @@ describe('Bun HTTP Server Integration', () => {

expect(observedTraceId).toBe(incomingTraceId);
});

test('applies the httpIntegration options that bunHttpServerIntegration does not set', async () => {
let span: ReturnType<typeof spanToJSON> | undefined;

const { port, close } = await startServer((_req, res) => {
const activeSpan = getActiveSpan();
span = activeSpan ? spanToJSON(activeSpan) : undefined;
res.end('ok');
});

await fetch(`http://localhost:${port}/ignored`).then(res => res.text());

await close();

expect(span).toBeUndefined();
});

test('prefers the bunHttpServerIntegration options over the httpIntegration options', async () => {
let span: ReturnType<typeof spanToJSON> | undefined;

const { port, close } = await startServer((_req, res) => {
const activeSpan = getActiveSpan();
span = activeSpan ? spanToJSON(activeSpan) : undefined;
res.end('ok');
});

await fetch(`http://localhost:${port}/`).then(res => res.text());

await close();

expect(span?.attributes['created.by']).toBe('bunHttpServer');
});
});
2 changes: 2 additions & 0 deletions packages/bun/test/integrations/bunRuntimeMetrics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ const mockEventLoopUtilization = jest.fn((curr?: object, _prev?: object) => {
return mockElu;
});

const realPerfHooks = await import('perf_hooks');
mock.module('perf_hooks', () => ({
...realPerfHooks,
performance: { eventLoopUtilization: mockEventLoopUtilization },
}));

Expand Down
23 changes: 23 additions & 0 deletions packages/node/src/integrations/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
CheckServerRequestOptions,
HttpIncomingMessage,
HttpServerResponse,
ServerRequestOptions,
} from '@sentry/core/server';
import { getRequestUrlFromClientRequest } from '@sentry/core/server';
import type { NodeClient } from '../../sdk/client';
Expand Down Expand Up @@ -96,6 +97,12 @@ type _ServerRequestOptionsCheck = AssertTrue<
CheckServerRequestOptions<HttpOptions, HttpIncomingMessage, HttpServerResponse>
>;

// Every shared option is a required key, so a new one fails to compile
// below until the integration passes it on.
type HttpServerRequestOptions = {
[K in keyof Required<ServerRequestOptions<HttpIncomingMessage, HttpServerResponse>>]: HttpOptions[K];
};

/**
* The http integration instruments Node's internal http and https modules.
* It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.
Expand All @@ -107,8 +114,24 @@ export const httpIntegration = defineIntegration((options: HttpOptions = {}) =>
const server = httpServerIntegration(options);
const serverSpans = httpServerSpansIntegration(options);

// Runtimes that do not publish `http.server.request.start` (such as
// Bun) create incoming-request spans in another integration, which
// reads these options.
const serverRequestOptions: HttpServerRequestOptions = {
spans: enableServerSpans ? undefined : false,
sessions: options.sessions,
sessionFlushingDelayMS: options.sessionFlushingDelayMS,
maxRequestBodySize: options.maxRequestBodySize,
ignoreRequestBody: options.ignoreRequestBody,
ignoreIncomingRequests: options.ignoreIncomingRequests,
ignoreStaticAssets: options.ignoreStaticAssets,
onSpanCreated: options.onSpanCreated,
onSpanEnd: options.onSpanEnd,
};

return {
name: INTEGRATION_NAME,
serverRequestOptions,
setup(client: NodeClient) {
const clientOptions = client.getOptions();

Expand Down
Loading