@sentry/core
Version:
Base implementation for all Sentry JavaScript SDKs
166 lines (165 loc) • 7.93 kB
JavaScript
import { serializeAttributes } from "../attributes.js";
import { getGlobalSingleton } from "../carrier.js";
import { getClient, getCurrentScope, getIsolationScope } from "../currentScopes.js";
import { DEBUG_BUILD } from "../debug-build.js";
import { debug } from "../utils/debug-logger.js";
import { CALLBACK_ERROR, safeCallback } from "../utils/safeCallback.js";
import { getCombinedScopeData } from "../utils/scopeData.js";
import { getActiveSpan } from "../utils/spanUtils.js";
import { timestampInSeconds } from "../utils/time.js";
import { getSequenceAttribute } from "../utils/timestampSequence.js";
import { _getTraceInfoFromScope } from "../utils/trace-info.js";
import { estimateMetricSizeInBytes, setupWeightBasedFlushing } from "../utils/weightBasedFlushing.js";
import { createMetricEnvelope } from "./envelope.js";
import { SENTRY_ENVIRONMENT, SENTRY_RELEASE, SENTRY_REPLAY_ID, SENTRY_SDK_NAME, SENTRY_SDK_VERSION, USER_EMAIL, USER_ID, USER_NAME } from "@sentry/conventions/attributes";
// src/metrics/internal.ts
const MAX_METRIC_BUFFER_SIZE = 1e3;
/**
* Sets a metric attribute if the value exists and the attribute key is not already present.
*
* @param metricAttributes - The metric attributes object to modify.
* @param key - The attribute key to set.
* @param value - The value to set (only sets if truthy and key not present).
* @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.
*/
function setMetricAttribute(metricAttributes, key, value, setEvenIfPresent = true) {
if (value && (setEvenIfPresent || !(key in metricAttributes))) metricAttributes[key] = value;
}
/**
* Captures a serialized metric event and adds it to the metric buffer for the given client.
*
* @param client - A client. Uses the current client if not provided.
* @param serializedMetric - The serialized metric event to capture.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureSerializedMetric(client, serializedMetric) {
const bufferMap = _getBufferMap();
const metricBuffer = _INTERNAL_getMetricBuffer(client);
if (metricBuffer === void 0) {
setupWeightBasedFlushing(client, "afterCaptureMetric", "flushMetrics", estimateMetricSizeInBytes, _INTERNAL_flushMetricsBuffer);
bufferMap.set(client, [serializedMetric]);
} else if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {
_INTERNAL_flushMetricsBuffer(client, metricBuffer);
bufferMap.set(client, [serializedMetric]);
} else bufferMap.set(client, [...metricBuffer, serializedMetric]);
}
/**
* Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)
*/
function _enrichMetricAttributes(beforeMetric, client, user) {
const { release, environment } = client.getOptions();
const processedMetricAttributes = { ...beforeMetric.attributes };
setMetricAttribute(processedMetricAttributes, USER_ID, user.id, false);
setMetricAttribute(processedMetricAttributes, USER_EMAIL, user.email, false);
setMetricAttribute(processedMetricAttributes, USER_NAME, user.username, false);
setMetricAttribute(processedMetricAttributes, SENTRY_RELEASE, release);
setMetricAttribute(processedMetricAttributes, SENTRY_ENVIRONMENT, environment);
const { name, version } = client.getSdkMetadata()?.sdk ?? {};
setMetricAttribute(processedMetricAttributes, SENTRY_SDK_NAME, name);
setMetricAttribute(processedMetricAttributes, SENTRY_SDK_VERSION, version);
const replay = client.getIntegrationByName("Replay");
const replayId = replay?.getReplayId(true);
setMetricAttribute(processedMetricAttributes, SENTRY_REPLAY_ID, replayId);
if (replayId && replay?.getRecordingMode() === "buffer") setMetricAttribute(processedMetricAttributes, "sentry._internal.replay_is_buffering", true);
return {
...beforeMetric,
attributes: processedMetricAttributes
};
}
/**
* Creates a serialized metric ready to be sent to Sentry.
*/
function _buildSerializedMetric(metric, client, currentScope, scopeAttributes) {
const [, traceContext] = _getTraceInfoFromScope(client, currentScope);
const span = getActiveSpan(currentScope);
const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;
const spanId = span ? span.spanContext().spanId : void 0;
const timestamp = timestampInSeconds();
const sequenceAttr = getSequenceAttribute(timestamp);
return {
timestamp,
trace_id: traceId ?? "",
span_id: spanId,
name: metric.name,
type: metric.type,
unit: metric.unit,
value: metric.value,
attributes: {
...serializeAttributes(scopeAttributes),
...serializeAttributes(metric.attributes, "skip-undefined"),
[sequenceAttr.key]: sequenceAttr.value
}
};
}
/**
* Captures a metric event and sends it to Sentry.
*
* @param metric - The metric event to capture.
* @param options - Options for capturing the metric.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_captureMetric(beforeMetric, options) {
const currentScope = options?.scope ?? getCurrentScope();
const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;
const client = currentScope?.getClient() ?? getClient();
if (!client) {
DEBUG_BUILD && debug.warn("No client available to capture metric.");
return;
}
const { beforeSendMetric } = client.getOptions();
const { user, attributes: scopeAttributes } = getCombinedScopeData(getIsolationScope(), currentScope);
const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);
client.emit("processMetric", enrichedMetric);
const processedMetric = beforeSendMetric ? safeCallback(DEBUG_BUILD ? "The `beforeSendMetric` callback threw an error, dropping the metric:" : "", () => beforeSendMetric(enrichedMetric), () => CALLBACK_ERROR) : enrichedMetric;
if (processedMetric === CALLBACK_ERROR) {
client.recordDroppedEvent("callback_error", "trace_metric", 1);
return;
}
if (!processedMetric) {
client.recordDroppedEvent("before_send", "trace_metric", 1);
DEBUG_BUILD && debug.log("`beforeSendMetric` returned `null`, will not send metric.");
return;
}
const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope, scopeAttributes);
DEBUG_BUILD && debug.log("[Metric]", serializedMetric);
captureSerializedMetric(client, serializedMetric);
client.emit("afterCaptureMetric", processedMetric);
}
/**
* Flushes the metrics buffer to Sentry.
*
* @param client - A client.
* @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.
*
* @experimental This method will experience breaking changes. This is not yet part of
* the stable Sentry SDK API and can be changed or removed without warning.
*/
function _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) {
const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];
if (metricBuffer.length === 0) return;
const clientOptions = client.getOptions();
const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn(), client.getDataCollectionOptions().userInfo);
_getBufferMap().set(client, []);
client.emit("flushMetrics");
client.sendEnvelope(envelope);
}
/**
* Returns the metric buffer for a given client.
*
* Exported for testing purposes.
*
* @param client - The client to get the metric buffer for.
* @returns The metric buffer for the given client.
*/
function _INTERNAL_getMetricBuffer(client) {
return _getBufferMap().get(client);
}
function _getBufferMap() {
return getGlobalSingleton("clientToMetricBufferMap", () => /* @__PURE__ */ new WeakMap());
}
export { _INTERNAL_captureMetric, _INTERNAL_captureSerializedMetric, _INTERNAL_flushMetricsBuffer, _INTERNAL_getMetricBuffer };
//# sourceMappingURL=internal.js.map