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
Expand Up @@ -49,7 +49,7 @@ describe('orchestrion mysql instrumentation (Bun)', () => {
// with the expected SQL
expect(line).toContain('statement=SELECT 1 AS solution');
// injected banner ran at bundle boot
expect(line).toContain('"bundler":true');
expect(line).toContain('"bundler":[]');
} finally {
if (outfile) {
rmSync(dirname(outfile), { recursive: true, force: true });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe('orchestrion pg instrumentation (Bun)', () => {
// with the expected SQL
expect(line).toContain('statement=SELECT 1 AS solution');
// injected banner ran at bundle boot
expect(line).toContain('"bundler":true');
expect(line).toContain('"bundler":[]');
} finally {
if (outfile) {
rmSync(dirname(outfile), { recursive: true, force: true });
Expand Down
4 changes: 2 additions & 2 deletions packages/bun/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import {
} from '@sentry/server-utils/orchestrion/config';

const BUNDLER_MARKER_BANNER =
';(globalThis.__SENTRY_ORCHESTRION__=(globalThis.__SENTRY_ORCHESTRION__||{})).bundler=true;';
';(globalThis.__SENTRY_ORCHESTRION__=(globalThis.__SENTRY_ORCHESTRION__||{})).bundler=[];';

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @isaacs do we actually need this? Can we properly inject this with the correct modules somehow?

Comment thread
cursor[bot] marked this conversation as resolved.

// Minimal shape of Bun's `PluginBuilder` that we touch. Typed locally instead
// of depending on `bun-types`, which would pull Bun's globals.
Expand All @@ -57,7 +57,7 @@ interface BunPluginBuilder {
* 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
* `globalThis.__SENTRY_ORCHESTRION__.bundler = []` when the bundle boots
*
* Pass the result to `Bun.build({ plugins: [...] })`.
*
Expand Down
16 changes: 16 additions & 0 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -927,6 +927,16 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
*/
public on(hook: 'stopUIProfiler', callback: () => void): () => void;

/**
* A hook that is called when the orchestrion runtime hook injects diagnostics
* channels into a module as it is loaded.
*
* The callback receives the name of the instrumented module.
*
* @returns {() => void} A function that, when executed, removes the registered callback.
*/
public on(hook: 'orchestrion.module-runtime-injected', callback: (moduleName: string) => void): () => void;

/**
* Register a hook on this client.
*/
Expand Down Expand Up @@ -1188,6 +1198,12 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
*/
public emit(hook: 'stopUIProfiler'): void;

/**
* Emit a hook event when the orchestrion runtime hook injects diagnostics
* channels into a module as it is loaded.
*/
public emit(hook: 'orchestrion.module-runtime-injected', moduleName: string): void;

/**
* Emit a hook that was previously registered via `on()`.
*/
Expand Down
37 changes: 12 additions & 25 deletions packages/server-utils/src/integrations/tracing-channel/amqplib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ import * as diagnosticsChannel from 'node:diagnostics_channel';
import type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';
import {
continueTrace,
debug,
defineIntegration,
getTraceData,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SPAN_KIND,
SPAN_STATUS_ERROR,
startInactiveSpan,
timestampInSeconds,
waitForTracingChannelBinding,
} from '@sentry/core';
// eslint-disable-next-line typescript/no-deprecated -- NET_PEER_* emitted alongside SERVER_* for backwards compatibility (TODO(v11): remove)
import {
Expand All @@ -27,9 +25,10 @@ import {
SERVER_PORT,
URL_FULL,
} from '@sentry/conventions/attributes';
import { DEBUG_BUILD } from '../../debug-build';
import { CHANNELS } from '../../orchestrion/channels';
import { bindTracingChannelToSpan } from '../../tracing-channel';
import { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';
import { amqplibModuleNames } from '../../orchestrion/config/amqplib';

// NOTE: this uses the same name as the OTel integration by design.
// When enabled, the OTel 'Amqplib' integration is omitted from the default set.
Expand Down Expand Up @@ -156,32 +155,20 @@ interface AmqpConnectContext {

const NOOP = (): void => {};

// Guards against subscribing to the amqplib channels more than once in a process. Core dedupes
// `setupOnce` by integration *name*, which is not enough here: the Deno SDK wraps this integration
// under a different name (`DenoAmqplib`) via `extendIntegration`, so adding both would otherwise run
// the subscribe logic twice and emit duplicate spans for every operation.
let subscribed = false;
function instrumentAmqplib(): void {
subscribeConnect();
subscribePublish();
subscribeConfirmPublish();
subscribeConsume();
subscribeDispatch();
subscribeSettle();
}

const _amqplibChannelIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
// `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.
if (!diagnosticsChannel.tracingChannel || subscribed) {
return;
}
subscribed = true;

DEBUG_BUILD && debug.log('[orchestrion:amqplib] subscribing to amqplib tracing channels');

waitForTracingChannelBinding(() => {
subscribeConnect();
subscribePublish();
subscribeConfirmPublish();
subscribeConsume();
subscribeDispatch();
subscribeSettle();
});
setup(client) {
invokeOrchestrionInstrumentation(client, amqplibModuleNames, instrumentAmqplib, []);
},
};
}) satisfies IntegrationFn;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
_INTERNAL_shouldSkipAiProviderWrapping,
addAnthropicRequestAttributes,
addAnthropicResponseAttributes,
debug,
defineIntegration,
extractAnthropicRequestAttributes,
GEN_AI_REQUEST_MODEL_ATTRIBUTE,
Expand All @@ -14,11 +13,11 @@ import {
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
shouldEnableTruncation,
startInactiveSpan,
waitForTracingChannelBinding,
} from '@sentry/core';
import { DEBUG_BUILD } from '../../debug-build';
import { CHANNELS } from '../../orchestrion/channels';
import { bindTracingChannelToSpan } from '../../tracing-channel';
import { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';
import { anthropicAiModuleNames } from '../../orchestrion/config/anthropic-ai';

// Same name as the OTel integration by design: when enabled, the OTel 'Anthropic_AI'
// integration is dropped from the default set (see the Node opt-in loader).
Expand Down Expand Up @@ -47,39 +46,30 @@ interface AnthropicChannelContext {
result?: unknown;
}

let subscribed = false;
function instrumentAnthropic(options: AnthropicAiOptions): void {
for (const { channel, operation, methodPath, stream } of INSTRUMENTED_CHANNELS) {
bindTracingChannelToSpan(
diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),
data => createGenAiSpan(data, operation, methodPath, options),
{
beforeSpanEnd: (span, data) => {
addAnthropicResponseAttributes(
span,
data.result as AnthropicAiResponse,
resolveAIRecordingOptions(options).recordOutputs,
);
},
deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, stream, options),
},
);
}
}

const _anthropicChannelIntegration = ((options: AnthropicAiOptions = {}) => {
return {
name: INTEGRATION_NAME,
setupOnce() {
// tracingChannel is unavailable before Node 18.19 and prevent double-subscribe
if (!diagnosticsChannel.tracingChannel || subscribed) {
return;
}
subscribed = true;

// `bindTracingChannelToSpan` needs the async-context binding that `initOpenTelemetry()` registers
// after `setupOnce` runs, so wait for it before subscribing.
waitForTracingChannelBinding(() => {
for (const { channel, operation, methodPath, stream } of INSTRUMENTED_CHANNELS) {
DEBUG_BUILD && debug.log(`[orchestrion:anthropic] subscribing to channel "${channel}"`);
bindTracingChannelToSpan(
diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),
data => createGenAiSpan(data, operation, methodPath, options),
{
beforeSpanEnd: (span, data) => {
addAnthropicResponseAttributes(
span,
data.result as AnthropicAiResponse,
resolveAIRecordingOptions(options).recordOutputs,
);
},
deferSpanEnd: ({ span, data }) => wrapStreamResult(span, data, stream, options),
},
);
}
});
setup(client) {
invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);
},
};
}) satisfies IntegrationFn;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import * as diagnosticsChannel from 'node:diagnostics_channel';
import type { IntegrationFn, Span, StartSpanOptions } from '@sentry/core';
import {
debug,
defineIntegration,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SPAN_KIND,
startInactiveSpan,
startSpan,
waitForTracingChannelBinding,
} from '@sentry/core';
import { DEBUG_BUILD } from '../../debug-build';
import type { ChannelName } from '../../orchestrion/channels';
import { CHANNELS } from '../../orchestrion/channels';
import type { TracingChannelPayloadWithSpan } from '../../tracing-channel';
import { bindTracingChannelToSpan } from '../../tracing-channel';
import { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';
import { dataloaderModuleNames } from '../../orchestrion/config/dataloader';

// NOTE: this uses the same name as the OTel integration by design.
// When enabled, the OTel 'Dataloader' integration is omitted from the default set.
Expand Down Expand Up @@ -78,25 +77,20 @@ function makeSpanOptions(loader: DataLoaderInstance | undefined, operation: Oper
};
}

function instrumentDataloader(): void {
subscribeConstruct();
subscribeLoad();
subscribeSimpleOperation(CHANNELS.DATALOADER_LOAD_MANY, 'loadMany');
subscribeSimpleOperation(CHANNELS.DATALOADER_PRIME, 'prime');
subscribeSimpleOperation(CHANNELS.DATALOADER_CLEAR, 'clear');
subscribeSimpleOperation(CHANNELS.DATALOADER_CLEAR_ALL, 'clearAll');
}

const _dataloaderChannelIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
// `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.
if (!diagnosticsChannel.tracingChannel) {
return;
}

DEBUG_BUILD && debug.log('[orchestrion:dataloader] subscribing to dataloader tracing channels');

waitForTracingChannelBinding(() => {
subscribeConstruct();
subscribeLoad();
subscribeSimpleOperation(CHANNELS.DATALOADER_LOAD_MANY, 'loadMany');
subscribeSimpleOperation(CHANNELS.DATALOADER_PRIME, 'prime');
subscribeSimpleOperation(CHANNELS.DATALOADER_CLEAR, 'clear');
subscribeSimpleOperation(CHANNELS.DATALOADER_CLEAR_ALL, 'clearAll');
});
setup(client) {
invokeOrchestrionInstrumentation(client, dataloaderModuleNames, instrumentDataloader, []);
},
};
}) satisfies IntegrationFn;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import * as diagnosticsChannel from 'node:diagnostics_channel';
import type { IntegrationFn } from '@sentry/core';
import { defineIntegration, waitForTracingChannelBinding } from '@sentry/core';
import { defineIntegration } from '@sentry/core';
import type { ExpressIntegrationOptions } from './types';
import { instrumentExpress } from './instrumentation';
import { expressModuleNames } from '../../../orchestrion/config/express';
import { invokeOrchestrionInstrumentation } from '../../../orchestrion/instrumentation';

// NOTE: this uses the same name as the OTel integration by design.
// When enabled, the OTel 'Express' integration is omitted from the default set.
Expand All @@ -11,15 +12,8 @@ const INTEGRATION_NAME = 'Express' as const;
const _expressChannelIntegration = ((options: ExpressIntegrationOptions = {}) => {
return {
name: INTEGRATION_NAME,
setupOnce() {
// `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.
if (!diagnosticsChannel.tracingChannel) {
return;
}

waitForTracingChannelBinding(() => {
instrumentExpress(options, diagnosticsChannel.tracingChannel);
});
setup(client) {
invokeOrchestrionInstrumentation(client, expressModuleNames, instrumentExpress, [options]);
},
};
}) satisfies IntegrationFn;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type * as diagnosticsChannel from 'node:diagnostics_channel';
import * as diagnosticsChannel from 'node:diagnostics_channel';
import { HTTP_ROUTE } from '@sentry/conventions/attributes';
import type { Span } from '@sentry/core';
import {
Expand Down Expand Up @@ -45,16 +45,8 @@ const ATTR_EXPRESS_TYPE = 'express.type';

const NOOP = (): void => {};

let _isInstrumented = false;

export function instrumentExpress(
options: ExpressIntegrationOptions,
tracingChannel: typeof diagnosticsChannel.tracingChannel,
): void {
if (_isInstrumented) {
return;
}
_isInstrumented = true;
export function instrumentExpress(options: ExpressIntegrationOptions): void {
const tracingChannel = diagnosticsChannel.tracingChannel;

// Record each layer's registered path *pattern* as it is registered, so the
// matched route can be reconstructed with its parameters intact at request
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { IntegrationFn } from '@sentry/core';
import { defineIntegration } from '@sentry/core';
import type { FastifyIntegration, FastifyReply, FastifyRequest } from './types';

import { instrumentFastify as _instrumentFastify } from './instrumentation';
import { defaultShouldHandleError, INTEGRATION_NAME } from './utils';
import { subscribeToFastifyErrorChannel, handleFastifyError as _handleFastifyError } from './errors';
Expand Down Expand Up @@ -76,9 +75,7 @@ const _fastifyIntegration = (({ shouldHandleError }: Partial<FastifyIntegrationO
* })
* ```
*/
export const fastifyIntegration = defineIntegration((options: Partial<FastifyIntegrationOptions> = {}) =>
_fastifyIntegration(options),
);
export const fastifyIntegration = defineIntegration(_fastifyIntegration);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

q: Just for my understanding, not to miss anything. The Fastify changes are unrelated theoretically right?

Ok to land here, since they are small changes 🤏

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fastify integration crashes without options

High Severity

Exporting defineIntegration(_fastifyIntegration) drops the previous wrapper that defaulted options to {}. The factory destructures its argument immediately, so calling fastifyIntegration() with no arguments passes undefined and throws at integration creation time.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit acd44ec. Configure here.


/**
* @deprecated This export is deprecated and will not longer be exposed in the next major version.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { FastifyReply, FastifyRequest } from './types';

export const INTEGRATION_NAME = 'Fastify';
export const INTEGRATION_NAME = 'Fastify' as const;

/**
* Default function to determine if an error should be sent to Sentry
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import * as diagnosticsChannel from 'node:diagnostics_channel';
import type { IntegrationFn } from '@sentry/core';
import {
defineIntegration,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
startInactiveSpan,
waitForTracingChannelBinding,
} from '@sentry/core';
import { defineIntegration, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startInactiveSpan } from '@sentry/core';
import { CHANNELS } from '../../orchestrion/channels';
import { bindTracingChannelToSpan } from '../../tracing-channel';
import { invokeOrchestrionInstrumentation } from '../../orchestrion/instrumentation';
import { genericPoolModuleNames } from '../../orchestrion/config/generic-pool';

// Same name as the OTel integration by design — when enabled, the OTel
// 'GenericPool' integration is omitted from the default set.
Expand All @@ -20,13 +17,8 @@ interface GenericPoolAcquireContext {
const _genericPoolChannelIntegration = (() => {
return {
name: INTEGRATION_NAME,
setupOnce() {
// `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.
if (!diagnosticsChannel.tracingChannel) {
return;
}

waitForTracingChannelBinding(() => instrumentGenericPool());
setup(client) {
invokeOrchestrionInstrumentation(client, genericPoolModuleNames, instrumentGenericPool, []);
},
};
}) satisfies IntegrationFn;
Expand Down
Loading