Skip to content
Open
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
9 changes: 9 additions & 0 deletions packages/core/src/utils/worldwide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */

import type { Integration } from '../types/integration';
import type { Carrier } from '../carrier';
import type { SdkSource } from './env';

Expand Down Expand Up @@ -63,6 +64,14 @@ export type InternalGlobal = {
runtime?: string[];
/** Empty array signifies bundler plugin ran */
bundler?: string[];
/**
* Channel-subscriber integration factories a bundler plugin's
* subscribe-injection stored here, keyed by export name (one per instrumented
* package actually bundled; the key dedupes packages split across several
* files). A bundler-only SDK (e.g. `@sentry/cloudflare`) reads these at
* `init()` and instantiates them.
*/
integrations?: Map<string, () => Integration>;
};
} & Carrier;

Expand Down
3 changes: 2 additions & 1 deletion packages/server-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@
"@apm-js-collab/code-transformer-bundler-plugins": "^0.7.1",
"@apm-js-collab/tracing-hooks": "^0.13.0",
"@sentry/conventions": "^0.16.0",
"@sentry/core": "10.66.0"
"@sentry/core": "10.66.0",
"meriyah": "^6.1.4"
},
"devDependencies": {
"@types/node": "^18.19.1",
Expand Down
31 changes: 29 additions & 2 deletions packages/server-utils/src/orchestrion/bundler/options.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { InstrumentationConfig, CustomTransform } from '..';
import { SENTRY_INSTRUMENTATIONS } from '../config';
import { subscribeInjectionOptions } from './subscribeInjection';
import type { CodeTransformerPluginOptions } from '@apm-js-collab/code-transformer-bundler-plugins/core';

export type PluginOptions = {
Expand All @@ -17,6 +18,26 @@ export type PluginOptions = {
* Defaults to `true`.
*/
shouldInjectDiagnostics?: boolean;
/**
* Inject a small marker-push into each instrumented module that imports only
* that package's channel-subscriber factory and pushes it onto
* `globalThis.__SENTRY_ORCHESTRION__.integrations`. A bundler-only SDK reads
* the marker at `init()` and instantiates the collected factories, so every
* transformed package's subscriber is wired up with no runtime module hook.
*
* Because each site imports a single named factory, it tree-shakes: a bundle
* carries subscriber code only for the packages actually transformed into it.
*
* This is what lets a bundler-only SDK (e.g. `@sentry/cloudflare`, which runs
* in workerd where requires can't be monkey-patched) record channel spans,
* but it is bundler-agnostic: any orchestrion bundler plugin can enable it.
* Leave it off for SDKs that wire the integrations up through a static import
* instead (e.g. `@sentry/node`'s `experimentalUseDiagnosticsChannelInjection()`),
* so the subscribers aren't registered twice.
*
* Defaults to `false`.
*/
injectChannelSubscribers?: boolean;
};

/**
Expand All @@ -29,8 +50,14 @@ export type PluginOptions = {
* visible to the runtime).
*/
export function orchestrionTransformOptions(options: PluginOptions): CodeTransformerPluginOptions {
const instrumentations = [...SENTRY_INSTRUMENTATIONS, ...(options.instrumentations || [])];
const customTransforms = options.customTransforms;
const subscribeInjection = options.injectChannelSubscribers ? subscribeInjectionOptions() : undefined;

const instrumentations = [
...SENTRY_INSTRUMENTATIONS,
...(options.instrumentations || []),
...(subscribeInjection?.instrumentations || []),
];
const customTransforms = { ...options.customTransforms, ...subscribeInjection?.customTransforms };

if (options.shouldInjectDiagnostics === false) {
return {
Expand Down
110 changes: 110 additions & 0 deletions packages/server-utils/src/orchestrion/bundler/subscribeInjection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import type { CustomTransform } from '@apm-js-collab/code-transformer';
import { parse } from 'meriyah';
import { SUBSCRIBE_INJECTIONS } from '../config';
import { subscriberExportForModule } from '../config/channel-integration-definitions';
import { SUBSCRIBE_TRANSFORM_NAME } from '../config/subscribe-injection';
import type { PluginOptions } from './options';

// Tracks Program nodes we already injected into, so a package with several
// instrumented files (or several configs pointing at one file) is injected only
// once per file. A `WeakSet` keyed by the node avoids mutating the emitted AST.
const injectedPrograms = new WeakSet<object>();

interface ProgramNode {
type: string;
body: Array<{ type: string; directive?: string }>;
}

/**
* Snippet injected into each instrumented module. It imports ONLY that package's
* channel-subscriber factory from `@sentry/server-utils/orchestrion` plus the two
* `@sentry/core` helpers it needs, then does two things when the module first
* evaluates:
*
* 1. Stores the factory on the global orchestrion marker under its export name,
* so a later `init()` (a fresh isolate, or a client created after this module
* loads) picks it up via `getDefaultIntegrations()`.
* 2. If a client already exists, registers the integration live on it right away.
*
* Step 2 is what makes this robust against module load order. Bundler-only SDKs
* (e.g. `@sentry/cloudflare`) call `init()` per request, but a package like
* `mysql` loads its instrumented file lazily on first use — i.e. AFTER that
* request's `init()` already snapshotted the marker. Without the live add, the
* first request that touches such a package would publish to a channel nobody
* subscribed to yet. `addIntegration` dedupes by integration name and only runs
* `setupOnce` once, so storing AND live-adding never double-subscribes.
*
* The marker is a `Map` keyed by export name so a package split across several
* instrumented files (e.g. `pg`'s JS and native clients, or openai's per-resource
* `.js`/`.mjs` files) registers its one subscriber once, no matter how many of
* its files land in the bundle — `.set` on the shared key is idempotent.
*
* Importing the single named factory (rather than a central dispatch that pulls
* in every subscriber) is what makes this tree-shake: a bundle carries only the
* subscriber code for packages actually transformed into it — the same
* "only-active-when-bundled" property the runtime module hook gives unbundled
* Node, but without a hook (workerd can't monkey-patch requires).
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName} } from '@sentry/server-utils/orchestrion';\nimport { getClient as __sentryGetClient } from '@sentry/core';`
: `const { ${exportName} } = require('@sentry/server-utils/orchestrion');\nconst { getClient: __sentryGetClient } = require('@sentry/core');`;

// `??=` keeps the marker init a no-op after the first instrumented file
// creates the Map; keying by export name dedupes packages split across files.
return (
`${importStmt}\n` +
'(globalThis.__SENTRY_ORCHESTRION__ ??= {}).integrations ??= new Map();\n' +

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.

note: This is now a new Map() instead of a [], as it could be that multiple files are modified by Orchestrion and this would not add any duplicates.

`globalThis.__SENTRY_ORCHESTRION__.integrations.set(${JSON.stringify(exportName)}, ${exportName});\n` +
`__sentryGetClient()?.addIntegration(${exportName}());`

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.

note: This one is something where I don't know how else to solve. I have a test in the GH stack above that is using MYSQL within Cloudflare. The lib/Connection.js is being required inline in some file, that means that this file is only being executed once this file is called.

Since at this time the client got already set up, and .integrations.push() would be too late for the first execution and only .addIntegration() would work. Not sure if there are better ways to do this.

I tried to kinda move that snipped then out of this file, but that didn't work that nicely

);
}

/**
* The custom transform registered under {@link SUBSCRIBE_TRANSFORM_NAME}. It is
* invoked with the matched `Program` node and mutates it in place, splicing the
* marker-push snippet in after any `'use strict'` directive.
*
* `state` carries the matched config spread with `{ moduleType }`; the config's
* `channelName` carries the package name (see `toSubscribeInjections`), which
* maps to the subscriber's export name.
*/
const injectSubscribe: CustomTransform = (state, program) => {
const node = program as ProgramNode;
if (injectedPrograms.has(node)) {
return;
}

const { moduleType, channelName } = state as { moduleType?: string; channelName?: string };
const exportName = channelName ? subscriberExportForModule(channelName) : undefined;
if (!exportName) {
return;
}

injectedPrograms.add(node);

const statements = parse(subscribeSnippet(exportName, moduleType === 'esm'), {
module: moduleType === 'esm',
next: true,
}).body as ProgramNode['body'];

const directiveIndex = node.body.findIndex(n => n.type === 'ExpressionStatement' && n.directive === 'use strict');
Comment thread
sentry[bot] marked this conversation as resolved.
node.body.splice(directiveIndex + 1, 0, ...statements);
Comment on lines +91 to +92

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bug: Code injection in ESM modules occurs at index 0 because 'use strict' is not found. This can place expressions before existing import statements, causing a syntax error.
Severity: MEDIUM

Suggested Fix

The injection logic should be updated to handle ESM modules correctly. Instead of searching for 'use strict', the code should parse the module to find the last import statement and inject the new code after it. If no imports exist, the code can be injected at the beginning of the module.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: packages/server-utils/src/orchestrion/bundler/subscribeInjection.ts#L91-L92

Potential issue: The code injects instrumentation by finding a `'use strict'` directive
and inserting statements after it. However, ESM modules are strict by default and lack
this directive. In such cases, `findIndex` returns `-1`, and the code incorrectly
splices new statements at the beginning of the module's body (`node.body.splice(0,
...)`). If the target ESM module contains its own `import` statements, this injection
will place other expression statements before them, which is a syntax error in
JavaScript. While existing tests do not cover this specific scenario, the logical flaw
could break instrumentation for any ESM module that has top-level imports.

};

/**
* The `instrumentations` + `customTransforms` a bundler plugin passes to
* {@link orchestrionTransformOptions} to enable the marker-push subscribe
* injection used by bundler-only SDKs (e.g. `@sentry/cloudflare`).
*
* The `SUBSCRIBE_INJECTIONS` configs ride alongside the real channel-publishing
* configs, and `injectSubscribe` runs on each matched module, so every
* transformed package self-registers its subscriber on the global marker
* without a runtime module hook.
*/
export function subscribeInjectionOptions(): Pick<PluginOptions, 'instrumentations' | 'customTransforms'> {
return {
instrumentations: SUBSCRIBE_INJECTIONS,
customTransforms: { [SUBSCRIBE_TRANSFORM_NAME]: injectSubscribe },
};
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/amqplib.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `amqplib` splits its API across three files:
// - `lib/channel_model.js` holds `class Channel` (publish/consume/ack/nack/reject/…) and
Expand Down Expand Up @@ -87,3 +88,5 @@ export const amqplibChannels = {
AMQPLIB_NACK_ALL: 'orchestrion:amqplib:nackAll',
AMQPLIB_CONNECT: 'orchestrion:amqplib:connect',
} as const;

export const amqplibSubscribeInjection = toSubscribeInjections(amqplibConfig);
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const anthropicAiConfig = [
// One entry each for CJS/ESM
Expand Down Expand Up @@ -38,3 +39,5 @@ export const anthropicAiChannels = {
ANTHROPIC_MODELS: 'orchestrion:@anthropic-ai/sdk:models',
ANTHROPIC_MESSAGES_STREAM: 'orchestrion:@anthropic-ai/sdk:messages-stream',
} as const;

export const anthropicAiSubscribeInjection = toSubscribeInjections(anthropicAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/aws-sdk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '@apm-js-collab/code-transformer';
import { toSubscribeInjections } from './subscribe-injection';

// The AWS SDK (v3) routes every command through the smithy `Client.prototype.send` method. Which
// package hosts that `Client` class changed across versions, so we target all of them; only the one
Expand Down Expand Up @@ -32,3 +33,5 @@ export const awsSdkChannels = {
AWS_SMITHY_CLIENT_SEND: 'orchestrion:@smithy/smithy-client:send',
AWS_SDK_SMITHY_CLIENT_SEND: 'orchestrion:@aws-sdk/smithy-client:send',
} as const;

export const awsSdkSubscribeInjection = toSubscribeInjections(awsSdkConfig);
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Build-time metadata mapping each instrumented package (orchestrion
* `module.name`) to the channel-subscriber integration that consumes the
* channels injected into it — by the `exportName` it is published under from
* `@sentry/server-utils/orchestrion`.
*
* Kept in a separate, factory-free module on purpose: the subscribe-injection
* transform (reachable from every orchestrion bundler plugin) reads this to
* generate the tiny snippet it injects into each instrumented file, and must
* not drag any subscriber code — or its `@sentry/core` span machinery — into
* the plugin's own build to do so.
*
* `exportName` must be a named export of `@sentry/server-utils/orchestrion`.
* `modules` must match `module.name` values in `SENTRY_INSTRUMENTATIONS` — e.g.
* `postgresChannelIntegration` covers both `pg` and `pg-pool`, and
* `redisChannelIntegration` both `redis` and `@redis/client`.
*
* `redis`, `ioredis` and `dataloader` are included even though they're not in
* the node SDK's `channelIntegrations` (they only partially replace an OTel
* integration there): in a bundler-only runtime like Cloudflare Workers there
* is no OTel integration to coordinate with, so subscribing whenever the
* package is bundled is unconditionally correct.
*/
export const CHANNEL_INTEGRATION_DEFINITIONS = [
{ exportName: 'postgresChannelIntegration', modules: ['pg', 'pg-pool'] },
{ exportName: 'postgresJsChannelIntegration', modules: ['postgres'] },
{ exportName: 'mysqlChannelIntegration', modules: ['mysql'] },
{ exportName: 'mysql2ChannelIntegration', modules: ['mysql2'] },
{ exportName: 'genericPoolChannelIntegration', modules: ['generic-pool'] },
{ exportName: 'lruMemoizerChannelIntegration', modules: ['lru-memoizer'] },
{ exportName: 'openaiChannelIntegration', modules: ['openai'] },
{ exportName: 'anthropicChannelIntegration', modules: ['@anthropic-ai/sdk'] },
{ exportName: 'googleGenAIChannelIntegration', modules: ['@google/genai'] },
{ exportName: 'vercelAiChannelIntegration', modules: ['ai'] },
{ exportName: 'amqplibChannelIntegration', modules: ['amqplib'] },
{ exportName: 'hapiChannelIntegration', modules: ['@hapi/hapi'] },
{ exportName: 'expressChannelIntegration', modules: ['express', 'router'] },
{ exportName: 'graphqlChannelIntegration', modules: ['graphql'] },
{ exportName: 'kafkajsChannelIntegration', modules: ['kafkajs'] },
{ exportName: 'redisChannelIntegration', modules: ['redis', '@redis/client'] },
{ exportName: 'ioredisChannelIntegration', modules: ['ioredis'] },
{ exportName: 'dataloaderChannelIntegration', modules: ['dataloader'] },
] as const satisfies ReadonlyArray<{ exportName: string; modules: readonly string[] }>;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AWS subscribe mapping missing

Medium Severity

awsSdkSubscribeInjection is included in SUBSCRIBE_INJECTIONS, but CHANNEL_INTEGRATION_DEFINITIONS has no entry for @smithy/core, @smithy/smithy-client, or @aws-sdk/smithy-client. subscriberExportForModule therefore returns nothing and injectSubscribe exits early, so AWS never self-registers awsChannelIntegration on the marker when injectChannelSubscribers is enabled.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6755627. Configure here.

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.

The rebase was adding more. I think I'll leave this until it is reviewed, do another rebase (as other integrations will come soon) and then push all of them

Comment on lines +33 to +43

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Bug: The CHANNEL_INTEGRATION_DEFINITIONS array is missing entries for AWS SDK modules, causing the injectSubscribe transform to silently no-op and disabling the awsChannelIntegration in bundler-only environments.
Severity: HIGH

Suggested Fix

Add an entry to the CHANNEL_INTEGRATION_DEFINITIONS array for the AWS SDK modules. This entry should associate the awsChannelIntegration export with the module names @smithy/core, @smithy/smithy-client, and @aws-sdk/smithy-client. For example: { exportName: 'awsChannelIntegration', modules: ['@smithy/core', '@smithy/smithy-client', '@aws-sdk/smithy-client'] }.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location:
packages/server-utils/src/orchestrion/config/channel-integration-definitions.ts#L24-L43

Potential issue: The `CHANNEL_INTEGRATION_DEFINITIONS` array lacks definitions for the
AWS SDK modules `@smithy/core`, `@smithy/smithy-client`, and `@aws-sdk/smithy-client`.
Consequently, when the `injectSubscribe` transform processes an AWS SDK file in a
bundler-only setup, the `subscriberExportForModule` function returns `undefined` for
these module names. This triggers a guard condition that causes the transform to exit
silently without injecting the necessary channel subscriber. As a result, the
`awsChannelIntegration` is completely non-functional in these environments, despite the
clear intent to support it.

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.


/** Look up the subscriber export name for an instrumented package, if any. */
export function subscriberExportForModule(moduleName: string): string | undefined {
return CHANNEL_INTEGRATION_DEFINITIONS.find(d => (d.modules as readonly string[]).includes(moduleName))?.exportName;
}
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/dataloader.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `dataloader` ships a single transpiled CommonJS `index.js`. Its class methods are emitted as
// `_proto.<name> = function <name>() {}` (named function *expressions*), so they match on
Expand Down Expand Up @@ -53,3 +54,5 @@ export const dataloaderChannels = {
DATALOADER_CLEAR: 'orchestrion:dataloader:clear',
DATALOADER_CLEAR_ALL: 'orchestrion:dataloader:clearAll',
} as const;

export const dataloaderSubscribeInjection = toSubscribeInjections(dataloaderConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/express.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const expressConfig = [
// Express funnels every middleware/route handler through a single method on
Expand Down Expand Up @@ -72,3 +73,5 @@ export const expressChannels = {
EXPRESS_REGISTER: 'orchestrion:express:register',
ROUTER_REGISTER: 'orchestrion:router:register',
} as const;

export const expressSubscribeInjection = toSubscribeInjections(expressConfig);
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// Two shapes of `acquire`, both publishing to the same `orchestrion:generic-pool:acquire` channel:
// - v3+: `class Pool { acquire(priority) }` returns a promise, so `kind: 'Auto'` resolves to `wrapPromise`.
Expand All @@ -21,3 +22,5 @@ export const genericPoolConfig = [
export const genericPoolChannels = {
GENERIC_POOL_ACQUIRE: 'orchestrion:generic-pool:acquire',
} as const;

export const genericPoolSubscribeInjection = toSubscribeInjections(genericPoolConfig);
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `@google/genai` ships one bundled file per module format and the matcher compares `filePath` exactly,
// so we list every file the `node` export condition resolves to across the supported range: `index.js`
Expand Down Expand Up @@ -38,3 +39,5 @@ export const googleGenAiChannels = {
GOOGLE_GENAI_EMBED_CONTENT: 'orchestrion:@google/genai:embed-content',
GOOGLE_GENAI_CHAT: 'orchestrion:@google/genai:chat',
} as const;

export const googleGenAiSubscribeInjection = toSubscribeInjections(googleGenAiConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/graphql.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// `parse`/`validate`/`execute` are top-level named `function` declarations in graphql's compiled
// files, stable across the supported majors, so `functionName` matches. `execute` returns
Expand Down Expand Up @@ -26,3 +27,5 @@ export const graphqlChannels = {
GRAPHQL_VALIDATE: 'orchestrion:graphql:validate',
GRAPHQL_EXECUTE: 'orchestrion:graphql:execute',
} as const;

export const graphqlSubscribeInjection = toSubscribeInjections(graphqlConfig);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/hapi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

export const hapiConfig = [
// hapi's `route`/`ext` live on an anonymous class (`internals.Server = class {}`),
Expand All @@ -21,3 +22,5 @@ export const hapiChannels = {
HAPI_ROUTE: 'orchestrion:@hapi/hapi:route',
HAPI_EXT: 'orchestrion:@hapi/hapi:ext',
} as const;

export const hapiSubscribeInjection = toSubscribeInjections(hapiConfig);
Loading
Loading