@mastra/otel-bridge 1.5.1-alpha.1 → 1.5.1
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 +22 -0
- package/dist/bridge.d.ts.map +1 -1
- package/dist/index.cjs +13 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @mastra/otel-bridge
|
|
2
2
|
|
|
3
|
+
## 1.5.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Fixed workflow traces breaking apart after suspend and resume when using OtelBridge. A resumed workflow run now continues the OpenTelemetry trace it started in instead of starting a brand-new one, even when the resume happens in a different process. This restores the trace continuity introduced in #12276 for setups that route spans through OpenTelemetry. Fixes [#20771](https://github.com/mastra-ai/mastra/issues/20771). ([#21047](https://github.com/mastra-ai/mastra/pull/21047))
|
|
8
|
+
|
|
9
|
+
- Updated dependencies [[`587f6ef`](https://github.com/mastra-ai/mastra/commit/587f6efcfc25880b93760a8607d1cd381ec612fe), [`e81744c`](https://github.com/mastra-ai/mastra/commit/e81744cd13c46619c142dc521dc0baac47607a84), [`7e096f0`](https://github.com/mastra-ai/mastra/commit/7e096f02f0dddbf09b85d306458351245ed2f886), [`d7e6745`](https://github.com/mastra-ai/mastra/commit/d7e67456954863c55440ea9c49bc6ceb9949972d), [`6223446`](https://github.com/mastra-ai/mastra/commit/6223446ddce6166e96e0ba5e00d628b615dee8ca), [`15101bb`](https://github.com/mastra-ai/mastra/commit/15101bb53c0d934f31af6b8813b88191e382a5e5), [`4e7a421`](https://github.com/mastra-ai/mastra/commit/4e7a421dce8a48742f785d1e93ad2f43a572b282), [`c2c3deb`](https://github.com/mastra-ai/mastra/commit/c2c3debcf670c7082d0a5e553aa99818a864698c), [`4077487`](https://github.com/mastra-ai/mastra/commit/407748777c9bc9d5795033f36220e97df5553355), [`d8308a2`](https://github.com/mastra-ai/mastra/commit/d8308a2be3c07e777393d1017a381dcae3890d30), [`b0a2a07`](https://github.com/mastra-ai/mastra/commit/b0a2a07800d42bd9823292e7db832374ed084c9c), [`74e5bd3`](https://github.com/mastra-ai/mastra/commit/74e5bd315b8b3a1e04cb6cf480bb0f5fc4951dc8), [`242e324`](https://github.com/mastra-ai/mastra/commit/242e3241e73cbd5c9bb86a31ebb49ca0256488d4), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`d774e89`](https://github.com/mastra-ai/mastra/commit/d774e8930c781df8c9effe3763e6b501c099b6cc), [`9c27a53`](https://github.com/mastra-ai/mastra/commit/9c27a53cd9d3de4f3f025bc387d94ce371c33f95), [`8f0a332`](https://github.com/mastra-ai/mastra/commit/8f0a3321bf180368d76fe7b36aa1a8f60f00b6de), [`d6c618f`](https://github.com/mastra-ai/mastra/commit/d6c618f37496f801827d4caa76feab742f1a7383), [`0b4f108`](https://github.com/mastra-ai/mastra/commit/0b4f1089aa8d92e67c2a8e99726822c5ee410784), [`9acb50f`](https://github.com/mastra-ai/mastra/commit/9acb50f71cec9c362f06820033f90ae6b1f8282f), [`46e9e3f`](https://github.com/mastra-ai/mastra/commit/46e9e3f73babe1bc70080a596cf2ac0b9da48519), [`3f9a190`](https://github.com/mastra-ai/mastra/commit/3f9a19057c027155867b9317294ee4ca7bd0581a), [`dff25a1`](https://github.com/mastra-ai/mastra/commit/dff25a1103fa72ee082a9b6f805ebeb5ce400753), [`6db7a5d`](https://github.com/mastra-ai/mastra/commit/6db7a5dd3dd2b6f7ef75dcd804fcffef5fa83963), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`583e235`](https://github.com/mastra-ai/mastra/commit/583e23519c13af16c1746f9c49722d011216611b), [`b098de9`](https://github.com/mastra-ai/mastra/commit/b098de9d7cb9f672e0883a5c716465a3a689693d), [`e8808e3`](https://github.com/mastra-ai/mastra/commit/e8808e3d8eb585a2565be53e56a7e0e1477352a4), [`a77f8d4`](https://github.com/mastra-ai/mastra/commit/a77f8d4740d2178a74c41e4bf678b4fcd8fa0bb2), [`7f78585`](https://github.com/mastra-ai/mastra/commit/7f785857e401570e2ffb316911f126ed363aa537), [`33374ba`](https://github.com/mastra-ai/mastra/commit/33374ba359e4fb13eaa918ae925fe167a3c55414), [`940bf5c`](https://github.com/mastra-ai/mastra/commit/940bf5ccf04f2c9ebd8a1390431733222a03b1cd), [`c549e2f`](https://github.com/mastra-ai/mastra/commit/c549e2f40edc1cac5d9e74e82f90da22b48df084), [`58c43d3`](https://github.com/mastra-ai/mastra/commit/58c43d3f7cb2eeaeb8ac733ae71dde822348e588), [`ef6e295`](https://github.com/mastra-ai/mastra/commit/ef6e295b59bc25a5b61b633a89c97bcfce9fb465), [`208e1b3`](https://github.com/mastra-ai/mastra/commit/208e1b39f30f4b386e494394e9d71d96f0f90241), [`c938d34`](https://github.com/mastra-ai/mastra/commit/c938d34739936c8ecbabd67ad6a4a4396f41c4c6), [`88ddc7c`](https://github.com/mastra-ai/mastra/commit/88ddc7ce01d40175f13a3228b789a906779680bd), [`f2a4afd`](https://github.com/mastra-ai/mastra/commit/f2a4afd7e37e809669001ed17724b341a5c1f45e), [`d438148`](https://github.com/mastra-ai/mastra/commit/d438148e222c1e2fb3c652725ce75680962ebec4), [`ba05fe0`](https://github.com/mastra-ai/mastra/commit/ba05fe0738f70cb686777546e968237d09269142), [`40d358e`](https://github.com/mastra-ai/mastra/commit/40d358e29d55543803e64b49241122f598ffabc7), [`d26a8d4`](https://github.com/mastra-ai/mastra/commit/d26a8d4281f28414715b333c85bedaf70d0b2890), [`e80cd7e`](https://github.com/mastra-ai/mastra/commit/e80cd7e7683e7d732e1cc6784bcac1d2640d2ce3), [`ccbbcd9`](https://github.com/mastra-ai/mastra/commit/ccbbcd974eedff4367a54ed0e24c9ee742ab2f61), [`1d9a0ea`](https://github.com/mastra-ai/mastra/commit/1d9a0ea4a9901baee6cd56737243bd6d1f631ac0), [`677cdc6`](https://github.com/mastra-ai/mastra/commit/677cdc6af564dec29a13464d12b7ab2a4efc22e9), [`c549e2f`](https://github.com/mastra-ai/mastra/commit/c549e2f40edc1cac5d9e74e82f90da22b48df084), [`a7dd322`](https://github.com/mastra-ai/mastra/commit/a7dd32247d95afc539f483ca37f4594af0387f59), [`3f5c6f7`](https://github.com/mastra-ai/mastra/commit/3f5c6f728ea35da344248de9aa070f12849f3aa0), [`a318490`](https://github.com/mastra-ai/mastra/commit/a318490e17da32f338d50929c770d901a9b3dd72), [`b860493`](https://github.com/mastra-ai/mastra/commit/b86049391100e665d579f700c8a2034c036defc3), [`d4be8c1`](https://github.com/mastra-ai/mastra/commit/d4be8c1739d22d621e3f78790e1dd5eb5ecc3589), [`a5d2eb1`](https://github.com/mastra-ai/mastra/commit/a5d2eb10347eade1ae2816d88f466c25186c54a5), [`3667679`](https://github.com/mastra-ai/mastra/commit/3667679db057edfb086846d13369fdda4902ad65), [`49696e8`](https://github.com/mastra-ai/mastra/commit/49696e8e42f870674a0a58f5abcd22cc54dd2864), [`2ef2f23`](https://github.com/mastra-ai/mastra/commit/2ef2f230a7aed342e7dc3b2000cd42e4c43e08a7), [`4c0b961`](https://github.com/mastra-ai/mastra/commit/4c0b9611e89c5097b7a02a28c6816e0adcbcfa09), [`763e0c6`](https://github.com/mastra-ai/mastra/commit/763e0c61e04d76ad9a9efd301aa57525ca0cbea9), [`20504b2`](https://github.com/mastra-ai/mastra/commit/20504b2ecebd0e077acda3d457ab57480a98ed3e), [`77e6b1b`](https://github.com/mastra-ai/mastra/commit/77e6b1bc4c46ce94fe501023fb4393c812ec6be3), [`c5f964d`](https://github.com/mastra-ai/mastra/commit/c5f964d3f77064e978f8066ec506eed77ba5c63c), [`23e0be2`](https://github.com/mastra-ai/mastra/commit/23e0be261381e49534b4ff3101c60ee64a946cbf), [`7fc8806`](https://github.com/mastra-ai/mastra/commit/7fc880627d3cbf995d31ea0e8b807bf15417e651), [`0e02eac`](https://github.com/mastra-ai/mastra/commit/0e02eacdb2e30e1697a41910b41163742a181dc1), [`4df174c`](https://github.com/mastra-ai/mastra/commit/4df174c32bddf093a82f273070b8380aef7c9e90), [`f7c25b5`](https://github.com/mastra-ai/mastra/commit/f7c25b5106ddfb48e591f98df7a51e0f2dd01dba), [`7aad631`](https://github.com/mastra-ai/mastra/commit/7aad631b43bc10db77d5b8c66b200d7a49d18bf2), [`512100a`](https://github.com/mastra-ai/mastra/commit/512100a7d8b7e9c920f2590c6b3612f5de0d3cff), [`e81744c`](https://github.com/mastra-ai/mastra/commit/e81744cd13c46619c142dc521dc0baac47607a84), [`f8f653f`](https://github.com/mastra-ai/mastra/commit/f8f653f10980d01a73706cc3c8689ca5e40ce808), [`dc09cc1`](https://github.com/mastra-ai/mastra/commit/dc09cc1083d861cde192c1cd235324dc75b8c731), [`e81744c`](https://github.com/mastra-ai/mastra/commit/e81744cd13c46619c142dc521dc0baac47607a84), [`9ef432b`](https://github.com/mastra-ai/mastra/commit/9ef432b6faa534b57b0d182a610e13dd9a7123ff), [`36b4649`](https://github.com/mastra-ai/mastra/commit/36b4649045a3a380cbab8ceca866db4086223aff), [`b9cf308`](https://github.com/mastra-ai/mastra/commit/b9cf30846f97f99ac1906ee8a68f4f2d117b0378), [`2e1d098`](https://github.com/mastra-ai/mastra/commit/2e1d0984e325fd319d32ea182f596b3170be3847), [`377eb81`](https://github.com/mastra-ai/mastra/commit/377eb81ce43b964e3a6b541df172da74a8ff3716), [`1794a79`](https://github.com/mastra-ai/mastra/commit/1794a79178c418004a7261b1ad9114066f7ef01d), [`0cdc5dc`](https://github.com/mastra-ai/mastra/commit/0cdc5dc69024957815da4f51acc4119eb4f447d7), [`5740ec6`](https://github.com/mastra-ai/mastra/commit/5740ec60c760ffdfbfaa59d603d03b847c864e05)]:
|
|
10
|
+
- @mastra/core@1.60.0
|
|
11
|
+
- @mastra/otel-exporter@1.3.9
|
|
12
|
+
- @mastra/observability@1.17.1
|
|
13
|
+
|
|
14
|
+
## 1.5.1-alpha.2
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- Fixed workflow traces breaking apart after suspend and resume when using OtelBridge. A resumed workflow run now continues the OpenTelemetry trace it started in instead of starting a brand-new one, even when the resume happens in a different process. This restores the trace continuity introduced in #12276 for setups that route spans through OpenTelemetry. Fixes [#20771](https://github.com/mastra-ai/mastra/issues/20771). ([#21047](https://github.com/mastra-ai/mastra/pull/21047))
|
|
19
|
+
|
|
20
|
+
- Updated dependencies [[`4e7a421`](https://github.com/mastra-ai/mastra/commit/4e7a421dce8a48742f785d1e93ad2f43a572b282), [`4077487`](https://github.com/mastra-ai/mastra/commit/407748777c9bc9d5795033f36220e97df5553355), [`242e324`](https://github.com/mastra-ai/mastra/commit/242e3241e73cbd5c9bb86a31ebb49ca0256488d4), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`d774e89`](https://github.com/mastra-ai/mastra/commit/d774e8930c781df8c9effe3763e6b501c099b6cc), [`9c27a53`](https://github.com/mastra-ai/mastra/commit/9c27a53cd9d3de4f3f025bc387d94ce371c33f95), [`dff25a1`](https://github.com/mastra-ai/mastra/commit/dff25a1103fa72ee082a9b6f805ebeb5ce400753), [`217e967`](https://github.com/mastra-ai/mastra/commit/217e9672d8b3160eb729d8e9f0044949e88da239), [`7f78585`](https://github.com/mastra-ai/mastra/commit/7f785857e401570e2ffb316911f126ed363aa537), [`f2a4afd`](https://github.com/mastra-ai/mastra/commit/f2a4afd7e37e809669001ed17724b341a5c1f45e), [`d438148`](https://github.com/mastra-ai/mastra/commit/d438148e222c1e2fb3c652725ce75680962ebec4), [`ba05fe0`](https://github.com/mastra-ai/mastra/commit/ba05fe0738f70cb686777546e968237d09269142), [`d26a8d4`](https://github.com/mastra-ai/mastra/commit/d26a8d4281f28414715b333c85bedaf70d0b2890), [`677cdc6`](https://github.com/mastra-ai/mastra/commit/677cdc6af564dec29a13464d12b7ab2a4efc22e9), [`a318490`](https://github.com/mastra-ai/mastra/commit/a318490e17da32f338d50929c770d901a9b3dd72), [`763e0c6`](https://github.com/mastra-ai/mastra/commit/763e0c61e04d76ad9a9efd301aa57525ca0cbea9), [`23e0be2`](https://github.com/mastra-ai/mastra/commit/23e0be261381e49534b4ff3101c60ee64a946cbf), [`7fc8806`](https://github.com/mastra-ai/mastra/commit/7fc880627d3cbf995d31ea0e8b807bf15417e651), [`0e02eac`](https://github.com/mastra-ai/mastra/commit/0e02eacdb2e30e1697a41910b41163742a181dc1), [`4df174c`](https://github.com/mastra-ai/mastra/commit/4df174c32bddf093a82f273070b8380aef7c9e90), [`f7c25b5`](https://github.com/mastra-ai/mastra/commit/f7c25b5106ddfb48e591f98df7a51e0f2dd01dba), [`dc09cc1`](https://github.com/mastra-ai/mastra/commit/dc09cc1083d861cde192c1cd235324dc75b8c731), [`36b4649`](https://github.com/mastra-ai/mastra/commit/36b4649045a3a380cbab8ceca866db4086223aff), [`377eb81`](https://github.com/mastra-ai/mastra/commit/377eb81ce43b964e3a6b541df172da74a8ff3716)]:
|
|
21
|
+
- @mastra/core@1.60.0-alpha.8
|
|
22
|
+
- @mastra/observability@1.17.1-alpha.2
|
|
23
|
+
- @mastra/otel-exporter@1.3.9-alpha.2
|
|
24
|
+
|
|
3
25
|
## 1.5.1-alpha.1
|
|
4
26
|
|
|
5
27
|
### Patch Changes
|
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,mBAAmB,EACpB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,YAAY,EAA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AO,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
|
@@ -128,10 +128,22 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
128
128
|
createSpan(options) {
|
|
129
129
|
try {
|
|
130
130
|
let parentOtelContext = _opentelemetry_api.context.active();
|
|
131
|
+
let usedPersistedParent = false;
|
|
131
132
|
const externalParentId = (0, _mastra_observability.getExternalParentId)(options);
|
|
132
133
|
if (externalParentId) {
|
|
133
134
|
const parentEntry = this.otelSpanMap.get(externalParentId);
|
|
134
135
|
if (parentEntry) parentOtelContext = parentEntry.otelContext;
|
|
136
|
+
} else if (options.traceId && options.parentSpanId) {
|
|
137
|
+
const candidate = {
|
|
138
|
+
traceId: options.traceId,
|
|
139
|
+
spanId: options.parentSpanId,
|
|
140
|
+
traceFlags: _opentelemetry_api.TraceFlags.SAMPLED,
|
|
141
|
+
isRemote: true
|
|
142
|
+
};
|
|
143
|
+
if ((0, _opentelemetry_api.isSpanContextValid)(candidate)) {
|
|
144
|
+
parentOtelContext = _opentelemetry_api.trace.setSpanContext(parentOtelContext, candidate);
|
|
145
|
+
usedPersistedParent = true;
|
|
146
|
+
}
|
|
135
147
|
}
|
|
136
148
|
const otelSpan = this.otelTracer.startSpan(options.name, {
|
|
137
149
|
kind: (0, _mastra_otel_exporter.getSpanKind)(options.type),
|
|
@@ -151,7 +163,7 @@ var OtelBridge = class extends _mastra_observability.BaseExporter {
|
|
|
151
163
|
});
|
|
152
164
|
const parentSpanContext = _opentelemetry_api.trace.getSpan(parentOtelContext)?.spanContext();
|
|
153
165
|
const parentSpanId = parentSpanContext && (0, _opentelemetry_api.isSpanContextValid)(parentSpanContext) ? parentSpanContext.spanId : void 0;
|
|
154
|
-
const parentIsMastraSpan = parentSpanId !== void 0 && this.otelSpanMap.has(parentSpanId);
|
|
166
|
+
const parentIsMastraSpan = parentSpanId !== void 0 && (this.otelSpanMap.has(parentSpanId) || usedPersistedParent);
|
|
155
167
|
this.logger.debug(`[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] [parentSpanId=${parentSpanId}] [parentIsMastraSpan=${parentIsMastraSpan}] [type=${options.type}] [mapSize=${this.otelSpanMap.size}]`);
|
|
156
168
|
return {
|
|
157
169
|
spanId,
|
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 ...(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.\n const parentIsMastraSpan = parentSpanId !== undefined && this.otelSpanMap.has(parentSpanId);\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,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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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gCAAgC;CACnD;AACF"}
|
package/dist/index.js
CHANGED
|
@@ -127,10 +127,22 @@ var OtelBridge = class extends BaseExporter {
|
|
|
127
127
|
createSpan(options) {
|
|
128
128
|
try {
|
|
129
129
|
let parentOtelContext = context.active();
|
|
130
|
+
let usedPersistedParent = false;
|
|
130
131
|
const externalParentId = getExternalParentId(options);
|
|
131
132
|
if (externalParentId) {
|
|
132
133
|
const parentEntry = this.otelSpanMap.get(externalParentId);
|
|
133
134
|
if (parentEntry) parentOtelContext = parentEntry.otelContext;
|
|
135
|
+
} else if (options.traceId && options.parentSpanId) {
|
|
136
|
+
const candidate = {
|
|
137
|
+
traceId: options.traceId,
|
|
138
|
+
spanId: options.parentSpanId,
|
|
139
|
+
traceFlags: TraceFlags.SAMPLED,
|
|
140
|
+
isRemote: true
|
|
141
|
+
};
|
|
142
|
+
if (isSpanContextValid(candidate)) {
|
|
143
|
+
parentOtelContext = trace.setSpanContext(parentOtelContext, candidate);
|
|
144
|
+
usedPersistedParent = true;
|
|
145
|
+
}
|
|
134
146
|
}
|
|
135
147
|
const otelSpan = this.otelTracer.startSpan(options.name, {
|
|
136
148
|
kind: getSpanKind(options.type),
|
|
@@ -150,7 +162,7 @@ var OtelBridge = class extends BaseExporter {
|
|
|
150
162
|
});
|
|
151
163
|
const parentSpanContext = trace.getSpan(parentOtelContext)?.spanContext();
|
|
152
164
|
const parentSpanId = parentSpanContext && isSpanContextValid(parentSpanContext) ? parentSpanContext.spanId : void 0;
|
|
153
|
-
const parentIsMastraSpan = parentSpanId !== void 0 && this.otelSpanMap.has(parentSpanId);
|
|
165
|
+
const parentIsMastraSpan = parentSpanId !== void 0 && (this.otelSpanMap.has(parentSpanId) || usedPersistedParent);
|
|
154
166
|
this.logger.debug(`[OtelBridge.createSpan] Created span [spanId=${spanId}] [traceId=${traceId}] [parentSpanId=${parentSpanId}] [parentIsMastraSpan=${parentIsMastraSpan}] [type=${options.type}] [mapSize=${this.otelSpanMap.size}]`);
|
|
155
167
|
return {
|
|
156
168
|
spanId,
|
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 ...(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.\n const parentIsMastraSpan = parentSpanId !== undefined && this.otelSpanMap.has(parentSpanId);\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,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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AS,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 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,cAAg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Q,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.1
|
|
3
|
+
"version": "1.5.1",
|
|
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.221.0",
|
|
29
|
-
"@mastra/
|
|
30
|
-
"@mastra/
|
|
29
|
+
"@mastra/observability": "1.17.1",
|
|
30
|
+
"@mastra/otel-exporter": "1.3.9"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@opentelemetry/sdk-logs": "^0.221.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/
|
|
40
|
-
"@
|
|
41
|
-
"@
|
|
39
|
+
"@internal/lint": "0.0.124",
|
|
40
|
+
"@internal/types-builder": "0.0.99",
|
|
41
|
+
"@mastra/core": "1.60.0"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@mastra/core": ">=1.16.0-0 <2.0.0-0",
|