@mastra/observability 1.24.0-alpha.3 → 1.24.0-alpha.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/dist/bus/observability-bus.d.ts +2 -1
- package/dist/bus/observability-bus.d.ts.map +1 -1
- package/dist/bus/route-event.d.ts.map +1 -1
- package/dist/default.d.ts +4 -1
- package/dist/default.d.ts.map +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +53 -53
- package/dist/docs/references/docs-observability-feedback.md +5 -7
- package/dist/docs/references/reference-observability-feedback.md +43 -14
- package/dist/docs/references/reference-observability-tracing-exporters-mastra-platform-exporter.md +19 -16
- package/dist/exporters/default.d.ts +4 -7
- package/dist/exporters/default.d.ts.map +1 -1
- package/dist/exporters/event-buffer.d.ts +5 -2
- package/dist/exporters/event-buffer.d.ts.map +1 -1
- package/dist/exporters/mastra-platform.d.ts +5 -1
- package/dist/exporters/mastra-platform.d.ts.map +1 -1
- package/dist/exporters/mastra-storage.d.ts +4 -7
- package/dist/exporters/mastra-storage.d.ts.map +1 -1
- package/dist/exporters/platform-resolved-record.d.ts +3 -0
- package/dist/exporters/platform-resolved-record.d.ts.map +1 -0
- package/dist/exporters/storage-annotation.d.ts +9 -0
- package/dist/exporters/storage-annotation.d.ts.map +1 -0
- package/dist/exporters/storage-byte-tracker.d.ts +2 -3
- package/dist/exporters/storage-byte-tracker.d.ts.map +1 -1
- package/dist/index.cjs +911 -730
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +911 -730
- package/dist/index.js.map +1 -1
- package/dist/instances/base.d.ts +2 -1
- package/dist/instances/base.d.ts.map +1 -1
- package/dist/metrics/pricing-data.json +279 -101
- package/dist/model-tracing.d.ts.map +1 -1
- package/dist/recorded.d.ts +4 -12
- package/dist/recorded.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -52,6 +52,9 @@ function routeToHandler(handler, event, logger) {
|
|
|
52
52
|
}), handler.name, "score", logger);
|
|
53
53
|
}
|
|
54
54
|
break;
|
|
55
|
+
case "feedback_replacement":
|
|
56
|
+
if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
|
|
57
|
+
break;
|
|
55
58
|
case "feedback": if (handler.onFeedbackEvent) return catchAsyncResult(handler.onFeedbackEvent(event), handler.name, "feedback", logger);
|
|
56
59
|
}
|
|
57
60
|
} catch (err) {
|
|
@@ -552,6 +555,10 @@ function cleanEvent(event, options) {
|
|
|
552
555
|
type: "score",
|
|
553
556
|
score: deepClean(event.score, options)
|
|
554
557
|
};
|
|
558
|
+
case "feedback_replacement": return {
|
|
559
|
+
type: event.type,
|
|
560
|
+
feedback: deepClean(event.feedback, options)
|
|
561
|
+
};
|
|
555
562
|
case "feedback": return {
|
|
556
563
|
type: "feedback",
|
|
557
564
|
feedback: deepClean(event.feedback, options)
|
|
@@ -644,10 +651,10 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
|
|
|
644
651
|
* emit() is synchronous — async handler promises are tracked internally
|
|
645
652
|
* and can be drained via flush().
|
|
646
653
|
*/
|
|
647
|
-
emit(event) {
|
|
654
|
+
emit(event, shouldHandle) {
|
|
648
655
|
const cleaned = cleanEvent(event, this.deepCleanOptions);
|
|
649
|
-
for (const exporter of this.exporters) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
|
|
650
|
-
if (this.bridge) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
|
|
656
|
+
for (const exporter of this.exporters) if (!shouldHandle || shouldHandle(exporter)) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
|
|
657
|
+
if (this.bridge && (!shouldHandle || shouldHandle(this.bridge))) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
|
|
651
658
|
super.emit(cleaned);
|
|
652
659
|
}
|
|
653
660
|
/**
|
|
@@ -3227,11 +3234,22 @@ var ModelSpanTracker = class {
|
|
|
3227
3234
|
* create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.
|
|
3228
3235
|
*/
|
|
3229
3236
|
wrapStream(stream, inferenceOnly = false) {
|
|
3237
|
+
let servedModelId;
|
|
3230
3238
|
return stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {
|
|
3231
3239
|
if (inferenceOnly) {
|
|
3232
3240
|
try {
|
|
3241
|
+
if (chunk.type === "response-metadata" && typeof chunk.payload?.modelId === "string") servedModelId = chunk.payload.modelId;
|
|
3233
3242
|
if (MODEL_RESPONSE_CHUNK_TYPES.has(chunk.type)) this.#captureCompletionStartTime();
|
|
3234
|
-
if (chunk.type === "finish")
|
|
3243
|
+
if (chunk.type === "finish") {
|
|
3244
|
+
const payload = servedModelId && !chunk.payload?.metadata?.modelId ? {
|
|
3245
|
+
...chunk.payload,
|
|
3246
|
+
metadata: {
|
|
3247
|
+
...chunk.payload?.metadata,
|
|
3248
|
+
modelId: servedModelId
|
|
3249
|
+
}
|
|
3250
|
+
} : chunk.payload;
|
|
3251
|
+
this.#endInferenceSpan(payload, false);
|
|
3252
|
+
}
|
|
3235
3253
|
} catch {}
|
|
3236
3254
|
controller.enqueue(chunk);
|
|
3237
3255
|
return;
|
|
@@ -4588,193 +4606,548 @@ var EventBuffer = class {
|
|
|
4588
4606
|
});
|
|
4589
4607
|
}
|
|
4590
4608
|
};
|
|
4591
|
-
// src/
|
|
4592
|
-
|
|
4593
|
-
|
|
4594
|
-
*/
|
|
4595
|
-
function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
|
|
4596
|
-
const observabilityStrategy = observabilityStorage.observabilityStrategy;
|
|
4597
|
-
if (config.strategy && config.strategy !== "auto") {
|
|
4598
|
-
if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
|
|
4599
|
-
logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
|
|
4600
|
-
userStrategy: config.strategy,
|
|
4601
|
-
storageAdapter: storageName,
|
|
4602
|
-
supportedStrategies: observabilityStrategy.supported,
|
|
4603
|
-
fallbackStrategy: observabilityStrategy.preferred
|
|
4604
|
-
});
|
|
4605
|
-
}
|
|
4606
|
-
return observabilityStrategy.preferred;
|
|
4609
|
+
// src/recorded.ts
|
|
4610
|
+
function nullToUndefined(value) {
|
|
4611
|
+
return value ?? void 0;
|
|
4607
4612
|
}
|
|
4608
|
-
|
|
4609
|
-
|
|
4610
|
-
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
|
|
4624
|
-
|
|
4625
|
-
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4635
|
-
|
|
4636
|
-
|
|
4637
|
-
|
|
4638
|
-
|
|
4639
|
-
|
|
4640
|
-
|
|
4641
|
-
|
|
4642
|
-
|
|
4643
|
-
|
|
4644
|
-
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
}
|
|
4659
|
-
this.#observabilityStorage = await this.#storage.getStore("observability");
|
|
4660
|
-
if (!this.#observabilityStorage) {
|
|
4661
|
-
this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
|
|
4662
|
-
return;
|
|
4663
|
-
}
|
|
4664
|
-
if (!this.#resolvedStrategy) {
|
|
4665
|
-
this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
|
|
4666
|
-
this.logger.debug("tracing storage exporter initialized", {
|
|
4667
|
-
strategy: this.#resolvedStrategy,
|
|
4668
|
-
source: this.#config.strategy !== "auto" ? "user" : "auto",
|
|
4669
|
-
storageAdapter: this.#storage.constructor.name,
|
|
4670
|
-
maxBatchSize: this.#config.maxBatchSize,
|
|
4671
|
-
maxBatchWaitMs: this.#config.maxBatchWaitMs
|
|
4672
|
-
});
|
|
4673
|
-
}
|
|
4674
|
-
if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
|
|
4675
|
-
} finally {
|
|
4676
|
-
this.#isInitializing = false;
|
|
4677
|
-
/**
|
|
4678
|
-
* Assumes caller waits until export of a parent span is completed before calling
|
|
4679
|
-
* export for child spans , order is not relevant for resolve
|
|
4680
|
-
*/
|
|
4681
|
-
this.#initPromises.forEach((resolve) => {
|
|
4682
|
-
resolve();
|
|
4683
|
-
});
|
|
4684
|
-
this.#initPromises.clear();
|
|
4685
|
-
}
|
|
4686
|
-
}
|
|
4687
|
-
/**
|
|
4688
|
-
* Checks if buffer should be flushed based on size or time triggers
|
|
4689
|
-
*/
|
|
4690
|
-
shouldFlush() {
|
|
4691
|
-
if (this.#resolvedStrategy === "realtime") return true;
|
|
4692
|
-
if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
|
|
4693
|
-
if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
|
|
4694
|
-
if (this.#eventBuffer.totalSize > 0) {
|
|
4695
|
-
if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
|
|
4696
|
-
}
|
|
4697
|
-
return false;
|
|
4698
|
-
}
|
|
4699
|
-
/**
|
|
4700
|
-
* Schedules a flush using setTimeout
|
|
4701
|
-
*/
|
|
4702
|
-
scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
|
|
4703
|
-
if (this.#flushTimer) clearTimeout(this.#flushTimer);
|
|
4704
|
-
this.#flushTimer = setTimeout(() => {
|
|
4705
|
-
this.#flushTimer = void 0;
|
|
4706
|
-
this.trackFlushBuffer().catch((error) => {
|
|
4707
|
-
this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
|
|
4708
|
-
});
|
|
4709
|
-
}, delayMs);
|
|
4710
|
-
}
|
|
4711
|
-
retryDelay(retryAttempt) {
|
|
4712
|
-
return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
|
|
4713
|
-
}
|
|
4714
|
-
retryAttempt(events) {
|
|
4715
|
-
return events.reduce((earliestAttempt, event) => {
|
|
4716
|
-
if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
|
|
4717
|
-
return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
|
|
4718
|
-
}, void 0);
|
|
4719
|
-
}
|
|
4720
|
-
logStorageFailure(signal, events, retryAttempt, error) {
|
|
4721
|
-
this.logger.warn("Failed to persist observability events", {
|
|
4722
|
-
signal,
|
|
4723
|
-
eventCount: events.length,
|
|
4724
|
-
retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
|
|
4725
|
-
maxRetries: this.#config.maxRetries,
|
|
4726
|
-
...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
|
|
4727
|
-
error: error instanceof Error ? error.message : String(error)
|
|
4728
|
-
});
|
|
4729
|
-
}
|
|
4730
|
-
/**
|
|
4731
|
-
* Checks flush triggers and schedules/triggers flush as needed.
|
|
4732
|
-
* Called after adding any event to the buffer.
|
|
4733
|
-
* Returns the flush promise when flushing so callers can await it.
|
|
4734
|
-
*/
|
|
4735
|
-
async handleBatchedFlush() {
|
|
4736
|
-
if (this.shouldFlush()) await this.trackFlushBuffer();
|
|
4737
|
-
else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
|
|
4738
|
-
}
|
|
4739
|
-
sanitizeDropError(error) {
|
|
4740
|
-
if (error instanceof MastraError) return {
|
|
4741
|
-
id: error.id,
|
|
4742
|
-
domain: String(error.domain),
|
|
4743
|
-
message: error.message
|
|
4744
|
-
};
|
|
4745
|
-
if (error instanceof Error) return { message: error.message };
|
|
4746
|
-
return { message: String(error) };
|
|
4747
|
-
}
|
|
4748
|
-
emitDrop(signal, reason, count, error) {
|
|
4749
|
-
if (count === 0) return;
|
|
4750
|
-
const dropEvent = {
|
|
4751
|
-
type: "drop",
|
|
4752
|
-
signal,
|
|
4753
|
-
reason,
|
|
4754
|
-
count,
|
|
4613
|
+
function mergeMetadata(base, extra) {
|
|
4614
|
+
if (!base && !extra) return void 0;
|
|
4615
|
+
return {
|
|
4616
|
+
...base ?? {},
|
|
4617
|
+
...extra ?? {}
|
|
4618
|
+
};
|
|
4619
|
+
}
|
|
4620
|
+
function normalizeErrorInfo(error) {
|
|
4621
|
+
if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
|
|
4622
|
+
return {
|
|
4623
|
+
message: error.message,
|
|
4624
|
+
id: "id" in error && typeof error.id === "string" ? error.id : void 0,
|
|
4625
|
+
name: "name" in error && typeof error.name === "string" ? error.name : void 0,
|
|
4626
|
+
stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
|
|
4627
|
+
domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
|
|
4628
|
+
category: "category" in error && typeof error.category === "string" ? error.category : void 0,
|
|
4629
|
+
details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
|
|
4630
|
+
};
|
|
4631
|
+
}
|
|
4632
|
+
function buildCorrelationContext(span, rootSpan, parent) {
|
|
4633
|
+
return {
|
|
4634
|
+
tags: rootSpan.tags ?? void 0,
|
|
4635
|
+
entityType: nullToUndefined(span.entityType),
|
|
4636
|
+
entityId: nullToUndefined(span.entityId),
|
|
4637
|
+
entityName: nullToUndefined(span.entityName),
|
|
4638
|
+
parentEntityType: parent?.entityType ?? void 0,
|
|
4639
|
+
parentEntityId: parent?.entityId ?? void 0,
|
|
4640
|
+
parentEntityName: parent?.entityName ?? void 0,
|
|
4641
|
+
rootEntityType: nullToUndefined(rootSpan.entityType),
|
|
4642
|
+
rootEntityId: nullToUndefined(rootSpan.entityId),
|
|
4643
|
+
rootEntityName: nullToUndefined(rootSpan.entityName),
|
|
4644
|
+
userId: nullToUndefined(span.userId),
|
|
4645
|
+
organizationId: nullToUndefined(span.organizationId),
|
|
4646
|
+
resourceId: nullToUndefined(span.resourceId),
|
|
4647
|
+
runId: nullToUndefined(span.runId),
|
|
4648
|
+
sessionId: nullToUndefined(span.sessionId),
|
|
4649
|
+
threadId: nullToUndefined(span.threadId),
|
|
4650
|
+
requestId: nullToUndefined(span.requestId),
|
|
4651
|
+
environment: nullToUndefined(span.environment),
|
|
4652
|
+
source: nullToUndefined(span.source),
|
|
4653
|
+
serviceName: nullToUndefined(span.serviceName),
|
|
4654
|
+
experimentId: nullToUndefined(span.experimentId)
|
|
4655
|
+
};
|
|
4656
|
+
}
|
|
4657
|
+
function buildScoreEvent(args) {
|
|
4658
|
+
const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
|
|
4659
|
+
return {
|
|
4660
|
+
type: "score",
|
|
4661
|
+
score: {
|
|
4662
|
+
scoreId: generateSignalId(),
|
|
4755
4663
|
timestamp: /* @__PURE__ */ new Date(),
|
|
4756
|
-
|
|
4757
|
-
|
|
4758
|
-
|
|
4759
|
-
|
|
4760
|
-
|
|
4761
|
-
|
|
4762
|
-
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
|
|
4770
|
-
this.emitDrop(signal, "unsupported-storage", events.length);
|
|
4771
|
-
return { failed: true };
|
|
4664
|
+
traceId,
|
|
4665
|
+
spanId,
|
|
4666
|
+
scorerId: score.scorerId,
|
|
4667
|
+
scorerName: score.scorerName,
|
|
4668
|
+
scorerVersion: score.scorerVersion,
|
|
4669
|
+
source: score.source,
|
|
4670
|
+
scoreSource: score.scoreSource,
|
|
4671
|
+
score: score.score,
|
|
4672
|
+
reason: score.reason,
|
|
4673
|
+
experimentId: score.experimentId,
|
|
4674
|
+
scoreTraceId: score.scoreTraceId,
|
|
4675
|
+
targetEntityType: score.targetEntityType,
|
|
4676
|
+
correlationContext,
|
|
4677
|
+
metadata: mergeMetadata(inheritedMetadata, score.metadata)
|
|
4772
4678
|
}
|
|
4773
|
-
|
|
4774
|
-
|
|
4775
|
-
|
|
4776
|
-
|
|
4777
|
-
|
|
4679
|
+
};
|
|
4680
|
+
}
|
|
4681
|
+
function buildFeedbackEvent(args) {
|
|
4682
|
+
const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
|
|
4683
|
+
return {
|
|
4684
|
+
type: "feedback",
|
|
4685
|
+
feedback: {
|
|
4686
|
+
feedbackId: generateSignalId(),
|
|
4687
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
4688
|
+
traceId,
|
|
4689
|
+
spanId,
|
|
4690
|
+
source: feedback.source,
|
|
4691
|
+
feedbackSource: feedback.feedbackSource,
|
|
4692
|
+
feedbackType: feedback.feedbackType,
|
|
4693
|
+
value: feedback.value,
|
|
4694
|
+
userId: feedback.userId,
|
|
4695
|
+
feedbackUserId: feedback.feedbackUserId,
|
|
4696
|
+
comment: feedback.comment,
|
|
4697
|
+
sourceId: feedback.sourceId,
|
|
4698
|
+
experimentId: feedback.experimentId,
|
|
4699
|
+
correlationContext,
|
|
4700
|
+
metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
|
|
4701
|
+
}
|
|
4702
|
+
};
|
|
4703
|
+
}
|
|
4704
|
+
function findSpanById(spans, spanId) {
|
|
4705
|
+
if (!spanId) return void 0;
|
|
4706
|
+
return spans.find((span) => span.spanId === spanId);
|
|
4707
|
+
}
|
|
4708
|
+
/** Resolve a storage exporter's copy without changing the event identity or other destinations' payloads. */
|
|
4709
|
+
function resolveRecordedEventFromTrace(trace, event) {
|
|
4710
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
4711
|
+
const spans = trace.spans.filter((span) => span.traceId === record.traceId);
|
|
4712
|
+
const span = record.spanId ? findSpanById(spans, record.spanId) : spans.find((span) => !span.parentSpanId);
|
|
4713
|
+
if (!span) return null;
|
|
4714
|
+
const byId = new Map(spans.map((span) => [span.spanId, span]));
|
|
4715
|
+
let root = span;
|
|
4716
|
+
const visited = /* @__PURE__ */ new Set();
|
|
4717
|
+
while (root.parentSpanId) {
|
|
4718
|
+
if (visited.has(root.spanId)) return null;
|
|
4719
|
+
visited.add(root.spanId);
|
|
4720
|
+
const parent = byId.get(root.parentSpanId);
|
|
4721
|
+
if (!parent) return null;
|
|
4722
|
+
root = parent;
|
|
4723
|
+
}
|
|
4724
|
+
const context = {
|
|
4725
|
+
correlationContext: buildCorrelationContext(span, root, span.parentSpanId ? byId.get(span.parentSpanId) : void 0),
|
|
4726
|
+
metadata: mergeMetadata(span.metadata, record.metadata)
|
|
4727
|
+
};
|
|
4728
|
+
return event.type === "score" ? {
|
|
4729
|
+
type: "score",
|
|
4730
|
+
score: {
|
|
4731
|
+
...event.score,
|
|
4732
|
+
...context
|
|
4733
|
+
}
|
|
4734
|
+
} : event.type === "feedback_replacement" ? {
|
|
4735
|
+
type: "feedback_replacement",
|
|
4736
|
+
feedback: {
|
|
4737
|
+
...event.feedback,
|
|
4738
|
+
...context
|
|
4739
|
+
}
|
|
4740
|
+
} : {
|
|
4741
|
+
type: "feedback",
|
|
4742
|
+
feedback: {
|
|
4743
|
+
...event.feedback,
|
|
4744
|
+
...context
|
|
4745
|
+
}
|
|
4746
|
+
};
|
|
4747
|
+
}
|
|
4748
|
+
var RecordedSpanImpl = class {
|
|
4749
|
+
id;
|
|
4750
|
+
traceId;
|
|
4751
|
+
name;
|
|
4752
|
+
type;
|
|
4753
|
+
entityType;
|
|
4754
|
+
entityId;
|
|
4755
|
+
entityName;
|
|
4756
|
+
startTime;
|
|
4757
|
+
endTime;
|
|
4758
|
+
attributes;
|
|
4759
|
+
metadata;
|
|
4760
|
+
tags;
|
|
4761
|
+
input;
|
|
4762
|
+
output;
|
|
4763
|
+
errorInfo;
|
|
4764
|
+
requestContext;
|
|
4765
|
+
isEvent;
|
|
4766
|
+
isRootSpan;
|
|
4767
|
+
parentSpanId;
|
|
4768
|
+
parent;
|
|
4769
|
+
children = [];
|
|
4770
|
+
#raw;
|
|
4771
|
+
#rootSpan;
|
|
4772
|
+
#emitRecordedEvent;
|
|
4773
|
+
#canEmitRecordedEvent;
|
|
4774
|
+
#debugRecordedAnnotationUnavailable;
|
|
4775
|
+
constructor(args) {
|
|
4776
|
+
const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
|
|
4777
|
+
this.#raw = raw;
|
|
4778
|
+
this.#rootSpan = rootSpan;
|
|
4779
|
+
this.#emitRecordedEvent = emitRecordedEvent;
|
|
4780
|
+
this.#canEmitRecordedEvent = canEmitRecordedEvent;
|
|
4781
|
+
this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
|
|
4782
|
+
this.id = raw.spanId;
|
|
4783
|
+
this.traceId = raw.traceId;
|
|
4784
|
+
this.name = raw.name;
|
|
4785
|
+
this.type = raw.spanType;
|
|
4786
|
+
this.entityType = raw.entityType ?? void 0;
|
|
4787
|
+
this.entityId = raw.entityId ?? void 0;
|
|
4788
|
+
this.entityName = raw.entityName ?? void 0;
|
|
4789
|
+
this.startTime = raw.startedAt;
|
|
4790
|
+
this.endTime = raw.endedAt ?? void 0;
|
|
4791
|
+
this.attributes = raw.attributes ?? void 0;
|
|
4792
|
+
this.metadata = raw.metadata ?? void 0;
|
|
4793
|
+
this.tags = raw.tags ?? void 0;
|
|
4794
|
+
this.input = raw.input ?? void 0;
|
|
4795
|
+
this.output = raw.output ?? void 0;
|
|
4796
|
+
this.errorInfo = normalizeErrorInfo(raw.error);
|
|
4797
|
+
this.requestContext = raw.requestContext ?? void 0;
|
|
4798
|
+
this.isEvent = raw.isEvent;
|
|
4799
|
+
this.isRootSpan = !raw.parentSpanId;
|
|
4800
|
+
this.parentSpanId = raw.parentSpanId ?? void 0;
|
|
4801
|
+
}
|
|
4802
|
+
async addScore(score) {
|
|
4803
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4804
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4805
|
+
kind: "score",
|
|
4806
|
+
traceId: this.traceId,
|
|
4807
|
+
spanId: this.id
|
|
4808
|
+
});
|
|
4809
|
+
return;
|
|
4810
|
+
}
|
|
4811
|
+
await this.#emitRecordedEvent(buildScoreEvent({
|
|
4812
|
+
traceId: this.#raw.traceId,
|
|
4813
|
+
spanId: this.id,
|
|
4814
|
+
correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
|
|
4815
|
+
score,
|
|
4816
|
+
inheritedMetadata: this.#raw.metadata
|
|
4817
|
+
}));
|
|
4818
|
+
}
|
|
4819
|
+
async addFeedback(feedback) {
|
|
4820
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4821
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4822
|
+
kind: "feedback",
|
|
4823
|
+
traceId: this.traceId,
|
|
4824
|
+
spanId: this.id
|
|
4825
|
+
});
|
|
4826
|
+
return;
|
|
4827
|
+
}
|
|
4828
|
+
await this.#emitRecordedEvent(buildFeedbackEvent({
|
|
4829
|
+
traceId: this.#raw.traceId,
|
|
4830
|
+
spanId: this.id,
|
|
4831
|
+
correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
|
|
4832
|
+
feedback,
|
|
4833
|
+
inheritedMetadata: this.#raw.metadata
|
|
4834
|
+
}));
|
|
4835
|
+
}
|
|
4836
|
+
};
|
|
4837
|
+
var RecordedTraceImpl = class {
|
|
4838
|
+
traceId;
|
|
4839
|
+
rootSpan;
|
|
4840
|
+
spans;
|
|
4841
|
+
#rootRecord;
|
|
4842
|
+
#emitRecordedEvent;
|
|
4843
|
+
#spanMap;
|
|
4844
|
+
#canEmitRecordedEvent;
|
|
4845
|
+
#debugRecordedAnnotationUnavailable;
|
|
4846
|
+
constructor(args) {
|
|
4847
|
+
this.traceId = args.traceId;
|
|
4848
|
+
this.rootSpan = args.rootSpan;
|
|
4849
|
+
this.#rootRecord = args.rootRecord;
|
|
4850
|
+
this.spans = args.spans;
|
|
4851
|
+
this.#emitRecordedEvent = args.emitRecordedEvent;
|
|
4852
|
+
this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
|
|
4853
|
+
this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
|
|
4854
|
+
this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
|
|
4855
|
+
}
|
|
4856
|
+
getSpan(spanId) {
|
|
4857
|
+
return this.#spanMap.get(spanId) ?? null;
|
|
4858
|
+
}
|
|
4859
|
+
async addScore(score) {
|
|
4860
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4861
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4862
|
+
kind: "score",
|
|
4863
|
+
traceId: this.traceId
|
|
4864
|
+
});
|
|
4865
|
+
return;
|
|
4866
|
+
}
|
|
4867
|
+
await this.#emitRecordedEvent(buildScoreEvent({
|
|
4868
|
+
traceId: this.#rootRecord.traceId,
|
|
4869
|
+
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
4870
|
+
score,
|
|
4871
|
+
inheritedMetadata: this.#rootRecord.metadata
|
|
4872
|
+
}));
|
|
4873
|
+
}
|
|
4874
|
+
async addFeedback(feedback) {
|
|
4875
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4876
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4877
|
+
kind: "feedback",
|
|
4878
|
+
traceId: this.traceId
|
|
4879
|
+
});
|
|
4880
|
+
return;
|
|
4881
|
+
}
|
|
4882
|
+
await this.#emitRecordedEvent(buildFeedbackEvent({
|
|
4883
|
+
traceId: this.#rootRecord.traceId,
|
|
4884
|
+
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
4885
|
+
feedback,
|
|
4886
|
+
inheritedMetadata: this.#rootRecord.metadata
|
|
4887
|
+
}));
|
|
4888
|
+
}
|
|
4889
|
+
};
|
|
4890
|
+
function findRootSpan(spans) {
|
|
4891
|
+
const spanIds = new Set(spans.map((span) => span.spanId));
|
|
4892
|
+
return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
|
|
4893
|
+
}
|
|
4894
|
+
function hydrateRecordedTrace(args) {
|
|
4895
|
+
const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
|
|
4896
|
+
const rootSpan = findRootSpan(trace.spans);
|
|
4897
|
+
if (!rootSpan) return null;
|
|
4898
|
+
const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
|
|
4899
|
+
raw,
|
|
4900
|
+
rootSpan,
|
|
4901
|
+
emitRecordedEvent,
|
|
4902
|
+
canEmitRecordedEvent,
|
|
4903
|
+
debugRecordedAnnotationUnavailable
|
|
4904
|
+
}));
|
|
4905
|
+
const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
|
|
4906
|
+
for (const span of recordedSpans) {
|
|
4907
|
+
if (!span.parentSpanId) continue;
|
|
4908
|
+
const parent = spanMap.get(span.parentSpanId);
|
|
4909
|
+
if (!parent) continue;
|
|
4910
|
+
span.parent = parent;
|
|
4911
|
+
parent.children.push(span);
|
|
4912
|
+
}
|
|
4913
|
+
const hydratedRootSpan = spanMap.get(rootSpan.spanId);
|
|
4914
|
+
if (!hydratedRootSpan) return null;
|
|
4915
|
+
return new RecordedTraceImpl({
|
|
4916
|
+
traceId: trace.traceId,
|
|
4917
|
+
rootSpan: hydratedRootSpan,
|
|
4918
|
+
rootRecord: rootSpan,
|
|
4919
|
+
spans: recordedSpans,
|
|
4920
|
+
emitRecordedEvent,
|
|
4921
|
+
canEmitRecordedEvent,
|
|
4922
|
+
debugRecordedAnnotationUnavailable
|
|
4923
|
+
});
|
|
4924
|
+
}
|
|
4925
|
+
// src/exporters/storage-annotation.ts
|
|
4926
|
+
const LOOKUP_DELAYS_MS = [
|
|
4927
|
+
0,
|
|
4928
|
+
100,
|
|
4929
|
+
250,
|
|
4930
|
+
500,
|
|
4931
|
+
1e3,
|
|
4932
|
+
2e3,
|
|
4933
|
+
2e3
|
|
4934
|
+
];
|
|
4935
|
+
/**
|
|
4936
|
+
* Resolve attached-storage context within a bounded retry window, including failed reads.
|
|
4937
|
+
* Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
|
|
4938
|
+
* Other destinations receive the original event independently.
|
|
4939
|
+
*/
|
|
4940
|
+
async function resolveStorageAnnotation(event, storage, flushSpans) {
|
|
4941
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
4942
|
+
if (record.correlationContext !== void 0) return event;
|
|
4943
|
+
if (!record.traceId) return null;
|
|
4944
|
+
let lastReadFailure;
|
|
4945
|
+
for (const delay of LOOKUP_DELAYS_MS) {
|
|
4946
|
+
if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
|
|
4947
|
+
let trace;
|
|
4948
|
+
try {
|
|
4949
|
+
trace = await storage.getTrace({ traceId: record.traceId });
|
|
4950
|
+
lastReadFailure = void 0;
|
|
4951
|
+
} catch (error) {
|
|
4952
|
+
lastReadFailure = { error };
|
|
4953
|
+
}
|
|
4954
|
+
if (trace) {
|
|
4955
|
+
const resolved = resolveRecordedEventFromTrace(trace, event);
|
|
4956
|
+
if (resolved) return resolved;
|
|
4957
|
+
}
|
|
4958
|
+
if (delay === 0) await flushSpans();
|
|
4959
|
+
}
|
|
4960
|
+
if (lastReadFailure) throw lastReadFailure.error;
|
|
4961
|
+
return null;
|
|
4962
|
+
}
|
|
4963
|
+
// src/exporters/default.ts
|
|
4964
|
+
/**
|
|
4965
|
+
* Resolves the final tracing storage strategy based on config and observability store hints
|
|
4966
|
+
*/
|
|
4967
|
+
function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
|
|
4968
|
+
const observabilityStrategy = observabilityStorage.observabilityStrategy;
|
|
4969
|
+
if (config.strategy && config.strategy !== "auto") {
|
|
4970
|
+
if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
|
|
4971
|
+
logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
|
|
4972
|
+
userStrategy: config.strategy,
|
|
4973
|
+
storageAdapter: storageName,
|
|
4974
|
+
supportedStrategies: observabilityStrategy.supported,
|
|
4975
|
+
fallbackStrategy: observabilityStrategy.preferred
|
|
4976
|
+
});
|
|
4977
|
+
}
|
|
4978
|
+
return observabilityStrategy.preferred;
|
|
4979
|
+
}
|
|
4980
|
+
const FLUSH_SUCCEEDED$1 = { failed: false };
|
|
4981
|
+
/** Max join/write rounds a single flush() makes before it returns under continuous traffic */
|
|
4982
|
+
const MAX_FLUSH_ROUNDS$1 = 3;
|
|
4983
|
+
/**
|
|
4984
|
+
* @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
|
|
4985
|
+
* This class is preserved unchanged so existing integrations (including code
|
|
4986
|
+
* that matches on the `mastra-default-observability-exporter` exporter name)
|
|
4987
|
+
* keep working. It will be removed in a future major version.
|
|
4988
|
+
*
|
|
4989
|
+
* Default storage-backed exporter. Buffers observability events and flushes them
|
|
4990
|
+
* in batches to the configured ObservabilityStorage backend with retry support.
|
|
4991
|
+
*/
|
|
4992
|
+
var DefaultExporter = class extends BaseExporter {
|
|
4993
|
+
name = "mastra-default-observability-exporter";
|
|
4994
|
+
#config;
|
|
4995
|
+
#isInitializing = false;
|
|
4996
|
+
#initPromises = /* @__PURE__ */ new Set();
|
|
4997
|
+
#eventBuffer;
|
|
4998
|
+
#storage;
|
|
4999
|
+
#observabilityStorage;
|
|
5000
|
+
#resolvedStrategy;
|
|
5001
|
+
#flushTimer;
|
|
5002
|
+
/** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
|
|
5003
|
+
#inFlightFlushes = /* @__PURE__ */ new Set();
|
|
5004
|
+
#pendingAnnotations = /* @__PURE__ */ new Set();
|
|
5005
|
+
#emitDropEvent;
|
|
5006
|
+
#unsupportedSignals = /* @__PURE__ */ new Set();
|
|
5007
|
+
constructor(config = {}) {
|
|
5008
|
+
super(config);
|
|
5009
|
+
this.#config = {
|
|
5010
|
+
...config,
|
|
5011
|
+
maxBatchSize: config.maxBatchSize ?? 1e3,
|
|
5012
|
+
maxBufferSize: config.maxBufferSize ?? 1e4,
|
|
5013
|
+
maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
|
|
5014
|
+
maxRetries: config.maxRetries ?? 4,
|
|
5015
|
+
retryDelayMs: config.retryDelayMs ?? 500,
|
|
5016
|
+
strategy: config.strategy ?? "auto"
|
|
5017
|
+
};
|
|
5018
|
+
this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
|
|
5019
|
+
}
|
|
5020
|
+
/**
|
|
5021
|
+
* Initialize the exporter (called after all dependencies are ready)
|
|
5022
|
+
*/
|
|
5023
|
+
async init(options) {
|
|
5024
|
+
try {
|
|
5025
|
+
this.#isInitializing = true;
|
|
5026
|
+
this.#emitDropEvent = options.emitDropEvent;
|
|
5027
|
+
this.#storage = options.mastra?.getStorage();
|
|
5028
|
+
if (!this.#storage) {
|
|
5029
|
+
this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
|
|
5030
|
+
return;
|
|
5031
|
+
}
|
|
5032
|
+
this.#observabilityStorage = await this.#storage.getStore("observability");
|
|
5033
|
+
if (!this.#observabilityStorage) {
|
|
5034
|
+
this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
|
|
5035
|
+
return;
|
|
5036
|
+
}
|
|
5037
|
+
if (!this.#resolvedStrategy) {
|
|
5038
|
+
this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
|
|
5039
|
+
this.logger.debug("tracing storage exporter initialized", {
|
|
5040
|
+
strategy: this.#resolvedStrategy,
|
|
5041
|
+
source: this.#config.strategy !== "auto" ? "user" : "auto",
|
|
5042
|
+
storageAdapter: this.#storage.constructor.name,
|
|
5043
|
+
maxBatchSize: this.#config.maxBatchSize,
|
|
5044
|
+
maxBatchWaitMs: this.#config.maxBatchWaitMs
|
|
5045
|
+
});
|
|
5046
|
+
}
|
|
5047
|
+
if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
|
|
5048
|
+
} finally {
|
|
5049
|
+
this.#isInitializing = false;
|
|
5050
|
+
/**
|
|
5051
|
+
* Assumes caller waits until export of a parent span is completed before calling
|
|
5052
|
+
* export for child spans , order is not relevant for resolve
|
|
5053
|
+
*/
|
|
5054
|
+
this.#initPromises.forEach((resolve) => {
|
|
5055
|
+
resolve();
|
|
5056
|
+
});
|
|
5057
|
+
this.#initPromises.clear();
|
|
5058
|
+
}
|
|
5059
|
+
}
|
|
5060
|
+
/**
|
|
5061
|
+
* Checks if buffer should be flushed based on size or time triggers
|
|
5062
|
+
*/
|
|
5063
|
+
shouldFlush() {
|
|
5064
|
+
if (this.#resolvedStrategy === "realtime") return true;
|
|
5065
|
+
if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
|
|
5066
|
+
if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
|
|
5067
|
+
if (this.#eventBuffer.totalSize > 0) {
|
|
5068
|
+
if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
|
|
5069
|
+
}
|
|
5070
|
+
return false;
|
|
5071
|
+
}
|
|
5072
|
+
/**
|
|
5073
|
+
* Schedules a flush using setTimeout
|
|
5074
|
+
*/
|
|
5075
|
+
scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
|
|
5076
|
+
if (this.#flushTimer) clearTimeout(this.#flushTimer);
|
|
5077
|
+
this.#flushTimer = setTimeout(() => {
|
|
5078
|
+
this.#flushTimer = void 0;
|
|
5079
|
+
this.trackFlushBuffer().catch((error) => {
|
|
5080
|
+
this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
|
|
5081
|
+
});
|
|
5082
|
+
}, delayMs);
|
|
5083
|
+
}
|
|
5084
|
+
retryDelay(retryAttempt) {
|
|
5085
|
+
return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
|
|
5086
|
+
}
|
|
5087
|
+
retryAttempt(events) {
|
|
5088
|
+
return events.reduce((earliestAttempt, event) => {
|
|
5089
|
+
if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
|
|
5090
|
+
return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
|
|
5091
|
+
}, void 0);
|
|
5092
|
+
}
|
|
5093
|
+
logStorageFailure(signal, events, retryAttempt, error) {
|
|
5094
|
+
this.logger.warn("Failed to persist observability events", {
|
|
5095
|
+
signal,
|
|
5096
|
+
eventCount: events.length,
|
|
5097
|
+
retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
|
|
5098
|
+
maxRetries: this.#config.maxRetries,
|
|
5099
|
+
...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
|
|
5100
|
+
error: error instanceof Error ? error.message : String(error)
|
|
5101
|
+
});
|
|
5102
|
+
}
|
|
5103
|
+
/**
|
|
5104
|
+
* Checks flush triggers and schedules/triggers flush as needed.
|
|
5105
|
+
* Called after adding any event to the buffer.
|
|
5106
|
+
* Returns the flush promise when flushing so callers can await it.
|
|
5107
|
+
*/
|
|
5108
|
+
async handleBatchedFlush() {
|
|
5109
|
+
if (this.shouldFlush()) await this.trackFlushBuffer();
|
|
5110
|
+
else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
|
|
5111
|
+
}
|
|
5112
|
+
sanitizeDropError(error) {
|
|
5113
|
+
if (error instanceof MastraError) return {
|
|
5114
|
+
id: error.id,
|
|
5115
|
+
domain: String(error.domain),
|
|
5116
|
+
message: error.message
|
|
5117
|
+
};
|
|
5118
|
+
if (error instanceof Error) return { message: error.message };
|
|
5119
|
+
return { message: String(error) };
|
|
5120
|
+
}
|
|
5121
|
+
emitDrop(signal, reason, count, error) {
|
|
5122
|
+
if (count === 0) return;
|
|
5123
|
+
const dropEvent = {
|
|
5124
|
+
type: "drop",
|
|
5125
|
+
signal,
|
|
5126
|
+
reason,
|
|
5127
|
+
count,
|
|
5128
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
5129
|
+
exporterName: this.name,
|
|
5130
|
+
...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
|
|
5131
|
+
...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
|
|
5132
|
+
};
|
|
5133
|
+
this.#emitDropEvent?.(dropEvent);
|
|
5134
|
+
}
|
|
5135
|
+
/**
|
|
5136
|
+
* Flush a batch of create events for a single signal type.
|
|
5137
|
+
* On "not implemented" errors, disables the signal for future flushes.
|
|
5138
|
+
* On other errors, re-adds events to the buffer for retry.
|
|
5139
|
+
*/
|
|
5140
|
+
async flushCreates(signal, events, storageCall) {
|
|
5141
|
+
if (events.length === 0) return FLUSH_SUCCEEDED$1;
|
|
5142
|
+
if (this.#unsupportedSignals.has(signal)) {
|
|
5143
|
+
this.emitDrop(signal, "unsupported-storage", events.length);
|
|
5144
|
+
return { failed: true };
|
|
5145
|
+
}
|
|
5146
|
+
try {
|
|
5147
|
+
await storageCall(events);
|
|
5148
|
+
return FLUSH_SUCCEEDED$1;
|
|
5149
|
+
} catch (error) {
|
|
5150
|
+
if (error instanceof MastraError && error.domain === ErrorDomain.MASTRA_OBSERVABILITY && error.id.endsWith("_NOT_IMPLEMENTED")) {
|
|
4778
5151
|
this.logger.warn(error.message);
|
|
4779
5152
|
this.#unsupportedSignals.add(signal);
|
|
4780
5153
|
this.emitDrop(signal, "unsupported-storage", events.length, error);
|
|
@@ -4901,7 +5274,10 @@ var DefaultExporter = class extends BaseExporter {
|
|
|
4901
5274
|
case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
|
|
4902
5275
|
}
|
|
4903
5276
|
const flushResults = await Promise.all([
|
|
4904
|
-
this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5277
|
+
this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5278
|
+
feedbacks: events.map((f) => buildFeedbackRecord(f)),
|
|
5279
|
+
onConflict: "ignore"
|
|
5280
|
+
})),
|
|
4905
5281
|
this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
|
|
4906
5282
|
this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
|
|
4907
5283
|
this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
|
|
@@ -4978,22 +5354,46 @@ var DefaultExporter = class extends BaseExporter {
|
|
|
4978
5354
|
this.#eventBuffer.addEvent(event);
|
|
4979
5355
|
await this.handleBatchedFlush();
|
|
4980
5356
|
}
|
|
4981
|
-
|
|
4982
|
-
|
|
4983
|
-
*/
|
|
4984
|
-
async onScoreEvent(event) {
|
|
4985
|
-
await this.waitForInit();
|
|
4986
|
-
if (!this.#observabilityStorage) return;
|
|
4987
|
-
this.#eventBuffer.addEvent(event);
|
|
4988
|
-
await this.handleBatchedFlush();
|
|
5357
|
+
onScoreEvent(event) {
|
|
5358
|
+
return this.enqueueAnnotation(event);
|
|
4989
5359
|
}
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
5360
|
+
onFeedbackReplacementEvent(event) {
|
|
5361
|
+
return this.enqueueAnnotation(event);
|
|
5362
|
+
}
|
|
5363
|
+
onFeedbackEvent(event) {
|
|
5364
|
+
return this.enqueueAnnotation(event);
|
|
5365
|
+
}
|
|
5366
|
+
enqueueAnnotation(event) {
|
|
5367
|
+
const pending = this.storeAnnotation(event);
|
|
5368
|
+
this.#pendingAnnotations.add(pending);
|
|
5369
|
+
pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
|
|
5370
|
+
return pending;
|
|
5371
|
+
}
|
|
5372
|
+
async storeAnnotation(event) {
|
|
4994
5373
|
await this.waitForInit();
|
|
4995
5374
|
if (!this.#observabilityStorage) return;
|
|
4996
|
-
this.#
|
|
5375
|
+
const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
|
|
5376
|
+
await Promise.allSettled([...this.#inFlightFlushes]);
|
|
5377
|
+
if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
|
|
5378
|
+
});
|
|
5379
|
+
if (!resolved) {
|
|
5380
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
5381
|
+
this.logger.warn("Storage export dropped because the target trace/span was not found", {
|
|
5382
|
+
eventType: event.type,
|
|
5383
|
+
traceId: record.traceId,
|
|
5384
|
+
spanId: record.spanId
|
|
5385
|
+
});
|
|
5386
|
+
return;
|
|
5387
|
+
}
|
|
5388
|
+
if (resolved.type === "feedback_replacement") {
|
|
5389
|
+
if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
|
|
5390
|
+
this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
|
|
5391
|
+
return;
|
|
5392
|
+
}
|
|
5393
|
+
await this.#observabilityStorage.replaceFeedback({ feedback: buildFeedbackRecord(resolved) });
|
|
5394
|
+
return;
|
|
5395
|
+
}
|
|
5396
|
+
this.#eventBuffer.addEvent(resolved);
|
|
4997
5397
|
await this.handleBatchedFlush();
|
|
4998
5398
|
}
|
|
4999
5399
|
/**
|
|
@@ -5002,6 +5402,7 @@ var DefaultExporter = class extends BaseExporter {
|
|
|
5002
5402
|
* are exported before the runtime instance is terminated.
|
|
5003
5403
|
*/
|
|
5004
5404
|
async flush() {
|
|
5405
|
+
await Promise.allSettled([...this.#pendingAnnotations]);
|
|
5005
5406
|
for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
|
|
5006
5407
|
if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
|
|
5007
5408
|
if (this.#eventBuffer.totalSize > 0) {
|
|
@@ -5151,6 +5552,7 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5151
5552
|
#flushTimer;
|
|
5152
5553
|
/** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
|
|
5153
5554
|
#inFlightFlushes = /* @__PURE__ */ new Set();
|
|
5555
|
+
#pendingAnnotations = /* @__PURE__ */ new Set();
|
|
5154
5556
|
#emitDropEvent;
|
|
5155
5557
|
#unsupportedSignals = /* @__PURE__ */ new Set();
|
|
5156
5558
|
constructor(config = {}) {
|
|
@@ -5521,7 +5923,10 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5521
5923
|
case TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
|
|
5522
5924
|
}
|
|
5523
5925
|
const createTasks = [
|
|
5524
|
-
() => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5926
|
+
() => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5927
|
+
feedbacks: events.map((f) => buildFeedbackRecord(f)),
|
|
5928
|
+
onConflict: "ignore"
|
|
5929
|
+
})),
|
|
5525
5930
|
() => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => buildLogRecord(l)) })),
|
|
5526
5931
|
() => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => buildMetricRecord(m)) })),
|
|
5527
5932
|
() => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => buildScoreRecord(s)) })),
|
|
@@ -5602,22 +6007,46 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5602
6007
|
this.#eventBuffer.addEvent(event);
|
|
5603
6008
|
await this.handleBatchedFlush();
|
|
5604
6009
|
}
|
|
5605
|
-
|
|
5606
|
-
|
|
5607
|
-
*/
|
|
5608
|
-
async onScoreEvent(event) {
|
|
5609
|
-
await this.ensureInitialized();
|
|
5610
|
-
if (!this.#observabilityStorage) return;
|
|
5611
|
-
this.#eventBuffer.addEvent(event);
|
|
5612
|
-
await this.handleBatchedFlush();
|
|
6010
|
+
onScoreEvent(event) {
|
|
6011
|
+
return this.enqueueAnnotation(event);
|
|
5613
6012
|
}
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
6013
|
+
onFeedbackReplacementEvent(event) {
|
|
6014
|
+
return this.enqueueAnnotation(event);
|
|
6015
|
+
}
|
|
6016
|
+
onFeedbackEvent(event) {
|
|
6017
|
+
return this.enqueueAnnotation(event);
|
|
6018
|
+
}
|
|
6019
|
+
enqueueAnnotation(event) {
|
|
6020
|
+
const pending = this.storeAnnotation(event);
|
|
6021
|
+
this.#pendingAnnotations.add(pending);
|
|
6022
|
+
pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
|
|
6023
|
+
return pending;
|
|
6024
|
+
}
|
|
6025
|
+
async storeAnnotation(event) {
|
|
5618
6026
|
await this.ensureInitialized();
|
|
5619
6027
|
if (!this.#observabilityStorage) return;
|
|
5620
|
-
this.#
|
|
6028
|
+
const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
|
|
6029
|
+
await Promise.allSettled([...this.#inFlightFlushes]);
|
|
6030
|
+
if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
|
|
6031
|
+
});
|
|
6032
|
+
if (!resolved) {
|
|
6033
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
6034
|
+
this.logger.warn("Storage export dropped because the target trace/span was not found", {
|
|
6035
|
+
eventType: event.type,
|
|
6036
|
+
traceId: record.traceId,
|
|
6037
|
+
spanId: record.spanId
|
|
6038
|
+
});
|
|
6039
|
+
return;
|
|
6040
|
+
}
|
|
6041
|
+
if (resolved.type === "feedback_replacement") {
|
|
6042
|
+
if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
|
|
6043
|
+
this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
|
|
6044
|
+
return;
|
|
6045
|
+
}
|
|
6046
|
+
await this.#observabilityStorage.replaceFeedback({ feedback: buildFeedbackRecord(resolved) });
|
|
6047
|
+
return;
|
|
6048
|
+
}
|
|
6049
|
+
this.#eventBuffer.addEvent(resolved);
|
|
5621
6050
|
await this.handleBatchedFlush();
|
|
5622
6051
|
}
|
|
5623
6052
|
/**
|
|
@@ -5626,6 +6055,7 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5626
6055
|
* are exported before the runtime instance is terminated.
|
|
5627
6056
|
*/
|
|
5628
6057
|
async flush() {
|
|
6058
|
+
await Promise.allSettled([...this.#pendingAnnotations]);
|
|
5629
6059
|
if (this.#byteTracker) {
|
|
5630
6060
|
if (!this.#observabilityStorage) return;
|
|
5631
6061
|
this.#byteDrainers++;
|
|
@@ -6052,8 +6482,9 @@ var BaseObservabilityInstance = class extends MastraBase {
|
|
|
6052
6482
|
* Internal hook used by RecordedTrace/RecordedSpan hydration to route
|
|
6053
6483
|
* non-tracing annotation events back through the normal exporter pipeline.
|
|
6054
6484
|
*/
|
|
6055
|
-
__emitRecordedEvent(event) {
|
|
6056
|
-
this.
|
|
6485
|
+
__emitRecordedEvent(event, shouldHandle) {
|
|
6486
|
+
if (shouldHandle) this.observabilityBus.emit(event, shouldHandle);
|
|
6487
|
+
else this.emitObservabilityEvent(event);
|
|
6057
6488
|
}
|
|
6058
6489
|
/**
|
|
6059
6490
|
* Internal hook used by the client observability proxy (`client/`)
|
|
@@ -8636,6 +9067,41 @@ var PlatformByteBatcher = class {
|
|
|
8636
9067
|
};
|
|
8637
9068
|
}
|
|
8638
9069
|
};
|
|
9070
|
+
// src/exporters/platform-resolved-record.ts
|
|
9071
|
+
/** Deliver one feedback or score record whose span context must be resolved by Platform. */
|
|
9072
|
+
async function publishResolvedRecord(url, body, headers, method = "POST") {
|
|
9073
|
+
const deadline = AbortSignal.timeout(3e4);
|
|
9074
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
9075
|
+
const response = await fetch(url, {
|
|
9076
|
+
method,
|
|
9077
|
+
headers,
|
|
9078
|
+
body,
|
|
9079
|
+
signal: deadline
|
|
9080
|
+
});
|
|
9081
|
+
if (response.ok) {
|
|
9082
|
+
await response.body?.cancel();
|
|
9083
|
+
return;
|
|
9084
|
+
}
|
|
9085
|
+
const error = await response.json().catch(() => null);
|
|
9086
|
+
const code = error?.code ?? error?.error?.code;
|
|
9087
|
+
if (!(response.status === 404 && (code === "TRACE_NOT_FOUND" || code === "SPAN_NOT_FOUND") || response.status === 503 && code === "ANCHOR_LOOKUP_UNAVAILABLE") || attempt === 5) throw new Error(`Platform record delivery failed: HTTP ${response.status}${code ? ` (${code})` : ""}`);
|
|
9088
|
+
const retryAfter = response.headers.get("retry-after");
|
|
9089
|
+
const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
|
|
9090
|
+
const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
|
|
9091
|
+
await new Promise((resolve, reject) => {
|
|
9092
|
+
deadline.throwIfAborted();
|
|
9093
|
+
const timer = setTimeout(() => {
|
|
9094
|
+
deadline.removeEventListener("abort", abort);
|
|
9095
|
+
resolve();
|
|
9096
|
+
}, Math.min(delay, 3e4));
|
|
9097
|
+
function abort() {
|
|
9098
|
+
clearTimeout(timer);
|
|
9099
|
+
reject(deadline.reason);
|
|
9100
|
+
}
|
|
9101
|
+
deadline.addEventListener("abort", abort, { once: true });
|
|
9102
|
+
});
|
|
9103
|
+
}
|
|
9104
|
+
}
|
|
8639
9105
|
// src/exporters/mastra-platform.ts
|
|
8640
9106
|
const SIGNAL_PUBLISH_SUFFIXES = {
|
|
8641
9107
|
traces: "/spans/publish",
|
|
@@ -8755,6 +9221,7 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
8755
9221
|
buffer;
|
|
8756
9222
|
flushTimer = null;
|
|
8757
9223
|
inFlightFlushes = /* @__PURE__ */ new Set();
|
|
9224
|
+
pendingRecords = /* @__PURE__ */ new Set();
|
|
8758
9225
|
quotaPaused = false;
|
|
8759
9226
|
quotaProbeTimer = null;
|
|
8760
9227
|
quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
|
|
@@ -8791,6 +9258,7 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
8791
9258
|
maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
|
|
8792
9259
|
maxRetries: config.maxRetries ?? 3,
|
|
8793
9260
|
accessToken: accessToken || "",
|
|
9261
|
+
projectId,
|
|
8794
9262
|
tracesEndpoint,
|
|
8795
9263
|
logsEndpoint: resolveConfiguredSignalEndpoint("logs", config.logsEndpoint),
|
|
8796
9264
|
metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config.metricsEndpoint),
|
|
@@ -8832,17 +9300,58 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
8832
9300
|
await this.handleBufferedEvent();
|
|
8833
9301
|
}
|
|
8834
9302
|
async onScoreEvent(event) {
|
|
8835
|
-
if (this.isDisabled) return;
|
|
9303
|
+
if (this.isDisabled || this.shuttingDown) return;
|
|
9304
|
+
if (event.score.correlationContext == null) {
|
|
9305
|
+
this.enqueueResolvedRecord("score", event.score);
|
|
9306
|
+
return;
|
|
9307
|
+
}
|
|
8836
9308
|
if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
|
|
8837
9309
|
this.addScoreToBuffer(event);
|
|
8838
9310
|
await this.handleBufferedEvent();
|
|
8839
9311
|
}
|
|
8840
9312
|
async onFeedbackEvent(event) {
|
|
8841
|
-
if (this.isDisabled) return;
|
|
9313
|
+
if (this.isDisabled || this.shuttingDown) return;
|
|
9314
|
+
if (event.feedback.correlationContext == null) {
|
|
9315
|
+
this.enqueueResolvedRecord("feedback", event.feedback);
|
|
9316
|
+
return;
|
|
9317
|
+
}
|
|
8842
9318
|
if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
|
|
8843
9319
|
this.addFeedbackToBuffer(event);
|
|
8844
9320
|
await this.handleBufferedEvent();
|
|
8845
9321
|
}
|
|
9322
|
+
onFeedbackReplacementEvent(event) {
|
|
9323
|
+
if (this.isDisabled || this.shuttingDown) return;
|
|
9324
|
+
if (!event.feedback.feedbackId?.trim()) {
|
|
9325
|
+
this.logger.warn("Dropping feedback replacement: feedbackId is required");
|
|
9326
|
+
return;
|
|
9327
|
+
}
|
|
9328
|
+
this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
|
|
9329
|
+
}
|
|
9330
|
+
enqueueResolvedRecord(kind, record, replacementId) {
|
|
9331
|
+
if (!record.traceId?.trim()) {
|
|
9332
|
+
this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
|
|
9333
|
+
return;
|
|
9334
|
+
}
|
|
9335
|
+
let body;
|
|
9336
|
+
try {
|
|
9337
|
+
body = JSON.stringify({ [kind]: record });
|
|
9338
|
+
} catch (error) {
|
|
9339
|
+
this.logger.warn(`Dropping unserializable ${kind}`, { error });
|
|
9340
|
+
return;
|
|
9341
|
+
}
|
|
9342
|
+
const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
|
|
9343
|
+
const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
|
|
9344
|
+
if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
|
|
9345
|
+
const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
|
|
9346
|
+
const headers = {
|
|
9347
|
+
Authorization: `Bearer ${this.platformConfig.accessToken}`,
|
|
9348
|
+
"Content-Type": "application/json",
|
|
9349
|
+
...projectId ? { "X-Mastra-Project-Id": projectId } : {}
|
|
9350
|
+
};
|
|
9351
|
+
this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
|
|
9352
|
+
const pending = publishResolvedRecord(url, body, headers, replacementId !== void 0 ? "PUT" : "POST").catch((error) => this.logger.warn(`Dropping ${kind} after Platform delivery failed`, { error })).finally(() => this.pendingRecords.delete(pending));
|
|
9353
|
+
this.pendingRecords.add(pending);
|
|
9354
|
+
}
|
|
8846
9355
|
addToBuffer(event) {
|
|
8847
9356
|
if (this.byteBatcher) {
|
|
8848
9357
|
this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
|
|
@@ -9183,6 +9692,13 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
9183
9692
|
* are exported before the runtime instance is terminated.
|
|
9184
9693
|
*/
|
|
9185
9694
|
async flush() {
|
|
9695
|
+
if (this.isDisabled) return;
|
|
9696
|
+
do {
|
|
9697
|
+
await this.flushBatches();
|
|
9698
|
+
await Promise.allSettled([...this.pendingRecords]);
|
|
9699
|
+
} while (this.pendingRecords.size > 0 || this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0 || (this.byteBatcher?.getStats().pendingBytes ?? 0) > 0);
|
|
9700
|
+
}
|
|
9701
|
+
async flushBatches() {
|
|
9186
9702
|
if (this.isDisabled) return;
|
|
9187
9703
|
if (this.byteBatcher) {
|
|
9188
9704
|
await this.byteBatcher.flush();
|
|
@@ -10135,463 +10651,159 @@ var TestExporter = class extends BaseExporter {
|
|
|
10135
10651
|
path,
|
|
10136
10652
|
expected,
|
|
10137
10653
|
actual
|
|
10138
|
-
});
|
|
10139
|
-
}
|
|
10140
|
-
/**
|
|
10141
|
-
* Check if a value is an __or__ marker object
|
|
10142
|
-
*/
|
|
10143
|
-
#isOrMarker(value) {
|
|
10144
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
|
|
10145
|
-
}
|
|
10146
|
-
/**
|
|
10147
|
-
* Check if a value is an __any__ marker object
|
|
10148
|
-
*/
|
|
10149
|
-
#isAnyMarker(value) {
|
|
10150
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
10151
|
-
if (!("__any__" in value)) return false;
|
|
10152
|
-
const constraint = value.__any__;
|
|
10153
|
-
return constraint === true || [
|
|
10154
|
-
"string",
|
|
10155
|
-
"number",
|
|
10156
|
-
"boolean",
|
|
10157
|
-
"object",
|
|
10158
|
-
"array"
|
|
10159
|
-
].includes(constraint);
|
|
10160
|
-
}
|
|
10161
|
-
/**
|
|
10162
|
-
* Check if a key should be skipped during comparison (metadata keys like __structure__)
|
|
10163
|
-
*/
|
|
10164
|
-
#isMetadataKey(key) {
|
|
10165
|
-
return key.startsWith("__") && key.endsWith("__");
|
|
10166
|
-
}
|
|
10167
|
-
/**
|
|
10168
|
-
* Custom JSON replacer to handle Date objects and other special types
|
|
10169
|
-
*/
|
|
10170
|
-
#jsonReplacer = (_key, value) => {
|
|
10171
|
-
if (value instanceof Date) return value.toISOString();
|
|
10172
|
-
return value;
|
|
10173
|
-
};
|
|
10174
|
-
/**
|
|
10175
|
-
* Get all stored debug logs (internal exporter logging, not signal logs)
|
|
10176
|
-
*/
|
|
10177
|
-
getLogs() {
|
|
10178
|
-
return [...this.#debugLogs];
|
|
10179
|
-
}
|
|
10180
|
-
/**
|
|
10181
|
-
* Dump debug logs to console for debugging (uses console.error for visibility in test output)
|
|
10182
|
-
*/
|
|
10183
|
-
dumpLogs() {
|
|
10184
|
-
console.error("\n=== TestExporter Logs ===");
|
|
10185
|
-
this.#debugLogs.forEach((log) => {
|
|
10186
|
-
console.error(log);
|
|
10187
|
-
});
|
|
10188
|
-
console.error("=== End Logs ===\n");
|
|
10189
|
-
}
|
|
10190
|
-
/**
|
|
10191
|
-
* Validate final state - useful for test assertions
|
|
10192
|
-
*
|
|
10193
|
-
* @returns Object with validation results
|
|
10194
|
-
*/
|
|
10195
|
-
validateFinalState() {
|
|
10196
|
-
const traceIds = this.getTraceIds();
|
|
10197
|
-
const incompleteSpans = this.getIncompleteSpans();
|
|
10198
|
-
const singleTraceId = traceIds.length === 1;
|
|
10199
|
-
const allSpansComplete = incompleteSpans.length === 0;
|
|
10200
|
-
return {
|
|
10201
|
-
valid: singleTraceId && allSpansComplete,
|
|
10202
|
-
singleTraceId,
|
|
10203
|
-
allSpansComplete,
|
|
10204
|
-
traceIds,
|
|
10205
|
-
incompleteSpans
|
|
10206
|
-
};
|
|
10654
|
+
});
|
|
10207
10655
|
}
|
|
10208
10656
|
/**
|
|
10209
|
-
*
|
|
10657
|
+
* Check if a value is an __or__ marker object
|
|
10210
10658
|
*/
|
|
10211
|
-
|
|
10212
|
-
|
|
10213
|
-
this.#spanStates.clear();
|
|
10214
|
-
this.#logEvents = [];
|
|
10215
|
-
this.#metricEvents = [];
|
|
10216
|
-
this.#scoreEvents = [];
|
|
10217
|
-
this.#feedbackEvents = [];
|
|
10218
|
-
this.#debugLogs = [];
|
|
10659
|
+
#isOrMarker(value) {
|
|
10660
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
|
|
10219
10661
|
}
|
|
10220
10662
|
/**
|
|
10221
|
-
*
|
|
10663
|
+
* Check if a value is an __any__ marker object
|
|
10222
10664
|
*/
|
|
10223
|
-
|
|
10224
|
-
|
|
10665
|
+
#isAnyMarker(value) {
|
|
10666
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
10667
|
+
if (!("__any__" in value)) return false;
|
|
10668
|
+
const constraint = value.__any__;
|
|
10669
|
+
return constraint === true || [
|
|
10670
|
+
"string",
|
|
10671
|
+
"number",
|
|
10672
|
+
"boolean",
|
|
10673
|
+
"object",
|
|
10674
|
+
"array"
|
|
10675
|
+
].includes(constraint);
|
|
10225
10676
|
}
|
|
10226
10677
|
/**
|
|
10227
|
-
*
|
|
10678
|
+
* Check if a key should be skipped during comparison (metadata keys like __structure__)
|
|
10228
10679
|
*/
|
|
10229
|
-
|
|
10230
|
-
|
|
10231
|
-
includeEvents: false,
|
|
10232
|
-
includeStats: false
|
|
10233
|
-
});
|
|
10234
|
-
return {
|
|
10235
|
-
startedAt: this.#internalMetrics.startedAt,
|
|
10236
|
-
lastEventAt: this.#internalMetrics.lastEventAt,
|
|
10237
|
-
totalEventsReceived: this.#internalMetrics.totalEventsReceived,
|
|
10238
|
-
bySignal: { ...this.#internalMetrics.bySignal },
|
|
10239
|
-
flushCount: this.#internalMetrics.flushCount,
|
|
10240
|
-
estimatedJsonBytes: new TextEncoder().encode(json).byteLength
|
|
10241
|
-
};
|
|
10680
|
+
#isMetadataKey(key) {
|
|
10681
|
+
return key.startsWith("__") && key.endsWith("__");
|
|
10242
10682
|
}
|
|
10243
10683
|
/**
|
|
10244
|
-
*
|
|
10684
|
+
* Custom JSON replacer to handle Date objects and other special types
|
|
10245
10685
|
*/
|
|
10246
|
-
|
|
10247
|
-
|
|
10248
|
-
|
|
10249
|
-
|
|
10250
|
-
const uptimeMs = Date.now() - metrics.startedAt.getTime();
|
|
10251
|
-
const summary = [
|
|
10252
|
-
`[TestExporter] flush #${metrics.flushCount} summary:`,
|
|
10253
|
-
` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
|
|
10254
|
-
` total events received: ${metrics.totalEventsReceived}`,
|
|
10255
|
-
` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
|
|
10256
|
-
` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
|
|
10257
|
-
` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
|
|
10258
|
-
].join("\n");
|
|
10259
|
-
this.logger.info(summary);
|
|
10260
|
-
}
|
|
10261
|
-
}
|
|
10262
|
-
async shutdown() {
|
|
10263
|
-
await this.flush();
|
|
10264
|
-
this.logger.info("TestExporter shutdown");
|
|
10265
|
-
}
|
|
10686
|
+
#jsonReplacer = (_key, value) => {
|
|
10687
|
+
if (value instanceof Date) return value.toISOString();
|
|
10688
|
+
return value;
|
|
10689
|
+
};
|
|
10266
10690
|
/**
|
|
10267
|
-
*
|
|
10691
|
+
* Get all stored debug logs (internal exporter logging, not signal logs)
|
|
10268
10692
|
*/
|
|
10269
|
-
|
|
10270
|
-
|
|
10271
|
-
for (const event of events) {
|
|
10272
|
-
const span = event.exportedSpan;
|
|
10273
|
-
if (event.type === TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
|
|
10274
|
-
}
|
|
10275
|
-
return Array.from(spanMap.values());
|
|
10276
|
-
}
|
|
10277
|
-
};
|
|
10278
|
-
/**
|
|
10279
|
-
* @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
|
|
10280
|
-
*/
|
|
10281
|
-
const JsonExporter = TestExporter;
|
|
10282
|
-
// src/instances/default.ts
|
|
10283
|
-
var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
|
|
10284
|
-
constructor(config) {
|
|
10285
|
-
super(config);
|
|
10286
|
-
}
|
|
10287
|
-
createSpan(options) {
|
|
10288
|
-
return new DefaultSpan(options, this);
|
|
10693
|
+
getLogs() {
|
|
10694
|
+
return [...this.#debugLogs];
|
|
10289
10695
|
}
|
|
10290
|
-
|
|
10291
|
-
|
|
10292
|
-
|
|
10293
|
-
|
|
10294
|
-
|
|
10295
|
-
|
|
10296
|
-
|
|
10297
|
-
|
|
10298
|
-
|
|
10299
|
-
...extra ?? {}
|
|
10300
|
-
};
|
|
10301
|
-
}
|
|
10302
|
-
function normalizeErrorInfo(error) {
|
|
10303
|
-
if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
|
|
10304
|
-
return {
|
|
10305
|
-
message: error.message,
|
|
10306
|
-
id: "id" in error && typeof error.id === "string" ? error.id : void 0,
|
|
10307
|
-
name: "name" in error && typeof error.name === "string" ? error.name : void 0,
|
|
10308
|
-
stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
|
|
10309
|
-
domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
|
|
10310
|
-
category: "category" in error && typeof error.category === "string" ? error.category : void 0,
|
|
10311
|
-
details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
|
|
10312
|
-
};
|
|
10313
|
-
}
|
|
10314
|
-
function buildCorrelationContext(span, rootSpan, parent) {
|
|
10315
|
-
return {
|
|
10316
|
-
tags: rootSpan.tags ?? void 0,
|
|
10317
|
-
entityType: nullToUndefined(span.entityType),
|
|
10318
|
-
entityId: nullToUndefined(span.entityId),
|
|
10319
|
-
entityName: nullToUndefined(span.entityName),
|
|
10320
|
-
parentEntityType: parent?.entityType ?? void 0,
|
|
10321
|
-
parentEntityId: parent?.entityId ?? void 0,
|
|
10322
|
-
parentEntityName: parent?.entityName ?? void 0,
|
|
10323
|
-
rootEntityType: nullToUndefined(rootSpan.entityType),
|
|
10324
|
-
rootEntityId: nullToUndefined(rootSpan.entityId),
|
|
10325
|
-
rootEntityName: nullToUndefined(rootSpan.entityName),
|
|
10326
|
-
userId: nullToUndefined(span.userId),
|
|
10327
|
-
organizationId: nullToUndefined(span.organizationId),
|
|
10328
|
-
resourceId: nullToUndefined(span.resourceId),
|
|
10329
|
-
runId: nullToUndefined(span.runId),
|
|
10330
|
-
sessionId: nullToUndefined(span.sessionId),
|
|
10331
|
-
threadId: nullToUndefined(span.threadId),
|
|
10332
|
-
requestId: nullToUndefined(span.requestId),
|
|
10333
|
-
environment: nullToUndefined(span.environment),
|
|
10334
|
-
source: nullToUndefined(span.source),
|
|
10335
|
-
serviceName: nullToUndefined(span.serviceName),
|
|
10336
|
-
experimentId: nullToUndefined(span.experimentId)
|
|
10337
|
-
};
|
|
10338
|
-
}
|
|
10339
|
-
function buildScoreEvent(args) {
|
|
10340
|
-
const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
|
|
10341
|
-
return {
|
|
10342
|
-
type: "score",
|
|
10343
|
-
score: {
|
|
10344
|
-
scoreId: generateSignalId(),
|
|
10345
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
10346
|
-
traceId,
|
|
10347
|
-
spanId,
|
|
10348
|
-
scorerId: score.scorerId,
|
|
10349
|
-
scorerName: score.scorerName,
|
|
10350
|
-
scorerVersion: score.scorerVersion,
|
|
10351
|
-
source: score.source,
|
|
10352
|
-
scoreSource: score.scoreSource,
|
|
10353
|
-
score: score.score,
|
|
10354
|
-
reason: score.reason,
|
|
10355
|
-
experimentId: score.experimentId,
|
|
10356
|
-
scoreTraceId: score.scoreTraceId,
|
|
10357
|
-
targetEntityType: score.targetEntityType,
|
|
10358
|
-
correlationContext,
|
|
10359
|
-
metadata: mergeMetadata(inheritedMetadata, score.metadata)
|
|
10360
|
-
}
|
|
10361
|
-
};
|
|
10362
|
-
}
|
|
10363
|
-
function buildFeedbackEvent(args) {
|
|
10364
|
-
const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
|
|
10365
|
-
return {
|
|
10366
|
-
type: "feedback",
|
|
10367
|
-
feedback: {
|
|
10368
|
-
feedbackId: generateSignalId(),
|
|
10369
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
10370
|
-
traceId,
|
|
10371
|
-
spanId,
|
|
10372
|
-
source: feedback.source,
|
|
10373
|
-
feedbackSource: feedback.feedbackSource,
|
|
10374
|
-
feedbackType: feedback.feedbackType,
|
|
10375
|
-
value: feedback.value,
|
|
10376
|
-
userId: feedback.userId,
|
|
10377
|
-
feedbackUserId: feedback.feedbackUserId,
|
|
10378
|
-
comment: feedback.comment,
|
|
10379
|
-
sourceId: feedback.sourceId,
|
|
10380
|
-
experimentId: feedback.experimentId,
|
|
10381
|
-
correlationContext,
|
|
10382
|
-
metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
|
|
10383
|
-
}
|
|
10384
|
-
};
|
|
10385
|
-
}
|
|
10386
|
-
function findSpanById(spans, spanId) {
|
|
10387
|
-
if (!spanId) return void 0;
|
|
10388
|
-
return spans.find((span) => span.spanId === spanId);
|
|
10389
|
-
}
|
|
10390
|
-
function buildRecordedScoreEventFromTrace(args) {
|
|
10391
|
-
const rootSpan = findRootSpan(args.trace.spans);
|
|
10392
|
-
if (!rootSpan) return null;
|
|
10393
|
-
const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
|
|
10394
|
-
if (!span) return null;
|
|
10395
|
-
const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
|
|
10396
|
-
return buildScoreEvent({
|
|
10397
|
-
traceId: span.traceId,
|
|
10398
|
-
spanId: args.spanId,
|
|
10399
|
-
correlationContext: buildCorrelationContext(span, rootSpan, parent),
|
|
10400
|
-
score: args.score,
|
|
10401
|
-
inheritedMetadata: span.metadata
|
|
10402
|
-
});
|
|
10403
|
-
}
|
|
10404
|
-
function buildRecordedFeedbackEventFromTrace(args) {
|
|
10405
|
-
const rootSpan = findRootSpan(args.trace.spans);
|
|
10406
|
-
if (!rootSpan) return null;
|
|
10407
|
-
const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
|
|
10408
|
-
if (!span) return null;
|
|
10409
|
-
const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
|
|
10410
|
-
return buildFeedbackEvent({
|
|
10411
|
-
traceId: span.traceId,
|
|
10412
|
-
spanId: args.spanId,
|
|
10413
|
-
correlationContext: buildCorrelationContext(span, rootSpan, parent),
|
|
10414
|
-
feedback: args.feedback,
|
|
10415
|
-
inheritedMetadata: span.metadata
|
|
10416
|
-
});
|
|
10417
|
-
}
|
|
10418
|
-
var RecordedSpanImpl = class {
|
|
10419
|
-
id;
|
|
10420
|
-
traceId;
|
|
10421
|
-
name;
|
|
10422
|
-
type;
|
|
10423
|
-
entityType;
|
|
10424
|
-
entityId;
|
|
10425
|
-
entityName;
|
|
10426
|
-
startTime;
|
|
10427
|
-
endTime;
|
|
10428
|
-
attributes;
|
|
10429
|
-
metadata;
|
|
10430
|
-
tags;
|
|
10431
|
-
input;
|
|
10432
|
-
output;
|
|
10433
|
-
errorInfo;
|
|
10434
|
-
requestContext;
|
|
10435
|
-
isEvent;
|
|
10436
|
-
isRootSpan;
|
|
10437
|
-
parentSpanId;
|
|
10438
|
-
parent;
|
|
10439
|
-
children = [];
|
|
10440
|
-
#raw;
|
|
10441
|
-
#rootSpan;
|
|
10442
|
-
#emitRecordedEvent;
|
|
10443
|
-
#canEmitRecordedEvent;
|
|
10444
|
-
#debugRecordedAnnotationUnavailable;
|
|
10445
|
-
constructor(args) {
|
|
10446
|
-
const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
|
|
10447
|
-
this.#raw = raw;
|
|
10448
|
-
this.#rootSpan = rootSpan;
|
|
10449
|
-
this.#emitRecordedEvent = emitRecordedEvent;
|
|
10450
|
-
this.#canEmitRecordedEvent = canEmitRecordedEvent;
|
|
10451
|
-
this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
|
|
10452
|
-
this.id = raw.spanId;
|
|
10453
|
-
this.traceId = raw.traceId;
|
|
10454
|
-
this.name = raw.name;
|
|
10455
|
-
this.type = raw.spanType;
|
|
10456
|
-
this.entityType = raw.entityType ?? void 0;
|
|
10457
|
-
this.entityId = raw.entityId ?? void 0;
|
|
10458
|
-
this.entityName = raw.entityName ?? void 0;
|
|
10459
|
-
this.startTime = raw.startedAt;
|
|
10460
|
-
this.endTime = raw.endedAt ?? void 0;
|
|
10461
|
-
this.attributes = raw.attributes ?? void 0;
|
|
10462
|
-
this.metadata = raw.metadata ?? void 0;
|
|
10463
|
-
this.tags = raw.tags ?? void 0;
|
|
10464
|
-
this.input = raw.input ?? void 0;
|
|
10465
|
-
this.output = raw.output ?? void 0;
|
|
10466
|
-
this.errorInfo = normalizeErrorInfo(raw.error);
|
|
10467
|
-
this.requestContext = raw.requestContext ?? void 0;
|
|
10468
|
-
this.isEvent = raw.isEvent;
|
|
10469
|
-
this.isRootSpan = !raw.parentSpanId;
|
|
10470
|
-
this.parentSpanId = raw.parentSpanId ?? void 0;
|
|
10696
|
+
/**
|
|
10697
|
+
* Dump debug logs to console for debugging (uses console.error for visibility in test output)
|
|
10698
|
+
*/
|
|
10699
|
+
dumpLogs() {
|
|
10700
|
+
console.error("\n=== TestExporter Logs ===");
|
|
10701
|
+
this.#debugLogs.forEach((log) => {
|
|
10702
|
+
console.error(log);
|
|
10703
|
+
});
|
|
10704
|
+
console.error("=== End Logs ===\n");
|
|
10471
10705
|
}
|
|
10472
|
-
|
|
10473
|
-
|
|
10474
|
-
|
|
10475
|
-
|
|
10476
|
-
|
|
10477
|
-
|
|
10478
|
-
|
|
10479
|
-
|
|
10480
|
-
|
|
10481
|
-
|
|
10482
|
-
|
|
10483
|
-
|
|
10484
|
-
|
|
10485
|
-
|
|
10486
|
-
|
|
10487
|
-
|
|
10706
|
+
/**
|
|
10707
|
+
* Validate final state - useful for test assertions
|
|
10708
|
+
*
|
|
10709
|
+
* @returns Object with validation results
|
|
10710
|
+
*/
|
|
10711
|
+
validateFinalState() {
|
|
10712
|
+
const traceIds = this.getTraceIds();
|
|
10713
|
+
const incompleteSpans = this.getIncompleteSpans();
|
|
10714
|
+
const singleTraceId = traceIds.length === 1;
|
|
10715
|
+
const allSpansComplete = incompleteSpans.length === 0;
|
|
10716
|
+
return {
|
|
10717
|
+
valid: singleTraceId && allSpansComplete,
|
|
10718
|
+
singleTraceId,
|
|
10719
|
+
allSpansComplete,
|
|
10720
|
+
traceIds,
|
|
10721
|
+
incompleteSpans
|
|
10722
|
+
};
|
|
10488
10723
|
}
|
|
10489
|
-
|
|
10490
|
-
|
|
10491
|
-
|
|
10492
|
-
|
|
10493
|
-
|
|
10494
|
-
|
|
10495
|
-
|
|
10496
|
-
|
|
10497
|
-
|
|
10498
|
-
|
|
10499
|
-
|
|
10500
|
-
spanId: this.id,
|
|
10501
|
-
correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
|
|
10502
|
-
feedback,
|
|
10503
|
-
inheritedMetadata: this.#raw.metadata
|
|
10504
|
-
}));
|
|
10724
|
+
/**
|
|
10725
|
+
* Clear all collected events and state across all signals
|
|
10726
|
+
*/
|
|
10727
|
+
clearEvents() {
|
|
10728
|
+
this.#tracingEvents = [];
|
|
10729
|
+
this.#spanStates.clear();
|
|
10730
|
+
this.#logEvents = [];
|
|
10731
|
+
this.#metricEvents = [];
|
|
10732
|
+
this.#scoreEvents = [];
|
|
10733
|
+
this.#feedbackEvents = [];
|
|
10734
|
+
this.#debugLogs = [];
|
|
10505
10735
|
}
|
|
10506
|
-
|
|
10507
|
-
|
|
10508
|
-
|
|
10509
|
-
|
|
10510
|
-
|
|
10511
|
-
#rootRecord;
|
|
10512
|
-
#emitRecordedEvent;
|
|
10513
|
-
#spanMap;
|
|
10514
|
-
#canEmitRecordedEvent;
|
|
10515
|
-
#debugRecordedAnnotationUnavailable;
|
|
10516
|
-
constructor(args) {
|
|
10517
|
-
this.traceId = args.traceId;
|
|
10518
|
-
this.rootSpan = args.rootSpan;
|
|
10519
|
-
this.#rootRecord = args.rootRecord;
|
|
10520
|
-
this.spans = args.spans;
|
|
10521
|
-
this.#emitRecordedEvent = args.emitRecordedEvent;
|
|
10522
|
-
this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
|
|
10523
|
-
this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
|
|
10524
|
-
this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
|
|
10736
|
+
/**
|
|
10737
|
+
* Alias for clearEvents (compatibility with TestExporter)
|
|
10738
|
+
*/
|
|
10739
|
+
reset() {
|
|
10740
|
+
this.clearEvents();
|
|
10525
10741
|
}
|
|
10526
|
-
|
|
10527
|
-
|
|
10742
|
+
/**
|
|
10743
|
+
* Get internal metrics about the exporter's own activity.
|
|
10744
|
+
*/
|
|
10745
|
+
getInternalMetrics() {
|
|
10746
|
+
const json = this.toJSON({
|
|
10747
|
+
includeEvents: false,
|
|
10748
|
+
includeStats: false
|
|
10749
|
+
});
|
|
10750
|
+
return {
|
|
10751
|
+
startedAt: this.#internalMetrics.startedAt,
|
|
10752
|
+
lastEventAt: this.#internalMetrics.lastEventAt,
|
|
10753
|
+
totalEventsReceived: this.#internalMetrics.totalEventsReceived,
|
|
10754
|
+
bySignal: { ...this.#internalMetrics.bySignal },
|
|
10755
|
+
flushCount: this.#internalMetrics.flushCount,
|
|
10756
|
+
estimatedJsonBytes: new TextEncoder().encode(json).byteLength
|
|
10757
|
+
};
|
|
10528
10758
|
}
|
|
10529
|
-
|
|
10530
|
-
|
|
10531
|
-
|
|
10532
|
-
|
|
10533
|
-
|
|
10534
|
-
|
|
10535
|
-
|
|
10759
|
+
/**
|
|
10760
|
+
* Flush buffered data and log internal metrics summary.
|
|
10761
|
+
*/
|
|
10762
|
+
async flush() {
|
|
10763
|
+
this.#internalMetrics.flushCount++;
|
|
10764
|
+
if (this.#config.logMetricsOnFlush) {
|
|
10765
|
+
const metrics = this.getInternalMetrics();
|
|
10766
|
+
const uptimeMs = Date.now() - metrics.startedAt.getTime();
|
|
10767
|
+
const summary = [
|
|
10768
|
+
`[TestExporter] flush #${metrics.flushCount} summary:`,
|
|
10769
|
+
` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
|
|
10770
|
+
` total events received: ${metrics.totalEventsReceived}`,
|
|
10771
|
+
` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
|
|
10772
|
+
` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
|
|
10773
|
+
` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
|
|
10774
|
+
].join("\n");
|
|
10775
|
+
this.logger.info(summary);
|
|
10536
10776
|
}
|
|
10537
|
-
await this.#emitRecordedEvent(buildScoreEvent({
|
|
10538
|
-
traceId: this.#rootRecord.traceId,
|
|
10539
|
-
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
10540
|
-
score,
|
|
10541
|
-
inheritedMetadata: this.#rootRecord.metadata
|
|
10542
|
-
}));
|
|
10543
10777
|
}
|
|
10544
|
-
async
|
|
10545
|
-
|
|
10546
|
-
|
|
10547
|
-
|
|
10548
|
-
|
|
10549
|
-
|
|
10550
|
-
|
|
10778
|
+
async shutdown() {
|
|
10779
|
+
await this.flush();
|
|
10780
|
+
this.logger.info("TestExporter shutdown");
|
|
10781
|
+
}
|
|
10782
|
+
/**
|
|
10783
|
+
* Extract unique spans from a list of events
|
|
10784
|
+
*/
|
|
10785
|
+
#getUniqueSpansFromEvents(events) {
|
|
10786
|
+
const spanMap = /* @__PURE__ */ new Map();
|
|
10787
|
+
for (const event of events) {
|
|
10788
|
+
const span = event.exportedSpan;
|
|
10789
|
+
if (event.type === TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
|
|
10551
10790
|
}
|
|
10552
|
-
|
|
10553
|
-
traceId: this.#rootRecord.traceId,
|
|
10554
|
-
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
10555
|
-
feedback,
|
|
10556
|
-
inheritedMetadata: this.#rootRecord.metadata
|
|
10557
|
-
}));
|
|
10791
|
+
return Array.from(spanMap.values());
|
|
10558
10792
|
}
|
|
10559
10793
|
};
|
|
10560
|
-
|
|
10561
|
-
|
|
10562
|
-
|
|
10563
|
-
|
|
10564
|
-
|
|
10565
|
-
|
|
10566
|
-
|
|
10567
|
-
|
|
10568
|
-
const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
|
|
10569
|
-
raw,
|
|
10570
|
-
rootSpan,
|
|
10571
|
-
emitRecordedEvent,
|
|
10572
|
-
canEmitRecordedEvent,
|
|
10573
|
-
debugRecordedAnnotationUnavailable
|
|
10574
|
-
}));
|
|
10575
|
-
const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
|
|
10576
|
-
for (const span of recordedSpans) {
|
|
10577
|
-
if (!span.parentSpanId) continue;
|
|
10578
|
-
const parent = spanMap.get(span.parentSpanId);
|
|
10579
|
-
if (!parent) continue;
|
|
10580
|
-
span.parent = parent;
|
|
10581
|
-
parent.children.push(span);
|
|
10794
|
+
/**
|
|
10795
|
+
* @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
|
|
10796
|
+
*/
|
|
10797
|
+
const JsonExporter = TestExporter;
|
|
10798
|
+
// src/instances/default.ts
|
|
10799
|
+
var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
|
|
10800
|
+
constructor(config) {
|
|
10801
|
+
super(config);
|
|
10582
10802
|
}
|
|
10583
|
-
|
|
10584
|
-
|
|
10585
|
-
|
|
10586
|
-
|
|
10587
|
-
rootSpan: hydratedRootSpan,
|
|
10588
|
-
rootRecord: rootSpan,
|
|
10589
|
-
spans: recordedSpans,
|
|
10590
|
-
emitRecordedEvent,
|
|
10591
|
-
canEmitRecordedEvent,
|
|
10592
|
-
debugRecordedAnnotationUnavailable
|
|
10593
|
-
});
|
|
10594
|
-
}
|
|
10803
|
+
createSpan(options) {
|
|
10804
|
+
return new DefaultSpan(options, this);
|
|
10805
|
+
}
|
|
10806
|
+
};
|
|
10595
10807
|
// src/registry.ts
|
|
10596
10808
|
/**
|
|
10597
10809
|
* Registry for Observability instances.
|
|
@@ -10898,23 +11110,6 @@ function isInstance(obj) {
|
|
|
10898
11110
|
return obj instanceof BaseObservabilityInstance;
|
|
10899
11111
|
}
|
|
10900
11112
|
/**
|
|
10901
|
-
* Delays (ms) between attempts to rehydrate a trace from storage when an
|
|
10902
|
-
* annotation (score/feedback) targets a span that has not been flushed by
|
|
10903
|
-
* the configured exporters yet. Exporters buffer and flush asynchronously:
|
|
10904
|
-
* by default they flush at 1000 spans or after a 5000ms wait
|
|
10905
|
-
* (`maxBatchWaitMs`), so an annotation emitted right after a span ends can
|
|
10906
|
-
* race the flush and be silently dropped. The schedule below sums to
|
|
10907
|
-
* ~5.85s, covering the default flush interval with margin.
|
|
10908
|
-
*/
|
|
10909
|
-
const RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS = [
|
|
10910
|
-
100,
|
|
10911
|
-
250,
|
|
10912
|
-
500,
|
|
10913
|
-
1e3,
|
|
10914
|
-
2e3,
|
|
10915
|
-
2e3
|
|
10916
|
-
];
|
|
10917
|
-
/**
|
|
10918
11113
|
* Manages observability instances and selects their configurations for Mastra operations.
|
|
10919
11114
|
* Configure instances and exporters to collect and export telemetry.
|
|
10920
11115
|
*
|
|
@@ -10941,6 +11136,7 @@ var Observability = class extends MastraBase {
|
|
|
10941
11136
|
#registry = new ObservabilityRegistry();
|
|
10942
11137
|
#mastra;
|
|
10943
11138
|
#clientObservabilityProxy;
|
|
11139
|
+
#pendingPersistedEvents = /* @__PURE__ */ new Set();
|
|
10944
11140
|
constructor(config) {
|
|
10945
11141
|
super({
|
|
10946
11142
|
component: RegisteredLogger.OBSERVABILITY,
|
|
@@ -11081,50 +11277,47 @@ var Observability = class extends MastraBase {
|
|
|
11081
11277
|
async addScore(args) {
|
|
11082
11278
|
const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
|
|
11083
11279
|
const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
|
|
11084
|
-
if (args.correlationContext)
|
|
11085
|
-
|
|
11086
|
-
|
|
11087
|
-
|
|
11088
|
-
|
|
11089
|
-
score: args.score
|
|
11090
|
-
}));
|
|
11091
|
-
return;
|
|
11092
|
-
}
|
|
11093
|
-
if (!args.traceId) return;
|
|
11094
|
-
const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedScoreEventFromTrace({
|
|
11095
|
-
trace,
|
|
11096
|
-
spanId: args.spanId,
|
|
11097
|
-
score: args.score
|
|
11280
|
+
if (!targetTraceId && !args.correlationContext) return;
|
|
11281
|
+
await this.#emitRecordedEvent(buildScoreEvent({
|
|
11282
|
+
...args,
|
|
11283
|
+
traceId: targetTraceId,
|
|
11284
|
+
spanId: targetSpanId
|
|
11098
11285
|
}));
|
|
11099
|
-
if (!event) {
|
|
11100
|
-
this.logger?.warn(`Score event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
|
|
11101
|
-
return;
|
|
11102
|
-
}
|
|
11103
|
-
await this.#emitRecordedEvent(event);
|
|
11104
11286
|
}
|
|
11105
11287
|
async addFeedback(args) {
|
|
11106
|
-
const
|
|
11107
|
-
const
|
|
11108
|
-
if (args.correlationContext)
|
|
11109
|
-
|
|
11110
|
-
|
|
11111
|
-
|
|
11112
|
-
|
|
11113
|
-
feedback: args.feedback
|
|
11114
|
-
}));
|
|
11115
|
-
return;
|
|
11116
|
-
}
|
|
11117
|
-
if (!args.traceId) return;
|
|
11118
|
-
const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedFeedbackEventFromTrace({
|
|
11119
|
-
trace,
|
|
11120
|
-
spanId: args.spanId,
|
|
11121
|
-
feedback: args.feedback
|
|
11288
|
+
const traceId = args.traceId ?? args.correlationContext?.traceId;
|
|
11289
|
+
const spanId = args.spanId ?? args.correlationContext?.spanId;
|
|
11290
|
+
if (!traceId && !args.correlationContext) return;
|
|
11291
|
+
await this.#emitRecordedEvent(buildFeedbackEvent({
|
|
11292
|
+
...args,
|
|
11293
|
+
traceId,
|
|
11294
|
+
spanId
|
|
11122
11295
|
}));
|
|
11123
|
-
|
|
11124
|
-
|
|
11125
|
-
|
|
11126
|
-
|
|
11127
|
-
|
|
11296
|
+
}
|
|
11297
|
+
async replaceFeedback(args) {
|
|
11298
|
+
if (!args.traceId?.trim() || !args.feedback.feedbackId?.trim() || !Number.isFinite(args.feedback.timestamp?.getTime())) throw new Error("Feedback replacement requires traceId, feedbackId, and the original timestamp");
|
|
11299
|
+
await this.#emitRecordedEvent({
|
|
11300
|
+
type: "feedback_replacement",
|
|
11301
|
+
feedback: {
|
|
11302
|
+
...args.feedback,
|
|
11303
|
+
traceId: args.traceId,
|
|
11304
|
+
spanId: args.spanId,
|
|
11305
|
+
correlationContext: args.correlationContext
|
|
11306
|
+
}
|
|
11307
|
+
});
|
|
11308
|
+
}
|
|
11309
|
+
/** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
|
|
11310
|
+
async __exportPersistedEvent(event) {
|
|
11311
|
+
const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
|
|
11312
|
+
const pending = this.#emitRecordedEvent(event, (handler) => !storageExporters.has(handler));
|
|
11313
|
+
this.#pendingPersistedEvents.add(pending);
|
|
11314
|
+
pending.then(() => this.#pendingPersistedEvents.delete(pending), (error) => {
|
|
11315
|
+
this.#pendingPersistedEvents.delete(pending);
|
|
11316
|
+
this.logger.error("Failed to notify exporters of persisted feedback/score", {
|
|
11317
|
+
error,
|
|
11318
|
+
eventType: event.type
|
|
11319
|
+
});
|
|
11320
|
+
});
|
|
11128
11321
|
}
|
|
11129
11322
|
/** Register a named observability instance, optionally marking it as default. */
|
|
11130
11323
|
registerInstance(name, instance, isDefault = false) {
|
|
@@ -11161,12 +11354,18 @@ var Observability = class extends MastraBase {
|
|
|
11161
11354
|
}
|
|
11162
11355
|
/** Flush all registered instances without shutting down. */
|
|
11163
11356
|
async flush() {
|
|
11357
|
+
await this.#drainPersistedEvents();
|
|
11164
11358
|
await this.#registry.flush();
|
|
11165
11359
|
}
|
|
11166
11360
|
/** Shut down all registered instances, flushing any pending data. */
|
|
11167
11361
|
async shutdown() {
|
|
11362
|
+
await this.#drainPersistedEvents();
|
|
11168
11363
|
await this.#registry.shutdown();
|
|
11169
11364
|
}
|
|
11365
|
+
/** Let custom handlers finish filling exporter buffers before the instance lifecycle drains them. */
|
|
11366
|
+
async #drainPersistedEvents() {
|
|
11367
|
+
while (this.#pendingPersistedEvents.size > 0) await Promise.allSettled([...this.#pendingPersistedEvents]);
|
|
11368
|
+
}
|
|
11170
11369
|
/**
|
|
11171
11370
|
* Returns the proxy responsible for client observability (W3C trace
|
|
11172
11371
|
* context injection + OTLP/JSON payload reception for spans/logs
|
|
@@ -11188,40 +11387,22 @@ var Observability = class extends MastraBase {
|
|
|
11188
11387
|
if (!storage) return null;
|
|
11189
11388
|
return await storage.getStore("observability") ?? null;
|
|
11190
11389
|
}
|
|
11191
|
-
/**
|
|
11192
|
-
* Build a recorded score/feedback event from storage, retrying briefly to
|
|
11193
|
-
* ride out the async exporter flush: annotations emitted right after a
|
|
11194
|
-
* span ends can otherwise race the flush and be silently dropped.
|
|
11195
|
-
*/
|
|
11196
|
-
async #buildRecordedEventWithRetry(traceId, build) {
|
|
11197
|
-
for (const delayMs of [0, ...RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS]) {
|
|
11198
|
-
if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
11199
|
-
const trace = await this.#getStoredTrace(traceId);
|
|
11200
|
-
const event = trace ? build(trace) : null;
|
|
11201
|
-
if (event) return event;
|
|
11202
|
-
}
|
|
11203
|
-
return null;
|
|
11204
|
-
}
|
|
11205
|
-
async #getStoredTrace(traceId) {
|
|
11206
|
-
const observabilityStorage = await this.#getObservabilityStorage();
|
|
11207
|
-
if (!observabilityStorage) return null;
|
|
11208
|
-
return observabilityStorage.getTrace({ traceId });
|
|
11209
|
-
}
|
|
11210
11390
|
#getRecordedTraceInstance() {
|
|
11211
11391
|
return this.getDefaultInstance() ?? Array.from(this.listInstances().values())[0];
|
|
11212
11392
|
}
|
|
11213
|
-
|
|
11393
|
+
/** Dispatch independently; the standard bus tracks delivery, while custom instances return handler promises. */
|
|
11394
|
+
async #emitRecordedEvent(event, shouldHandle) {
|
|
11214
11395
|
const instance = this.#getRecordedTraceInstance();
|
|
11215
11396
|
if (!instance) {
|
|
11216
11397
|
this.logger?.debug(event.type === "score" ? "Score event was dropped because no observability instance is registered" : "Feedback event was dropped because no observability instance is registered", { eventType: event.type });
|
|
11217
11398
|
return;
|
|
11218
11399
|
}
|
|
11219
11400
|
if (instance instanceof BaseObservabilityInstance) {
|
|
11220
|
-
instance.__emitRecordedEvent(event);
|
|
11401
|
+
instance.__emitRecordedEvent(event, shouldHandle);
|
|
11221
11402
|
return;
|
|
11222
11403
|
}
|
|
11223
11404
|
const bridge = instance.getBridge();
|
|
11224
|
-
const handlerResults = [...instance.getExporters().map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
|
|
11405
|
+
const handlerResults = [...instance.getExporters().filter((exporter) => !shouldHandle || shouldHandle(exporter)).map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge && (!shouldHandle || shouldHandle(bridge)) ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
|
|
11225
11406
|
if (handlerResults.length > 0) await Promise.allSettled(handlerResults);
|
|
11226
11407
|
}
|
|
11227
11408
|
};
|