Skip to content
Merged
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.67.0"
"@sentry/core": "10.67.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 Down Expand Up @@ -53,8 +74,14 @@ export function externalizedModulesWarning(externalizedModules: string[]): strin
* 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
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 (plus the `registerOrchestrionChannelIntegration`
* helper) from `@sentry/server-utils/orchestrion`, and hands both to the helper,
* which stores the factory on the global marker and live-registers it on any
* existing client (see that helper for the load-order and dedup rationale).
*
* 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). The helper is
* generic (references no factory), so importing it alongside doesn't pull siblings.
*/
function subscribeSnippet(exportName: string, esm: boolean): string {
const importStmt = esm
? `import { ${exportName}, registerOrchestrionChannelIntegration } from '@sentry/server-utils/orchestrion';`
: `const { ${exportName}, registerOrchestrionChannelIntegration } = require('@sentry/server-utils/orchestrion');`;

return `${importStmt}\nregisterOrchestrionChannelIntegration(${JSON.stringify(exportName)}, ${exportName});`;
}

/**
* 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 thread
sentry[bot] marked this conversation as resolved.
};

/**
* 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[] }>;
Comment thread
JPeer264 marked this conversation as resolved.
Comment thread
sentry[bot] marked this conversation as resolved.

/** 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);
3 changes: 3 additions & 0 deletions packages/server-utils/src/orchestrion/config/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { InstrumentationConfig } from '..';
import { toSubscribeInjections } from './subscribe-injection';

// TODO: Stub for the `firebase` orchestrion integration (ports `FirebaseInstrumentation`).
export const firebaseConfig: InstrumentationConfig[] = [];

export const firebaseChannels = {} as const;

export const firebaseSubscribeInjection = toSubscribeInjections(firebaseConfig);
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