Skip to content
Draft
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
Original file line number Diff line number Diff line change
@@ -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);
Original file line number Diff line number Diff line change
@@ -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}`);
Original file line number Diff line number Diff line change
@@ -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',
);
});
});
37 changes: 27 additions & 10 deletions packages/server-utils/src/orchestrion/detect.ts
Original file line number Diff line number Diff line change
@@ -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';

/**
Expand Down Expand Up @@ -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;
}
Expand All @@ -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.',
);
});
}
38 changes: 37 additions & 1 deletion packages/server-utils/test/orchestrion/detect.test.ts
Original file line number Diff line number Diff line change
@@ -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(() => {
Expand Down Expand Up @@ -33,6 +34,7 @@ describe('detectOrchestrionSetup', () => {

afterEach(() => {
delete GLOBAL_OBJ.__SENTRY_ORCHESTRION__;
getCurrentScope().setClient(undefined);
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
Expand Down Expand Up @@ -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);
Expand Down
Loading