@mastra/otel-bridge 1.4.5-alpha.2 → 1.4.5
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/CHANGELOG.md +41 -0
- package/dist/bridge.d.ts.map +1 -1
- package/dist/index.cjs +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,46 @@
|
|
|
1
1
|
# @mastra/otel-bridge
|
|
2
2
|
|
|
3
|
+
## 1.4.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed the OpenTelemetry bridge ignoring a span's explicit start time, which would report wrong durations for spans created after the work they represent began (such as provider tool call spans). ([#20522](https://github.com/mastra-ai/mastra/pull/20522))
|
|
8
|
+
|
|
9
|
+
- Fixed a memory leak where spans removed by export filtering were never released. ([#20463](https://github.com/mastra-ai/mastra/pull/20463))
|
|
10
|
+
|
|
11
|
+
The bridge creates an OpenTelemetry span when a Mastra span starts and frees it when the span ends. Span-end events are only delivered for spans that survive export filtering, so every span dropped by `excludeSpanTypes`, a `spanFilter`, or a span output processor left one entry behind for the life of the process. There was no bound or sweep on it, so long-running services grew steadily.
|
|
12
|
+
|
|
13
|
+
The filtered spans are still not exported, so what you see in your tracing backend is unchanged.
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
new Observability({
|
|
17
|
+
configs: {
|
|
18
|
+
default: {
|
|
19
|
+
serviceName: 'my-service',
|
|
20
|
+
bridge: new OtelBridge(),
|
|
21
|
+
// Previously leaked one entry per excluded span; now released on span end.
|
|
22
|
+
excludeSpanTypes: [SpanType.MODEL_CHUNK, SpanType.MODEL_STEP],
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Fixes [#20368](https://github.com/mastra-ai/mastra/issues/20368).
|
|
29
|
+
|
|
30
|
+
- Updated dependencies [[`4844167`](https://github.com/mastra-ai/mastra/commit/4844167cff2d5ec5004e94edd34970833040fa3f), [`c5e56ff`](https://github.com/mastra-ai/mastra/commit/c5e56ff3bcabdf062708f2d48744fec304df6792), [`594f7b2`](https://github.com/mastra-ai/mastra/commit/594f7b28f5263fb9982fd50d95c471fb971ea984), [`7f4e26d`](https://github.com/mastra-ai/mastra/commit/7f4e26dd57bd9b23c278ea21235ab823a3810a6c), [`311f943`](https://github.com/mastra-ai/mastra/commit/311f943bee60e8fdf5c84499ea50e884276c936c), [`322daa6`](https://github.com/mastra-ai/mastra/commit/322daa6d90552909204044790d850958f6745fed), [`db4e6ff`](https://github.com/mastra-ai/mastra/commit/db4e6ff744503112eb64deeaf6c2b54bf26a54c7), [`5faf93f`](https://github.com/mastra-ai/mastra/commit/5faf93f03e19daea394b9e2a923f2e4f833407f2), [`82201f7`](https://github.com/mastra-ai/mastra/commit/82201f75fae8e050a8de2df08b74875ee74c6b83), [`2c34a58`](https://github.com/mastra-ai/mastra/commit/2c34a58aff529d7f42f883b2c7f3e7d6745fc224), [`cadaa13`](https://github.com/mastra-ai/mastra/commit/cadaa1372e1077c8e85eb64c5499ba8803caa323), [`0c89896`](https://github.com/mastra-ai/mastra/commit/0c8989673fb7d106837098398131e570c6023b68), [`6d19a65`](https://github.com/mastra-ai/mastra/commit/6d19a6517f5da3911023d446b7e2d5dad8adb1cb), [`23b4238`](https://github.com/mastra-ai/mastra/commit/23b423844ad0bcf2a502a68dd62866d6160f9f6d), [`80ad891`](https://github.com/mastra-ai/mastra/commit/80ad891f8cd10379aa5b5af7510c763783b2ab56), [`fb18da5`](https://github.com/mastra-ai/mastra/commit/fb18da56fc35689ae370621a8f10b5b0d8606e20), [`fb18da5`](https://github.com/mastra-ai/mastra/commit/fb18da56fc35689ae370621a8f10b5b0d8606e20), [`e320a76`](https://github.com/mastra-ai/mastra/commit/e320a763feaf65c6be3cebecf746defcbde161b3), [`03b4918`](https://github.com/mastra-ai/mastra/commit/03b4918c80d188ce375334c393e131c6e94bd7eb), [`14ef73a`](https://github.com/mastra-ai/mastra/commit/14ef73a4bbd73e7808414816eb0628ce1d80b5d7), [`14ef73a`](https://github.com/mastra-ai/mastra/commit/14ef73a4bbd73e7808414816eb0628ce1d80b5d7), [`b582f7f`](https://github.com/mastra-ai/mastra/commit/b582f7fa2f9c1f87d19efc63d344fbe5dda2608c), [`0a6598b`](https://github.com/mastra-ai/mastra/commit/0a6598bde80bde008986ad6616bed9632b9294cb), [`06000d7`](https://github.com/mastra-ai/mastra/commit/06000d73712911572e913b8a83339270296d0a22), [`1d677d5`](https://github.com/mastra-ai/mastra/commit/1d677d5f99d7db403f7828585e8c25f299f72628), [`9e1dad8`](https://github.com/mastra-ai/mastra/commit/9e1dad8f7b1cab2bb7ade90e5b7561f24577b88a), [`2f43145`](https://github.com/mastra-ai/mastra/commit/2f4314504c03cbba280414ac81ba3197448ee6b0), [`0c89896`](https://github.com/mastra-ai/mastra/commit/0c8989673fb7d106837098398131e570c6023b68), [`4e35a56`](https://github.com/mastra-ai/mastra/commit/4e35a56cdf8d74a5ff6d5eda01f2c1deaf6cc7be), [`d94b8e1`](https://github.com/mastra-ai/mastra/commit/d94b8e1cee67416d518a8c30099040061bef6a1c), [`93e28ec`](https://github.com/mastra-ai/mastra/commit/93e28ecce9031c02397e0ae8406593e5c7a95883), [`729dab4`](https://github.com/mastra-ai/mastra/commit/729dab408faccfaef0cbb048e5a4338f9172847e), [`484003d`](https://github.com/mastra-ai/mastra/commit/484003d33ff59330c86b19863e4a38732d7e4155), [`3de0188`](https://github.com/mastra-ai/mastra/commit/3de0188bfaf9a9c09c95fe322b53838cf52c70b6), [`9fbd007`](https://github.com/mastra-ai/mastra/commit/9fbd0077b31a28054b16e1467f1b577e8ed62be4), [`34d34d8`](https://github.com/mastra-ai/mastra/commit/34d34d8c811df512fef4dd5459f79b7821be1866), [`b582f7f`](https://github.com/mastra-ai/mastra/commit/b582f7fa2f9c1f87d19efc63d344fbe5dda2608c), [`933d291`](https://github.com/mastra-ai/mastra/commit/933d291146b789c19442ad206f94da3e4be90c64), [`a1cb98d`](https://github.com/mastra-ai/mastra/commit/a1cb98d11990b560b98482292a1f34aa1a2d9092), [`598ad82`](https://github.com/mastra-ai/mastra/commit/598ad82d41c41389a686338a1d0e50b7400e1938), [`1fd6aad`](https://github.com/mastra-ai/mastra/commit/1fd6aad1ea4a9d32f65efa832307c35e981a4c0a)]:
|
|
31
|
+
- @mastra/core@1.56.0
|
|
32
|
+
- @mastra/observability@1.16.4
|
|
33
|
+
- @mastra/otel-exporter@1.3.7
|
|
34
|
+
|
|
35
|
+
## 1.4.5-alpha.3
|
|
36
|
+
|
|
37
|
+
### Patch Changes
|
|
38
|
+
|
|
39
|
+
- Fixed the OpenTelemetry bridge ignoring a span's explicit start time, which would report wrong durations for spans created after the work they represent began (such as provider tool call spans). ([#20522](https://github.com/mastra-ai/mastra/pull/20522))
|
|
40
|
+
|
|
41
|
+
- Updated dependencies [[`82201f7`](https://github.com/mastra-ai/mastra/commit/82201f75fae8e050a8de2df08b74875ee74c6b83), [`fb18da5`](https://github.com/mastra-ai/mastra/commit/fb18da56fc35689ae370621a8f10b5b0d8606e20), [`fb18da5`](https://github.com/mastra-ai/mastra/commit/fb18da56fc35689ae370621a8f10b5b0d8606e20), [`0a6598b`](https://github.com/mastra-ai/mastra/commit/0a6598bde80bde008986ad6616bed9632b9294cb), [`9e1dad8`](https://github.com/mastra-ai/mastra/commit/9e1dad8f7b1cab2bb7ade90e5b7561f24577b88a), [`2f43145`](https://github.com/mastra-ai/mastra/commit/2f4314504c03cbba280414ac81ba3197448ee6b0), [`34d34d8`](https://github.com/mastra-ai/mastra/commit/34d34d8c811df512fef4dd5459f79b7821be1866)]:
|
|
42
|
+
- @mastra/core@1.56.0-alpha.6
|
|
43
|
+
|
|
3
44
|
## 1.4.5-alpha.2
|
|
4
45
|
|
|
5
46
|
### Patch Changes
|
package/dist/bridge.d.ts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,CAAC,iBAAiB;IA0BzB;;OAEG;IACH,IAAI,CAAC,OAAO,EAAE,mBAAmB;IAQjC;;;;;;OAMG;IACH,UAAU,CAAC,OAAO,EAAE,iBAAiB,CAAC,QAAQ,CAAC,GAAG,OAAO,GAAG,SAAS;IAkErE;;;;;OAKG;YACW,eAAe;IAwD7B;;;;;;OAMG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAQjC;;;;;;;;;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;IAIrE;;;;;;OAMG;IACH,oBAAoB,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC;IAIvD;;;;;;;OAOG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;YAKd,aAAa;IAoB3B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAYhC"}
|
package/dist/index.cjs
CHANGED
|
@@ -133,7 +133,10 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
133
133
|
const parentEntry = this.otelSpanMap.get(externalParentId);
|
|
134
134
|
if (parentEntry) parentOtelContext = parentEntry.otelContext;
|
|
135
135
|
}
|
|
136
|
-
const otelSpan = this.otelTracer.startSpan(options.name, {
|
|
136
|
+
const otelSpan = this.otelTracer.startSpan(options.name, {
|
|
137
|
+
kind: (0, _mastra_otel_exporter.getSpanKind)(options.type),
|
|
138
|
+
...options.startTime ? { startTime: options.startTime } : {}
|
|
139
|
+
}, parentOtelContext);
|
|
137
140
|
const spanContext = _opentelemetry_api.trace.setSpan(parentOtelContext, otelSpan);
|
|
138
141
|
const otelSpanContext = otelSpan.spanContext();
|
|
139
142
|
if (!(0, _opentelemetry_api.isSpanContextValid)(otelSpanContext)) {
|
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\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 }\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 },\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 this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return { spanId, traceId, parentSpanId };\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,MAAM,UAAA,GAAA,sBAAA,WAAA,CAAoB,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;EAC7D;CACF;;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,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\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\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 }\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 this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return { spanId, traceId, parentSpanId };\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,MAAM,UAAA,GAAA,sBAAA,WAAA,CAAoB,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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AC3D;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/dist/index.js
CHANGED
|
@@ -132,7 +132,10 @@ var OtelBridge = class extends BaseExporter {
|
|
|
132
132
|
const parentEntry = this.otelSpanMap.get(externalParentId);
|
|
133
133
|
if (parentEntry) parentOtelContext = parentEntry.otelContext;
|
|
134
134
|
}
|
|
135
|
-
const otelSpan = this.otelTracer.startSpan(options.name, {
|
|
135
|
+
const otelSpan = this.otelTracer.startSpan(options.name, {
|
|
136
|
+
kind: getSpanKind(options.type),
|
|
137
|
+
...options.startTime ? { startTime: options.startTime } : {}
|
|
138
|
+
}, parentOtelContext);
|
|
136
139
|
const spanContext = trace.setSpan(parentOtelContext, otelSpan);
|
|
137
140
|
const otelSpanContext = otelSpan.spanContext();
|
|
138
141
|
if (!isSpanContextValid(otelSpanContext)) {
|
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\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 }\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 },\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 this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return { spanId, traceId, parentSpanId };\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,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,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\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\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 }\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 this.logger.debug(\n `[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] ` +\n `[parentSpanId=${parentSpanId}] [type=${options.type}] [mapSize=${this.otelSpanMap.size}]`,\n );\n\n return { spanId, traceId, parentSpanId };\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,I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B,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.4.5
|
|
3
|
+
"version": "1.4.5",
|
|
4
4
|
"description": "OpenTelemetry observability bridge for Mastra",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -26,8 +26,8 @@
|
|
|
26
26
|
"dependencies": {
|
|
27
27
|
"@opentelemetry/api": "^1.9.1",
|
|
28
28
|
"@opentelemetry/api-logs": "^0.218.0",
|
|
29
|
-
"@mastra/
|
|
30
|
-
"@mastra/
|
|
29
|
+
"@mastra/otel-exporter": "1.3.7",
|
|
30
|
+
"@mastra/observability": "1.16.4"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@opentelemetry/sdk-logs": "^0.218.0",
|
|
@@ -36,9 +36,9 @@
|
|
|
36
36
|
"tsdown": "0.22.9",
|
|
37
37
|
"typescript": "^6.0.3",
|
|
38
38
|
"vitest": "4.1.10",
|
|
39
|
-
"@internal/lint": "0.0.
|
|
40
|
-
"@mastra/core": "1.56.0
|
|
41
|
-
"@internal/types-builder": "0.0.
|
|
39
|
+
"@internal/lint": "0.0.120",
|
|
40
|
+
"@mastra/core": "1.56.0",
|
|
41
|
+
"@internal/types-builder": "0.0.95"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@mastra/core": ">=1.16.0-0 <2.0.0-0",
|