@mastra/observability 1.24.0-alpha.4 → 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 +900 -730
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +900 -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/recorded.d.ts +4 -12
- package/dist/recorded.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -77,6 +77,9 @@ function routeToHandler(handler, event, logger) {
|
|
|
77
77
|
}), handler.name, "score", logger);
|
|
78
78
|
}
|
|
79
79
|
break;
|
|
80
|
+
case "feedback_replacement":
|
|
81
|
+
if (handler.onFeedbackReplacementEvent) return catchAsyncResult(handler.onFeedbackReplacementEvent(event), handler.name, "feedback replacement", logger);
|
|
82
|
+
break;
|
|
80
83
|
case "feedback": if (handler.onFeedbackEvent) return catchAsyncResult(handler.onFeedbackEvent(event), handler.name, "feedback", logger);
|
|
81
84
|
}
|
|
82
85
|
} catch (err) {
|
|
@@ -577,6 +580,10 @@ function cleanEvent(event, options) {
|
|
|
577
580
|
type: "score",
|
|
578
581
|
score: deepClean(event.score, options)
|
|
579
582
|
};
|
|
583
|
+
case "feedback_replacement": return {
|
|
584
|
+
type: event.type,
|
|
585
|
+
feedback: deepClean(event.feedback, options)
|
|
586
|
+
};
|
|
580
587
|
case "feedback": return {
|
|
581
588
|
type: "feedback",
|
|
582
589
|
feedback: deepClean(event.feedback, options)
|
|
@@ -669,10 +676,10 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
|
|
|
669
676
|
* emit() is synchronous — async handler promises are tracked internally
|
|
670
677
|
* and can be drained via flush().
|
|
671
678
|
*/
|
|
672
|
-
emit(event) {
|
|
679
|
+
emit(event, shouldHandle) {
|
|
673
680
|
const cleaned = cleanEvent(event, this.deepCleanOptions);
|
|
674
|
-
for (const exporter of this.exporters) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
|
|
675
|
-
if (this.bridge) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
|
|
681
|
+
for (const exporter of this.exporters) if (!shouldHandle || shouldHandle(exporter)) this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
|
|
682
|
+
if (this.bridge && (!shouldHandle || shouldHandle(this.bridge))) this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
|
|
676
683
|
super.emit(cleaned);
|
|
677
684
|
}
|
|
678
685
|
/**
|
|
@@ -4624,194 +4631,549 @@ var EventBuffer = class {
|
|
|
4624
4631
|
});
|
|
4625
4632
|
}
|
|
4626
4633
|
};
|
|
4627
|
-
// src/
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
*/
|
|
4631
|
-
function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
|
|
4632
|
-
const observabilityStrategy = observabilityStorage.observabilityStrategy;
|
|
4633
|
-
if (config.strategy && config.strategy !== "auto") {
|
|
4634
|
-
if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
|
|
4635
|
-
logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
|
|
4636
|
-
userStrategy: config.strategy,
|
|
4637
|
-
storageAdapter: storageName,
|
|
4638
|
-
supportedStrategies: observabilityStrategy.supported,
|
|
4639
|
-
fallbackStrategy: observabilityStrategy.preferred
|
|
4640
|
-
});
|
|
4641
|
-
}
|
|
4642
|
-
return observabilityStrategy.preferred;
|
|
4634
|
+
// src/recorded.ts
|
|
4635
|
+
function nullToUndefined(value) {
|
|
4636
|
+
return value ?? void 0;
|
|
4643
4637
|
}
|
|
4644
|
-
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
4663
|
-
|
|
4664
|
-
|
|
4665
|
-
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4675
|
-
|
|
4676
|
-
|
|
4677
|
-
|
|
4678
|
-
|
|
4679
|
-
|
|
4680
|
-
|
|
4681
|
-
|
|
4682
|
-
|
|
4683
|
-
|
|
4684
|
-
|
|
4685
|
-
|
|
4686
|
-
|
|
4687
|
-
|
|
4688
|
-
|
|
4689
|
-
|
|
4690
|
-
|
|
4691
|
-
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
}
|
|
4695
|
-
this.#observabilityStorage = await this.#storage.getStore("observability");
|
|
4696
|
-
if (!this.#observabilityStorage) {
|
|
4697
|
-
this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
|
|
4698
|
-
return;
|
|
4699
|
-
}
|
|
4700
|
-
if (!this.#resolvedStrategy) {
|
|
4701
|
-
this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
|
|
4702
|
-
this.logger.debug("tracing storage exporter initialized", {
|
|
4703
|
-
strategy: this.#resolvedStrategy,
|
|
4704
|
-
source: this.#config.strategy !== "auto" ? "user" : "auto",
|
|
4705
|
-
storageAdapter: this.#storage.constructor.name,
|
|
4706
|
-
maxBatchSize: this.#config.maxBatchSize,
|
|
4707
|
-
maxBatchWaitMs: this.#config.maxBatchWaitMs
|
|
4708
|
-
});
|
|
4709
|
-
}
|
|
4710
|
-
if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
|
|
4711
|
-
} finally {
|
|
4712
|
-
this.#isInitializing = false;
|
|
4713
|
-
/**
|
|
4714
|
-
* Assumes caller waits until export of a parent span is completed before calling
|
|
4715
|
-
* export for child spans , order is not relevant for resolve
|
|
4716
|
-
*/
|
|
4717
|
-
this.#initPromises.forEach((resolve) => {
|
|
4718
|
-
resolve();
|
|
4719
|
-
});
|
|
4720
|
-
this.#initPromises.clear();
|
|
4721
|
-
}
|
|
4722
|
-
}
|
|
4723
|
-
/**
|
|
4724
|
-
* Checks if buffer should be flushed based on size or time triggers
|
|
4725
|
-
*/
|
|
4726
|
-
shouldFlush() {
|
|
4727
|
-
if (this.#resolvedStrategy === "realtime") return true;
|
|
4728
|
-
if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
|
|
4729
|
-
if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
|
|
4730
|
-
if (this.#eventBuffer.totalSize > 0) {
|
|
4731
|
-
if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
|
|
4732
|
-
}
|
|
4733
|
-
return false;
|
|
4734
|
-
}
|
|
4735
|
-
/**
|
|
4736
|
-
* Schedules a flush using setTimeout
|
|
4737
|
-
*/
|
|
4738
|
-
scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
|
|
4739
|
-
if (this.#flushTimer) clearTimeout(this.#flushTimer);
|
|
4740
|
-
this.#flushTimer = setTimeout(() => {
|
|
4741
|
-
this.#flushTimer = void 0;
|
|
4742
|
-
this.trackFlushBuffer().catch((error) => {
|
|
4743
|
-
this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
|
|
4744
|
-
});
|
|
4745
|
-
}, delayMs);
|
|
4746
|
-
}
|
|
4747
|
-
retryDelay(retryAttempt) {
|
|
4748
|
-
return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
|
|
4749
|
-
}
|
|
4750
|
-
retryAttempt(events) {
|
|
4751
|
-
return events.reduce((earliestAttempt, event) => {
|
|
4752
|
-
if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
|
|
4753
|
-
return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
|
|
4754
|
-
}, void 0);
|
|
4755
|
-
}
|
|
4756
|
-
logStorageFailure(signal, events, retryAttempt, error) {
|
|
4757
|
-
this.logger.warn("Failed to persist observability events", {
|
|
4758
|
-
signal,
|
|
4759
|
-
eventCount: events.length,
|
|
4760
|
-
retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
|
|
4761
|
-
maxRetries: this.#config.maxRetries,
|
|
4762
|
-
...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
|
|
4763
|
-
error: error instanceof Error ? error.message : String(error)
|
|
4764
|
-
});
|
|
4765
|
-
}
|
|
4766
|
-
/**
|
|
4767
|
-
* Checks flush triggers and schedules/triggers flush as needed.
|
|
4768
|
-
* Called after adding any event to the buffer.
|
|
4769
|
-
* Returns the flush promise when flushing so callers can await it.
|
|
4770
|
-
*/
|
|
4771
|
-
async handleBatchedFlush() {
|
|
4772
|
-
if (this.shouldFlush()) await this.trackFlushBuffer();
|
|
4773
|
-
else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
|
|
4774
|
-
}
|
|
4775
|
-
sanitizeDropError(error) {
|
|
4776
|
-
if (error instanceof _mastra_core_error.MastraError) return {
|
|
4777
|
-
id: error.id,
|
|
4778
|
-
domain: String(error.domain),
|
|
4779
|
-
message: error.message
|
|
4780
|
-
};
|
|
4781
|
-
if (error instanceof Error) return { message: error.message };
|
|
4782
|
-
return { message: String(error) };
|
|
4783
|
-
}
|
|
4784
|
-
emitDrop(signal, reason, count, error) {
|
|
4785
|
-
if (count === 0) return;
|
|
4786
|
-
const dropEvent = {
|
|
4787
|
-
type: "drop",
|
|
4788
|
-
signal,
|
|
4789
|
-
reason,
|
|
4790
|
-
count,
|
|
4638
|
+
function mergeMetadata(base, extra) {
|
|
4639
|
+
if (!base && !extra) return void 0;
|
|
4640
|
+
return {
|
|
4641
|
+
...base ?? {},
|
|
4642
|
+
...extra ?? {}
|
|
4643
|
+
};
|
|
4644
|
+
}
|
|
4645
|
+
function normalizeErrorInfo(error) {
|
|
4646
|
+
if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
|
|
4647
|
+
return {
|
|
4648
|
+
message: error.message,
|
|
4649
|
+
id: "id" in error && typeof error.id === "string" ? error.id : void 0,
|
|
4650
|
+
name: "name" in error && typeof error.name === "string" ? error.name : void 0,
|
|
4651
|
+
stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
|
|
4652
|
+
domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
|
|
4653
|
+
category: "category" in error && typeof error.category === "string" ? error.category : void 0,
|
|
4654
|
+
details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
|
|
4655
|
+
};
|
|
4656
|
+
}
|
|
4657
|
+
function buildCorrelationContext(span, rootSpan, parent) {
|
|
4658
|
+
return {
|
|
4659
|
+
tags: rootSpan.tags ?? void 0,
|
|
4660
|
+
entityType: nullToUndefined(span.entityType),
|
|
4661
|
+
entityId: nullToUndefined(span.entityId),
|
|
4662
|
+
entityName: nullToUndefined(span.entityName),
|
|
4663
|
+
parentEntityType: parent?.entityType ?? void 0,
|
|
4664
|
+
parentEntityId: parent?.entityId ?? void 0,
|
|
4665
|
+
parentEntityName: parent?.entityName ?? void 0,
|
|
4666
|
+
rootEntityType: nullToUndefined(rootSpan.entityType),
|
|
4667
|
+
rootEntityId: nullToUndefined(rootSpan.entityId),
|
|
4668
|
+
rootEntityName: nullToUndefined(rootSpan.entityName),
|
|
4669
|
+
userId: nullToUndefined(span.userId),
|
|
4670
|
+
organizationId: nullToUndefined(span.organizationId),
|
|
4671
|
+
resourceId: nullToUndefined(span.resourceId),
|
|
4672
|
+
runId: nullToUndefined(span.runId),
|
|
4673
|
+
sessionId: nullToUndefined(span.sessionId),
|
|
4674
|
+
threadId: nullToUndefined(span.threadId),
|
|
4675
|
+
requestId: nullToUndefined(span.requestId),
|
|
4676
|
+
environment: nullToUndefined(span.environment),
|
|
4677
|
+
source: nullToUndefined(span.source),
|
|
4678
|
+
serviceName: nullToUndefined(span.serviceName),
|
|
4679
|
+
experimentId: nullToUndefined(span.experimentId)
|
|
4680
|
+
};
|
|
4681
|
+
}
|
|
4682
|
+
function buildScoreEvent(args) {
|
|
4683
|
+
const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
|
|
4684
|
+
return {
|
|
4685
|
+
type: "score",
|
|
4686
|
+
score: {
|
|
4687
|
+
scoreId: generateSignalId(),
|
|
4791
4688
|
timestamp: /* @__PURE__ */ new Date(),
|
|
4792
|
-
|
|
4793
|
-
|
|
4794
|
-
|
|
4795
|
-
|
|
4796
|
-
|
|
4797
|
-
|
|
4798
|
-
|
|
4799
|
-
|
|
4800
|
-
|
|
4801
|
-
|
|
4802
|
-
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
this.emitDrop(signal, "unsupported-storage", events.length);
|
|
4807
|
-
return { failed: true };
|
|
4689
|
+
traceId,
|
|
4690
|
+
spanId,
|
|
4691
|
+
scorerId: score.scorerId,
|
|
4692
|
+
scorerName: score.scorerName,
|
|
4693
|
+
scorerVersion: score.scorerVersion,
|
|
4694
|
+
source: score.source,
|
|
4695
|
+
scoreSource: score.scoreSource,
|
|
4696
|
+
score: score.score,
|
|
4697
|
+
reason: score.reason,
|
|
4698
|
+
experimentId: score.experimentId,
|
|
4699
|
+
scoreTraceId: score.scoreTraceId,
|
|
4700
|
+
targetEntityType: score.targetEntityType,
|
|
4701
|
+
correlationContext,
|
|
4702
|
+
metadata: mergeMetadata(inheritedMetadata, score.metadata)
|
|
4808
4703
|
}
|
|
4809
|
-
|
|
4810
|
-
|
|
4811
|
-
|
|
4812
|
-
|
|
4813
|
-
|
|
4814
|
-
|
|
4704
|
+
};
|
|
4705
|
+
}
|
|
4706
|
+
function buildFeedbackEvent(args) {
|
|
4707
|
+
const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
|
|
4708
|
+
return {
|
|
4709
|
+
type: "feedback",
|
|
4710
|
+
feedback: {
|
|
4711
|
+
feedbackId: generateSignalId(),
|
|
4712
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
4713
|
+
traceId,
|
|
4714
|
+
spanId,
|
|
4715
|
+
source: feedback.source,
|
|
4716
|
+
feedbackSource: feedback.feedbackSource,
|
|
4717
|
+
feedbackType: feedback.feedbackType,
|
|
4718
|
+
value: feedback.value,
|
|
4719
|
+
userId: feedback.userId,
|
|
4720
|
+
feedbackUserId: feedback.feedbackUserId,
|
|
4721
|
+
comment: feedback.comment,
|
|
4722
|
+
sourceId: feedback.sourceId,
|
|
4723
|
+
experimentId: feedback.experimentId,
|
|
4724
|
+
correlationContext,
|
|
4725
|
+
metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
|
|
4726
|
+
}
|
|
4727
|
+
};
|
|
4728
|
+
}
|
|
4729
|
+
function findSpanById(spans, spanId) {
|
|
4730
|
+
if (!spanId) return void 0;
|
|
4731
|
+
return spans.find((span) => span.spanId === spanId);
|
|
4732
|
+
}
|
|
4733
|
+
/** Resolve a storage exporter's copy without changing the event identity or other destinations' payloads. */
|
|
4734
|
+
function resolveRecordedEventFromTrace(trace, event) {
|
|
4735
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
4736
|
+
const spans = trace.spans.filter((span) => span.traceId === record.traceId);
|
|
4737
|
+
const span = record.spanId ? findSpanById(spans, record.spanId) : spans.find((span) => !span.parentSpanId);
|
|
4738
|
+
if (!span) return null;
|
|
4739
|
+
const byId = new Map(spans.map((span) => [span.spanId, span]));
|
|
4740
|
+
let root = span;
|
|
4741
|
+
const visited = /* @__PURE__ */ new Set();
|
|
4742
|
+
while (root.parentSpanId) {
|
|
4743
|
+
if (visited.has(root.spanId)) return null;
|
|
4744
|
+
visited.add(root.spanId);
|
|
4745
|
+
const parent = byId.get(root.parentSpanId);
|
|
4746
|
+
if (!parent) return null;
|
|
4747
|
+
root = parent;
|
|
4748
|
+
}
|
|
4749
|
+
const context = {
|
|
4750
|
+
correlationContext: buildCorrelationContext(span, root, span.parentSpanId ? byId.get(span.parentSpanId) : void 0),
|
|
4751
|
+
metadata: mergeMetadata(span.metadata, record.metadata)
|
|
4752
|
+
};
|
|
4753
|
+
return event.type === "score" ? {
|
|
4754
|
+
type: "score",
|
|
4755
|
+
score: {
|
|
4756
|
+
...event.score,
|
|
4757
|
+
...context
|
|
4758
|
+
}
|
|
4759
|
+
} : event.type === "feedback_replacement" ? {
|
|
4760
|
+
type: "feedback_replacement",
|
|
4761
|
+
feedback: {
|
|
4762
|
+
...event.feedback,
|
|
4763
|
+
...context
|
|
4764
|
+
}
|
|
4765
|
+
} : {
|
|
4766
|
+
type: "feedback",
|
|
4767
|
+
feedback: {
|
|
4768
|
+
...event.feedback,
|
|
4769
|
+
...context
|
|
4770
|
+
}
|
|
4771
|
+
};
|
|
4772
|
+
}
|
|
4773
|
+
var RecordedSpanImpl = class {
|
|
4774
|
+
id;
|
|
4775
|
+
traceId;
|
|
4776
|
+
name;
|
|
4777
|
+
type;
|
|
4778
|
+
entityType;
|
|
4779
|
+
entityId;
|
|
4780
|
+
entityName;
|
|
4781
|
+
startTime;
|
|
4782
|
+
endTime;
|
|
4783
|
+
attributes;
|
|
4784
|
+
metadata;
|
|
4785
|
+
tags;
|
|
4786
|
+
input;
|
|
4787
|
+
output;
|
|
4788
|
+
errorInfo;
|
|
4789
|
+
requestContext;
|
|
4790
|
+
isEvent;
|
|
4791
|
+
isRootSpan;
|
|
4792
|
+
parentSpanId;
|
|
4793
|
+
parent;
|
|
4794
|
+
children = [];
|
|
4795
|
+
#raw;
|
|
4796
|
+
#rootSpan;
|
|
4797
|
+
#emitRecordedEvent;
|
|
4798
|
+
#canEmitRecordedEvent;
|
|
4799
|
+
#debugRecordedAnnotationUnavailable;
|
|
4800
|
+
constructor(args) {
|
|
4801
|
+
const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
|
|
4802
|
+
this.#raw = raw;
|
|
4803
|
+
this.#rootSpan = rootSpan;
|
|
4804
|
+
this.#emitRecordedEvent = emitRecordedEvent;
|
|
4805
|
+
this.#canEmitRecordedEvent = canEmitRecordedEvent;
|
|
4806
|
+
this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
|
|
4807
|
+
this.id = raw.spanId;
|
|
4808
|
+
this.traceId = raw.traceId;
|
|
4809
|
+
this.name = raw.name;
|
|
4810
|
+
this.type = raw.spanType;
|
|
4811
|
+
this.entityType = raw.entityType ?? void 0;
|
|
4812
|
+
this.entityId = raw.entityId ?? void 0;
|
|
4813
|
+
this.entityName = raw.entityName ?? void 0;
|
|
4814
|
+
this.startTime = raw.startedAt;
|
|
4815
|
+
this.endTime = raw.endedAt ?? void 0;
|
|
4816
|
+
this.attributes = raw.attributes ?? void 0;
|
|
4817
|
+
this.metadata = raw.metadata ?? void 0;
|
|
4818
|
+
this.tags = raw.tags ?? void 0;
|
|
4819
|
+
this.input = raw.input ?? void 0;
|
|
4820
|
+
this.output = raw.output ?? void 0;
|
|
4821
|
+
this.errorInfo = normalizeErrorInfo(raw.error);
|
|
4822
|
+
this.requestContext = raw.requestContext ?? void 0;
|
|
4823
|
+
this.isEvent = raw.isEvent;
|
|
4824
|
+
this.isRootSpan = !raw.parentSpanId;
|
|
4825
|
+
this.parentSpanId = raw.parentSpanId ?? void 0;
|
|
4826
|
+
}
|
|
4827
|
+
async addScore(score) {
|
|
4828
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4829
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4830
|
+
kind: "score",
|
|
4831
|
+
traceId: this.traceId,
|
|
4832
|
+
spanId: this.id
|
|
4833
|
+
});
|
|
4834
|
+
return;
|
|
4835
|
+
}
|
|
4836
|
+
await this.#emitRecordedEvent(buildScoreEvent({
|
|
4837
|
+
traceId: this.#raw.traceId,
|
|
4838
|
+
spanId: this.id,
|
|
4839
|
+
correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
|
|
4840
|
+
score,
|
|
4841
|
+
inheritedMetadata: this.#raw.metadata
|
|
4842
|
+
}));
|
|
4843
|
+
}
|
|
4844
|
+
async addFeedback(feedback) {
|
|
4845
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4846
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4847
|
+
kind: "feedback",
|
|
4848
|
+
traceId: this.traceId,
|
|
4849
|
+
spanId: this.id
|
|
4850
|
+
});
|
|
4851
|
+
return;
|
|
4852
|
+
}
|
|
4853
|
+
await this.#emitRecordedEvent(buildFeedbackEvent({
|
|
4854
|
+
traceId: this.#raw.traceId,
|
|
4855
|
+
spanId: this.id,
|
|
4856
|
+
correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
|
|
4857
|
+
feedback,
|
|
4858
|
+
inheritedMetadata: this.#raw.metadata
|
|
4859
|
+
}));
|
|
4860
|
+
}
|
|
4861
|
+
};
|
|
4862
|
+
var RecordedTraceImpl = class {
|
|
4863
|
+
traceId;
|
|
4864
|
+
rootSpan;
|
|
4865
|
+
spans;
|
|
4866
|
+
#rootRecord;
|
|
4867
|
+
#emitRecordedEvent;
|
|
4868
|
+
#spanMap;
|
|
4869
|
+
#canEmitRecordedEvent;
|
|
4870
|
+
#debugRecordedAnnotationUnavailable;
|
|
4871
|
+
constructor(args) {
|
|
4872
|
+
this.traceId = args.traceId;
|
|
4873
|
+
this.rootSpan = args.rootSpan;
|
|
4874
|
+
this.#rootRecord = args.rootRecord;
|
|
4875
|
+
this.spans = args.spans;
|
|
4876
|
+
this.#emitRecordedEvent = args.emitRecordedEvent;
|
|
4877
|
+
this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
|
|
4878
|
+
this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
|
|
4879
|
+
this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
|
|
4880
|
+
}
|
|
4881
|
+
getSpan(spanId) {
|
|
4882
|
+
return this.#spanMap.get(spanId) ?? null;
|
|
4883
|
+
}
|
|
4884
|
+
async addScore(score) {
|
|
4885
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4886
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4887
|
+
kind: "score",
|
|
4888
|
+
traceId: this.traceId
|
|
4889
|
+
});
|
|
4890
|
+
return;
|
|
4891
|
+
}
|
|
4892
|
+
await this.#emitRecordedEvent(buildScoreEvent({
|
|
4893
|
+
traceId: this.#rootRecord.traceId,
|
|
4894
|
+
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
4895
|
+
score,
|
|
4896
|
+
inheritedMetadata: this.#rootRecord.metadata
|
|
4897
|
+
}));
|
|
4898
|
+
}
|
|
4899
|
+
async addFeedback(feedback) {
|
|
4900
|
+
if (!this.#canEmitRecordedEvent()) {
|
|
4901
|
+
this.#debugRecordedAnnotationUnavailable({
|
|
4902
|
+
kind: "feedback",
|
|
4903
|
+
traceId: this.traceId
|
|
4904
|
+
});
|
|
4905
|
+
return;
|
|
4906
|
+
}
|
|
4907
|
+
await this.#emitRecordedEvent(buildFeedbackEvent({
|
|
4908
|
+
traceId: this.#rootRecord.traceId,
|
|
4909
|
+
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
4910
|
+
feedback,
|
|
4911
|
+
inheritedMetadata: this.#rootRecord.metadata
|
|
4912
|
+
}));
|
|
4913
|
+
}
|
|
4914
|
+
};
|
|
4915
|
+
function findRootSpan(spans) {
|
|
4916
|
+
const spanIds = new Set(spans.map((span) => span.spanId));
|
|
4917
|
+
return spans.find((span) => !span.parentSpanId) ?? spans.find((span) => !spanIds.has(span.parentSpanId)) ?? spans[0];
|
|
4918
|
+
}
|
|
4919
|
+
function hydrateRecordedTrace(args) {
|
|
4920
|
+
const { trace, emitRecordedEvent, canEmitRecordedEvent = () => true, debugRecordedAnnotationUnavailable = () => {} } = args;
|
|
4921
|
+
const rootSpan = findRootSpan(trace.spans);
|
|
4922
|
+
if (!rootSpan) return null;
|
|
4923
|
+
const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
|
|
4924
|
+
raw,
|
|
4925
|
+
rootSpan,
|
|
4926
|
+
emitRecordedEvent,
|
|
4927
|
+
canEmitRecordedEvent,
|
|
4928
|
+
debugRecordedAnnotationUnavailable
|
|
4929
|
+
}));
|
|
4930
|
+
const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
|
|
4931
|
+
for (const span of recordedSpans) {
|
|
4932
|
+
if (!span.parentSpanId) continue;
|
|
4933
|
+
const parent = spanMap.get(span.parentSpanId);
|
|
4934
|
+
if (!parent) continue;
|
|
4935
|
+
span.parent = parent;
|
|
4936
|
+
parent.children.push(span);
|
|
4937
|
+
}
|
|
4938
|
+
const hydratedRootSpan = spanMap.get(rootSpan.spanId);
|
|
4939
|
+
if (!hydratedRootSpan) return null;
|
|
4940
|
+
return new RecordedTraceImpl({
|
|
4941
|
+
traceId: trace.traceId,
|
|
4942
|
+
rootSpan: hydratedRootSpan,
|
|
4943
|
+
rootRecord: rootSpan,
|
|
4944
|
+
spans: recordedSpans,
|
|
4945
|
+
emitRecordedEvent,
|
|
4946
|
+
canEmitRecordedEvent,
|
|
4947
|
+
debugRecordedAnnotationUnavailable
|
|
4948
|
+
});
|
|
4949
|
+
}
|
|
4950
|
+
// src/exporters/storage-annotation.ts
|
|
4951
|
+
const LOOKUP_DELAYS_MS = [
|
|
4952
|
+
0,
|
|
4953
|
+
100,
|
|
4954
|
+
250,
|
|
4955
|
+
500,
|
|
4956
|
+
1e3,
|
|
4957
|
+
2e3,
|
|
4958
|
+
2e3
|
|
4959
|
+
];
|
|
4960
|
+
/**
|
|
4961
|
+
* Resolve attached-storage context within a bounded retry window, including failed reads.
|
|
4962
|
+
* Exhaustion returns null for missing anchors or throws the last read error for the exporter to report.
|
|
4963
|
+
* Other destinations receive the original event independently.
|
|
4964
|
+
*/
|
|
4965
|
+
async function resolveStorageAnnotation(event, storage, flushSpans) {
|
|
4966
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
4967
|
+
if (record.correlationContext !== void 0) return event;
|
|
4968
|
+
if (!record.traceId) return null;
|
|
4969
|
+
let lastReadFailure;
|
|
4970
|
+
for (const delay of LOOKUP_DELAYS_MS) {
|
|
4971
|
+
if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
|
|
4972
|
+
let trace;
|
|
4973
|
+
try {
|
|
4974
|
+
trace = await storage.getTrace({ traceId: record.traceId });
|
|
4975
|
+
lastReadFailure = void 0;
|
|
4976
|
+
} catch (error) {
|
|
4977
|
+
lastReadFailure = { error };
|
|
4978
|
+
}
|
|
4979
|
+
if (trace) {
|
|
4980
|
+
const resolved = resolveRecordedEventFromTrace(trace, event);
|
|
4981
|
+
if (resolved) return resolved;
|
|
4982
|
+
}
|
|
4983
|
+
if (delay === 0) await flushSpans();
|
|
4984
|
+
}
|
|
4985
|
+
if (lastReadFailure) throw lastReadFailure.error;
|
|
4986
|
+
return null;
|
|
4987
|
+
}
|
|
4988
|
+
// src/exporters/default.ts
|
|
4989
|
+
/**
|
|
4990
|
+
* Resolves the final tracing storage strategy based on config and observability store hints
|
|
4991
|
+
*/
|
|
4992
|
+
function resolveTracingStorageStrategy$1(config, observabilityStorage, storageName, logger) {
|
|
4993
|
+
const observabilityStrategy = observabilityStorage.observabilityStrategy;
|
|
4994
|
+
if (config.strategy && config.strategy !== "auto") {
|
|
4995
|
+
if (observabilityStrategy.supported.includes(config.strategy)) return config.strategy;
|
|
4996
|
+
logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
|
|
4997
|
+
userStrategy: config.strategy,
|
|
4998
|
+
storageAdapter: storageName,
|
|
4999
|
+
supportedStrategies: observabilityStrategy.supported,
|
|
5000
|
+
fallbackStrategy: observabilityStrategy.preferred
|
|
5001
|
+
});
|
|
5002
|
+
}
|
|
5003
|
+
return observabilityStrategy.preferred;
|
|
5004
|
+
}
|
|
5005
|
+
const FLUSH_SUCCEEDED$1 = { failed: false };
|
|
5006
|
+
/** Max join/write rounds a single flush() makes before it returns under continuous traffic */
|
|
5007
|
+
const MAX_FLUSH_ROUNDS$1 = 3;
|
|
5008
|
+
/**
|
|
5009
|
+
* @deprecated Use `MastraStorageExporter` from `@mastra/observability` instead.
|
|
5010
|
+
* This class is preserved unchanged so existing integrations (including code
|
|
5011
|
+
* that matches on the `mastra-default-observability-exporter` exporter name)
|
|
5012
|
+
* keep working. It will be removed in a future major version.
|
|
5013
|
+
*
|
|
5014
|
+
* Default storage-backed exporter. Buffers observability events and flushes them
|
|
5015
|
+
* in batches to the configured ObservabilityStorage backend with retry support.
|
|
5016
|
+
*/
|
|
5017
|
+
var DefaultExporter = class extends BaseExporter {
|
|
5018
|
+
name = "mastra-default-observability-exporter";
|
|
5019
|
+
#config;
|
|
5020
|
+
#isInitializing = false;
|
|
5021
|
+
#initPromises = /* @__PURE__ */ new Set();
|
|
5022
|
+
#eventBuffer;
|
|
5023
|
+
#storage;
|
|
5024
|
+
#observabilityStorage;
|
|
5025
|
+
#resolvedStrategy;
|
|
5026
|
+
#flushTimer;
|
|
5027
|
+
/** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
|
|
5028
|
+
#inFlightFlushes = /* @__PURE__ */ new Set();
|
|
5029
|
+
#pendingAnnotations = /* @__PURE__ */ new Set();
|
|
5030
|
+
#emitDropEvent;
|
|
5031
|
+
#unsupportedSignals = /* @__PURE__ */ new Set();
|
|
5032
|
+
constructor(config = {}) {
|
|
5033
|
+
super(config);
|
|
5034
|
+
this.#config = {
|
|
5035
|
+
...config,
|
|
5036
|
+
maxBatchSize: config.maxBatchSize ?? 1e3,
|
|
5037
|
+
maxBufferSize: config.maxBufferSize ?? 1e4,
|
|
5038
|
+
maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
|
|
5039
|
+
maxRetries: config.maxRetries ?? 4,
|
|
5040
|
+
retryDelayMs: config.retryDelayMs ?? 500,
|
|
5041
|
+
strategy: config.strategy ?? "auto"
|
|
5042
|
+
};
|
|
5043
|
+
this.#eventBuffer = new EventBuffer({ maxRetries: this.#config.maxRetries ?? 4 });
|
|
5044
|
+
}
|
|
5045
|
+
/**
|
|
5046
|
+
* Initialize the exporter (called after all dependencies are ready)
|
|
5047
|
+
*/
|
|
5048
|
+
async init(options) {
|
|
5049
|
+
try {
|
|
5050
|
+
this.#isInitializing = true;
|
|
5051
|
+
this.#emitDropEvent = options.emitDropEvent;
|
|
5052
|
+
this.#storage = options.mastra?.getStorage();
|
|
5053
|
+
if (!this.#storage) {
|
|
5054
|
+
this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
|
|
5055
|
+
return;
|
|
5056
|
+
}
|
|
5057
|
+
this.#observabilityStorage = await this.#storage.getStore("observability");
|
|
5058
|
+
if (!this.#observabilityStorage) {
|
|
5059
|
+
this.logger.warn("DefaultExporter disabled: Observability storage not available. Traces will not be persisted.");
|
|
5060
|
+
return;
|
|
5061
|
+
}
|
|
5062
|
+
if (!this.#resolvedStrategy) {
|
|
5063
|
+
this.#resolvedStrategy = resolveTracingStorageStrategy$1(this.#config, this.#observabilityStorage, this.#storage.constructor.name, this.logger);
|
|
5064
|
+
this.logger.debug("tracing storage exporter initialized", {
|
|
5065
|
+
strategy: this.#resolvedStrategy,
|
|
5066
|
+
source: this.#config.strategy !== "auto" ? "user" : "auto",
|
|
5067
|
+
storageAdapter: this.#storage.constructor.name,
|
|
5068
|
+
maxBatchSize: this.#config.maxBatchSize,
|
|
5069
|
+
maxBatchWaitMs: this.#config.maxBatchWaitMs
|
|
5070
|
+
});
|
|
5071
|
+
}
|
|
5072
|
+
if (this.#resolvedStrategy) this.#eventBuffer.init({ strategy: this.#resolvedStrategy });
|
|
5073
|
+
} finally {
|
|
5074
|
+
this.#isInitializing = false;
|
|
5075
|
+
/**
|
|
5076
|
+
* Assumes caller waits until export of a parent span is completed before calling
|
|
5077
|
+
* export for child spans , order is not relevant for resolve
|
|
5078
|
+
*/
|
|
5079
|
+
this.#initPromises.forEach((resolve) => {
|
|
5080
|
+
resolve();
|
|
5081
|
+
});
|
|
5082
|
+
this.#initPromises.clear();
|
|
5083
|
+
}
|
|
5084
|
+
}
|
|
5085
|
+
/**
|
|
5086
|
+
* Checks if buffer should be flushed based on size or time triggers
|
|
5087
|
+
*/
|
|
5088
|
+
shouldFlush() {
|
|
5089
|
+
if (this.#resolvedStrategy === "realtime") return true;
|
|
5090
|
+
if (this.#eventBuffer.totalSize >= this.#config.maxBufferSize) return true;
|
|
5091
|
+
if (this.#eventBuffer.totalSize >= this.#config.maxBatchSize) return true;
|
|
5092
|
+
if (this.#eventBuffer.totalSize > 0) {
|
|
5093
|
+
if (this.#eventBuffer.elapsed >= this.#config.maxBatchWaitMs) return true;
|
|
5094
|
+
}
|
|
5095
|
+
return false;
|
|
5096
|
+
}
|
|
5097
|
+
/**
|
|
5098
|
+
* Schedules a flush using setTimeout
|
|
5099
|
+
*/
|
|
5100
|
+
scheduleFlush(delayMs = this.#config.maxBatchWaitMs) {
|
|
5101
|
+
if (this.#flushTimer) clearTimeout(this.#flushTimer);
|
|
5102
|
+
this.#flushTimer = setTimeout(() => {
|
|
5103
|
+
this.#flushTimer = void 0;
|
|
5104
|
+
this.trackFlushBuffer().catch((error) => {
|
|
5105
|
+
this.logger.error("Scheduled flush failed", { error: error instanceof Error ? error.message : String(error) });
|
|
5106
|
+
});
|
|
5107
|
+
}, delayMs);
|
|
5108
|
+
}
|
|
5109
|
+
retryDelay(retryAttempt) {
|
|
5110
|
+
return this.#config.retryDelayMs * 2 ** (retryAttempt - 1);
|
|
5111
|
+
}
|
|
5112
|
+
retryAttempt(events) {
|
|
5113
|
+
return events.reduce((earliestAttempt, event) => {
|
|
5114
|
+
if (event.retryCount > this.#config.maxRetries) return earliestAttempt;
|
|
5115
|
+
return earliestAttempt === void 0 ? event.retryCount : Math.min(earliestAttempt, event.retryCount);
|
|
5116
|
+
}, void 0);
|
|
5117
|
+
}
|
|
5118
|
+
logStorageFailure(signal, events, retryAttempt, error) {
|
|
5119
|
+
this.logger.warn("Failed to persist observability events", {
|
|
5120
|
+
signal,
|
|
5121
|
+
eventCount: events.length,
|
|
5122
|
+
retryAttempt: retryAttempt ?? events.reduce((latestAttempt, event) => Math.max(latestAttempt, event.retryCount), 0),
|
|
5123
|
+
maxRetries: this.#config.maxRetries,
|
|
5124
|
+
...retryAttempt === void 0 ? {} : { nextRetryDelayMs: this.retryDelay(retryAttempt) },
|
|
5125
|
+
error: error instanceof Error ? error.message : String(error)
|
|
5126
|
+
});
|
|
5127
|
+
}
|
|
5128
|
+
/**
|
|
5129
|
+
* Checks flush triggers and schedules/triggers flush as needed.
|
|
5130
|
+
* Called after adding any event to the buffer.
|
|
5131
|
+
* Returns the flush promise when flushing so callers can await it.
|
|
5132
|
+
*/
|
|
5133
|
+
async handleBatchedFlush() {
|
|
5134
|
+
if (this.shouldFlush()) await this.trackFlushBuffer();
|
|
5135
|
+
else if (this.#eventBuffer.totalSize === 1) this.scheduleFlush();
|
|
5136
|
+
}
|
|
5137
|
+
sanitizeDropError(error) {
|
|
5138
|
+
if (error instanceof _mastra_core_error.MastraError) return {
|
|
5139
|
+
id: error.id,
|
|
5140
|
+
domain: String(error.domain),
|
|
5141
|
+
message: error.message
|
|
5142
|
+
};
|
|
5143
|
+
if (error instanceof Error) return { message: error.message };
|
|
5144
|
+
return { message: String(error) };
|
|
5145
|
+
}
|
|
5146
|
+
emitDrop(signal, reason, count, error) {
|
|
5147
|
+
if (count === 0) return;
|
|
5148
|
+
const dropEvent = {
|
|
5149
|
+
type: "drop",
|
|
5150
|
+
signal,
|
|
5151
|
+
reason,
|
|
5152
|
+
count,
|
|
5153
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
5154
|
+
exporterName: this.name,
|
|
5155
|
+
...this.#observabilityStorage ? { storageName: this.#observabilityStorage.constructor.name } : {},
|
|
5156
|
+
...error === void 0 ? {} : { error: this.sanitizeDropError(error) }
|
|
5157
|
+
};
|
|
5158
|
+
this.#emitDropEvent?.(dropEvent);
|
|
5159
|
+
}
|
|
5160
|
+
/**
|
|
5161
|
+
* Flush a batch of create events for a single signal type.
|
|
5162
|
+
* On "not implemented" errors, disables the signal for future flushes.
|
|
5163
|
+
* On other errors, re-adds events to the buffer for retry.
|
|
5164
|
+
*/
|
|
5165
|
+
async flushCreates(signal, events, storageCall) {
|
|
5166
|
+
if (events.length === 0) return FLUSH_SUCCEEDED$1;
|
|
5167
|
+
if (this.#unsupportedSignals.has(signal)) {
|
|
5168
|
+
this.emitDrop(signal, "unsupported-storage", events.length);
|
|
5169
|
+
return { failed: true };
|
|
5170
|
+
}
|
|
5171
|
+
try {
|
|
5172
|
+
await storageCall(events);
|
|
5173
|
+
return FLUSH_SUCCEEDED$1;
|
|
5174
|
+
} catch (error) {
|
|
5175
|
+
if (error instanceof _mastra_core_error.MastraError && error.domain === _mastra_core_error.ErrorDomain.MASTRA_OBSERVABILITY && error.id.endsWith("_NOT_IMPLEMENTED")) {
|
|
5176
|
+
this.logger.warn(error.message);
|
|
4815
5177
|
this.#unsupportedSignals.add(signal);
|
|
4816
5178
|
this.emitDrop(signal, "unsupported-storage", events.length, error);
|
|
4817
5179
|
return { failed: true };
|
|
@@ -4937,7 +5299,10 @@ var DefaultExporter = class extends BaseExporter {
|
|
|
4937
5299
|
case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
|
|
4938
5300
|
}
|
|
4939
5301
|
const flushResults = await Promise.all([
|
|
4940
|
-
this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5302
|
+
this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5303
|
+
feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)),
|
|
5304
|
+
onConflict: "ignore"
|
|
5305
|
+
})),
|
|
4941
5306
|
this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
|
|
4942
5307
|
this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
|
|
4943
5308
|
this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
|
|
@@ -5014,22 +5379,46 @@ var DefaultExporter = class extends BaseExporter {
|
|
|
5014
5379
|
this.#eventBuffer.addEvent(event);
|
|
5015
5380
|
await this.handleBatchedFlush();
|
|
5016
5381
|
}
|
|
5017
|
-
|
|
5018
|
-
|
|
5019
|
-
*/
|
|
5020
|
-
async onScoreEvent(event) {
|
|
5021
|
-
await this.waitForInit();
|
|
5022
|
-
if (!this.#observabilityStorage) return;
|
|
5023
|
-
this.#eventBuffer.addEvent(event);
|
|
5024
|
-
await this.handleBatchedFlush();
|
|
5382
|
+
onScoreEvent(event) {
|
|
5383
|
+
return this.enqueueAnnotation(event);
|
|
5025
5384
|
}
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
|
|
5385
|
+
onFeedbackReplacementEvent(event) {
|
|
5386
|
+
return this.enqueueAnnotation(event);
|
|
5387
|
+
}
|
|
5388
|
+
onFeedbackEvent(event) {
|
|
5389
|
+
return this.enqueueAnnotation(event);
|
|
5390
|
+
}
|
|
5391
|
+
enqueueAnnotation(event) {
|
|
5392
|
+
const pending = this.storeAnnotation(event);
|
|
5393
|
+
this.#pendingAnnotations.add(pending);
|
|
5394
|
+
pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
|
|
5395
|
+
return pending;
|
|
5396
|
+
}
|
|
5397
|
+
async storeAnnotation(event) {
|
|
5030
5398
|
await this.waitForInit();
|
|
5031
5399
|
if (!this.#observabilityStorage) return;
|
|
5032
|
-
this.#
|
|
5400
|
+
const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
|
|
5401
|
+
await Promise.allSettled([...this.#inFlightFlushes]);
|
|
5402
|
+
if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
|
|
5403
|
+
});
|
|
5404
|
+
if (!resolved) {
|
|
5405
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
5406
|
+
this.logger.warn("Storage export dropped because the target trace/span was not found", {
|
|
5407
|
+
eventType: event.type,
|
|
5408
|
+
traceId: record.traceId,
|
|
5409
|
+
spanId: record.spanId
|
|
5410
|
+
});
|
|
5411
|
+
return;
|
|
5412
|
+
}
|
|
5413
|
+
if (resolved.type === "feedback_replacement") {
|
|
5414
|
+
if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
|
|
5415
|
+
this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
|
|
5416
|
+
return;
|
|
5417
|
+
}
|
|
5418
|
+
await this.#observabilityStorage.replaceFeedback({ feedback: (0, _mastra_core_storage.buildFeedbackRecord)(resolved) });
|
|
5419
|
+
return;
|
|
5420
|
+
}
|
|
5421
|
+
this.#eventBuffer.addEvent(resolved);
|
|
5033
5422
|
await this.handleBatchedFlush();
|
|
5034
5423
|
}
|
|
5035
5424
|
/**
|
|
@@ -5038,6 +5427,7 @@ var DefaultExporter = class extends BaseExporter {
|
|
|
5038
5427
|
* are exported before the runtime instance is terminated.
|
|
5039
5428
|
*/
|
|
5040
5429
|
async flush() {
|
|
5430
|
+
await Promise.allSettled([...this.#pendingAnnotations]);
|
|
5041
5431
|
for (let round = 0; round < MAX_FLUSH_ROUNDS$1; round++) {
|
|
5042
5432
|
if (this.#inFlightFlushes.size > 0) await Promise.allSettled([...this.#inFlightFlushes]);
|
|
5043
5433
|
if (this.#eventBuffer.totalSize > 0) {
|
|
@@ -5187,6 +5577,7 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5187
5577
|
#flushTimer;
|
|
5188
5578
|
/** Storage writes (timer, size trigger, or flush()) that haven't finished yet */
|
|
5189
5579
|
#inFlightFlushes = /* @__PURE__ */ new Set();
|
|
5580
|
+
#pendingAnnotations = /* @__PURE__ */ new Set();
|
|
5190
5581
|
#emitDropEvent;
|
|
5191
5582
|
#unsupportedSignals = /* @__PURE__ */ new Set();
|
|
5192
5583
|
constructor(config = {}) {
|
|
@@ -5557,7 +5948,10 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5557
5948
|
case _mastra_core_observability.TracingEventType.SPAN_ENDED: endSpanEvents.push(updateEvent);
|
|
5558
5949
|
}
|
|
5559
5950
|
const createTasks = [
|
|
5560
|
-
() => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5951
|
+
() => this.flushCreates("feedback", createFeedbackEvents, (events) => this.#observabilityStorage.batchCreateFeedback({
|
|
5952
|
+
feedbacks: events.map((f) => (0, _mastra_core_storage.buildFeedbackRecord)(f)),
|
|
5953
|
+
onConflict: "ignore"
|
|
5954
|
+
})),
|
|
5561
5955
|
() => this.flushCreates("log", createLogEvents, (events) => this.#observabilityStorage.batchCreateLogs({ logs: events.map((l) => (0, _mastra_core_storage.buildLogRecord)(l)) })),
|
|
5562
5956
|
() => this.flushCreates("metric", createMetricEvents, (events) => this.#observabilityStorage.batchCreateMetrics({ metrics: events.map((m) => (0, _mastra_core_storage.buildMetricRecord)(m)) })),
|
|
5563
5957
|
() => this.flushCreates("score", createScoreEvents, (events) => this.#observabilityStorage.batchCreateScores({ scores: events.map((s) => (0, _mastra_core_storage.buildScoreRecord)(s)) })),
|
|
@@ -5638,22 +6032,46 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5638
6032
|
this.#eventBuffer.addEvent(event);
|
|
5639
6033
|
await this.handleBatchedFlush();
|
|
5640
6034
|
}
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
*/
|
|
5644
|
-
async onScoreEvent(event) {
|
|
5645
|
-
await this.ensureInitialized();
|
|
5646
|
-
if (!this.#observabilityStorage) return;
|
|
5647
|
-
this.#eventBuffer.addEvent(event);
|
|
5648
|
-
await this.handleBatchedFlush();
|
|
6035
|
+
onScoreEvent(event) {
|
|
6036
|
+
return this.enqueueAnnotation(event);
|
|
5649
6037
|
}
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
|
|
6038
|
+
onFeedbackReplacementEvent(event) {
|
|
6039
|
+
return this.enqueueAnnotation(event);
|
|
6040
|
+
}
|
|
6041
|
+
onFeedbackEvent(event) {
|
|
6042
|
+
return this.enqueueAnnotation(event);
|
|
6043
|
+
}
|
|
6044
|
+
enqueueAnnotation(event) {
|
|
6045
|
+
const pending = this.storeAnnotation(event);
|
|
6046
|
+
this.#pendingAnnotations.add(pending);
|
|
6047
|
+
pending.then(() => this.#pendingAnnotations.delete(pending), () => this.#pendingAnnotations.delete(pending));
|
|
6048
|
+
return pending;
|
|
6049
|
+
}
|
|
6050
|
+
async storeAnnotation(event) {
|
|
5654
6051
|
await this.ensureInitialized();
|
|
5655
6052
|
if (!this.#observabilityStorage) return;
|
|
5656
|
-
this.#
|
|
6053
|
+
const resolved = await resolveStorageAnnotation(event, this.#observabilityStorage, async () => {
|
|
6054
|
+
await Promise.allSettled([...this.#inFlightFlushes]);
|
|
6055
|
+
if (this.#eventBuffer.totalSize) await this.trackFlushBuffer();
|
|
6056
|
+
});
|
|
6057
|
+
if (!resolved) {
|
|
6058
|
+
const record = event.type === "score" ? event.score : event.feedback;
|
|
6059
|
+
this.logger.warn("Storage export dropped because the target trace/span was not found", {
|
|
6060
|
+
eventType: event.type,
|
|
6061
|
+
traceId: record.traceId,
|
|
6062
|
+
spanId: record.spanId
|
|
6063
|
+
});
|
|
6064
|
+
return;
|
|
6065
|
+
}
|
|
6066
|
+
if (resolved.type === "feedback_replacement") {
|
|
6067
|
+
if (typeof this.#observabilityStorage.replaceFeedback !== "function" || !this.#observabilityStorage.getFeatures?.()?.includes("feedback-replacement")) {
|
|
6068
|
+
this.logger.warn("Storage exporter skipped feedback replacement: upgrade the storage adapter and @mastra/core");
|
|
6069
|
+
return;
|
|
6070
|
+
}
|
|
6071
|
+
await this.#observabilityStorage.replaceFeedback({ feedback: (0, _mastra_core_storage.buildFeedbackRecord)(resolved) });
|
|
6072
|
+
return;
|
|
6073
|
+
}
|
|
6074
|
+
this.#eventBuffer.addEvent(resolved);
|
|
5657
6075
|
await this.handleBatchedFlush();
|
|
5658
6076
|
}
|
|
5659
6077
|
/**
|
|
@@ -5662,6 +6080,7 @@ var MastraStorageExporter = class extends BaseExporter {
|
|
|
5662
6080
|
* are exported before the runtime instance is terminated.
|
|
5663
6081
|
*/
|
|
5664
6082
|
async flush() {
|
|
6083
|
+
await Promise.allSettled([...this.#pendingAnnotations]);
|
|
5665
6084
|
if (this.#byteTracker) {
|
|
5666
6085
|
if (!this.#observabilityStorage) return;
|
|
5667
6086
|
this.#byteDrainers++;
|
|
@@ -6088,8 +6507,9 @@ var BaseObservabilityInstance = class extends _mastra_core_base.MastraBase {
|
|
|
6088
6507
|
* Internal hook used by RecordedTrace/RecordedSpan hydration to route
|
|
6089
6508
|
* non-tracing annotation events back through the normal exporter pipeline.
|
|
6090
6509
|
*/
|
|
6091
|
-
__emitRecordedEvent(event) {
|
|
6092
|
-
this.
|
|
6510
|
+
__emitRecordedEvent(event, shouldHandle) {
|
|
6511
|
+
if (shouldHandle) this.observabilityBus.emit(event, shouldHandle);
|
|
6512
|
+
else this.emitObservabilityEvent(event);
|
|
6093
6513
|
}
|
|
6094
6514
|
/**
|
|
6095
6515
|
* Internal hook used by the client observability proxy (`client/`)
|
|
@@ -8672,6 +9092,41 @@ var PlatformByteBatcher = class {
|
|
|
8672
9092
|
};
|
|
8673
9093
|
}
|
|
8674
9094
|
};
|
|
9095
|
+
// src/exporters/platform-resolved-record.ts
|
|
9096
|
+
/** Deliver one feedback or score record whose span context must be resolved by Platform. */
|
|
9097
|
+
async function publishResolvedRecord(url, body, headers, method = "POST") {
|
|
9098
|
+
const deadline = AbortSignal.timeout(3e4);
|
|
9099
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
9100
|
+
const response = await fetch(url, {
|
|
9101
|
+
method,
|
|
9102
|
+
headers,
|
|
9103
|
+
body,
|
|
9104
|
+
signal: deadline
|
|
9105
|
+
});
|
|
9106
|
+
if (response.ok) {
|
|
9107
|
+
await response.body?.cancel();
|
|
9108
|
+
return;
|
|
9109
|
+
}
|
|
9110
|
+
const error = await response.json().catch(() => null);
|
|
9111
|
+
const code = error?.code ?? error?.error?.code;
|
|
9112
|
+
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})` : ""}`);
|
|
9113
|
+
const retryAfter = response.headers.get("retry-after");
|
|
9114
|
+
const retryAfterMs = retryAfter ? /^\d+(?:\.\d+)?$/.test(retryAfter) ? Number(retryAfter) * 1e3 : Date.parse(retryAfter) - Date.now() : 0;
|
|
9115
|
+
const delay = Math.max(Math.min(500 * 2 ** attempt, 4e3), Number.isFinite(retryAfterMs) ? retryAfterMs : 0);
|
|
9116
|
+
await new Promise((resolve, reject) => {
|
|
9117
|
+
deadline.throwIfAborted();
|
|
9118
|
+
const timer = setTimeout(() => {
|
|
9119
|
+
deadline.removeEventListener("abort", abort);
|
|
9120
|
+
resolve();
|
|
9121
|
+
}, Math.min(delay, 3e4));
|
|
9122
|
+
function abort() {
|
|
9123
|
+
clearTimeout(timer);
|
|
9124
|
+
reject(deadline.reason);
|
|
9125
|
+
}
|
|
9126
|
+
deadline.addEventListener("abort", abort, { once: true });
|
|
9127
|
+
});
|
|
9128
|
+
}
|
|
9129
|
+
}
|
|
8675
9130
|
// src/exporters/mastra-platform.ts
|
|
8676
9131
|
const SIGNAL_PUBLISH_SUFFIXES = {
|
|
8677
9132
|
traces: "/spans/publish",
|
|
@@ -8791,6 +9246,7 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
8791
9246
|
buffer;
|
|
8792
9247
|
flushTimer = null;
|
|
8793
9248
|
inFlightFlushes = /* @__PURE__ */ new Set();
|
|
9249
|
+
pendingRecords = /* @__PURE__ */ new Set();
|
|
8794
9250
|
quotaPaused = false;
|
|
8795
9251
|
quotaProbeTimer = null;
|
|
8796
9252
|
quotaProbeIntervalSeconds = DEFAULT_QUOTA_PROBE_INTERVAL_SECONDS;
|
|
@@ -8827,6 +9283,7 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
8827
9283
|
maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
|
|
8828
9284
|
maxRetries: config.maxRetries ?? 3,
|
|
8829
9285
|
accessToken: accessToken || "",
|
|
9286
|
+
projectId,
|
|
8830
9287
|
tracesEndpoint,
|
|
8831
9288
|
logsEndpoint: resolveConfiguredSignalEndpoint("logs", config.logsEndpoint),
|
|
8832
9289
|
metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config.metricsEndpoint),
|
|
@@ -8868,17 +9325,58 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
8868
9325
|
await this.handleBufferedEvent();
|
|
8869
9326
|
}
|
|
8870
9327
|
async onScoreEvent(event) {
|
|
8871
|
-
if (this.isDisabled) return;
|
|
9328
|
+
if (this.isDisabled || this.shuttingDown) return;
|
|
9329
|
+
if (event.score.correlationContext == null) {
|
|
9330
|
+
this.enqueueResolvedRecord("score", event.score);
|
|
9331
|
+
return;
|
|
9332
|
+
}
|
|
8872
9333
|
if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
|
|
8873
9334
|
this.addScoreToBuffer(event);
|
|
8874
9335
|
await this.handleBufferedEvent();
|
|
8875
9336
|
}
|
|
8876
9337
|
async onFeedbackEvent(event) {
|
|
8877
|
-
if (this.isDisabled) return;
|
|
9338
|
+
if (this.isDisabled || this.shuttingDown) return;
|
|
9339
|
+
if (event.feedback.correlationContext == null) {
|
|
9340
|
+
this.enqueueResolvedRecord("feedback", event.feedback);
|
|
9341
|
+
return;
|
|
9342
|
+
}
|
|
8878
9343
|
if (this.quotaPaused || this.authFailureCooldown.dropEventIfCoolingDown()) return;
|
|
8879
9344
|
this.addFeedbackToBuffer(event);
|
|
8880
9345
|
await this.handleBufferedEvent();
|
|
8881
9346
|
}
|
|
9347
|
+
onFeedbackReplacementEvent(event) {
|
|
9348
|
+
if (this.isDisabled || this.shuttingDown) return;
|
|
9349
|
+
if (!event.feedback.feedbackId?.trim()) {
|
|
9350
|
+
this.logger.warn("Dropping feedback replacement: feedbackId is required");
|
|
9351
|
+
return;
|
|
9352
|
+
}
|
|
9353
|
+
this.enqueueResolvedRecord("feedback", event.feedback, event.feedback.feedbackId);
|
|
9354
|
+
}
|
|
9355
|
+
enqueueResolvedRecord(kind, record, replacementId) {
|
|
9356
|
+
if (!record.traceId?.trim()) {
|
|
9357
|
+
this.logger.warn(`Dropping ${kind}: context resolution requires traceId`);
|
|
9358
|
+
return;
|
|
9359
|
+
}
|
|
9360
|
+
let body;
|
|
9361
|
+
try {
|
|
9362
|
+
body = JSON.stringify({ [kind]: record });
|
|
9363
|
+
} catch (error) {
|
|
9364
|
+
this.logger.warn(`Dropping unserializable ${kind}`, { error });
|
|
9365
|
+
return;
|
|
9366
|
+
}
|
|
9367
|
+
const collectorEndpoint = kind === "score" ? this.platformConfig.scoresEndpoint : this.platformConfig.feedbackEndpoint;
|
|
9368
|
+
const url = new URL(`/api/observability/${kind === "score" ? "scores" : "feedback"}`, collectorEndpoint);
|
|
9369
|
+
if (replacementId !== void 0) url.pathname += `/${encodeURIComponent(replacementId)}`;
|
|
9370
|
+
const projectId = new URL(collectorEndpoint).pathname.match(/\/projects\/([^/]+)\/ai\//)?.[1] ?? this.platformConfig.projectId;
|
|
9371
|
+
const headers = {
|
|
9372
|
+
Authorization: `Bearer ${this.platformConfig.accessToken}`,
|
|
9373
|
+
"Content-Type": "application/json",
|
|
9374
|
+
...projectId ? { "X-Mastra-Project-Id": projectId } : {}
|
|
9375
|
+
};
|
|
9376
|
+
this.flushBatches().catch((error) => this.logger.warn("Failed to flush buffered telemetry", { error }));
|
|
9377
|
+
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));
|
|
9378
|
+
this.pendingRecords.add(pending);
|
|
9379
|
+
}
|
|
8882
9380
|
addToBuffer(event) {
|
|
8883
9381
|
if (this.byteBatcher) {
|
|
8884
9382
|
this.byteBatcher.add("traces", this.formatSpan(event.exportedSpan));
|
|
@@ -9219,6 +9717,13 @@ var MastraPlatformExporter = class extends BaseExporter {
|
|
|
9219
9717
|
* are exported before the runtime instance is terminated.
|
|
9220
9718
|
*/
|
|
9221
9719
|
async flush() {
|
|
9720
|
+
if (this.isDisabled) return;
|
|
9721
|
+
do {
|
|
9722
|
+
await this.flushBatches();
|
|
9723
|
+
await Promise.allSettled([...this.pendingRecords]);
|
|
9724
|
+
} while (this.pendingRecords.size > 0 || this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0 || (this.byteBatcher?.getStats().pendingBytes ?? 0) > 0);
|
|
9725
|
+
}
|
|
9726
|
+
async flushBatches() {
|
|
9222
9727
|
if (this.isDisabled) return;
|
|
9223
9728
|
if (this.byteBatcher) {
|
|
9224
9729
|
await this.byteBatcher.flush();
|
|
@@ -10171,463 +10676,159 @@ var TestExporter = class extends BaseExporter {
|
|
|
10171
10676
|
path,
|
|
10172
10677
|
expected,
|
|
10173
10678
|
actual
|
|
10174
|
-
});
|
|
10175
|
-
}
|
|
10176
|
-
/**
|
|
10177
|
-
* Check if a value is an __or__ marker object
|
|
10178
|
-
*/
|
|
10179
|
-
#isOrMarker(value) {
|
|
10180
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
|
|
10181
|
-
}
|
|
10182
|
-
/**
|
|
10183
|
-
* Check if a value is an __any__ marker object
|
|
10184
|
-
*/
|
|
10185
|
-
#isAnyMarker(value) {
|
|
10186
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
10187
|
-
if (!("__any__" in value)) return false;
|
|
10188
|
-
const constraint = value.__any__;
|
|
10189
|
-
return constraint === true || [
|
|
10190
|
-
"string",
|
|
10191
|
-
"number",
|
|
10192
|
-
"boolean",
|
|
10193
|
-
"object",
|
|
10194
|
-
"array"
|
|
10195
|
-
].includes(constraint);
|
|
10196
|
-
}
|
|
10197
|
-
/**
|
|
10198
|
-
* Check if a key should be skipped during comparison (metadata keys like __structure__)
|
|
10199
|
-
*/
|
|
10200
|
-
#isMetadataKey(key) {
|
|
10201
|
-
return key.startsWith("__") && key.endsWith("__");
|
|
10202
|
-
}
|
|
10203
|
-
/**
|
|
10204
|
-
* Custom JSON replacer to handle Date objects and other special types
|
|
10205
|
-
*/
|
|
10206
|
-
#jsonReplacer = (_key, value) => {
|
|
10207
|
-
if (value instanceof Date) return value.toISOString();
|
|
10208
|
-
return value;
|
|
10209
|
-
};
|
|
10210
|
-
/**
|
|
10211
|
-
* Get all stored debug logs (internal exporter logging, not signal logs)
|
|
10212
|
-
*/
|
|
10213
|
-
getLogs() {
|
|
10214
|
-
return [...this.#debugLogs];
|
|
10215
|
-
}
|
|
10216
|
-
/**
|
|
10217
|
-
* Dump debug logs to console for debugging (uses console.error for visibility in test output)
|
|
10218
|
-
*/
|
|
10219
|
-
dumpLogs() {
|
|
10220
|
-
console.error("\n=== TestExporter Logs ===");
|
|
10221
|
-
this.#debugLogs.forEach((log) => {
|
|
10222
|
-
console.error(log);
|
|
10223
|
-
});
|
|
10224
|
-
console.error("=== End Logs ===\n");
|
|
10225
|
-
}
|
|
10226
|
-
/**
|
|
10227
|
-
* Validate final state - useful for test assertions
|
|
10228
|
-
*
|
|
10229
|
-
* @returns Object with validation results
|
|
10230
|
-
*/
|
|
10231
|
-
validateFinalState() {
|
|
10232
|
-
const traceIds = this.getTraceIds();
|
|
10233
|
-
const incompleteSpans = this.getIncompleteSpans();
|
|
10234
|
-
const singleTraceId = traceIds.length === 1;
|
|
10235
|
-
const allSpansComplete = incompleteSpans.length === 0;
|
|
10236
|
-
return {
|
|
10237
|
-
valid: singleTraceId && allSpansComplete,
|
|
10238
|
-
singleTraceId,
|
|
10239
|
-
allSpansComplete,
|
|
10240
|
-
traceIds,
|
|
10241
|
-
incompleteSpans
|
|
10242
|
-
};
|
|
10679
|
+
});
|
|
10243
10680
|
}
|
|
10244
10681
|
/**
|
|
10245
|
-
*
|
|
10682
|
+
* Check if a value is an __or__ marker object
|
|
10246
10683
|
*/
|
|
10247
|
-
|
|
10248
|
-
|
|
10249
|
-
this.#spanStates.clear();
|
|
10250
|
-
this.#logEvents = [];
|
|
10251
|
-
this.#metricEvents = [];
|
|
10252
|
-
this.#scoreEvents = [];
|
|
10253
|
-
this.#feedbackEvents = [];
|
|
10254
|
-
this.#debugLogs = [];
|
|
10684
|
+
#isOrMarker(value) {
|
|
10685
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && "__or__" in value && Array.isArray(value.__or__);
|
|
10255
10686
|
}
|
|
10256
10687
|
/**
|
|
10257
|
-
*
|
|
10688
|
+
* Check if a value is an __any__ marker object
|
|
10258
10689
|
*/
|
|
10259
|
-
|
|
10260
|
-
|
|
10690
|
+
#isAnyMarker(value) {
|
|
10691
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
10692
|
+
if (!("__any__" in value)) return false;
|
|
10693
|
+
const constraint = value.__any__;
|
|
10694
|
+
return constraint === true || [
|
|
10695
|
+
"string",
|
|
10696
|
+
"number",
|
|
10697
|
+
"boolean",
|
|
10698
|
+
"object",
|
|
10699
|
+
"array"
|
|
10700
|
+
].includes(constraint);
|
|
10261
10701
|
}
|
|
10262
10702
|
/**
|
|
10263
|
-
*
|
|
10703
|
+
* Check if a key should be skipped during comparison (metadata keys like __structure__)
|
|
10264
10704
|
*/
|
|
10265
|
-
|
|
10266
|
-
|
|
10267
|
-
includeEvents: false,
|
|
10268
|
-
includeStats: false
|
|
10269
|
-
});
|
|
10270
|
-
return {
|
|
10271
|
-
startedAt: this.#internalMetrics.startedAt,
|
|
10272
|
-
lastEventAt: this.#internalMetrics.lastEventAt,
|
|
10273
|
-
totalEventsReceived: this.#internalMetrics.totalEventsReceived,
|
|
10274
|
-
bySignal: { ...this.#internalMetrics.bySignal },
|
|
10275
|
-
flushCount: this.#internalMetrics.flushCount,
|
|
10276
|
-
estimatedJsonBytes: new TextEncoder().encode(json).byteLength
|
|
10277
|
-
};
|
|
10705
|
+
#isMetadataKey(key) {
|
|
10706
|
+
return key.startsWith("__") && key.endsWith("__");
|
|
10278
10707
|
}
|
|
10279
10708
|
/**
|
|
10280
|
-
*
|
|
10709
|
+
* Custom JSON replacer to handle Date objects and other special types
|
|
10281
10710
|
*/
|
|
10282
|
-
|
|
10283
|
-
|
|
10284
|
-
|
|
10285
|
-
|
|
10286
|
-
const uptimeMs = Date.now() - metrics.startedAt.getTime();
|
|
10287
|
-
const summary = [
|
|
10288
|
-
`[TestExporter] flush #${metrics.flushCount} summary:`,
|
|
10289
|
-
` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
|
|
10290
|
-
` total events received: ${metrics.totalEventsReceived}`,
|
|
10291
|
-
` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
|
|
10292
|
-
` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
|
|
10293
|
-
` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
|
|
10294
|
-
].join("\n");
|
|
10295
|
-
this.logger.info(summary);
|
|
10296
|
-
}
|
|
10297
|
-
}
|
|
10298
|
-
async shutdown() {
|
|
10299
|
-
await this.flush();
|
|
10300
|
-
this.logger.info("TestExporter shutdown");
|
|
10301
|
-
}
|
|
10711
|
+
#jsonReplacer = (_key, value) => {
|
|
10712
|
+
if (value instanceof Date) return value.toISOString();
|
|
10713
|
+
return value;
|
|
10714
|
+
};
|
|
10302
10715
|
/**
|
|
10303
|
-
*
|
|
10716
|
+
* Get all stored debug logs (internal exporter logging, not signal logs)
|
|
10304
10717
|
*/
|
|
10305
|
-
|
|
10306
|
-
|
|
10307
|
-
for (const event of events) {
|
|
10308
|
-
const span = event.exportedSpan;
|
|
10309
|
-
if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
|
|
10310
|
-
}
|
|
10311
|
-
return Array.from(spanMap.values());
|
|
10312
|
-
}
|
|
10313
|
-
};
|
|
10314
|
-
/**
|
|
10315
|
-
* @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
|
|
10316
|
-
*/
|
|
10317
|
-
const JsonExporter = TestExporter;
|
|
10318
|
-
// src/instances/default.ts
|
|
10319
|
-
var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
|
|
10320
|
-
constructor(config) {
|
|
10321
|
-
super(config);
|
|
10322
|
-
}
|
|
10323
|
-
createSpan(options) {
|
|
10324
|
-
return new DefaultSpan(options, this);
|
|
10718
|
+
getLogs() {
|
|
10719
|
+
return [...this.#debugLogs];
|
|
10325
10720
|
}
|
|
10326
|
-
|
|
10327
|
-
|
|
10328
|
-
|
|
10329
|
-
|
|
10330
|
-
|
|
10331
|
-
|
|
10332
|
-
|
|
10333
|
-
|
|
10334
|
-
|
|
10335
|
-
...extra ?? {}
|
|
10336
|
-
};
|
|
10337
|
-
}
|
|
10338
|
-
function normalizeErrorInfo(error) {
|
|
10339
|
-
if (!error || typeof error !== "object" || !("message" in error) || typeof error.message !== "string") return;
|
|
10340
|
-
return {
|
|
10341
|
-
message: error.message,
|
|
10342
|
-
id: "id" in error && typeof error.id === "string" ? error.id : void 0,
|
|
10343
|
-
name: "name" in error && typeof error.name === "string" ? error.name : void 0,
|
|
10344
|
-
stack: "stack" in error && typeof error.stack === "string" ? error.stack : void 0,
|
|
10345
|
-
domain: "domain" in error && typeof error.domain === "string" ? error.domain : void 0,
|
|
10346
|
-
category: "category" in error && typeof error.category === "string" ? error.category : void 0,
|
|
10347
|
-
details: "details" in error && error.details && typeof error.details === "object" ? error.details : void 0
|
|
10348
|
-
};
|
|
10349
|
-
}
|
|
10350
|
-
function buildCorrelationContext(span, rootSpan, parent) {
|
|
10351
|
-
return {
|
|
10352
|
-
tags: rootSpan.tags ?? void 0,
|
|
10353
|
-
entityType: nullToUndefined(span.entityType),
|
|
10354
|
-
entityId: nullToUndefined(span.entityId),
|
|
10355
|
-
entityName: nullToUndefined(span.entityName),
|
|
10356
|
-
parentEntityType: parent?.entityType ?? void 0,
|
|
10357
|
-
parentEntityId: parent?.entityId ?? void 0,
|
|
10358
|
-
parentEntityName: parent?.entityName ?? void 0,
|
|
10359
|
-
rootEntityType: nullToUndefined(rootSpan.entityType),
|
|
10360
|
-
rootEntityId: nullToUndefined(rootSpan.entityId),
|
|
10361
|
-
rootEntityName: nullToUndefined(rootSpan.entityName),
|
|
10362
|
-
userId: nullToUndefined(span.userId),
|
|
10363
|
-
organizationId: nullToUndefined(span.organizationId),
|
|
10364
|
-
resourceId: nullToUndefined(span.resourceId),
|
|
10365
|
-
runId: nullToUndefined(span.runId),
|
|
10366
|
-
sessionId: nullToUndefined(span.sessionId),
|
|
10367
|
-
threadId: nullToUndefined(span.threadId),
|
|
10368
|
-
requestId: nullToUndefined(span.requestId),
|
|
10369
|
-
environment: nullToUndefined(span.environment),
|
|
10370
|
-
source: nullToUndefined(span.source),
|
|
10371
|
-
serviceName: nullToUndefined(span.serviceName),
|
|
10372
|
-
experimentId: nullToUndefined(span.experimentId)
|
|
10373
|
-
};
|
|
10374
|
-
}
|
|
10375
|
-
function buildScoreEvent(args) {
|
|
10376
|
-
const { traceId, spanId, correlationContext, score, inheritedMetadata } = args;
|
|
10377
|
-
return {
|
|
10378
|
-
type: "score",
|
|
10379
|
-
score: {
|
|
10380
|
-
scoreId: generateSignalId(),
|
|
10381
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
10382
|
-
traceId,
|
|
10383
|
-
spanId,
|
|
10384
|
-
scorerId: score.scorerId,
|
|
10385
|
-
scorerName: score.scorerName,
|
|
10386
|
-
scorerVersion: score.scorerVersion,
|
|
10387
|
-
source: score.source,
|
|
10388
|
-
scoreSource: score.scoreSource,
|
|
10389
|
-
score: score.score,
|
|
10390
|
-
reason: score.reason,
|
|
10391
|
-
experimentId: score.experimentId,
|
|
10392
|
-
scoreTraceId: score.scoreTraceId,
|
|
10393
|
-
targetEntityType: score.targetEntityType,
|
|
10394
|
-
correlationContext,
|
|
10395
|
-
metadata: mergeMetadata(inheritedMetadata, score.metadata)
|
|
10396
|
-
}
|
|
10397
|
-
};
|
|
10398
|
-
}
|
|
10399
|
-
function buildFeedbackEvent(args) {
|
|
10400
|
-
const { traceId, spanId, correlationContext, feedback, inheritedMetadata } = args;
|
|
10401
|
-
return {
|
|
10402
|
-
type: "feedback",
|
|
10403
|
-
feedback: {
|
|
10404
|
-
feedbackId: generateSignalId(),
|
|
10405
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
10406
|
-
traceId,
|
|
10407
|
-
spanId,
|
|
10408
|
-
source: feedback.source,
|
|
10409
|
-
feedbackSource: feedback.feedbackSource,
|
|
10410
|
-
feedbackType: feedback.feedbackType,
|
|
10411
|
-
value: feedback.value,
|
|
10412
|
-
userId: feedback.userId,
|
|
10413
|
-
feedbackUserId: feedback.feedbackUserId,
|
|
10414
|
-
comment: feedback.comment,
|
|
10415
|
-
sourceId: feedback.sourceId,
|
|
10416
|
-
experimentId: feedback.experimentId,
|
|
10417
|
-
correlationContext,
|
|
10418
|
-
metadata: mergeMetadata(inheritedMetadata, feedback.metadata)
|
|
10419
|
-
}
|
|
10420
|
-
};
|
|
10421
|
-
}
|
|
10422
|
-
function findSpanById(spans, spanId) {
|
|
10423
|
-
if (!spanId) return void 0;
|
|
10424
|
-
return spans.find((span) => span.spanId === spanId);
|
|
10425
|
-
}
|
|
10426
|
-
function buildRecordedScoreEventFromTrace(args) {
|
|
10427
|
-
const rootSpan = findRootSpan(args.trace.spans);
|
|
10428
|
-
if (!rootSpan) return null;
|
|
10429
|
-
const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
|
|
10430
|
-
if (!span) return null;
|
|
10431
|
-
const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
|
|
10432
|
-
return buildScoreEvent({
|
|
10433
|
-
traceId: span.traceId,
|
|
10434
|
-
spanId: args.spanId,
|
|
10435
|
-
correlationContext: buildCorrelationContext(span, rootSpan, parent),
|
|
10436
|
-
score: args.score,
|
|
10437
|
-
inheritedMetadata: span.metadata
|
|
10438
|
-
});
|
|
10439
|
-
}
|
|
10440
|
-
function buildRecordedFeedbackEventFromTrace(args) {
|
|
10441
|
-
const rootSpan = findRootSpan(args.trace.spans);
|
|
10442
|
-
if (!rootSpan) return null;
|
|
10443
|
-
const span = args.spanId ? findSpanById(args.trace.spans, args.spanId) : rootSpan;
|
|
10444
|
-
if (!span) return null;
|
|
10445
|
-
const parent = span.parentSpanId ? findSpanById(args.trace.spans, span.parentSpanId) : void 0;
|
|
10446
|
-
return buildFeedbackEvent({
|
|
10447
|
-
traceId: span.traceId,
|
|
10448
|
-
spanId: args.spanId,
|
|
10449
|
-
correlationContext: buildCorrelationContext(span, rootSpan, parent),
|
|
10450
|
-
feedback: args.feedback,
|
|
10451
|
-
inheritedMetadata: span.metadata
|
|
10452
|
-
});
|
|
10453
|
-
}
|
|
10454
|
-
var RecordedSpanImpl = class {
|
|
10455
|
-
id;
|
|
10456
|
-
traceId;
|
|
10457
|
-
name;
|
|
10458
|
-
type;
|
|
10459
|
-
entityType;
|
|
10460
|
-
entityId;
|
|
10461
|
-
entityName;
|
|
10462
|
-
startTime;
|
|
10463
|
-
endTime;
|
|
10464
|
-
attributes;
|
|
10465
|
-
metadata;
|
|
10466
|
-
tags;
|
|
10467
|
-
input;
|
|
10468
|
-
output;
|
|
10469
|
-
errorInfo;
|
|
10470
|
-
requestContext;
|
|
10471
|
-
isEvent;
|
|
10472
|
-
isRootSpan;
|
|
10473
|
-
parentSpanId;
|
|
10474
|
-
parent;
|
|
10475
|
-
children = [];
|
|
10476
|
-
#raw;
|
|
10477
|
-
#rootSpan;
|
|
10478
|
-
#emitRecordedEvent;
|
|
10479
|
-
#canEmitRecordedEvent;
|
|
10480
|
-
#debugRecordedAnnotationUnavailable;
|
|
10481
|
-
constructor(args) {
|
|
10482
|
-
const { raw, rootSpan, emitRecordedEvent, canEmitRecordedEvent, debugRecordedAnnotationUnavailable } = args;
|
|
10483
|
-
this.#raw = raw;
|
|
10484
|
-
this.#rootSpan = rootSpan;
|
|
10485
|
-
this.#emitRecordedEvent = emitRecordedEvent;
|
|
10486
|
-
this.#canEmitRecordedEvent = canEmitRecordedEvent;
|
|
10487
|
-
this.#debugRecordedAnnotationUnavailable = debugRecordedAnnotationUnavailable;
|
|
10488
|
-
this.id = raw.spanId;
|
|
10489
|
-
this.traceId = raw.traceId;
|
|
10490
|
-
this.name = raw.name;
|
|
10491
|
-
this.type = raw.spanType;
|
|
10492
|
-
this.entityType = raw.entityType ?? void 0;
|
|
10493
|
-
this.entityId = raw.entityId ?? void 0;
|
|
10494
|
-
this.entityName = raw.entityName ?? void 0;
|
|
10495
|
-
this.startTime = raw.startedAt;
|
|
10496
|
-
this.endTime = raw.endedAt ?? void 0;
|
|
10497
|
-
this.attributes = raw.attributes ?? void 0;
|
|
10498
|
-
this.metadata = raw.metadata ?? void 0;
|
|
10499
|
-
this.tags = raw.tags ?? void 0;
|
|
10500
|
-
this.input = raw.input ?? void 0;
|
|
10501
|
-
this.output = raw.output ?? void 0;
|
|
10502
|
-
this.errorInfo = normalizeErrorInfo(raw.error);
|
|
10503
|
-
this.requestContext = raw.requestContext ?? void 0;
|
|
10504
|
-
this.isEvent = raw.isEvent;
|
|
10505
|
-
this.isRootSpan = !raw.parentSpanId;
|
|
10506
|
-
this.parentSpanId = raw.parentSpanId ?? void 0;
|
|
10721
|
+
/**
|
|
10722
|
+
* Dump debug logs to console for debugging (uses console.error for visibility in test output)
|
|
10723
|
+
*/
|
|
10724
|
+
dumpLogs() {
|
|
10725
|
+
console.error("\n=== TestExporter Logs ===");
|
|
10726
|
+
this.#debugLogs.forEach((log) => {
|
|
10727
|
+
console.error(log);
|
|
10728
|
+
});
|
|
10729
|
+
console.error("=== End Logs ===\n");
|
|
10507
10730
|
}
|
|
10508
|
-
|
|
10509
|
-
|
|
10510
|
-
|
|
10511
|
-
|
|
10512
|
-
|
|
10513
|
-
|
|
10514
|
-
|
|
10515
|
-
|
|
10516
|
-
|
|
10517
|
-
|
|
10518
|
-
|
|
10519
|
-
|
|
10520
|
-
|
|
10521
|
-
|
|
10522
|
-
|
|
10523
|
-
|
|
10731
|
+
/**
|
|
10732
|
+
* Validate final state - useful for test assertions
|
|
10733
|
+
*
|
|
10734
|
+
* @returns Object with validation results
|
|
10735
|
+
*/
|
|
10736
|
+
validateFinalState() {
|
|
10737
|
+
const traceIds = this.getTraceIds();
|
|
10738
|
+
const incompleteSpans = this.getIncompleteSpans();
|
|
10739
|
+
const singleTraceId = traceIds.length === 1;
|
|
10740
|
+
const allSpansComplete = incompleteSpans.length === 0;
|
|
10741
|
+
return {
|
|
10742
|
+
valid: singleTraceId && allSpansComplete,
|
|
10743
|
+
singleTraceId,
|
|
10744
|
+
allSpansComplete,
|
|
10745
|
+
traceIds,
|
|
10746
|
+
incompleteSpans
|
|
10747
|
+
};
|
|
10524
10748
|
}
|
|
10525
|
-
|
|
10526
|
-
|
|
10527
|
-
|
|
10528
|
-
|
|
10529
|
-
|
|
10530
|
-
|
|
10531
|
-
|
|
10532
|
-
|
|
10533
|
-
|
|
10534
|
-
|
|
10535
|
-
|
|
10536
|
-
spanId: this.id,
|
|
10537
|
-
correlationContext: buildCorrelationContext(this.#raw, this.#rootSpan, this.parent),
|
|
10538
|
-
feedback,
|
|
10539
|
-
inheritedMetadata: this.#raw.metadata
|
|
10540
|
-
}));
|
|
10749
|
+
/**
|
|
10750
|
+
* Clear all collected events and state across all signals
|
|
10751
|
+
*/
|
|
10752
|
+
clearEvents() {
|
|
10753
|
+
this.#tracingEvents = [];
|
|
10754
|
+
this.#spanStates.clear();
|
|
10755
|
+
this.#logEvents = [];
|
|
10756
|
+
this.#metricEvents = [];
|
|
10757
|
+
this.#scoreEvents = [];
|
|
10758
|
+
this.#feedbackEvents = [];
|
|
10759
|
+
this.#debugLogs = [];
|
|
10541
10760
|
}
|
|
10542
|
-
|
|
10543
|
-
|
|
10544
|
-
|
|
10545
|
-
|
|
10546
|
-
|
|
10547
|
-
#rootRecord;
|
|
10548
|
-
#emitRecordedEvent;
|
|
10549
|
-
#spanMap;
|
|
10550
|
-
#canEmitRecordedEvent;
|
|
10551
|
-
#debugRecordedAnnotationUnavailable;
|
|
10552
|
-
constructor(args) {
|
|
10553
|
-
this.traceId = args.traceId;
|
|
10554
|
-
this.rootSpan = args.rootSpan;
|
|
10555
|
-
this.#rootRecord = args.rootRecord;
|
|
10556
|
-
this.spans = args.spans;
|
|
10557
|
-
this.#emitRecordedEvent = args.emitRecordedEvent;
|
|
10558
|
-
this.#spanMap = new Map(args.spans.map((span) => [span.id, span]));
|
|
10559
|
-
this.#canEmitRecordedEvent = args.canEmitRecordedEvent;
|
|
10560
|
-
this.#debugRecordedAnnotationUnavailable = args.debugRecordedAnnotationUnavailable;
|
|
10761
|
+
/**
|
|
10762
|
+
* Alias for clearEvents (compatibility with TestExporter)
|
|
10763
|
+
*/
|
|
10764
|
+
reset() {
|
|
10765
|
+
this.clearEvents();
|
|
10561
10766
|
}
|
|
10562
|
-
|
|
10563
|
-
|
|
10767
|
+
/**
|
|
10768
|
+
* Get internal metrics about the exporter's own activity.
|
|
10769
|
+
*/
|
|
10770
|
+
getInternalMetrics() {
|
|
10771
|
+
const json = this.toJSON({
|
|
10772
|
+
includeEvents: false,
|
|
10773
|
+
includeStats: false
|
|
10774
|
+
});
|
|
10775
|
+
return {
|
|
10776
|
+
startedAt: this.#internalMetrics.startedAt,
|
|
10777
|
+
lastEventAt: this.#internalMetrics.lastEventAt,
|
|
10778
|
+
totalEventsReceived: this.#internalMetrics.totalEventsReceived,
|
|
10779
|
+
bySignal: { ...this.#internalMetrics.bySignal },
|
|
10780
|
+
flushCount: this.#internalMetrics.flushCount,
|
|
10781
|
+
estimatedJsonBytes: new TextEncoder().encode(json).byteLength
|
|
10782
|
+
};
|
|
10564
10783
|
}
|
|
10565
|
-
|
|
10566
|
-
|
|
10567
|
-
|
|
10568
|
-
|
|
10569
|
-
|
|
10570
|
-
|
|
10571
|
-
|
|
10784
|
+
/**
|
|
10785
|
+
* Flush buffered data and log internal metrics summary.
|
|
10786
|
+
*/
|
|
10787
|
+
async flush() {
|
|
10788
|
+
this.#internalMetrics.flushCount++;
|
|
10789
|
+
if (this.#config.logMetricsOnFlush) {
|
|
10790
|
+
const metrics = this.getInternalMetrics();
|
|
10791
|
+
const uptimeMs = Date.now() - metrics.startedAt.getTime();
|
|
10792
|
+
const summary = [
|
|
10793
|
+
`[TestExporter] flush #${metrics.flushCount} summary:`,
|
|
10794
|
+
` uptime: ${(uptimeMs / 1e3).toFixed(1)}s`,
|
|
10795
|
+
` total events received: ${metrics.totalEventsReceived}`,
|
|
10796
|
+
` by signal: tracing=${metrics.bySignal.tracing}, log=${metrics.bySignal.log}, metric=${metrics.bySignal.metric}, score=${metrics.bySignal.score}, feedback=${metrics.bySignal.feedback}`,
|
|
10797
|
+
` buffered: spans=${this.#spanStates.size}, logs=${this.#logEvents.length}, metrics=${this.#metricEvents.length}, scores=${this.#scoreEvents.length}, feedback=${this.#feedbackEvents.length}`,
|
|
10798
|
+
` estimated JSON size: ${(metrics.estimatedJsonBytes / 1024).toFixed(1)}KB`
|
|
10799
|
+
].join("\n");
|
|
10800
|
+
this.logger.info(summary);
|
|
10572
10801
|
}
|
|
10573
|
-
await this.#emitRecordedEvent(buildScoreEvent({
|
|
10574
|
-
traceId: this.#rootRecord.traceId,
|
|
10575
|
-
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
10576
|
-
score,
|
|
10577
|
-
inheritedMetadata: this.#rootRecord.metadata
|
|
10578
|
-
}));
|
|
10579
10802
|
}
|
|
10580
|
-
async
|
|
10581
|
-
|
|
10582
|
-
|
|
10583
|
-
|
|
10584
|
-
|
|
10585
|
-
|
|
10586
|
-
|
|
10803
|
+
async shutdown() {
|
|
10804
|
+
await this.flush();
|
|
10805
|
+
this.logger.info("TestExporter shutdown");
|
|
10806
|
+
}
|
|
10807
|
+
/**
|
|
10808
|
+
* Extract unique spans from a list of events
|
|
10809
|
+
*/
|
|
10810
|
+
#getUniqueSpansFromEvents(events) {
|
|
10811
|
+
const spanMap = /* @__PURE__ */ new Map();
|
|
10812
|
+
for (const event of events) {
|
|
10813
|
+
const span = event.exportedSpan;
|
|
10814
|
+
if (event.type === _mastra_core_observability.TracingEventType.SPAN_ENDED || !spanMap.has(span.id)) spanMap.set(span.id, span);
|
|
10587
10815
|
}
|
|
10588
|
-
|
|
10589
|
-
traceId: this.#rootRecord.traceId,
|
|
10590
|
-
correlationContext: buildCorrelationContext(this.#rootRecord, this.#rootRecord),
|
|
10591
|
-
feedback,
|
|
10592
|
-
inheritedMetadata: this.#rootRecord.metadata
|
|
10593
|
-
}));
|
|
10816
|
+
return Array.from(spanMap.values());
|
|
10594
10817
|
}
|
|
10595
10818
|
};
|
|
10596
|
-
|
|
10597
|
-
|
|
10598
|
-
|
|
10599
|
-
|
|
10600
|
-
|
|
10601
|
-
|
|
10602
|
-
|
|
10603
|
-
|
|
10604
|
-
const recordedSpans = trace.spans.map((raw) => new RecordedSpanImpl({
|
|
10605
|
-
raw,
|
|
10606
|
-
rootSpan,
|
|
10607
|
-
emitRecordedEvent,
|
|
10608
|
-
canEmitRecordedEvent,
|
|
10609
|
-
debugRecordedAnnotationUnavailable
|
|
10610
|
-
}));
|
|
10611
|
-
const spanMap = new Map(recordedSpans.map((span) => [span.id, span]));
|
|
10612
|
-
for (const span of recordedSpans) {
|
|
10613
|
-
if (!span.parentSpanId) continue;
|
|
10614
|
-
const parent = spanMap.get(span.parentSpanId);
|
|
10615
|
-
if (!parent) continue;
|
|
10616
|
-
span.parent = parent;
|
|
10617
|
-
parent.children.push(span);
|
|
10819
|
+
/**
|
|
10820
|
+
* @deprecated Use `TestExporter` instead. This alias will be removed in a future version.
|
|
10821
|
+
*/
|
|
10822
|
+
const JsonExporter = TestExporter;
|
|
10823
|
+
// src/instances/default.ts
|
|
10824
|
+
var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
|
|
10825
|
+
constructor(config) {
|
|
10826
|
+
super(config);
|
|
10618
10827
|
}
|
|
10619
|
-
|
|
10620
|
-
|
|
10621
|
-
|
|
10622
|
-
|
|
10623
|
-
rootSpan: hydratedRootSpan,
|
|
10624
|
-
rootRecord: rootSpan,
|
|
10625
|
-
spans: recordedSpans,
|
|
10626
|
-
emitRecordedEvent,
|
|
10627
|
-
canEmitRecordedEvent,
|
|
10628
|
-
debugRecordedAnnotationUnavailable
|
|
10629
|
-
});
|
|
10630
|
-
}
|
|
10828
|
+
createSpan(options) {
|
|
10829
|
+
return new DefaultSpan(options, this);
|
|
10830
|
+
}
|
|
10831
|
+
};
|
|
10631
10832
|
// src/registry.ts
|
|
10632
10833
|
/**
|
|
10633
10834
|
* Registry for Observability instances.
|
|
@@ -10934,23 +11135,6 @@ function isInstance(obj) {
|
|
|
10934
11135
|
return obj instanceof BaseObservabilityInstance;
|
|
10935
11136
|
}
|
|
10936
11137
|
/**
|
|
10937
|
-
* Delays (ms) between attempts to rehydrate a trace from storage when an
|
|
10938
|
-
* annotation (score/feedback) targets a span that has not been flushed by
|
|
10939
|
-
* the configured exporters yet. Exporters buffer and flush asynchronously:
|
|
10940
|
-
* by default they flush at 1000 spans or after a 5000ms wait
|
|
10941
|
-
* (`maxBatchWaitMs`), so an annotation emitted right after a span ends can
|
|
10942
|
-
* race the flush and be silently dropped. The schedule below sums to
|
|
10943
|
-
* ~5.85s, covering the default flush interval with margin.
|
|
10944
|
-
*/
|
|
10945
|
-
const RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS = [
|
|
10946
|
-
100,
|
|
10947
|
-
250,
|
|
10948
|
-
500,
|
|
10949
|
-
1e3,
|
|
10950
|
-
2e3,
|
|
10951
|
-
2e3
|
|
10952
|
-
];
|
|
10953
|
-
/**
|
|
10954
11138
|
* Manages observability instances and selects their configurations for Mastra operations.
|
|
10955
11139
|
* Configure instances and exporters to collect and export telemetry.
|
|
10956
11140
|
*
|
|
@@ -10977,6 +11161,7 @@ var Observability = class extends _mastra_core_base.MastraBase {
|
|
|
10977
11161
|
#registry = new ObservabilityRegistry();
|
|
10978
11162
|
#mastra;
|
|
10979
11163
|
#clientObservabilityProxy;
|
|
11164
|
+
#pendingPersistedEvents = /* @__PURE__ */ new Set();
|
|
10980
11165
|
constructor(config) {
|
|
10981
11166
|
super({
|
|
10982
11167
|
component: _mastra_core_logger.RegisteredLogger.OBSERVABILITY,
|
|
@@ -11117,50 +11302,47 @@ var Observability = class extends _mastra_core_base.MastraBase {
|
|
|
11117
11302
|
async addScore(args) {
|
|
11118
11303
|
const targetTraceId = args.traceId ?? args.correlationContext?.traceId;
|
|
11119
11304
|
const targetSpanId = args.spanId ?? args.correlationContext?.spanId;
|
|
11120
|
-
if (args.correlationContext)
|
|
11121
|
-
|
|
11122
|
-
|
|
11123
|
-
|
|
11124
|
-
|
|
11125
|
-
score: args.score
|
|
11126
|
-
}));
|
|
11127
|
-
return;
|
|
11128
|
-
}
|
|
11129
|
-
if (!args.traceId) return;
|
|
11130
|
-
const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedScoreEventFromTrace({
|
|
11131
|
-
trace,
|
|
11132
|
-
spanId: args.spanId,
|
|
11133
|
-
score: args.score
|
|
11305
|
+
if (!targetTraceId && !args.correlationContext) return;
|
|
11306
|
+
await this.#emitRecordedEvent(buildScoreEvent({
|
|
11307
|
+
...args,
|
|
11308
|
+
traceId: targetTraceId,
|
|
11309
|
+
spanId: targetSpanId
|
|
11134
11310
|
}));
|
|
11135
|
-
if (!event) {
|
|
11136
|
-
this.logger?.warn(`Score event was dropped because the target trace/span was not found in observability storage (traceId: ${args.traceId}, spanId: ${args.spanId})`);
|
|
11137
|
-
return;
|
|
11138
|
-
}
|
|
11139
|
-
await this.#emitRecordedEvent(event);
|
|
11140
11311
|
}
|
|
11141
11312
|
async addFeedback(args) {
|
|
11142
|
-
const
|
|
11143
|
-
const
|
|
11144
|
-
if (args.correlationContext)
|
|
11145
|
-
|
|
11146
|
-
|
|
11147
|
-
|
|
11148
|
-
|
|
11149
|
-
feedback: args.feedback
|
|
11150
|
-
}));
|
|
11151
|
-
return;
|
|
11152
|
-
}
|
|
11153
|
-
if (!args.traceId) return;
|
|
11154
|
-
const event = await this.#buildRecordedEventWithRetry(args.traceId, (trace) => buildRecordedFeedbackEventFromTrace({
|
|
11155
|
-
trace,
|
|
11156
|
-
spanId: args.spanId,
|
|
11157
|
-
feedback: args.feedback
|
|
11313
|
+
const traceId = args.traceId ?? args.correlationContext?.traceId;
|
|
11314
|
+
const spanId = args.spanId ?? args.correlationContext?.spanId;
|
|
11315
|
+
if (!traceId && !args.correlationContext) return;
|
|
11316
|
+
await this.#emitRecordedEvent(buildFeedbackEvent({
|
|
11317
|
+
...args,
|
|
11318
|
+
traceId,
|
|
11319
|
+
spanId
|
|
11158
11320
|
}));
|
|
11159
|
-
|
|
11160
|
-
|
|
11161
|
-
|
|
11162
|
-
|
|
11163
|
-
|
|
11321
|
+
}
|
|
11322
|
+
async replaceFeedback(args) {
|
|
11323
|
+
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");
|
|
11324
|
+
await this.#emitRecordedEvent({
|
|
11325
|
+
type: "feedback_replacement",
|
|
11326
|
+
feedback: {
|
|
11327
|
+
...args.feedback,
|
|
11328
|
+
traceId: args.traceId,
|
|
11329
|
+
spanId: args.spanId,
|
|
11330
|
+
correlationContext: args.correlationContext
|
|
11331
|
+
}
|
|
11332
|
+
});
|
|
11333
|
+
}
|
|
11334
|
+
/** @internal Queue an HTTP-created record; flush/shutdown await delivery without holding the HTTP response open. */
|
|
11335
|
+
async __exportPersistedEvent(event) {
|
|
11336
|
+
const storageExporters = new Set(this.#getRecordedTraceInstance()?.getExporters().filter(isMastraBuiltInStorageExporter));
|
|
11337
|
+
const pending = this.#emitRecordedEvent(event, (handler) => !storageExporters.has(handler));
|
|
11338
|
+
this.#pendingPersistedEvents.add(pending);
|
|
11339
|
+
pending.then(() => this.#pendingPersistedEvents.delete(pending), (error) => {
|
|
11340
|
+
this.#pendingPersistedEvents.delete(pending);
|
|
11341
|
+
this.logger.error("Failed to notify exporters of persisted feedback/score", {
|
|
11342
|
+
error,
|
|
11343
|
+
eventType: event.type
|
|
11344
|
+
});
|
|
11345
|
+
});
|
|
11164
11346
|
}
|
|
11165
11347
|
/** Register a named observability instance, optionally marking it as default. */
|
|
11166
11348
|
registerInstance(name, instance, isDefault = false) {
|
|
@@ -11197,12 +11379,18 @@ var Observability = class extends _mastra_core_base.MastraBase {
|
|
|
11197
11379
|
}
|
|
11198
11380
|
/** Flush all registered instances without shutting down. */
|
|
11199
11381
|
async flush() {
|
|
11382
|
+
await this.#drainPersistedEvents();
|
|
11200
11383
|
await this.#registry.flush();
|
|
11201
11384
|
}
|
|
11202
11385
|
/** Shut down all registered instances, flushing any pending data. */
|
|
11203
11386
|
async shutdown() {
|
|
11387
|
+
await this.#drainPersistedEvents();
|
|
11204
11388
|
await this.#registry.shutdown();
|
|
11205
11389
|
}
|
|
11390
|
+
/** Let custom handlers finish filling exporter buffers before the instance lifecycle drains them. */
|
|
11391
|
+
async #drainPersistedEvents() {
|
|
11392
|
+
while (this.#pendingPersistedEvents.size > 0) await Promise.allSettled([...this.#pendingPersistedEvents]);
|
|
11393
|
+
}
|
|
11206
11394
|
/**
|
|
11207
11395
|
* Returns the proxy responsible for client observability (W3C trace
|
|
11208
11396
|
* context injection + OTLP/JSON payload reception for spans/logs
|
|
@@ -11224,40 +11412,22 @@ var Observability = class extends _mastra_core_base.MastraBase {
|
|
|
11224
11412
|
if (!storage) return null;
|
|
11225
11413
|
return await storage.getStore("observability") ?? null;
|
|
11226
11414
|
}
|
|
11227
|
-
/**
|
|
11228
|
-
* Build a recorded score/feedback event from storage, retrying briefly to
|
|
11229
|
-
* ride out the async exporter flush: annotations emitted right after a
|
|
11230
|
-
* span ends can otherwise race the flush and be silently dropped.
|
|
11231
|
-
*/
|
|
11232
|
-
async #buildRecordedEventWithRetry(traceId, build) {
|
|
11233
|
-
for (const delayMs of [0, ...RECORDED_TRACE_LOOKUP_RETRY_DELAYS_MS]) {
|
|
11234
|
-
if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
11235
|
-
const trace = await this.#getStoredTrace(traceId);
|
|
11236
|
-
const event = trace ? build(trace) : null;
|
|
11237
|
-
if (event) return event;
|
|
11238
|
-
}
|
|
11239
|
-
return null;
|
|
11240
|
-
}
|
|
11241
|
-
async #getStoredTrace(traceId) {
|
|
11242
|
-
const observabilityStorage = await this.#getObservabilityStorage();
|
|
11243
|
-
if (!observabilityStorage) return null;
|
|
11244
|
-
return observabilityStorage.getTrace({ traceId });
|
|
11245
|
-
}
|
|
11246
11415
|
#getRecordedTraceInstance() {
|
|
11247
11416
|
return this.getDefaultInstance() ?? Array.from(this.listInstances().values())[0];
|
|
11248
11417
|
}
|
|
11249
|
-
|
|
11418
|
+
/** Dispatch independently; the standard bus tracks delivery, while custom instances return handler promises. */
|
|
11419
|
+
async #emitRecordedEvent(event, shouldHandle) {
|
|
11250
11420
|
const instance = this.#getRecordedTraceInstance();
|
|
11251
11421
|
if (!instance) {
|
|
11252
11422
|
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 });
|
|
11253
11423
|
return;
|
|
11254
11424
|
}
|
|
11255
11425
|
if (instance instanceof BaseObservabilityInstance) {
|
|
11256
|
-
instance.__emitRecordedEvent(event);
|
|
11426
|
+
instance.__emitRecordedEvent(event, shouldHandle);
|
|
11257
11427
|
return;
|
|
11258
11428
|
}
|
|
11259
11429
|
const bridge = instance.getBridge();
|
|
11260
|
-
const handlerResults = [...instance.getExporters().map((exporter) => routeToHandler(exporter, event, this.logger)), ...bridge ? [routeToHandler(bridge, event, this.logger)] : []].filter((result) => !!result && typeof result.then === "function");
|
|
11430
|
+
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");
|
|
11261
11431
|
if (handlerResults.length > 0) await Promise.allSettled(handlerResults);
|
|
11262
11432
|
}
|
|
11263
11433
|
};
|