@mastra/otel-bridge 1.5.10 → 1.5.11-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bridge.d.ts +8 -0
- package/dist/bridge.d.ts.map +1 -1
- package/dist/index.cjs +19 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +19 -2
- package/dist/index.js.map +1 -1
- package/package.json +6 -4
package/dist/bridge.d.ts
CHANGED
|
@@ -52,6 +52,8 @@ export declare class OtelBridge extends BaseExporter implements ObservabilityBri
|
|
|
52
52
|
private otelLogger;
|
|
53
53
|
private otelSpanMap;
|
|
54
54
|
private spanConverter?;
|
|
55
|
+
private hasCustomTracerProvider;
|
|
56
|
+
private warnedNoTracerProvider;
|
|
55
57
|
constructor(config?: OtelBridgeConfig);
|
|
56
58
|
/**
|
|
57
59
|
* Handle Mastra tracing events
|
|
@@ -93,6 +95,12 @@ export declare class OtelBridge extends BaseExporter implements ObservabilityBri
|
|
|
93
95
|
* @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails
|
|
94
96
|
*/
|
|
95
97
|
createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Warn once per bridge that no tracer provider is producing spans. Checked
|
|
100
|
+
* lazily on span creation rather than at startup, because the OTEL SDK is
|
|
101
|
+
* often registered after the bridge is constructed.
|
|
102
|
+
*/
|
|
103
|
+
private warnNoTracerProvider;
|
|
96
104
|
/**
|
|
97
105
|
* Handle SPAN_ENDED event
|
|
98
106
|
*
|
package/dist/bridge.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.d.ts","sourceRoot":"","sources":["../src/bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,mBAAmB,EACnB,YAAY,EACZ,QAAQ,EACR,iBAAiB,EACjB,QAAQ,EACR,OAAO,EACP,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vC,YAAY,MAAM,GAAE,gBAAqB,EAOxC;IAED;;;;;;;OAOG;IACH,UAAgB,mBAAmB,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAItE;IAED;;;;;;;;;;;;;OAaG;IACG,UAAU,CAAC,KAAK,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAuB/C;IAED;;OAEG;IACH,OAAO,CAAC,iBAAiB;IA0BzB;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,mBAAmB,QAMhC;IAED;;;;;;OAMG;IACH,UAAU,CAAC,OAAO,EAAE,iBAAiB,CAAC,QAAQ,CAAC,GAAG,OAAO,GAAG,SAAS,CAyGpE;IAED;;;;OAIG;IACH,OAAO,CAAC,oBAAoB;IAiB5B;;;;;OAKG;YACW,eAAe;IA0D7B;;;;;;OAMG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAMhC;IAED;;;;;;;;;OASG;IACH,OAAO,CAAC,sBAAsB;IAgB9B;;;;;;OAMG;IACH,gBAAgB,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAEpE;IAED;;;;;;OAMG;IACH,oBAAoB,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAEtD;IAED;;;;;;;OAOG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAG3B;YAEa,aAAa;IAoB3B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAW9B;CACF"}
|
package/dist/index.cjs
CHANGED
|
@@ -5,6 +5,7 @@ let _mastra_otel_exporter = require("@mastra/otel-exporter");
|
|
|
5
5
|
let _opentelemetry_api = require("@opentelemetry/api");
|
|
6
6
|
let _opentelemetry_api_logs = require("@opentelemetry/api-logs");
|
|
7
7
|
//#region src/bridge.ts
|
|
8
|
+
const SETUP_DOCS_URL = "https://mastra.ai/reference/observability/tracing/bridges/otel#setup-requirements";
|
|
8
9
|
/**
|
|
9
10
|
* OpenTelemetry Bridge implementation
|
|
10
11
|
*
|
|
@@ -37,8 +38,11 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
37
38
|
otelLogger;
|
|
38
39
|
otelSpanMap = /* @__PURE__ */ new Map();
|
|
39
40
|
spanConverter;
|
|
41
|
+
hasCustomTracerProvider;
|
|
42
|
+
warnedNoTracerProvider = false;
|
|
40
43
|
constructor(config = {}) {
|
|
41
44
|
super(config);
|
|
45
|
+
this.hasCustomTracerProvider = config.tracerProvider !== void 0;
|
|
42
46
|
this.tracerProvider = config.tracerProvider ?? _opentelemetry_api.trace.getTracerProvider();
|
|
43
47
|
this.otelTracer = this.tracerProvider.getTracer("@mastra/otel-bridge", "1.0.0");
|
|
44
48
|
this.loggerProvider = config.loggerProvider ?? _opentelemetry_api_logs.logs.getLoggerProvider();
|
|
@@ -151,7 +155,9 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
151
155
|
}, parentOtelContext);
|
|
152
156
|
const spanContext = _opentelemetry_api.trace.setSpan(parentOtelContext, otelSpan);
|
|
153
157
|
const otelSpanContext = otelSpan.spanContext();
|
|
154
|
-
|
|
158
|
+
const parentOtelSpanContext = _opentelemetry_api.trace.getSpanContext(parentOtelContext);
|
|
159
|
+
if (!(0, _opentelemetry_api.isSpanContextValid)(otelSpanContext) || parentOtelSpanContext !== void 0 && otelSpanContext.spanId === parentOtelSpanContext.spanId) {
|
|
160
|
+
this.warnNoTracerProvider();
|
|
155
161
|
otelSpan.end();
|
|
156
162
|
return;
|
|
157
163
|
}
|
|
@@ -176,6 +182,17 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
176
182
|
}
|
|
177
183
|
}
|
|
178
184
|
/**
|
|
185
|
+
* Warn once per bridge that no tracer provider is producing spans. Checked
|
|
186
|
+
* lazily on span creation rather than at startup, because the OTEL SDK is
|
|
187
|
+
* often registered after the bridge is constructed.
|
|
188
|
+
*/
|
|
189
|
+
warnNoTracerProvider() {
|
|
190
|
+
if (this.warnedNoTracerProvider) return;
|
|
191
|
+
this.warnedNoTracerProvider = true;
|
|
192
|
+
const cause = this.hasCustomTracerProvider ? "The tracerProvider passed to OtelBridge returned a no-op span" : "No OpenTelemetry tracer provider is registered globally";
|
|
193
|
+
this.logger.warn(`[OtelBridge] ${cause}, so Mastra spans will not be exported through OpenTelemetry. Register a tracer provider before running agents or workflows (for example, call \`sdk.start()\` on \`NodeSDK\` from \`@opentelemetry/sdk-node\`, or \`trace.setGlobalTracerProvider(provider)\`), or pass it directly with \`new OtelBridge({ tracerProvider })\`. See ${SETUP_DOCS_URL}`);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
179
196
|
* Handle SPAN_ENDED event
|
|
180
197
|
*
|
|
181
198
|
* Retrieves the OTEL span created at SPAN_STARTED, sets all final attributes,
|
|
@@ -186,7 +203,7 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
186
203
|
const mastraSpan = event.exportedSpan;
|
|
187
204
|
const entry = this.otelSpanMap.get(mastraSpan.id);
|
|
188
205
|
if (!entry) {
|
|
189
|
-
this.logger.
|
|
206
|
+
this.logger.debug(`[OtelBridge] No OTEL span found for Mastra span [id=${mastraSpan.id}].`);
|
|
190
207
|
return;
|
|
191
208
|
}
|
|
192
209
|
this.otelSpanMap.delete(mastraSpan.id);
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["BaseExporter","otelTrace","otelLogs","TracingEventType","TraceFlags","otelContext","SpanConverter"],"sources":["../src/bridge.ts"],"sourcesContent":["/**\n * OpenTelemetry Bridge for Mastra Observability\n *\n * This bridge enables bidirectional integration with OpenTelemetry infrastructure:\n * 1. Reads OTEL trace context from active spans (via AsyncLocalStorage)\n * 2. Creates real OTEL spans when Mastra spans are created\n * 3. Maintains span context for proper parent-child relationships\n * 4. Allows OTEL-instrumented code (DB, HTTP clients) in tools/workflows to have correct parents\n *\n * This creates complete distributed traces where Mastra spans are properly\n * nested within OTEL spans from auto-instrumentation, and any OTEL-instrumented\n * operations within Mastra spans maintain the correct hierarchy.\n */\n\nimport type {\n ObservabilityBridge,\n TracingEvent,\n LogEvent,\n CreateSpanOptions,\n SpanType,\n SpanIds,\n InitExporterOptions,\n} from '@mastra/core/observability';\nimport { TracingEventType } from '@mastra/core/observability';\nimport { BaseExporter, getExternalParentId } from '@mastra/observability';\nimport type { BaseExporterConfig } from '@mastra/observability';\nimport { SpanConverter, convertLog, getSpanKind } from '@mastra/otel-exporter';\nimport { trace as otelTrace, context as otelContext, isSpanContextValid, TraceFlags } from '@opentelemetry/api';\nimport type { Span as OtelSpan, Context as OtelContext, TracerProvider, Tracer } from '@opentelemetry/api';\nimport { logs as otelLogs } from '@opentelemetry/api-logs';\nimport type { Logger as OtelLogger, LoggerProvider } from '@opentelemetry/api-logs';\n\nexport type OtelBridgeConfig = BaseExporterConfig & {\n tracerProvider?: TracerProvider;\n loggerProvider?: LoggerProvider;\n};\n\n/**\n * OpenTelemetry Bridge implementation\n *\n * Creates real OTEL spans when Mastra spans are created, maintaining proper\n * context propagation for nested instrumentation.\n *\n * @example\n * ```typescript\n * import { OtelBridge } from '@mastra/otel-bridge';\n * import { Mastra } from '@mastra/core';\n *\n * const mastra = new Mastra({\n * agents: { myAgent },\n * observability: {\n * configs: {\n * default: {\n * serviceName: 'my-service',\n * bridge: new OtelBridge(),\n * }\n * }\n * }\n * });\n * ```\n */\nexport class OtelBridge extends BaseExporter implements ObservabilityBridge {\n name = 'otel';\n private tracerProvider: TracerProvider;\n private loggerProvider: LoggerProvider;\n private otelTracer: Tracer;\n private otelLogger: OtelLogger;\n private otelSpanMap = new Map<string, { otelSpan: OtelSpan; otelContext: OtelContext }>();\n private spanConverter?: SpanConverter;\n\n constructor(config: OtelBridgeConfig = {}) {\n super(config);\n this.tracerProvider = config.tracerProvider ?? otelTrace.getTracerProvider();\n this.otelTracer = this.tracerProvider.getTracer('@mastra/otel-bridge', '1.0.0');\n this.loggerProvider = config.loggerProvider ?? otelLogs.getLoggerProvider();\n this.otelLogger = this.loggerProvider.getLogger('@mastra/otel-bridge', '1.0.0');\n }\n\n /**\n * Handle Mastra tracing events\n *\n * Ships OTEL spans when Mastra spans end.\n * This maintains proper span hierarchy and allows OTEL-instrumented code within\n * Mastra spans to have correct parent-child relationships.\n * Note: OTEL spans are created when registerSpan is called when the span is first created.\n */\n protected async _exportTracingEvent(event: TracingEvent): Promise<void> {\n if (event.type === TracingEventType.SPAN_ENDED) {\n await this.handleSpanEnded(event);\n }\n }\n\n /**\n * Forward Mastra log events into the globally-registered OTEL LoggerProvider.\n *\n * If the user has not registered a LoggerProvider (e.g. via @opentelemetry/sdk-logs\n * or NodeSDK's logRecordProcessor option), the API returns a no-op logger and\n * emit() is a silent no-op — the bridge degrades gracefully.\n *\n * Trace correlation:\n * - If the log carries a spanId we have an OTEL span for, emit under that span's\n * stored context so the log nests beneath it in the trace.\n * - Else if the log carries traceId+spanId, attach a SpanContext built from those\n * IDs so backends still correlate by ID.\n * - Else emit under whatever context is currently active.\n */\n async onLogEvent(event: LogEvent): Promise<void> {\n if (this.isDisabled) return;\n\n try {\n const params = convertLog(event.log);\n\n const attributes = { ...params.attributes };\n if (params.traceId) attributes['mastra.traceId'] = params.traceId;\n if (params.spanId) attributes['mastra.spanId'] = params.spanId;\n\n const logContext = this.resolveLogContext(params.traceId, params.spanId);\n\n this.otelLogger.emit({\n timestamp: params.timestamp,\n severityNumber: params.severityNumber,\n severityText: params.severityText,\n body: params.body,\n attributes,\n context: logContext,\n });\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to emit log:', error);\n }\n }\n\n /**\n * Pick the OTEL Context to emit a log under so trace correlation is correct.\n */\n private resolveLogContext(traceId?: string, spanId?: string): OtelContext {\n // 1. Prefer the stored OTEL context for the originating Mastra span.\n if (spanId) {\n const entry = this.otelSpanMap.get(spanId);\n if (entry) return entry.otelContext;\n }\n\n // 2. Fall back to a context with a span context built from the raw IDs,\n // but only when both IDs form a valid W3C span context. Injecting\n // malformed IDs would surface as garbage trace links downstream.\n if (traceId && spanId) {\n const candidate = {\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n if (isSpanContextValid(candidate)) {\n return otelTrace.setSpanContext(otelContext.active(), candidate);\n }\n }\n\n // 3. Fall through to whatever is currently active.\n return otelContext.active();\n }\n\n /**\n * Initialize with tracing configuration\n */\n init(options: InitExporterOptions) {\n this.spanConverter = new SpanConverter({\n packageName: '@mastra/otel-bridge',\n serviceName: options.config?.serviceName,\n format: 'GenAI_v1_38_0',\n });\n }\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined {\n try {\n // Determine parent context\n let parentOtelContext = otelContext.active();\n let usedPersistedParent = false;\n\n // Get external parent ID (walks up chain to find non-internal parent)\n const externalParentId = getExternalParentId(options);\n if (externalParentId) {\n // Look up external parent's OTEL span from map\n const parentEntry = this.otelSpanMap.get(externalParentId);\n if (parentEntry) {\n parentOtelContext = parentEntry.otelContext;\n }\n } else if (options.traceId && options.parentSpanId) {\n // Root spans restored from persisted state (e.g. workflow suspend/resume)\n // carry the original trace ID and parent span ID, but the parent OTEL span\n // is no longer alive — it ended when the run suspended, possibly in another\n // process. Parent under a remote span context built from the persisted IDs\n // so the span continues the original trace instead of joining whatever\n // context happens to be active. Skip malformed IDs; injecting them would\n // surface as garbage trace links downstream.\n const candidate = {\n traceId: options.traceId,\n spanId: options.parentSpanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: true,\n };\n if (isSpanContextValid(candidate)) {\n parentOtelContext = otelTrace.setSpanContext(parentOtelContext, candidate);\n usedPersistedParent = true;\n }\n }\n\n // Create OTEL span with SpanKind (must be set at creation, immutable)\n const otelSpan = this.otelTracer.startSpan(\n options.name,\n {\n kind: getSpanKind(options.type),\n ...(options.startTime ? { startTime: options.startTime } : {}),\n },\n parentOtelContext,\n );\n\n // Create context with this span active\n const spanContext = otelTrace.setSpan(parentOtelContext, otelSpan);\n\n // Get OTEL span identifiers\n const otelSpanContext = otelSpan.spanContext();\n\n // If no OTEL SDK is registered, the global tracer returns a non-recording\n // span with an invalid span context (all-zero span/trace IDs). Returning\n // those IDs would collide across every Mastra span and break downstream\n // exporters. Bail out so DefaultSpan falls through to its own ID generator.\n if (!isSpanContextValid(otelSpanContext)) {\n // End the span we just started so its lifecycle stays clean on\n // providers that do track non-recording spans.\n otelSpan.end();\n return undefined;\n }\n\n const spanId = otelSpanContext.spanId;\n const traceId = otelSpanContext.traceId;\n\n // Store for later retrieval (for executeWithSpanContext and event handling)\n this.otelSpanMap.set(spanId, { otelSpan, otelContext: spanContext });\n\n // Get parentSpanId from parent context if available\n const parentSpan = otelTrace.getSpan(parentOtelContext);\n const parentSpanContext = parentSpan?.spanContext();\n const parentSpanId =\n parentSpanContext && isSpanContextValid(parentSpanContext) ? parentSpanContext.spanId : undefined;\n\n // Declare which kind of parent was used: a span this bridge created for\n // a Mastra span is part of the Mastra trace, while anything else in the\n // ambient OTEL context belongs to the external tracing system. A parent\n // restored from persisted state is a Mastra span in storage — it ended at\n // suspend (possibly in another process), so it is absent from the live map.\n const parentIsMastraSpan =\n parentSpanId !== undefined && (this.otelSpanMap.has(parentSpanId) || usedPersistedParent);\n\n this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [parentIsMastraSpan=${parentIsMastraSpan}] ` +\n `[type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return {\n spanId,\n traceId,\n ...(parentIsMastraSpan ? { parentSpanId } : { externalParentSpanId: parentSpanId }),\n };\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to create span:', error);\n return undefined;\n }\n }\n\n /**\n * Handle SPAN_ENDED event\n *\n * Retrieves the OTEL span created at SPAN_STARTED, sets all final attributes,\n * events, and status, then ends the span. Cleans up the span map entry.\n */\n private async handleSpanEnded(event: TracingEvent): Promise<void> {\n try {\n const mastraSpan = event.exportedSpan;\n const entry = this.otelSpanMap.get(mastraSpan.id);\n\n if (!entry) {\n this.logger.warn(`[OtelBridge] No OTEL span found for Mastra span [id=${mastraSpan.id}].`);\n return;\n }\n\n // Remove from map immediately to prevent memory leak\n this.otelSpanMap.delete(mastraSpan.id);\n\n if (!this.spanConverter) {\n return;\n }\n\n const { otelSpan } = entry;\n\n this.logger.debug(`[OtelBridge] Ending OTEL span [mastraId=${mastraSpan.id}] [name=${mastraSpan.name}]`);\n\n // Use SpanConverter to get consistent span formatting with otel-exporter\n const readableSpan = await this.spanConverter!.convertSpan(mastraSpan);\n\n // Update span name to match the converter's formatting\n otelSpan.updateName(readableSpan.name);\n\n // Set all attributes from the converter (includes OTEL semantic conventions)\n for (const [key, value] of Object.entries(readableSpan.attributes)) {\n if (value !== undefined && value !== null && typeof value !== 'object') {\n otelSpan.setAttribute(key, value);\n }\n }\n\n // Set status from the converter\n otelSpan.setStatus(readableSpan.status);\n\n // Add exception events if present\n for (const event of readableSpan.events) {\n if (event.name === 'exception' && event.attributes) {\n const error = new Error(event.attributes['exception.message'] as string);\n otelSpan.recordException(error);\n }\n }\n\n // End the span with the actual end time\n otelSpan.end(mastraSpan.endTime);\n\n this.logger.debug(\n `[OtelBridge] Completed OTEL span [mastraId=${mastraSpan.id}] [traceId=${otelSpan.spanContext().traceId}]`,\n );\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to handle SPAN_ENDED:', error);\n }\n }\n\n /**\n * Release the OTEL span held for a Mastra span that ended without being exported.\n *\n * The OTEL span is deliberately not ended: ending it would hand it to the OTEL\n * span processors and export a span the user's filtering just removed. Dropping\n * the reference is enough, since span processors only queue spans on end.\n */\n releaseSpan(spanId: string): void {\n if (this.otelSpanMap.delete(spanId)) {\n this.logger.debug(\n `[OtelBridge.releaseSpan] Released unexported span [spanId=${spanId}] [mapSize=${this.otelSpanMap.size}]`,\n );\n }\n }\n\n /**\n * Execute a function (sync or async) within the OTEL context of a Mastra span.\n * Retrieves the stored OTEL context for the span and executes the function within it.\n *\n * This is the core implementation used by both executeInContext and executeInContextSync.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The function to execute within the span context\n * @returns The result of the function execution\n */\n private executeWithSpanContext<T>(spanId: string, fn: () => T): T {\n const entry = this.otelSpanMap.get(spanId);\n\n this.logger.debug(\n `[OtelBridge.executeWithSpanContext] spanId=${spanId}, ` +\n `inMap=${!!entry}, ` +\n `storedOtelSpan=${entry?.otelSpan.spanContext().spanId || 'none'}`,\n );\n\n const spanContext = entry?.otelContext;\n if (spanContext) {\n return otelContext.with(spanContext, fn);\n }\n return fn();\n }\n\n /**\n * Execute an async function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext<T>(spanId: string, fn: () => Promise<T>): Promise<T> {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Execute a synchronous function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync<T>(spanId: string, fn: () => T): T {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Force flush any buffered spans without shutting down the bridge.\n *\n * Attempts to flush the underlying OTEL tracer provider if it supports\n * the forceFlush operation. This is useful in serverless environments\n * where you need to ensure all spans are exported before the runtime\n * instance is terminated.\n */\n async flush(): Promise<void> {\n await this.flushProvider(this.tracerProvider, 'tracer');\n await this.flushProvider(this.loggerProvider, 'logger');\n }\n\n private async flushProvider(provider: unknown, label: 'tracer' | 'logger'): Promise<void> {\n try {\n if (\n provider &&\n typeof provider === 'object' &&\n 'forceFlush' in provider &&\n typeof (provider as { forceFlush: unknown }).forceFlush === 'function'\n ) {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n this.logger.debug(`[OtelBridge] Flushed ${label} provider`);\n } else {\n this.logger.debug(\n `[OtelBridge] ${label === 'tracer' ? 'Tracer' : 'Logger'} provider does not support forceFlush`,\n );\n }\n } catch (error) {\n this.logger.error(`[OtelBridge] Failed to flush ${label} provider:`, error);\n }\n }\n\n /**\n * Shutdown the bridge and clean up resources\n */\n async shutdown(): Promise<void> {\n // Flush before shutdown\n await this.flush();\n\n // End any remaining spans\n for (const [spanId, { otelSpan }] of this.otelSpanMap.entries()) {\n this.logger.warn(`[OtelBridge] Force-ending span that was not properly closed [id=${spanId}]`);\n otelSpan.end();\n }\n this.otelSpanMap.clear();\n this.logger.info('[OtelBridge] Shutdown complete');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,aAAb,cAAgCA,sBAAAA,aAA4C;CAC1E,OAAO;CACP;CACA;CACA;CACA;CACA,8BAAsB,IAAI,IAA8D;CACxF;CAEA,YAAY,SAA2B,CAAC,GAAG;EACzC,MAAM,MAAM;EACZ,KAAK,iBAAiB,OAAO,kBAAkBC,mBAAAA,MAAU,kBAAkB;EAC3E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;EAC9E,KAAK,iBAAiB,OAAO,kBAAkBC,wBAAAA,KAAS,kBAAkB;EAC1E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;CAChF;;;;;;;;;CAUA,MAAgB,oBAAoB,OAAoC;EACtE,IAAI,MAAM,SAASC,2BAAAA,iBAAiB,YAClC,MAAM,KAAK,gBAAgB,KAAK;CAEpC;;;;;;;;;;;;;;;CAgBA,MAAM,WAAW,OAAgC;EAC/C,IAAI,KAAK,YAAY;EAErB,IAAI;GACF,M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C,OAAO,UAC1C,CAAC,CAAC,MAAM,mBACC,OAAO,SAAS,YAAY,CAAC,CAAC,UAAU,QAC9D;EAEA,MAAM,cAAc,OAAO;EAC3B,IAAI,aACF,OAAOI,mBAAAA,QAAY,KAAK,aAAa,EAAE;EAEzC,OAAO,GAAG;CACZ;;;;;;;;CASA,iBAAoB,QAAgB,IAAkC;EACpE,OAAO,KAAK,uBAAuB,QAAQ,EAAE;CAC/C;;;;;;;;CASA,qBAAwB,QAAgB,IAAgB;EACtD,OAAO,KAAK,uBAAuB,QAAQ,EAAE;CAC/C;;;;;;;;;CAUA,MAAM,QAAuB;EAC3B,MAAM,KAAK,cAAc,KAAK,gBAAgB,QAAQ;EACtD,MAAM,KAAK,cAAc,KAAK,gBAAgB,QAAQ;CACxD;CAEA,MAAc,cAAc,UAAmB,OAA2C;EACxF,IAAI;GACF,IACE,YACA,OAAO,aAAa,YACpB,gBAAgB,YAChB,OAAQ,SAAqC,eAAe,YAC5D;IACA,MAAO,SAAiD,WAAW;IACnE,KAAK,OAAO,MAAM,wBAAwB,MAAM,UAAU;GAC5D,OACE,KAAK,OAAO,MACV,gBAAgB,UAAU,WAAW,WAAW,SAAS,sCAC3D;EAEJ,SAAS,OAAO;GACd,KAAK,OAAO,MAAM,gCAAgC,MAAM,aAAa,KAAK;EAC5E;CACF;;;;CAKA,MAAM,WAA0B;EAE9B,MAAM,KAAK,MAAM;EAGjB,KAAK,MAAM,CAAC,QAAQ,EAAE,eAAe,KAAK,YAAY,QAAQ,GAAG;GAC/D,KAAK,OAAO,KAAK,mEAAmE,OAAO,EAAE;GAC7F,SAAS,IAAI;EACf;EACA,KAAK,YAAY,MAAM;EACvB,KAAK,OAAO,KAAK,gCAAgC;CACnD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["BaseExporter","otelTrace","otelLogs","TracingEventType","TraceFlags","otelContext","SpanConverter"],"sources":["../src/bridge.ts"],"sourcesContent":["/**\n * OpenTelemetry Bridge for Mastra Observability\n *\n * This bridge enables bidirectional integration with OpenTelemetry infrastructure:\n * 1. Reads OTEL trace context from active spans (via AsyncLocalStorage)\n * 2. Creates real OTEL spans when Mastra spans are created\n * 3. Maintains span context for proper parent-child relationships\n * 4. Allows OTEL-instrumented code (DB, HTTP clients) in tools/workflows to have correct parents\n *\n * This creates complete distributed traces where Mastra spans are properly\n * nested within OTEL spans from auto-instrumentation, and any OTEL-instrumented\n * operations within Mastra spans maintain the correct hierarchy.\n */\n\nimport type {\n ObservabilityBridge,\n TracingEvent,\n LogEvent,\n CreateSpanOptions,\n SpanType,\n SpanIds,\n InitExporterOptions,\n} from '@mastra/core/observability';\nimport { TracingEventType } from '@mastra/core/observability';\nimport { BaseExporter, getExternalParentId } from '@mastra/observability';\nimport type { BaseExporterConfig } from '@mastra/observability';\nimport { SpanConverter, convertLog, getSpanKind } from '@mastra/otel-exporter';\nimport { trace as otelTrace, context as otelContext, isSpanContextValid, TraceFlags } from '@opentelemetry/api';\nimport type { Span as OtelSpan, Context as OtelContext, TracerProvider, Tracer } from '@opentelemetry/api';\nimport { logs as otelLogs } from '@opentelemetry/api-logs';\nimport type { Logger as OtelLogger, LoggerProvider } from '@opentelemetry/api-logs';\n\nconst SETUP_DOCS_URL = 'https://mastra.ai/reference/observability/tracing/bridges/otel#setup-requirements';\n\nexport type OtelBridgeConfig = BaseExporterConfig & {\n tracerProvider?: TracerProvider;\n loggerProvider?: LoggerProvider;\n};\n\n/**\n * OpenTelemetry Bridge implementation\n *\n * Creates real OTEL spans when Mastra spans are created, maintaining proper\n * context propagation for nested instrumentation.\n *\n * @example\n * ```typescript\n * import { OtelBridge } from '@mastra/otel-bridge';\n * import { Mastra } from '@mastra/core';\n *\n * const mastra = new Mastra({\n * agents: { myAgent },\n * observability: {\n * configs: {\n * default: {\n * serviceName: 'my-service',\n * bridge: new OtelBridge(),\n * }\n * }\n * }\n * });\n * ```\n */\nexport class OtelBridge extends BaseExporter implements ObservabilityBridge {\n name = 'otel';\n private tracerProvider: TracerProvider;\n private loggerProvider: LoggerProvider;\n private otelTracer: Tracer;\n private otelLogger: OtelLogger;\n private otelSpanMap = new Map<string, { otelSpan: OtelSpan; otelContext: OtelContext }>();\n private spanConverter?: SpanConverter;\n private hasCustomTracerProvider: boolean;\n private warnedNoTracerProvider = false;\n\n constructor(config: OtelBridgeConfig = {}) {\n super(config);\n this.hasCustomTracerProvider = config.tracerProvider !== undefined;\n this.tracerProvider = config.tracerProvider ?? otelTrace.getTracerProvider();\n this.otelTracer = this.tracerProvider.getTracer('@mastra/otel-bridge', '1.0.0');\n this.loggerProvider = config.loggerProvider ?? otelLogs.getLoggerProvider();\n this.otelLogger = this.loggerProvider.getLogger('@mastra/otel-bridge', '1.0.0');\n }\n\n /**\n * Handle Mastra tracing events\n *\n * Ships OTEL spans when Mastra spans end.\n * This maintains proper span hierarchy and allows OTEL-instrumented code within\n * Mastra spans to have correct parent-child relationships.\n * Note: OTEL spans are created when registerSpan is called when the span is first created.\n */\n protected async _exportTracingEvent(event: TracingEvent): Promise<void> {\n if (event.type === TracingEventType.SPAN_ENDED) {\n await this.handleSpanEnded(event);\n }\n }\n\n /**\n * Forward Mastra log events into the globally-registered OTEL LoggerProvider.\n *\n * If the user has not registered a LoggerProvider (e.g. via @opentelemetry/sdk-logs\n * or NodeSDK's logRecordProcessor option), the API returns a no-op logger and\n * emit() is a silent no-op — the bridge degrades gracefully.\n *\n * Trace correlation:\n * - If the log carries a spanId we have an OTEL span for, emit under that span's\n * stored context so the log nests beneath it in the trace.\n * - Else if the log carries traceId+spanId, attach a SpanContext built from those\n * IDs so backends still correlate by ID.\n * - Else emit under whatever context is currently active.\n */\n async onLogEvent(event: LogEvent): Promise<void> {\n if (this.isDisabled) return;\n\n try {\n const params = convertLog(event.log);\n\n const attributes = { ...params.attributes };\n if (params.traceId) attributes['mastra.traceId'] = params.traceId;\n if (params.spanId) attributes['mastra.spanId'] = params.spanId;\n\n const logContext = this.resolveLogContext(params.traceId, params.spanId);\n\n this.otelLogger.emit({\n timestamp: params.timestamp,\n severityNumber: params.severityNumber,\n severityText: params.severityText,\n body: params.body,\n attributes,\n context: logContext,\n });\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to emit log:', error);\n }\n }\n\n /**\n * Pick the OTEL Context to emit a log under so trace correlation is correct.\n */\n private resolveLogContext(traceId?: string, spanId?: string): OtelContext {\n // 1. Prefer the stored OTEL context for the originating Mastra span.\n if (spanId) {\n const entry = this.otelSpanMap.get(spanId);\n if (entry) return entry.otelContext;\n }\n\n // 2. Fall back to a context with a span context built from the raw IDs,\n // but only when both IDs form a valid W3C span context. Injecting\n // malformed IDs would surface as garbage trace links downstream.\n if (traceId && spanId) {\n const candidate = {\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n if (isSpanContextValid(candidate)) {\n return otelTrace.setSpanContext(otelContext.active(), candidate);\n }\n }\n\n // 3. Fall through to whatever is currently active.\n return otelContext.active();\n }\n\n /**\n * Initialize with tracing configuration\n */\n init(options: InitExporterOptions) {\n this.spanConverter = new SpanConverter({\n packageName: '@mastra/otel-bridge',\n serviceName: options.config?.serviceName,\n format: 'GenAI_v1_38_0',\n });\n }\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined {\n try {\n // Determine parent context\n let parentOtelContext = otelContext.active();\n let usedPersistedParent = false;\n\n // Get external parent ID (walks up chain to find non-internal parent)\n const externalParentId = getExternalParentId(options);\n if (externalParentId) {\n // Look up external parent's OTEL span from map\n const parentEntry = this.otelSpanMap.get(externalParentId);\n if (parentEntry) {\n parentOtelContext = parentEntry.otelContext;\n }\n } else if (options.traceId && options.parentSpanId) {\n // Root spans restored from persisted state (e.g. workflow suspend/resume)\n // carry the original trace ID and parent span ID, but the parent OTEL span\n // is no longer alive — it ended when the run suspended, possibly in another\n // process. Parent under a remote span context built from the persisted IDs\n // so the span continues the original trace instead of joining whatever\n // context happens to be active. Skip malformed IDs; injecting them would\n // surface as garbage trace links downstream.\n const candidate = {\n traceId: options.traceId,\n spanId: options.parentSpanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: true,\n };\n if (isSpanContextValid(candidate)) {\n parentOtelContext = otelTrace.setSpanContext(parentOtelContext, candidate);\n usedPersistedParent = true;\n }\n }\n\n // Create OTEL span with SpanKind (must be set at creation, immutable)\n const otelSpan = this.otelTracer.startSpan(\n options.name,\n {\n kind: getSpanKind(options.type),\n ...(options.startTime ? { startTime: options.startTime } : {}),\n },\n parentOtelContext,\n );\n\n // Create context with this span active\n const spanContext = otelTrace.setSpan(parentOtelContext, otelSpan);\n\n // Get OTEL span identifiers\n const otelSpanContext = otelSpan.spanContext();\n\n // If no OTEL SDK is registered, the global tracer is a no-op. With no\n // parent it returns a span with an invalid (all-zero) span context; with\n // a parent in the context (e.g. an outer span from another, unregistered\n // provider) it returns a span wrapping the parent's span context. Either\n // way, returning those IDs would collide across every Mastra span and\n // break downstream exporters. Bail out so DefaultSpan falls through to\n // its own ID generator. A real tracer always mints a fresh span ID, even\n // for spans its sampler drops.\n const parentOtelSpanContext = otelTrace.getSpanContext(parentOtelContext);\n if (\n !isSpanContextValid(otelSpanContext) ||\n (parentOtelSpanContext !== undefined && otelSpanContext.spanId === parentOtelSpanContext.spanId)\n ) {\n this.warnNoTracerProvider();\n // End the span we just started so its lifecycle stays clean on\n // providers that do track non-recording spans.\n otelSpan.end();\n return undefined;\n }\n\n const spanId = otelSpanContext.spanId;\n const traceId = otelSpanContext.traceId;\n\n // Store for later retrieval (for executeWithSpanContext and event handling)\n this.otelSpanMap.set(spanId, { otelSpan, otelContext: spanContext });\n\n // Get parentSpanId from parent context if available\n const parentSpan = otelTrace.getSpan(parentOtelContext);\n const parentSpanContext = parentSpan?.spanContext();\n const parentSpanId =\n parentSpanContext && isSpanContextValid(parentSpanContext) ? parentSpanContext.spanId : undefined;\n\n // Declare which kind of parent was used: a span this bridge created for\n // a Mastra span is part of the Mastra trace, while anything else in the\n // ambient OTEL context belongs to the external tracing system. A parent\n // restored from persisted state is a Mastra span in storage — it ended at\n // suspend (possibly in another process), so it is absent from the live map.\n const parentIsMastraSpan =\n parentSpanId !== undefined && (this.otelSpanMap.has(parentSpanId) || usedPersistedParent);\n\n this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [parentIsMastraSpan=${parentIsMastraSpan}] ` +\n `[type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return {\n spanId,\n traceId,\n ...(parentIsMastraSpan ? { parentSpanId } : { externalParentSpanId: parentSpanId }),\n };\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to create span:', error);\n return undefined;\n }\n }\n\n /**\n * Warn once per bridge that no tracer provider is producing spans. Checked\n * lazily on span creation rather than at startup, because the OTEL SDK is\n * often registered after the bridge is constructed.\n */\n private warnNoTracerProvider(): void {\n if (this.warnedNoTracerProvider) return;\n this.warnedNoTracerProvider = true;\n\n const cause = this.hasCustomTracerProvider\n ? 'The tracerProvider passed to OtelBridge returned a no-op span'\n : 'No OpenTelemetry tracer provider is registered globally';\n\n this.logger.warn(\n `[OtelBridge] ${cause}, so Mastra spans will not be exported through OpenTelemetry. ` +\n 'Register a tracer provider before running agents or workflows (for example, call `sdk.start()` on ' +\n '`NodeSDK` from `@opentelemetry/sdk-node`, or `trace.setGlobalTracerProvider(provider)`), ' +\n 'or pass it directly with `new OtelBridge({ tracerProvider })`. ' +\n `See ${SETUP_DOCS_URL}`,\n );\n }\n\n /**\n * Handle SPAN_ENDED event\n *\n * Retrieves the OTEL span created at SPAN_STARTED, sets all final attributes,\n * events, and status, then ends the span. Cleans up the span map entry.\n */\n private async handleSpanEnded(event: TracingEvent): Promise<void> {\n try {\n const mastraSpan = event.exportedSpan;\n const entry = this.otelSpanMap.get(mastraSpan.id);\n\n if (!entry) {\n // Expected when no tracer provider is registered; warnNoTracerProvider()\n // already reported that once, so don't repeat it for every span.\n this.logger.debug(`[OtelBridge] No OTEL span found for Mastra span [id=${mastraSpan.id}].`);\n return;\n }\n\n // Remove from map immediately to prevent memory leak\n this.otelSpanMap.delete(mastraSpan.id);\n\n if (!this.spanConverter) {\n return;\n }\n\n const { otelSpan } = entry;\n\n this.logger.debug(`[OtelBridge] Ending OTEL span [mastraId=${mastraSpan.id}] [name=${mastraSpan.name}]`);\n\n // Use SpanConverter to get consistent span formatting with otel-exporter\n const readableSpan = await this.spanConverter!.convertSpan(mastraSpan);\n\n // Update span name to match the converter's formatting\n otelSpan.updateName(readableSpan.name);\n\n // Set all attributes from the converter (includes OTEL semantic conventions)\n for (const [key, value] of Object.entries(readableSpan.attributes)) {\n if (value !== undefined && value !== null && typeof value !== 'object') {\n otelSpan.setAttribute(key, value);\n }\n }\n\n // Set status from the converter\n otelSpan.setStatus(readableSpan.status);\n\n // Add exception events if present\n for (const event of readableSpan.events) {\n if (event.name === 'exception' && event.attributes) {\n const error = new Error(event.attributes['exception.message'] as string);\n otelSpan.recordException(error);\n }\n }\n\n // End the span with the actual end time\n otelSpan.end(mastraSpan.endTime);\n\n this.logger.debug(\n `[OtelBridge] Completed OTEL span [mastraId=${mastraSpan.id}] [traceId=${otelSpan.spanContext().traceId}]`,\n );\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to handle SPAN_ENDED:', error);\n }\n }\n\n /**\n * Release the OTEL span held for a Mastra span that ended without being exported.\n *\n * The OTEL span is deliberately not ended: ending it would hand it to the OTEL\n * span processors and export a span the user's filtering just removed. Dropping\n * the reference is enough, since span processors only queue spans on end.\n */\n releaseSpan(spanId: string): void {\n if (this.otelSpanMap.delete(spanId)) {\n this.logger.debug(\n `[OtelBridge.releaseSpan] Released unexported span [spanId=${spanId}] [mapSize=${this.otelSpanMap.size}]`,\n );\n }\n }\n\n /**\n * Execute a function (sync or async) within the OTEL context of a Mastra span.\n * Retrieves the stored OTEL context for the span and executes the function within it.\n *\n * This is the core implementation used by both executeInContext and executeInContextSync.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The function to execute within the span context\n * @returns The result of the function execution\n */\n private executeWithSpanContext<T>(spanId: string, fn: () => T): T {\n const entry = this.otelSpanMap.get(spanId);\n\n this.logger.debug(\n `[OtelBridge.executeWithSpanContext] spanId=${spanId}, ` +\n `inMap=${!!entry}, ` +\n `storedOtelSpan=${entry?.otelSpan.spanContext().spanId || 'none'}`,\n );\n\n const spanContext = entry?.otelContext;\n if (spanContext) {\n return otelContext.with(spanContext, fn);\n }\n return fn();\n }\n\n /**\n * Execute an async function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext<T>(spanId: string, fn: () => Promise<T>): Promise<T> {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Execute a synchronous function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync<T>(spanId: string, fn: () => T): T {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Force flush any buffered spans without shutting down the bridge.\n *\n * Attempts to flush the underlying OTEL tracer provider if it supports\n * the forceFlush operation. This is useful in serverless environments\n * where you need to ensure all spans are exported before the runtime\n * instance is terminated.\n */\n async flush(): Promise<void> {\n await this.flushProvider(this.tracerProvider, 'tracer');\n await this.flushProvider(this.loggerProvider, 'logger');\n }\n\n private async flushProvider(provider: unknown, label: 'tracer' | 'logger'): Promise<void> {\n try {\n if (\n provider &&\n typeof provider === 'object' &&\n 'forceFlush' in provider &&\n typeof (provider as { forceFlush: unknown }).forceFlush === 'function'\n ) {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n this.logger.debug(`[OtelBridge] Flushed ${label} provider`);\n } else {\n this.logger.debug(\n `[OtelBridge] ${label === 'tracer' ? 'Tracer' : 'Logger'} provider does not support forceFlush`,\n );\n }\n } catch (error) {\n this.logger.error(`[OtelBridge] Failed to flush ${label} provider:`, error);\n }\n }\n\n /**\n * Shutdown the bridge and clean up resources\n */\n async shutdown(): Promise<void> {\n // Flush before shutdown\n await this.flush();\n\n // End any remaining spans\n for (const [spanId, { otelSpan }] of this.otelSpanMap.entries()) {\n this.logger.warn(`[OtelBridge] Force-ending span that was not properly closed [id=${spanId}]`);\n otelSpan.end();\n }\n this.otelSpanMap.clear();\n this.logger.info('[OtelBridge] Shutdown complete');\n }\n}\n"],"mappings":";;;;;;;AAgCA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;AA+BvB,IAAa,aAAb,cAAgCA,sBAAAA,aAA4C;CAC1E,OAAO;CACP;CACA;CACA;CACA;CACA,8BAAsB,IAAI,IAA8D;CACxF;CACA;CACA,yBAAiC;CAEjC,YAAY,SAA2B,CAAC,GAAG;EACzC,MAAM,MAAM;EACZ,KAAK,0BAA0B,OAAO,mBAAmB,KAAA;EACzD,KAAK,iBAAiB,OAAO,kBAAkBC,mBAAAA,MAAU,kBAAkB;EAC3E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;EAC9E,KAAK,iBAAiB,OAAO,kBAAkBC,wBAAAA,KAAS,kBAAkB;EAC1E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;CAChF;;;;;;;;;CAUA,MAAgB,oBAAoB,OAAoC;EACtE,IAAI,MAAM,SAASC,2BAAAA,iBAAiB,YAClC,MAAM,KAAK,gBAAgB,KAAK;CAEpC;;;;;;;;;;;;;;;CAgBA,MAAM,WAAW,OAAgC;EAC/C,IAAI,KAAK,YAAY;EAErB,IAAI;GACF,MAAM,UAAA,GAAA,sBAAA,WAAA,CAAoB,MAAM,GAAG;GAEnC,MAAM,aAAa,EAAE,GAAG,OAAO,WAAW;GAC1C,IAAI,OAAO,SAAS,WA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;AACF"}
|
package/dist/index.js
CHANGED
|
@@ -4,6 +4,7 @@ import { SpanConverter, convertLog, getSpanKind } from "@mastra/otel-exporter";
|
|
|
4
4
|
import { TraceFlags, context, isSpanContextValid, trace } from "@opentelemetry/api";
|
|
5
5
|
import { logs } from "@opentelemetry/api-logs";
|
|
6
6
|
//#region src/bridge.ts
|
|
7
|
+
const SETUP_DOCS_URL = "https://mastra.ai/reference/observability/tracing/bridges/otel#setup-requirements";
|
|
7
8
|
/**
|
|
8
9
|
* OpenTelemetry Bridge implementation
|
|
9
10
|
*
|
|
@@ -36,8 +37,11 @@ var OtelBridge = class extends BaseExporter {
|
|
|
36
37
|
otelLogger;
|
|
37
38
|
otelSpanMap = /* @__PURE__ */ new Map();
|
|
38
39
|
spanConverter;
|
|
40
|
+
hasCustomTracerProvider;
|
|
41
|
+
warnedNoTracerProvider = false;
|
|
39
42
|
constructor(config = {}) {
|
|
40
43
|
super(config);
|
|
44
|
+
this.hasCustomTracerProvider = config.tracerProvider !== void 0;
|
|
41
45
|
this.tracerProvider = config.tracerProvider ?? trace.getTracerProvider();
|
|
42
46
|
this.otelTracer = this.tracerProvider.getTracer("@mastra/otel-bridge", "1.0.0");
|
|
43
47
|
this.loggerProvider = config.loggerProvider ?? logs.getLoggerProvider();
|
|
@@ -150,7 +154,9 @@ var OtelBridge = class extends BaseExporter {
|
|
|
150
154
|
}, parentOtelContext);
|
|
151
155
|
const spanContext = trace.setSpan(parentOtelContext, otelSpan);
|
|
152
156
|
const otelSpanContext = otelSpan.spanContext();
|
|
153
|
-
|
|
157
|
+
const parentOtelSpanContext = trace.getSpanContext(parentOtelContext);
|
|
158
|
+
if (!isSpanContextValid(otelSpanContext) || parentOtelSpanContext !== void 0 && otelSpanContext.spanId === parentOtelSpanContext.spanId) {
|
|
159
|
+
this.warnNoTracerProvider();
|
|
154
160
|
otelSpan.end();
|
|
155
161
|
return;
|
|
156
162
|
}
|
|
@@ -175,6 +181,17 @@ var OtelBridge = class extends BaseExporter {
|
|
|
175
181
|
}
|
|
176
182
|
}
|
|
177
183
|
/**
|
|
184
|
+
* Warn once per bridge that no tracer provider is producing spans. Checked
|
|
185
|
+
* lazily on span creation rather than at startup, because the OTEL SDK is
|
|
186
|
+
* often registered after the bridge is constructed.
|
|
187
|
+
*/
|
|
188
|
+
warnNoTracerProvider() {
|
|
189
|
+
if (this.warnedNoTracerProvider) return;
|
|
190
|
+
this.warnedNoTracerProvider = true;
|
|
191
|
+
const cause = this.hasCustomTracerProvider ? "The tracerProvider passed to OtelBridge returned a no-op span" : "No OpenTelemetry tracer provider is registered globally";
|
|
192
|
+
this.logger.warn(`[OtelBridge] ${cause}, so Mastra spans will not be exported through OpenTelemetry. Register a tracer provider before running agents or workflows (for example, call \`sdk.start()\` on \`NodeSDK\` from \`@opentelemetry/sdk-node\`, or \`trace.setGlobalTracerProvider(provider)\`), or pass it directly with \`new OtelBridge({ tracerProvider })\`. See ${SETUP_DOCS_URL}`);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
178
195
|
* Handle SPAN_ENDED event
|
|
179
196
|
*
|
|
180
197
|
* Retrieves the OTEL span created at SPAN_STARTED, sets all final attributes,
|
|
@@ -185,7 +202,7 @@ var OtelBridge = class extends BaseExporter {
|
|
|
185
202
|
const mastraSpan = event.exportedSpan;
|
|
186
203
|
const entry = this.otelSpanMap.get(mastraSpan.id);
|
|
187
204
|
if (!entry) {
|
|
188
|
-
this.logger.
|
|
205
|
+
this.logger.debug(`[OtelBridge] No OTEL span found for Mastra span [id=${mastraSpan.id}].`);
|
|
189
206
|
return;
|
|
190
207
|
}
|
|
191
208
|
this.otelSpanMap.delete(mastraSpan.id);
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["otelTrace","otelLogs","otelContext"],"sources":["../src/bridge.ts"],"sourcesContent":["/**\n * OpenTelemetry Bridge for Mastra Observability\n *\n * This bridge enables bidirectional integration with OpenTelemetry infrastructure:\n * 1. Reads OTEL trace context from active spans (via AsyncLocalStorage)\n * 2. Creates real OTEL spans when Mastra spans are created\n * 3. Maintains span context for proper parent-child relationships\n * 4. Allows OTEL-instrumented code (DB, HTTP clients) in tools/workflows to have correct parents\n *\n * This creates complete distributed traces where Mastra spans are properly\n * nested within OTEL spans from auto-instrumentation, and any OTEL-instrumented\n * operations within Mastra spans maintain the correct hierarchy.\n */\n\nimport type {\n ObservabilityBridge,\n TracingEvent,\n LogEvent,\n CreateSpanOptions,\n SpanType,\n SpanIds,\n InitExporterOptions,\n} from '@mastra/core/observability';\nimport { TracingEventType } from '@mastra/core/observability';\nimport { BaseExporter, getExternalParentId } from '@mastra/observability';\nimport type { BaseExporterConfig } from '@mastra/observability';\nimport { SpanConverter, convertLog, getSpanKind } from '@mastra/otel-exporter';\nimport { trace as otelTrace, context as otelContext, isSpanContextValid, TraceFlags } from '@opentelemetry/api';\nimport type { Span as OtelSpan, Context as OtelContext, TracerProvider, Tracer } from '@opentelemetry/api';\nimport { logs as otelLogs } from '@opentelemetry/api-logs';\nimport type { Logger as OtelLogger, LoggerProvider } from '@opentelemetry/api-logs';\n\nexport type OtelBridgeConfig = BaseExporterConfig & {\n tracerProvider?: TracerProvider;\n loggerProvider?: LoggerProvider;\n};\n\n/**\n * OpenTelemetry Bridge implementation\n *\n * Creates real OTEL spans when Mastra spans are created, maintaining proper\n * context propagation for nested instrumentation.\n *\n * @example\n * ```typescript\n * import { OtelBridge } from '@mastra/otel-bridge';\n * import { Mastra } from '@mastra/core';\n *\n * const mastra = new Mastra({\n * agents: { myAgent },\n * observability: {\n * configs: {\n * default: {\n * serviceName: 'my-service',\n * bridge: new OtelBridge(),\n * }\n * }\n * }\n * });\n * ```\n */\nexport class OtelBridge extends BaseExporter implements ObservabilityBridge {\n name = 'otel';\n private tracerProvider: TracerProvider;\n private loggerProvider: LoggerProvider;\n private otelTracer: Tracer;\n private otelLogger: OtelLogger;\n private otelSpanMap = new Map<string, { otelSpan: OtelSpan; otelContext: OtelContext }>();\n private spanConverter?: SpanConverter;\n\n constructor(config: OtelBridgeConfig = {}) {\n super(config);\n this.tracerProvider = config.tracerProvider ?? otelTrace.getTracerProvider();\n this.otelTracer = this.tracerProvider.getTracer('@mastra/otel-bridge', '1.0.0');\n this.loggerProvider = config.loggerProvider ?? otelLogs.getLoggerProvider();\n this.otelLogger = this.loggerProvider.getLogger('@mastra/otel-bridge', '1.0.0');\n }\n\n /**\n * Handle Mastra tracing events\n *\n * Ships OTEL spans when Mastra spans end.\n * This maintains proper span hierarchy and allows OTEL-instrumented code within\n * Mastra spans to have correct parent-child relationships.\n * Note: OTEL spans are created when registerSpan is called when the span is first created.\n */\n protected async _exportTracingEvent(event: TracingEvent): Promise<void> {\n if (event.type === TracingEventType.SPAN_ENDED) {\n await this.handleSpanEnded(event);\n }\n }\n\n /**\n * Forward Mastra log events into the globally-registered OTEL LoggerProvider.\n *\n * If the user has not registered a LoggerProvider (e.g. via @opentelemetry/sdk-logs\n * or NodeSDK's logRecordProcessor option), the API returns a no-op logger and\n * emit() is a silent no-op — the bridge degrades gracefully.\n *\n * Trace correlation:\n * - If the log carries a spanId we have an OTEL span for, emit under that span's\n * stored context so the log nests beneath it in the trace.\n * - Else if the log carries traceId+spanId, attach a SpanContext built from those\n * IDs so backends still correlate by ID.\n * - Else emit under whatever context is currently active.\n */\n async onLogEvent(event: LogEvent): Promise<void> {\n if (this.isDisabled) return;\n\n try {\n const params = convertLog(event.log);\n\n const attributes = { ...params.attributes };\n if (params.traceId) attributes['mastra.traceId'] = params.traceId;\n if (params.spanId) attributes['mastra.spanId'] = params.spanId;\n\n const logContext = this.resolveLogContext(params.traceId, params.spanId);\n\n this.otelLogger.emit({\n timestamp: params.timestamp,\n severityNumber: params.severityNumber,\n severityText: params.severityText,\n body: params.body,\n attributes,\n context: logContext,\n });\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to emit log:', error);\n }\n }\n\n /**\n * Pick the OTEL Context to emit a log under so trace correlation is correct.\n */\n private resolveLogContext(traceId?: string, spanId?: string): OtelContext {\n // 1. Prefer the stored OTEL context for the originating Mastra span.\n if (spanId) {\n const entry = this.otelSpanMap.get(spanId);\n if (entry) return entry.otelContext;\n }\n\n // 2. Fall back to a context with a span context built from the raw IDs,\n // but only when both IDs form a valid W3C span context. Injecting\n // malformed IDs would surface as garbage trace links downstream.\n if (traceId && spanId) {\n const candidate = {\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n if (isSpanContextValid(candidate)) {\n return otelTrace.setSpanContext(otelContext.active(), candidate);\n }\n }\n\n // 3. Fall through to whatever is currently active.\n return otelContext.active();\n }\n\n /**\n * Initialize with tracing configuration\n */\n init(options: InitExporterOptions) {\n this.spanConverter = new SpanConverter({\n packageName: '@mastra/otel-bridge',\n serviceName: options.config?.serviceName,\n format: 'GenAI_v1_38_0',\n });\n }\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined {\n try {\n // Determine parent context\n let parentOtelContext = otelContext.active();\n let usedPersistedParent = false;\n\n // Get external parent ID (walks up chain to find non-internal parent)\n const externalParentId = getExternalParentId(options);\n if (externalParentId) {\n // Look up external parent's OTEL span from map\n const parentEntry = this.otelSpanMap.get(externalParentId);\n if (parentEntry) {\n parentOtelContext = parentEntry.otelContext;\n }\n } else if (options.traceId && options.parentSpanId) {\n // Root spans restored from persisted state (e.g. workflow suspend/resume)\n // carry the original trace ID and parent span ID, but the parent OTEL span\n // is no longer alive — it ended when the run suspended, possibly in another\n // process. Parent under a remote span context built from the persisted IDs\n // so the span continues the original trace instead of joining whatever\n // context happens to be active. Skip malformed IDs; injecting them would\n // surface as garbage trace links downstream.\n const candidate = {\n traceId: options.traceId,\n spanId: options.parentSpanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: true,\n };\n if (isSpanContextValid(candidate)) {\n parentOtelContext = otelTrace.setSpanContext(parentOtelContext, candidate);\n usedPersistedParent = true;\n }\n }\n\n // Create OTEL span with SpanKind (must be set at creation, immutable)\n const otelSpan = this.otelTracer.startSpan(\n options.name,\n {\n kind: getSpanKind(options.type),\n ...(options.startTime ? { startTime: options.startTime } : {}),\n },\n parentOtelContext,\n );\n\n // Create context with this span active\n const spanContext = otelTrace.setSpan(parentOtelContext, otelSpan);\n\n // Get OTEL span identifiers\n const otelSpanContext = otelSpan.spanContext();\n\n // If no OTEL SDK is registered, the global tracer returns a non-recording\n // span with an invalid span context (all-zero span/trace IDs). Returning\n // those IDs would collide across every Mastra span and break downstream\n // exporters. Bail out so DefaultSpan falls through to its own ID generator.\n if (!isSpanContextValid(otelSpanContext)) {\n // End the span we just started so its lifecycle stays clean on\n // providers that do track non-recording spans.\n otelSpan.end();\n return undefined;\n }\n\n const spanId = otelSpanContext.spanId;\n const traceId = otelSpanContext.traceId;\n\n // Store for later retrieval (for executeWithSpanContext and event handling)\n this.otelSpanMap.set(spanId, { otelSpan, otelContext: spanContext });\n\n // Get parentSpanId from parent context if available\n const parentSpan = otelTrace.getSpan(parentOtelContext);\n const parentSpanContext = parentSpan?.spanContext();\n const parentSpanId =\n parentSpanContext && isSpanContextValid(parentSpanContext) ? parentSpanContext.spanId : undefined;\n\n // Declare which kind of parent was used: a span this bridge created for\n // a Mastra span is part of the Mastra trace, while anything else in the\n // ambient OTEL context belongs to the external tracing system. A parent\n // restored from persisted state is a Mastra span in storage — it ended at\n // suspend (possibly in another process), so it is absent from the live map.\n const parentIsMastraSpan =\n parentSpanId !== undefined && (this.otelSpanMap.has(parentSpanId) || usedPersistedParent);\n\n this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [parentIsMastraSpan=${parentIsMastraSpan}] ` +\n `[type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return {\n spanId,\n traceId,\n ...(parentIsMastraSpan ? { parentSpanId } : { externalParentSpanId: parentSpanId }),\n };\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to create span:', error);\n return undefined;\n }\n }\n\n /**\n * Handle SPAN_ENDED event\n *\n * Retrieves the OTEL span created at SPAN_STARTED, sets all final attributes,\n * events, and status, then ends the span. Cleans up the span map entry.\n */\n private async handleSpanEnded(event: TracingEvent): Promise<void> {\n try {\n const mastraSpan = event.exportedSpan;\n const entry = this.otelSpanMap.get(mastraSpan.id);\n\n if (!entry) {\n this.logger.warn(`[OtelBridge] No OTEL span found for Mastra span [id=${mastraSpan.id}].`);\n return;\n }\n\n // Remove from map immediately to prevent memory leak\n this.otelSpanMap.delete(mastraSpan.id);\n\n if (!this.spanConverter) {\n return;\n }\n\n const { otelSpan } = entry;\n\n this.logger.debug(`[OtelBridge] Ending OTEL span [mastraId=${mastraSpan.id}] [name=${mastraSpan.name}]`);\n\n // Use SpanConverter to get consistent span formatting with otel-exporter\n const readableSpan = await this.spanConverter!.convertSpan(mastraSpan);\n\n // Update span name to match the converter's formatting\n otelSpan.updateName(readableSpan.name);\n\n // Set all attributes from the converter (includes OTEL semantic conventions)\n for (const [key, value] of Object.entries(readableSpan.attributes)) {\n if (value !== undefined && value !== null && typeof value !== 'object') {\n otelSpan.setAttribute(key, value);\n }\n }\n\n // Set status from the converter\n otelSpan.setStatus(readableSpan.status);\n\n // Add exception events if present\n for (const event of readableSpan.events) {\n if (event.name === 'exception' && event.attributes) {\n const error = new Error(event.attributes['exception.message'] as string);\n otelSpan.recordException(error);\n }\n }\n\n // End the span with the actual end time\n otelSpan.end(mastraSpan.endTime);\n\n this.logger.debug(\n `[OtelBridge] Completed OTEL span [mastraId=${mastraSpan.id}] [traceId=${otelSpan.spanContext().traceId}]`,\n );\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to handle SPAN_ENDED:', error);\n }\n }\n\n /**\n * Release the OTEL span held for a Mastra span that ended without being exported.\n *\n * The OTEL span is deliberately not ended: ending it would hand it to the OTEL\n * span processors and export a span the user's filtering just removed. Dropping\n * the reference is enough, since span processors only queue spans on end.\n */\n releaseSpan(spanId: string): void {\n if (this.otelSpanMap.delete(spanId)) {\n this.logger.debug(\n `[OtelBridge.releaseSpan] Released unexported span [spanId=${spanId}] [mapSize=${this.otelSpanMap.size}]`,\n );\n }\n }\n\n /**\n * Execute a function (sync or async) within the OTEL context of a Mastra span.\n * Retrieves the stored OTEL context for the span and executes the function within it.\n *\n * This is the core implementation used by both executeInContext and executeInContextSync.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The function to execute within the span context\n * @returns The result of the function execution\n */\n private executeWithSpanContext<T>(spanId: string, fn: () => T): T {\n const entry = this.otelSpanMap.get(spanId);\n\n this.logger.debug(\n `[OtelBridge.executeWithSpanContext] spanId=${spanId}, ` +\n `inMap=${!!entry}, ` +\n `storedOtelSpan=${entry?.otelSpan.spanContext().spanId || 'none'}`,\n );\n\n const spanContext = entry?.otelContext;\n if (spanContext) {\n return otelContext.with(spanContext, fn);\n }\n return fn();\n }\n\n /**\n * Execute an async function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext<T>(spanId: string, fn: () => Promise<T>): Promise<T> {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Execute a synchronous function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync<T>(spanId: string, fn: () => T): T {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Force flush any buffered spans without shutting down the bridge.\n *\n * Attempts to flush the underlying OTEL tracer provider if it supports\n * the forceFlush operation. This is useful in serverless environments\n * where you need to ensure all spans are exported before the runtime\n * instance is terminated.\n */\n async flush(): Promise<void> {\n await this.flushProvider(this.tracerProvider, 'tracer');\n await this.flushProvider(this.loggerProvider, 'logger');\n }\n\n private async flushProvider(provider: unknown, label: 'tracer' | 'logger'): Promise<void> {\n try {\n if (\n provider &&\n typeof provider === 'object' &&\n 'forceFlush' in provider &&\n typeof (provider as { forceFlush: unknown }).forceFlush === 'function'\n ) {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n this.logger.debug(`[OtelBridge] Flushed ${label} provider`);\n } else {\n this.logger.debug(\n `[OtelBridge] ${label === 'tracer' ? 'Tracer' : 'Logger'} provider does not support forceFlush`,\n );\n }\n } catch (error) {\n this.logger.error(`[OtelBridge] Failed to flush ${label} provider:`, error);\n }\n }\n\n /**\n * Shutdown the bridge and clean up resources\n */\n async shutdown(): Promise<void> {\n // Flush before shutdown\n await this.flush();\n\n // End any remaining spans\n for (const [spanId, { otelSpan }] of this.otelSpanMap.entries()) {\n this.logger.warn(`[OtelBridge] Force-ending span that was not properly closed [id=${spanId}]`);\n otelSpan.end();\n }\n this.otelSpanMap.clear();\n this.logger.info('[OtelBridge] Shutdown complete');\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,IAAa,aAAb,cAAgC,aAA4C;CAC1E,OAAO;CACP;CACA;CACA;CACA;CACA,8BAAsB,IAAI,IAA8D;CACxF;CAEA,YAAY,SAA2B,CAAC,GAAG;EACzC,MAAM,MAAM;EACZ,KAAK,iBAAiB,OAAO,kBAAkBA,MAAU,kBAAkB;EAC3E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;EAC9E,KAAK,iBAAiB,OAAO,kBAAkBC,KAAS,kBAAkB;EAC1E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;CAChF;;;;;;;;;CAUA,MAAgB,oBAAoB,OAAoC;EACtE,IAAI,MAAM,SAAS,iBAAiB,YAClC,MAAM,KAAK,gBAAgB,KAAK;CAEpC;;;;;;;;;;;;;;;CAgBA,MAAM,WAAW,OAAgC;EAC/C,IAAI,KAAK,YAA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,QAAgB,IAAkC;EACpE,OAAO,KAAK,uBAAuB,QAAQ,EAAE;CAC/C;;;;;;;;CASA,qBAAwB,QAAgB,IAAgB;EACtD,OAAO,KAAK,uBAAuB,QAAQ,EAAE;CAC/C;;;;;;;;;CAUA,MAAM,QAAuB;EAC3B,MAAM,KAAK,cAAc,KAAK,gBAAgB,QAAQ;EACtD,MAAM,KAAK,cAAc,KAAK,gBAAgB,QAAQ;CACxD;CAEA,MAAc,cAAc,UAAmB,OAA2C;EACxF,IAAI;GACF,IACE,YACA,OAAO,aAAa,YACpB,gBAAgB,YAChB,OAAQ,SAAqC,eAAe,YAC5D;IACA,MAAO,SAAiD,WAAW;IACnE,KAAK,OAAO,MAAM,wBAAwB,MAAM,UAAU;GAC5D,OACE,KAAK,OAAO,MACV,gBAAgB,UAAU,WAAW,WAAW,SAAS,sCAC3D;EAEJ,SAAS,OAAO;GACd,KAAK,OAAO,MAAM,gCAAgC,MAAM,aAAa,KAAK;EAC5E;CACF;;;;CAKA,MAAM,WAA0B;EAE9B,MAAM,KAAK,MAAM;EAGjB,KAAK,MAAM,CAAC,QAAQ,EAAE,eAAe,KAAK,YAAY,QAAQ,GAAG;GAC/D,KAAK,OAAO,KAAK,mEAAmE,OAAO,EAAE;GAC7F,SAAS,IAAI;EACf;EACA,KAAK,YAAY,MAAM;EACvB,KAAK,OAAO,KAAK,gCAAgC;CACnD;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["otelTrace","otelLogs","otelContext"],"sources":["../src/bridge.ts"],"sourcesContent":["/**\n * OpenTelemetry Bridge for Mastra Observability\n *\n * This bridge enables bidirectional integration with OpenTelemetry infrastructure:\n * 1. Reads OTEL trace context from active spans (via AsyncLocalStorage)\n * 2. Creates real OTEL spans when Mastra spans are created\n * 3. Maintains span context for proper parent-child relationships\n * 4. Allows OTEL-instrumented code (DB, HTTP clients) in tools/workflows to have correct parents\n *\n * This creates complete distributed traces where Mastra spans are properly\n * nested within OTEL spans from auto-instrumentation, and any OTEL-instrumented\n * operations within Mastra spans maintain the correct hierarchy.\n */\n\nimport type {\n ObservabilityBridge,\n TracingEvent,\n LogEvent,\n CreateSpanOptions,\n SpanType,\n SpanIds,\n InitExporterOptions,\n} from '@mastra/core/observability';\nimport { TracingEventType } from '@mastra/core/observability';\nimport { BaseExporter, getExternalParentId } from '@mastra/observability';\nimport type { BaseExporterConfig } from '@mastra/observability';\nimport { SpanConverter, convertLog, getSpanKind } from '@mastra/otel-exporter';\nimport { trace as otelTrace, context as otelContext, isSpanContextValid, TraceFlags } from '@opentelemetry/api';\nimport type { Span as OtelSpan, Context as OtelContext, TracerProvider, Tracer } from '@opentelemetry/api';\nimport { logs as otelLogs } from '@opentelemetry/api-logs';\nimport type { Logger as OtelLogger, LoggerProvider } from '@opentelemetry/api-logs';\n\nconst SETUP_DOCS_URL = 'https://mastra.ai/reference/observability/tracing/bridges/otel#setup-requirements';\n\nexport type OtelBridgeConfig = BaseExporterConfig & {\n tracerProvider?: TracerProvider;\n loggerProvider?: LoggerProvider;\n};\n\n/**\n * OpenTelemetry Bridge implementation\n *\n * Creates real OTEL spans when Mastra spans are created, maintaining proper\n * context propagation for nested instrumentation.\n *\n * @example\n * ```typescript\n * import { OtelBridge } from '@mastra/otel-bridge';\n * import { Mastra } from '@mastra/core';\n *\n * const mastra = new Mastra({\n * agents: { myAgent },\n * observability: {\n * configs: {\n * default: {\n * serviceName: 'my-service',\n * bridge: new OtelBridge(),\n * }\n * }\n * }\n * });\n * ```\n */\nexport class OtelBridge extends BaseExporter implements ObservabilityBridge {\n name = 'otel';\n private tracerProvider: TracerProvider;\n private loggerProvider: LoggerProvider;\n private otelTracer: Tracer;\n private otelLogger: OtelLogger;\n private otelSpanMap = new Map<string, { otelSpan: OtelSpan; otelContext: OtelContext }>();\n private spanConverter?: SpanConverter;\n private hasCustomTracerProvider: boolean;\n private warnedNoTracerProvider = false;\n\n constructor(config: OtelBridgeConfig = {}) {\n super(config);\n this.hasCustomTracerProvider = config.tracerProvider !== undefined;\n this.tracerProvider = config.tracerProvider ?? otelTrace.getTracerProvider();\n this.otelTracer = this.tracerProvider.getTracer('@mastra/otel-bridge', '1.0.0');\n this.loggerProvider = config.loggerProvider ?? otelLogs.getLoggerProvider();\n this.otelLogger = this.loggerProvider.getLogger('@mastra/otel-bridge', '1.0.0');\n }\n\n /**\n * Handle Mastra tracing events\n *\n * Ships OTEL spans when Mastra spans end.\n * This maintains proper span hierarchy and allows OTEL-instrumented code within\n * Mastra spans to have correct parent-child relationships.\n * Note: OTEL spans are created when registerSpan is called when the span is first created.\n */\n protected async _exportTracingEvent(event: TracingEvent): Promise<void> {\n if (event.type === TracingEventType.SPAN_ENDED) {\n await this.handleSpanEnded(event);\n }\n }\n\n /**\n * Forward Mastra log events into the globally-registered OTEL LoggerProvider.\n *\n * If the user has not registered a LoggerProvider (e.g. via @opentelemetry/sdk-logs\n * or NodeSDK's logRecordProcessor option), the API returns a no-op logger and\n * emit() is a silent no-op — the bridge degrades gracefully.\n *\n * Trace correlation:\n * - If the log carries a spanId we have an OTEL span for, emit under that span's\n * stored context so the log nests beneath it in the trace.\n * - Else if the log carries traceId+spanId, attach a SpanContext built from those\n * IDs so backends still correlate by ID.\n * - Else emit under whatever context is currently active.\n */\n async onLogEvent(event: LogEvent): Promise<void> {\n if (this.isDisabled) return;\n\n try {\n const params = convertLog(event.log);\n\n const attributes = { ...params.attributes };\n if (params.traceId) attributes['mastra.traceId'] = params.traceId;\n if (params.spanId) attributes['mastra.spanId'] = params.spanId;\n\n const logContext = this.resolveLogContext(params.traceId, params.spanId);\n\n this.otelLogger.emit({\n timestamp: params.timestamp,\n severityNumber: params.severityNumber,\n severityText: params.severityText,\n body: params.body,\n attributes,\n context: logContext,\n });\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to emit log:', error);\n }\n }\n\n /**\n * Pick the OTEL Context to emit a log under so trace correlation is correct.\n */\n private resolveLogContext(traceId?: string, spanId?: string): OtelContext {\n // 1. Prefer the stored OTEL context for the originating Mastra span.\n if (spanId) {\n const entry = this.otelSpanMap.get(spanId);\n if (entry) return entry.otelContext;\n }\n\n // 2. Fall back to a context with a span context built from the raw IDs,\n // but only when both IDs form a valid W3C span context. Injecting\n // malformed IDs would surface as garbage trace links downstream.\n if (traceId && spanId) {\n const candidate = {\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n if (isSpanContextValid(candidate)) {\n return otelTrace.setSpanContext(otelContext.active(), candidate);\n }\n }\n\n // 3. Fall through to whatever is currently active.\n return otelContext.active();\n }\n\n /**\n * Initialize with tracing configuration\n */\n init(options: InitExporterOptions) {\n this.spanConverter = new SpanConverter({\n packageName: '@mastra/otel-bridge',\n serviceName: options.config?.serviceName,\n format: 'GenAI_v1_38_0',\n });\n }\n\n /**\n * Create a span in the bridge's tracing system.\n * Called during Mastra span construction to get bridge-generated identifiers.\n *\n * @param options - Span creation options from Mastra\n * @returns Span identifiers (spanId, traceId, parentSpanId) from bridge, or undefined if creation fails\n */\n createSpan(options: CreateSpanOptions<SpanType>): SpanIds | undefined {\n try {\n // Determine parent context\n let parentOtelContext = otelContext.active();\n let usedPersistedParent = false;\n\n // Get external parent ID (walks up chain to find non-internal parent)\n const externalParentId = getExternalParentId(options);\n if (externalParentId) {\n // Look up external parent's OTEL span from map\n const parentEntry = this.otelSpanMap.get(externalParentId);\n if (parentEntry) {\n parentOtelContext = parentEntry.otelContext;\n }\n } else if (options.traceId && options.parentSpanId) {\n // Root spans restored from persisted state (e.g. workflow suspend/resume)\n // carry the original trace ID and parent span ID, but the parent OTEL span\n // is no longer alive — it ended when the run suspended, possibly in another\n // process. Parent under a remote span context built from the persisted IDs\n // so the span continues the original trace instead of joining whatever\n // context happens to be active. Skip malformed IDs; injecting them would\n // surface as garbage trace links downstream.\n const candidate = {\n traceId: options.traceId,\n spanId: options.parentSpanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: true,\n };\n if (isSpanContextValid(candidate)) {\n parentOtelContext = otelTrace.setSpanContext(parentOtelContext, candidate);\n usedPersistedParent = true;\n }\n }\n\n // Create OTEL span with SpanKind (must be set at creation, immutable)\n const otelSpan = this.otelTracer.startSpan(\n options.name,\n {\n kind: getSpanKind(options.type),\n ...(options.startTime ? { startTime: options.startTime } : {}),\n },\n parentOtelContext,\n );\n\n // Create context with this span active\n const spanContext = otelTrace.setSpan(parentOtelContext, otelSpan);\n\n // Get OTEL span identifiers\n const otelSpanContext = otelSpan.spanContext();\n\n // If no OTEL SDK is registered, the global tracer is a no-op. With no\n // parent it returns a span with an invalid (all-zero) span context; with\n // a parent in the context (e.g. an outer span from another, unregistered\n // provider) it returns a span wrapping the parent's span context. Either\n // way, returning those IDs would collide across every Mastra span and\n // break downstream exporters. Bail out so DefaultSpan falls through to\n // its own ID generator. A real tracer always mints a fresh span ID, even\n // for spans its sampler drops.\n const parentOtelSpanContext = otelTrace.getSpanContext(parentOtelContext);\n if (\n !isSpanContextValid(otelSpanContext) ||\n (parentOtelSpanContext !== undefined && otelSpanContext.spanId === parentOtelSpanContext.spanId)\n ) {\n this.warnNoTracerProvider();\n // End the span we just started so its lifecycle stays clean on\n // providers that do track non-recording spans.\n otelSpan.end();\n return undefined;\n }\n\n const spanId = otelSpanContext.spanId;\n const traceId = otelSpanContext.traceId;\n\n // Store for later retrieval (for executeWithSpanContext and event handling)\n this.otelSpanMap.set(spanId, { otelSpan, otelContext: spanContext });\n\n // Get parentSpanId from parent context if available\n const parentSpan = otelTrace.getSpan(parentOtelContext);\n const parentSpanContext = parentSpan?.spanContext();\n const parentSpanId =\n parentSpanContext && isSpanContextValid(parentSpanContext) ? parentSpanContext.spanId : undefined;\n\n // Declare which kind of parent was used: a span this bridge created for\n // a Mastra span is part of the Mastra trace, while anything else in the\n // ambient OTEL context belongs to the external tracing system. A parent\n // restored from persisted state is a Mastra span in storage — it ended at\n // suspend (possibly in another process), so it is absent from the live map.\n const parentIsMastraSpan =\n parentSpanId !== undefined && (this.otelSpanMap.has(parentSpanId) || usedPersistedParent);\n\n this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [parentIsMastraSpan=${parentIsMastraSpan}] ` +\n `[type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return {\n spanId,\n traceId,\n ...(parentIsMastraSpan ? { parentSpanId } : { externalParentSpanId: parentSpanId }),\n };\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to create span:', error);\n return undefined;\n }\n }\n\n /**\n * Warn once per bridge that no tracer provider is producing spans. Checked\n * lazily on span creation rather than at startup, because the OTEL SDK is\n * often registered after the bridge is constructed.\n */\n private warnNoTracerProvider(): void {\n if (this.warnedNoTracerProvider) return;\n this.warnedNoTracerProvider = true;\n\n const cause = this.hasCustomTracerProvider\n ? 'The tracerProvider passed to OtelBridge returned a no-op span'\n : 'No OpenTelemetry tracer provider is registered globally';\n\n this.logger.warn(\n `[OtelBridge] ${cause}, so Mastra spans will not be exported through OpenTelemetry. ` +\n 'Register a tracer provider before running agents or workflows (for example, call `sdk.start()` on ' +\n '`NodeSDK` from `@opentelemetry/sdk-node`, or `trace.setGlobalTracerProvider(provider)`), ' +\n 'or pass it directly with `new OtelBridge({ tracerProvider })`. ' +\n `See ${SETUP_DOCS_URL}`,\n );\n }\n\n /**\n * Handle SPAN_ENDED event\n *\n * Retrieves the OTEL span created at SPAN_STARTED, sets all final attributes,\n * events, and status, then ends the span. Cleans up the span map entry.\n */\n private async handleSpanEnded(event: TracingEvent): Promise<void> {\n try {\n const mastraSpan = event.exportedSpan;\n const entry = this.otelSpanMap.get(mastraSpan.id);\n\n if (!entry) {\n // Expected when no tracer provider is registered; warnNoTracerProvider()\n // already reported that once, so don't repeat it for every span.\n this.logger.debug(`[OtelBridge] No OTEL span found for Mastra span [id=${mastraSpan.id}].`);\n return;\n }\n\n // Remove from map immediately to prevent memory leak\n this.otelSpanMap.delete(mastraSpan.id);\n\n if (!this.spanConverter) {\n return;\n }\n\n const { otelSpan } = entry;\n\n this.logger.debug(`[OtelBridge] Ending OTEL span [mastraId=${mastraSpan.id}] [name=${mastraSpan.name}]`);\n\n // Use SpanConverter to get consistent span formatting with otel-exporter\n const readableSpan = await this.spanConverter!.convertSpan(mastraSpan);\n\n // Update span name to match the converter's formatting\n otelSpan.updateName(readableSpan.name);\n\n // Set all attributes from the converter (includes OTEL semantic conventions)\n for (const [key, value] of Object.entries(readableSpan.attributes)) {\n if (value !== undefined && value !== null && typeof value !== 'object') {\n otelSpan.setAttribute(key, value);\n }\n }\n\n // Set status from the converter\n otelSpan.setStatus(readableSpan.status);\n\n // Add exception events if present\n for (const event of readableSpan.events) {\n if (event.name === 'exception' && event.attributes) {\n const error = new Error(event.attributes['exception.message'] as string);\n otelSpan.recordException(error);\n }\n }\n\n // End the span with the actual end time\n otelSpan.end(mastraSpan.endTime);\n\n this.logger.debug(\n `[OtelBridge] Completed OTEL span [mastraId=${mastraSpan.id}] [traceId=${otelSpan.spanContext().traceId}]`,\n );\n } catch (error) {\n this.logger.error('[OtelBridge] Failed to handle SPAN_ENDED:', error);\n }\n }\n\n /**\n * Release the OTEL span held for a Mastra span that ended without being exported.\n *\n * The OTEL span is deliberately not ended: ending it would hand it to the OTEL\n * span processors and export a span the user's filtering just removed. Dropping\n * the reference is enough, since span processors only queue spans on end.\n */\n releaseSpan(spanId: string): void {\n if (this.otelSpanMap.delete(spanId)) {\n this.logger.debug(\n `[OtelBridge.releaseSpan] Released unexported span [spanId=${spanId}] [mapSize=${this.otelSpanMap.size}]`,\n );\n }\n }\n\n /**\n * Execute a function (sync or async) within the OTEL context of a Mastra span.\n * Retrieves the stored OTEL context for the span and executes the function within it.\n *\n * This is the core implementation used by both executeInContext and executeInContextSync.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The function to execute within the span context\n * @returns The result of the function execution\n */\n private executeWithSpanContext<T>(spanId: string, fn: () => T): T {\n const entry = this.otelSpanMap.get(spanId);\n\n this.logger.debug(\n `[OtelBridge.executeWithSpanContext] spanId=${spanId}, ` +\n `inMap=${!!entry}, ` +\n `storedOtelSpan=${entry?.otelSpan.spanContext().spanId || 'none'}`,\n );\n\n const spanContext = entry?.otelContext;\n if (spanContext) {\n return otelContext.with(spanContext, fn);\n }\n return fn();\n }\n\n /**\n * Execute an async function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The async function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContext<T>(spanId: string, fn: () => Promise<T>): Promise<T> {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Execute a synchronous function within the OTEL context of a Mastra span.\n *\n * @param spanId - The ID of the Mastra span to use as context\n * @param fn - The synchronous function to execute within the span context\n * @returns The result of the function execution\n */\n executeInContextSync<T>(spanId: string, fn: () => T): T {\n return this.executeWithSpanContext(spanId, fn);\n }\n\n /**\n * Force flush any buffered spans without shutting down the bridge.\n *\n * Attempts to flush the underlying OTEL tracer provider if it supports\n * the forceFlush operation. This is useful in serverless environments\n * where you need to ensure all spans are exported before the runtime\n * instance is terminated.\n */\n async flush(): Promise<void> {\n await this.flushProvider(this.tracerProvider, 'tracer');\n await this.flushProvider(this.loggerProvider, 'logger');\n }\n\n private async flushProvider(provider: unknown, label: 'tracer' | 'logger'): Promise<void> {\n try {\n if (\n provider &&\n typeof provider === 'object' &&\n 'forceFlush' in provider &&\n typeof (provider as { forceFlush: unknown }).forceFlush === 'function'\n ) {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n this.logger.debug(`[OtelBridge] Flushed ${label} provider`);\n } else {\n this.logger.debug(\n `[OtelBridge] ${label === 'tracer' ? 'Tracer' : 'Logger'} provider does not support forceFlush`,\n );\n }\n } catch (error) {\n this.logger.error(`[OtelBridge] Failed to flush ${label} provider:`, error);\n }\n }\n\n /**\n * Shutdown the bridge and clean up resources\n */\n async shutdown(): Promise<void> {\n // Flush before shutdown\n await this.flush();\n\n // End any remaining spans\n for (const [spanId, { otelSpan }] of this.otelSpanMap.entries()) {\n this.logger.warn(`[OtelBridge] Force-ending span that was not properly closed [id=${spanId}]`);\n otelSpan.end();\n }\n this.otelSpanMap.clear();\n this.logger.info('[OtelBridge] Shutdown complete');\n }\n}\n"],"mappings":";;;;;;AAgCA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;AA+BvB,IAAa,aAAb,cAAgC,aAA4C;CAC1E,OAAO;CACP;CACA;CACA;CACA;CACA,8BAAsB,IAAI,IAA8D;CACxF;CACA;CACA,yBAAiC;CAEjC,YAAY,SAA2B,CAAC,GAAG;EACzC,MAAM,MAAM;EACZ,KAAK,0BAA0B,OAAO,mBAAmB,KAAA;EACzD,KAAK,iBAAiB,OAAO,kBAAkBA,MAAU,kBAAkB;EAC3E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;EAC9E,KAAK,iBAAiB,OAAO,kBAAkBC,KAAS,kBAAkB;EAC1E,KAAK,aAAa,KAAK,eAAe,UAAU,uBAAuB,OAAO;CAChF;;;;;;;;;CAUA,MAAgB,oBAAoB,OAAoC;EACtE,IAAI,MAAM,SAAS,iBAAiB,YAClC,MAAM,KAAK,gBAAgB,KAAK;CAEpC;;;;;;;;;;;;;;;CAgBA,MAAM,WAAW,OAAgC;EAC/C,IAAI,KAAK,YAAY;EAErB,IAAI;GACF,MAAM,SAAS,WAAW,MAAM,GAAG;GAEnC,MAAM,aAAa,EAAE,GAAG,OAAO,WAAW;GAC1C,IAAI,OAAO,SAAS,WAAW,oBAAoB,OAAO;GAC1D,IAAI,OAAO,QAAQ,WAAW,mBAAmB,OAAO;GAExD,MAAM,aAAa,KAAK,kBAAkB,OAAO,SAAS,OAAO,MAAM;GAEvE,KAAK,WAAW,KAAK;IACnB,WAAW,OAAO;IAClB,gBAAgB,OAAO;IACvB,cAAc,OAAO;IACrB,MAAM,OAAO;IACb;IACA,SAAS;GACX,CAAC;EACH,SAAS,OAAO;GACd,KAAK,OAAO,MAAM,oCAAoC,KAAK;E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;;;;;CAUA,MAAM,QAAuB;EAC3B,MAAM,KAAK,cAAc,KAAK,gBAAgB,QAAQ;EACtD,MAAM,KAAK,cAAc,KAAK,gBAAgB,QAAQ;CACxD;CAEA,MAAc,cAAc,UAAmB,OAA2C;EACxF,IAAI;GACF,IACE,YACA,OAAO,aAAa,YACpB,gBAAgB,YAChB,OAAQ,SAAqC,eAAe,YAC5D;IACA,MAAO,SAAiD,WAAW;IACnE,KAAK,OAAO,MAAM,wBAAwB,MAAM,UAAU;GAC5D,OACE,KAAK,OAAO,MACV,gBAAgB,UAAU,WAAW,WAAW,SAAS,sCAC3D;EAEJ,SAAS,OAAO;GACd,KAAK,OAAO,MAAM,gCAAgC,MAAM,aAAa,KAAK;EAC5E;CACF;;;;CAKA,MAAM,WAA0B;EAE9B,MAAM,KAAK,MAAM;EAGjB,KAAK,MAAM,CAAC,QAAQ,EAAE,eAAe,KAAK,YAAY,QAAQ,GAAG;GAC/D,KAAK,OAAO,KAAK,mEAAmE,OAAO,EAAE;GAC7F,SAAS,IAAI;EACf;EACA,KAAK,YAAY,MAAM;EACvB,KAAK,OAAO,KAAK,gCAAgC;CACnD;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/otel-bridge",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.11-alpha.0",
|
|
4
4
|
"description": "OpenTelemetry observability bridge for Mastra",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -29,15 +29,17 @@
|
|
|
29
29
|
"@mastra/otel-exporter": "1.4.1"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
+
"@opentelemetry/context-async-hooks": "^2.10.0",
|
|
32
33
|
"@opentelemetry/sdk-logs": "^0.221.0",
|
|
33
34
|
"@types/node": "22.20.1",
|
|
34
35
|
"eslint": "^10.7.0",
|
|
35
36
|
"tsdown": "0.22.9",
|
|
36
37
|
"typescript": "^7.0.2",
|
|
37
38
|
"vitest": "4.1.11",
|
|
38
|
-
"@internal/
|
|
39
|
-
"@internal/
|
|
40
|
-
"@mastra/core": "1.
|
|
39
|
+
"@internal/types-builder": "0.0.111",
|
|
40
|
+
"@internal/ai-sdk-v5": "0.0.83",
|
|
41
|
+
"@mastra/core": "1.71.0-alpha.0",
|
|
42
|
+
"@internal/lint": "0.0.136"
|
|
41
43
|
},
|
|
42
44
|
"peerDependencies": {
|
|
43
45
|
"@mastra/core": ">=1.16.0-0 <2.0.0-0",
|