@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
138 lines (137 loc) • 5.57 kB
JavaScript
import { DEBUG_BUILD } from "../../debug-build.js";
import { debug } from "../../utils/debug-logger.js";
import { spanToJSON } from "../../utils/spanUtils.js";
import { safeUnref } from "../../utils/timer.js";
import { freezeDscOnSpan, getDynamicSamplingContextFromSpan } from "../dynamicSamplingContext.js";
import { createStreamedSpanEnvelope } from "./envelope.js";
import { estimateSerializedSpanSizeInBytes } from "./estimateSize.js";
import { SENTRY_SEGMENT_NAME } from "@sentry/conventions/attributes";
// src/tracing/spans/spanBuffer.ts
/**
* We must not send more than 1000 spans in one envelope.
* Otherwise the envelope is dropped by Relay.
*/
const MAX_SPANS_PER_ENVELOPE = 1e3;
const MAX_TRACE_WEIGHT_IN_BYTES = 5e6;
/**
* A buffer for serialized streamed span JSON objects that flushes them to Sentry in Span v2 envelopes.
* Handles per-trace timeout-based flushing, size thresholds, and graceful shutdown.
* Also handles computation of the Dynamic Sampling Context (DSC) for the trace, if it wasn't yet
* frozen onto the segment span.
*
* For this, we need the reference to the segment span instance, from
* which we compute the DSC. Doing this in the buffer ensures that we compute the DSC as late as possible,
* allowing span name and data updates up to this point. Worth noting here that the segment span is likely
* still active and modifyable when child spans are added to the buffer.
*/
var SpanBuffer = class {
constructor(client, options) {
this._traceBuckets = /* @__PURE__ */ new Map();
this._client = client;
const { maxSpanLimit, flushInterval, maxTraceWeightInBytes } = options ?? {};
this._maxSpanLimit = maxSpanLimit && maxSpanLimit > 0 && maxSpanLimit <= MAX_SPANS_PER_ENVELOPE ? maxSpanLimit : MAX_SPANS_PER_ENVELOPE;
this._flushInterval = flushInterval && flushInterval > 0 ? flushInterval : 5e3;
this._maxTraceWeight = maxTraceWeightInBytes && maxTraceWeightInBytes > 0 ? maxTraceWeightInBytes : MAX_TRACE_WEIGHT_IN_BYTES;
this._client.on("flush", () => {
this.drain();
});
this._client.on("close", () => {
this._traceBuckets.forEach((bucket) => {
clearTimeout(bucket.timeout);
});
this._traceBuckets.clear();
});
}
/**
* Add a span to the buffer.
*/
add(spanJSON) {
const traceId = spanJSON.trace_id;
let bucket = this._traceBuckets.get(traceId);
if (!bucket) {
bucket = {
spans: /* @__PURE__ */ new Set(),
size: 0,
timeout: safeUnref(setTimeout(() => {
this.flush(traceId);
}, this._flushInterval))
};
this._traceBuckets.set(traceId, bucket);
}
bucket.spans.add(spanJSON);
bucket.size += estimateSerializedSpanSizeInBytes(spanJSON);
if (bucket.spans.size >= this._maxSpanLimit || bucket.size >= this._maxTraceWeight) this.flush(traceId);
}
/**
* Drain and flush all buffered traces.
*/
drain() {
if (!this._traceBuckets.size) return;
DEBUG_BUILD && debug.log(`Flushing span tree map with ${this._traceBuckets.size} traces`);
this._traceBuckets.forEach((_, traceId) => {
this.flush(traceId);
});
}
/**
* Flush spans of a specific trace.
* In contrast to {@link SpanBuffer.drain}, this method does not flush all traces, but only the one with the given traceId.
*/
flush(traceId) {
const bucket = this._traceBuckets.get(traceId);
if (!bucket) return;
if (!bucket.spans.size) {
this._removeTrace(traceId);
return;
}
const spans = Array.from(bucket.spans);
const segmentSpan = spans[0]?._segmentSpan;
if (!segmentSpan) {
DEBUG_BUILD && debug.warn("No segment span reference found on span JSON, cannot compute DSC");
this._removeTrace(traceId);
return;
}
const dsc = getDynamicSamplingContextFromSpan(segmentSpan);
freezeDscOnSpan(segmentSpan, dsc);
const currentSegmentNames = /* @__PURE__ */ new Map();
const getCurrentSegmentName = (span) => {
let name = currentSegmentNames.get(span);
if (name === void 0) {
name = spanToJSON(span).name;
currentSegmentNames.set(span, name);
}
return name;
};
const cleanedSpans = spans.map((spanJSON) => {
const { _segmentSpan, _segmentNameAtCapture, ...cleanSpanJSON } = spanJSON;
refreshSegmentName(cleanSpanJSON, _segmentNameAtCapture, () => getCurrentSegmentName(_segmentSpan));
return cleanSpanJSON;
});
const envelope = createStreamedSpanEnvelope(cleanedSpans, dsc, this._client);
DEBUG_BUILD && debug.log(`Sending span envelope for trace ${traceId} with ${cleanedSpans.length} spans`);
this._client.sendEnvelope(envelope).then(null, (reason) => {
DEBUG_BUILD && debug.error("Error while sending streamed span envelope:", reason);
});
this._removeTrace(traceId);
}
_removeTrace(traceId) {
const bucket = this._traceBuckets.get(traceId);
if (bucket) clearTimeout(bucket.timeout);
this._traceBuckets.delete(traceId);
}
};
/**
* Spans are captured when they end, but the segment span can still be renamed afterwards
* (e.g. once the route is known). Only replace the value we set at capture time, so that
* values set by users or `beforeSendSpan` are kept.
*/
function refreshSegmentName(spanJSON, segmentNameAtCapture, getCurrentSegmentName) {
const segmentNameAttribute = spanJSON.attributes[SENTRY_SEGMENT_NAME];
if (segmentNameAtCapture === void 0 || segmentNameAttribute?.value !== segmentNameAtCapture) return;
const currentSegmentName = getCurrentSegmentName();
if (currentSegmentName !== segmentNameAtCapture) spanJSON.attributes[SENTRY_SEGMENT_NAME] = {
...segmentNameAttribute,
value: currentSegmentName
};
}
export { SpanBuffer };
//# sourceMappingURL=spanBuffer.js.map