diff --git a/dev-packages/bun-integration-tests/suites/no-channel-injection/app.ts b/dev-packages/bun-integration-tests/suites/no-channel-injection/app.ts new file mode 100644 index 000000000000..fd1319dea4a7 --- /dev/null +++ b/dev-packages/bun-integration-tests/suites/no-channel-injection/app.ts @@ -0,0 +1,4 @@ +import * as Sentry from '@sentry/bun'; + +// The SDK checks for channel injection when the first span starts. +Sentry.startSpan({ name: 'request' }, () => undefined); diff --git a/dev-packages/bun-integration-tests/suites/no-channel-injection/build.ts b/dev-packages/bun-integration-tests/suites/no-channel-injection/build.ts new file mode 100644 index 000000000000..5664c9ecc97f --- /dev/null +++ b/dev-packages/bun-integration-tests/suites/no-channel-injection/build.ts @@ -0,0 +1,23 @@ +// Builds `app.ts` with `@sentry/bun/plugin` and prints the path of the output file. The test runs +// that file with `instrument.ts` preloaded, so the SDK starts before the built app loads. +import { sentryBunPlugin } from '@sentry/bun/plugin'; +import { join } from 'node:path'; + +const result = await Bun.build({ + entrypoints: [join(import.meta.dir, 'app.ts')], + target: 'bun', + outdir: join(import.meta.dir, '..', '..', 'build', 'no-channel-injection'), + // The preloaded instrument file is not bundled, so the app must use the same `@sentry/*` packages. + external: ['@sentry/*'], + plugins: [sentryBunPlugin()], +}); + +const output = result.outputs.find(file => file.kind === 'entry-point'); +if (!result.success || !output) { + // eslint-disable-next-line no-console + console.error('BUILD_FAILED', result.logs); + process.exit(1); +} + +// eslint-disable-next-line no-console +console.log(`BUILD_OK ${output.path}`); diff --git a/dev-packages/bun-integration-tests/suites/no-channel-injection/scenario.ts b/dev-packages/bun-integration-tests/suites/no-channel-injection/instrument.ts similarity index 100% rename from dev-packages/bun-integration-tests/suites/no-channel-injection/scenario.ts rename to dev-packages/bun-integration-tests/suites/no-channel-injection/instrument.ts diff --git a/dev-packages/bun-integration-tests/suites/no-channel-injection/test.ts b/dev-packages/bun-integration-tests/suites/no-channel-injection/test.ts index 0a8953ea3aba..7f6a2a77e0a9 100644 --- a/dev-packages/bun-integration-tests/suites/no-channel-injection/test.ts +++ b/dev-packages/bun-integration-tests/suites/no-channel-injection/test.ts @@ -1,22 +1,40 @@ import { spawnSync } from 'child_process'; -import { join } from 'path'; +import { rmSync } from 'fs'; +import { dirname, join } from 'path'; import { describe, expect, it } from 'vitest'; -function runScenario(file: string): string { - const res = spawnSync('bun', ['run', join(__dirname, file)], { cwd: __dirname, encoding: 'utf8' }); +function runBun(...args: string[]): string { + const res = spawnSync('bun', args, { cwd: __dirname, encoding: 'utf8' }); expect(res.status, `run failed:\nstderr:\n${res.stderr}\nstdout:\n${res.stdout}`).toBe(0); return `${res.stdout}${res.stderr}`; } describe('no channel injection (Bun)', () => { - it('warns without `debug` when the app runs unbuilt with `bun run`', () => { - const output = runScenario('scenario.ts'); + it('warns without `debug` when the app runs unbuilt', () => { + const output = runBun('--preload', join(__dirname, 'instrument.ts'), join(__dirname, 'app.ts')); expect(output).toContain('No diagnostics-channel injection detected'); expect(output).toContain('@sentry/bun/plugin'); }); + it('does not warn when `bun --preload` starts the SDK before an app built with `@sentry/bun/plugin`', () => { + const outfile = runBun('run', join(__dirname, 'build.ts')) + .match(/BUILD_OK (.+)/)?.[1] + ?.trim(); + expect(outfile).toBeTruthy(); + + try { + const output = runBun('--preload', join(__dirname, 'instrument.ts'), outfile as string); + + expect(output).not.toContain('No diagnostics-channel injection detected'); + } finally { + rmSync(dirname(outfile as string), { recursive: true, force: true }); + } + }); + it('does not warn when no channel integration is installed', () => { - expect(runScenario('scenario-no-integrations.ts')).not.toContain('No diagnostics-channel injection detected'); + expect(runBun('run', join(__dirname, 'scenario-no-integrations.ts'))).not.toContain( + 'No diagnostics-channel injection detected', + ); }); }); diff --git a/packages/server-utils/src/orchestrion/detect.ts b/packages/server-utils/src/orchestrion/detect.ts index f388648e4c16..0411b1ba97a8 100644 --- a/packages/server-utils/src/orchestrion/detect.ts +++ b/packages/server-utils/src/orchestrion/detect.ts @@ -1,4 +1,4 @@ -import { consoleSandbox, debug, GLOBAL_OBJ } from '@sentry/core'; +import { consoleSandbox, debug, getClient, GLOBAL_OBJ, hasSpansEnabled } from '@sentry/core'; import { isBun } from '../utils/runtime'; /** @@ -38,16 +38,16 @@ export function detectOrchestrionSetup(): void { if (!runtime && !bundler) { if (channelIntegrations && isBun()) { - if (!marker.warnedBunRunNotInjected) { - marker.warnedBunRunNotInjected = true; - consoleSandbox(() => { - // oxlint-disable-next-line no-console - console.warn( - '[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record ' + - 'spans or capture errors, because Bun cannot instrument modules at runtime. Build your app with ' + - '`@sentry/bun/plugin` to enable them.', - ); + const client = getClient(); + if (client && hasSpansEnabled(client.getOptions())) { + // With `bun --preload`, `init()` runs before the app loads, and an app built with a bundler + // plugin sets the marker only when it loads. So wait for the first span to check. + const unsubscribe = client.on('spanStart', () => { + unsubscribe(); + warnIfBunRunNotInjected(); }); + } else { + warnIfBunRunNotInjected(); } return; } @@ -73,3 +73,20 @@ export function detectOrchestrionSetup(): void { : '[Sentry] Bundler plugin did not run', ); } + +function warnIfBunRunNotInjected(): void { + const marker = GLOBAL_OBJ.__SENTRY_ORCHESTRION__ ?? {}; + if (marker.runtime || marker.bundler || marker.warnedBunRunNotInjected) { + return; + } + + marker.warnedBunRunNotInjected = true; + consoleSandbox(() => { + // oxlint-disable-next-line no-console + console.warn( + '[Sentry] No diagnostics-channel injection detected. Channel-based integrations will not record ' + + 'spans or capture errors, because Bun cannot instrument modules at runtime. Build your app with ' + + '`@sentry/bun/plugin` to enable them.', + ); + }); +} diff --git a/packages/server-utils/test/orchestrion/detect.test.ts b/packages/server-utils/test/orchestrion/detect.test.ts index 041971d83ba0..aefc18999691 100644 --- a/packages/server-utils/test/orchestrion/detect.test.ts +++ b/packages/server-utils/test/orchestrion/detect.test.ts @@ -1,6 +1,7 @@ -import { GLOBAL_OBJ } from '@sentry/core'; +import { getCurrentScope, GLOBAL_OBJ, setCurrentClient, startSpan } from '@sentry/core'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { detectOrchestrionSetup, getOrchestrionInjectedModules } from '../../src/orchestrion/detect'; +import { getDefaultTestClientOptions, TestClient } from '../mocks/client'; describe('getOrchestrionInjectedModules', () => { beforeEach(() => { @@ -33,6 +34,7 @@ describe('detectOrchestrionSetup', () => { afterEach(() => { delete GLOBAL_OBJ.__SENTRY_ORCHESTRION__; + getCurrentScope().setClient(undefined); vi.unstubAllGlobals(); vi.restoreAllMocks(); }); @@ -78,6 +80,40 @@ describe('detectOrchestrionSetup', () => { expect(warn).not.toHaveBeenCalled(); }); + it('warns on Bun at the first span instead of at init when spans are enabled', () => { + vi.stubGlobal('Bun', {}); + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { channelIntegrations: true }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: 1 })); + setCurrentClient(client); + client.init(); + + detectOrchestrionSetup(); + + expect(warn).not.toHaveBeenCalled(); + + startSpan({ name: 'first' }, () => undefined); + startSpan({ name: 'second' }, () => undefined); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('@sentry/bun/plugin')); + }); + + it('does not warn on Bun when the app sets the bundler marker after init, as with `bun --preload`', () => { + vi.stubGlobal('Bun', {}); + GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { channelIntegrations: true }; + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + const client = new TestClient(getDefaultTestClientOptions({ tracesSampleRate: 1 })); + setCurrentClient(client); + client.init(); + + detectOrchestrionSetup(); + GLOBAL_OBJ.__SENTRY_ORCHESTRION__.bundler = new Set(); + startSpan({ name: 'request' }, () => undefined); + + expect(warn).not.toHaveBeenCalled(); + }); + it('does not warn outside Bun when debug is off', () => { GLOBAL_OBJ.__SENTRY_ORCHESTRION__ = { channelIntegrations: true }; const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);