-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(bun): Add orchestrion bun build plugin #21410
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,37 @@ | ||
| // Builds the smoke scenario with the orchestrion `bun build` plugin and writes | ||
| // the bundle to a temp dir, printing the output path for test.ts to execute. | ||
| // | ||
| // A successful build proves `bun build` runs with the plugin; running the bundle | ||
| // (see test.ts) then proves the bundled `mysql` is actually instrumented. | ||
|
|
||
| // @ts-ignore -- subpath export resolved by Bun at runtime; the package | ||
| // tsconfig's node module resolution can't see `exports` subpaths. | ||
| import { sentryBunPlugin } from '@sentry/bun/plugin'; | ||
| import { tmpdir } from 'os'; | ||
| import { join } from 'path'; | ||
|
|
||
| void (async () => { | ||
| const outdir = join(tmpdir(), `sentry-bun-orchestrion-${process.pid}-${Date.now()}`); | ||
| const result = await Bun.build({ | ||
| entrypoints: [join(__dirname, 'scenario.ts')], | ||
| target: 'bun', | ||
| outdir, | ||
| plugins: [sentryBunPlugin()], | ||
| }); | ||
|
|
||
| if (!result.success) { | ||
| // eslint-disable-next-line no-console | ||
| console.error('BUILD_FAILED', result.logs); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| const output = result.outputs[0]; | ||
| if (!output) { | ||
| // eslint-disable-next-line no-console | ||
| console.error('BUILD_FAILED no outputs'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // eslint-disable-next-line no-console | ||
| console.log(`BUILD_OK outfile=${output.path}`); | ||
| })(); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| // Bundled entry for the `bun build` smoke test. | ||
| // | ||
| // Once `Bun.build` (with the orchestrion plugin) has transformed `mysql`, | ||
| // calling `connection.query()` publishes to the `orchestrion:mysql:query` | ||
| // tracing channel. | ||
| // | ||
| // `start` fires synchronously on the call, so no live database is needed. | ||
| // | ||
| // We subscribe, run a query, and report which channel events fired | ||
| // (plus the detection marker the plugin's banner sets at boot). | ||
|
|
||
| import { tracingChannel } from 'node:diagnostics_channel'; | ||
|
|
||
| // @ts-ignore -- `mysql` ships no type declarations; only needed at runtime. | ||
| import mysql from 'mysql'; | ||
|
|
||
| interface QueryContext { | ||
| arguments?: unknown[]; | ||
| } | ||
| interface Connection { | ||
| query(sql: string, cb: () => void): void; | ||
| destroy(): void; | ||
| } | ||
| interface MysqlModule { | ||
| createConnection(opts: { host: string; user: string }): Connection; | ||
| } | ||
|
|
||
| const events: string[] = []; | ||
| let statement = ''; | ||
|
|
||
| tracingChannel('orchestrion:mysql:query').subscribe({ | ||
| start(message: unknown) { | ||
| events.push('start'); | ||
| const first = (message as QueryContext).arguments?.[0]; | ||
| statement = typeof first === 'string' ? first : ''; | ||
| }, | ||
| end() { | ||
| events.push('end'); | ||
| }, | ||
| asyncStart() {}, | ||
| asyncEnd() { | ||
| events.push('asyncEnd'); | ||
| }, | ||
| error() {}, | ||
| }); | ||
|
|
||
| const conn = (mysql as MysqlModule).createConnection({ host: '127.0.0.1', user: 'root' }); | ||
| try { | ||
| conn.query('SELECT 1 AS solution', () => {}); | ||
| } catch { | ||
| // No live server — `start` has already published synchronously by this point. | ||
| } | ||
| try { | ||
| conn.destroy(); | ||
| } catch { | ||
| // ignore | ||
| } | ||
|
|
||
| const marker = (globalThis as { __SENTRY_ORCHESTRION__?: { runtime?: boolean; bundler?: boolean } }) | ||
| .__SENTRY_ORCHESTRION__; | ||
|
|
||
| setTimeout(() => { | ||
| // eslint-disable-next-line no-console | ||
| console.log(`SCENARIO events=${events.join(',')} statement=${statement} marker=${JSON.stringify(marker ?? null)}`); | ||
| process.exit(0); | ||
| }, 200); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| import { spawnSync } from 'child_process'; | ||
| import { rmSync } from 'fs'; | ||
| import { dirname, join } from 'path'; | ||
| import { describe, expect, it } from 'vitest'; | ||
|
|
||
| const dir = __dirname; | ||
|
|
||
| // Cap each `bun` subprocess. The test runs two of them sequentially, so its own | ||
| // timeout (see the `it(...)` below) must exceed `2 * SUBPROCESS_TIMEOUT_MS` — | ||
| // otherwise the suite's default `testTimeout` (20s) fails the test before these | ||
| // caps do, e.g. on a slow CI runner where the build+run legitimately takes >20s. | ||
| const SUBPROCESS_TIMEOUT_MS = 60_000; | ||
|
|
||
| function runBun(args: string[]): { stdout: string; stderr: string; status: number | null } { | ||
| const res = spawnSync('bun', args, { cwd: dir, encoding: 'utf8', timeout: SUBPROCESS_TIMEOUT_MS }); | ||
| return { stdout: res.stdout ?? '', stderr: res.stderr ?? '', status: res.status }; | ||
| } | ||
|
|
||
| // Bun orchestrion instrumentation is BUILD-ONLY (`@sentry/bun/plugin` is a | ||
| // `Bun.build` plugin; there is no `bun run` preload). | ||
| // | ||
| // A `bun run` runtime plugin cannot instrument CommonJS dependencies like | ||
| // `mysql`: any module returned by a runtime `onLoad` plugin in Bun loses its | ||
| // CommonJS named exports | ||
| // | ||
| // When https://github.com/oven-sh/bun/pull/31770 lands, we can revisit an | ||
| // auto-load plugin for `bun run`. | ||
| describe('orchestrion mysql instrumentation (Bun)', () => { | ||
| it('bundles `mysql` with the plugin, and the built output fires the mysql channel when run', () => { | ||
| // Build the scenario with the orchestrion `bun build` plugin. | ||
| const build = runBun(['run', join(dir, 'build.ts')]); | ||
| expect(build.status, `build failed:\nstderr:\n${build.stderr}\nstdout:\n${build.stdout}`).toBe(0); | ||
|
|
||
| const outfile = build.stdout.match(/BUILD_OK outfile=(.+)/)?.[1]?.trim(); | ||
| expect(outfile, `no outfile in build output:\n${build.stdout}`).toBeTruthy(); | ||
|
|
||
| try { | ||
| // Run the built bundle. The bundled (transformed) `mysql` should publish | ||
| // to the `orchestrion:mysql:query` channel when `connection.query()` is | ||
| // called, and the plugin's banner should set the `bundler` marker at boot. | ||
| const run = runBun(['run', outfile as string]); | ||
| expect(run.status, `run failed:\nstderr:\n${run.stderr}\nstdout:\n${run.stdout}`).toBe(0); | ||
|
cursor[bot] marked this conversation as resolved.
|
||
|
|
||
| const line = run.stdout.split('\n').find(l => l.startsWith('SCENARIO')) ?? ''; | ||
| // channel `start` fired on `connection.query()` | ||
| expect(line).toContain('events=start'); | ||
| // with the expected SQL | ||
| expect(line).toContain('statement=SELECT 1 AS solution'); | ||
| // injected banner ran at bundle boot | ||
| expect(line).toContain('"bundler":true'); | ||
| } finally { | ||
| if (outfile) { | ||
| rmSync(dirname(outfile), { recursive: true, force: true }); | ||
| } | ||
| } | ||
| // Allow for both sequential `runBun` calls hitting their subprocess cap, so | ||
| // the `spawnSync` timeouts — not Vitest's 20s default — are the binding limit. | ||
| }, 2 * SUBPROCESS_TIMEOUT_MS); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,10 @@ | ||
| import { makeBaseNPMConfig, makeNPMConfigVariants } from '@sentry-internal/rollup-utils'; | ||
|
|
||
| export default makeNPMConfigVariants(makeBaseNPMConfig()); | ||
| export default makeNPMConfigVariants( | ||
| makeBaseNPMConfig({ | ||
| // `src/plugin.ts` backs the `@sentry/bun/plugin` subpath (the orchestrion | ||
| // `bun build` plugin). It isn't reachable from `src/index.ts`, so we list it | ||
| // as a separate entrypoint to get both ESM and CJS builds. | ||
| entrypoints: ['src/index.ts', 'src/plugin.ts'], | ||
| }), | ||
| ); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| /** | ||
| * orchestrion code-transform plugin for Bun's bundler (`bun build`). | ||
| * | ||
| * Usage: | ||
| * | ||
| * ```ts | ||
| * import { sentryBunPlugin } from '@sentry/bun/plugin'; | ||
| * await Bun.build({ | ||
| * entrypoints: ['./app.ts'], | ||
| * plugins: [sentryBunPlugin()], | ||
| * }); | ||
| * ``` | ||
| * | ||
| * This is BUILD-ONLY. Runtime instrumentation (`bun run`) is intentionally not | ||
| * offered: a module returned by a runtime `onLoad` plugin in Bun loses its | ||
| * CommonJS named exports. | ||
| * | ||
| * When https://github.com/oven-sh/bun/pull/31770 lands, we can revisit. | ||
| * | ||
| * Until then, Bun apps must bundle to get orchestrion instrumentation. In dev | ||
| * (ie, `bun run`) there is simply no instrumentation, which is clearer than | ||
| * partial/inconsistent coverage. | ||
| * | ||
| * Shipped as both ESM and CJS (via the `@sentry/bun/plugin` subpath) so a user's | ||
| * `bun build` script can be authored in either module system. It's a plain | ||
| * library import here (not a `--import`/`--preload` hook), so CJS is fine; Bun | ||
| * resolves the underlying ESM-only transformer in either module system. | ||
| * | ||
| * @module | ||
| */ | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
| type UnknownPlugin = any; | ||
|
|
||
| // `@apm-js-collab/code-transformer-bundler-plugins/bun` is published ESM-only | ||
| // (no `require` arm, unlike its `/vite` entry). The ESM build imports it; the | ||
| // CJS build requires it. Bun resolves correctly for ESM modules in either | ||
| // module system. | ||
| import codeTransformer from '@apm-js-collab/code-transformer-bundler-plugins/bun'; | ||
| import { SENTRY_INSTRUMENTATIONS } from '@sentry/server-utils/orchestrion/config'; | ||
|
|
||
| const BUNDLER_MARKER_BANNER = | ||
| ';(globalThis.__SENTRY_ORCHESTRION__=(globalThis.__SENTRY_ORCHESTRION__||{})).bundler=true;'; | ||
|
|
||
| // Minimal shape of Bun's `PluginBuilder` that we touch. Typed locally instead | ||
| // of depending on `bun-types`, which would pull Bun's globals. | ||
| interface BunPluginBuilder { | ||
| config?: { banner?: string }; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the orchestrion code-transform plugin for Bun's bundler, configured | ||
| * with the central `SENTRY_INSTRUMENTATIONS`. The plugin injects | ||
| * `diagnostics_channel.tracingChannel` calls into the instrumented libraries as | ||
| * `bun build` bundles them, and injects a banner that sets | ||
| * `globalThis.__SENTRY_ORCHESTRION__.bundler = true` when the bundle boots | ||
| * | ||
| * Pass the result to `Bun.build({ plugins: [...] })`. | ||
| * | ||
| * @example | ||
| * ```ts | ||
| * import { sentryBunPlugin } from '@sentry/bun/plugin'; | ||
| * await Bun.build({ entrypoints: ['./app.ts'], plugins: [sentryBunPlugin()] }); | ||
| * ``` | ||
| */ | ||
| export function sentryBunPlugin(): UnknownPlugin { | ||
| // Typed upstream as an esbuild `Plugin`, but Bun passes its own | ||
| // `PluginBuilder` (which has the `onLoad` the transform uses) to `setup`. | ||
| // Cast to the Bun-compatible shape so we can forward Bun's builder to its | ||
| // `setup`. | ||
| const transformer = codeTransformer({ instrumentations: SENTRY_INSTRUMENTATIONS }) as unknown as { | ||
| setup: (build: BunPluginBuilder) => void; | ||
| }; | ||
|
|
||
| return { | ||
| name: 'sentry-orchestrion', | ||
| setup(build: BunPluginBuilder): void { | ||
| // Inject a banner so the bundled output sets `bundler: true` at boot. | ||
| // `config` is the `Bun.build` config and is present when this plugin | ||
| // is passed to `Bun.build({ plugins: [...] })`. | ||
| if (build.config) { | ||
| const existing = build.config.banner ?? ''; | ||
| build.config.banner = existing ? `${existing}\n${BUNDLER_MARKER_BANNER}` : BUNDLER_MARKER_BANNER; | ||
| } | ||
|
|
||
| // Delegate to the upstream code-transformer, which registers the `onLoad` | ||
| // hook that does the actual channel injection. | ||
| transformer.setup(build); | ||
|
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. External deps skip instrumentationMedium Severity The Bun orchestrion plugin only merges the bundler marker into Reviewed by Cursor Bugbot for commit 69a65aa. Configure here. |
||
| }, | ||
| }; | ||
| } | ||


Uh oh!
There was an error while loading. Please reload this page.