-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathinternal.ts
More file actions
220 lines (185 loc) · 7.9 KB
/
internal.ts
File metadata and controls
220 lines (185 loc) · 7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { safeSetAttribute, serializeAttributes } from '../attributes';
import { getGlobalSingleton } from '../carrier';
import type { Client } from '../client';
import { getClient, getCurrentScope } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';
import type { Scope } from '../scope';
import type { Integration } from '../types-hoist/integration';
import type { Metric, SerializedMetric } from '../types-hoist/metric';
import type { User } from '../types-hoist/user';
import { debug } from '../utils/debug-logger';
import { getFinalScopeData } from '../utils/scope-utils';
import { _getSpanForScope } from '../utils/spanOnScope';
import { timestampInSeconds } from '../utils/time';
import { _getTraceInfoFromScope } from '../utils/trace-info';
import { createMetricEnvelope } from './envelope';
const MAX_METRIC_BUFFER_SIZE = 1000;
/**
* 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.
*/
export function _INTERNAL_captureSerializedMetric(client: Client, serializedMetric: SerializedMetric): void {
const bufferMap = _getBufferMap();
const metricBuffer = _INTERNAL_getMetricBuffer(client);
if (metricBuffer === undefined) {
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]);
}
}
}
/**
* Options for capturing a metric internally.
*/
export interface InternalCaptureMetricOptions {
/**
* The scope to capture the metric with.
*/
scope?: Scope;
/**
* A function to capture the serialized metric.
*/
captureSerializedMetric?: (client: Client, metric: SerializedMetric) => void;
}
/**
* Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)
*/
function _enrichMetricAttributes(beforeMetric: Metric, client: Client, user: User): Metric {
const { release, environment } = client.getOptions();
const processedMetricAttributes = {
...beforeMetric.attributes,
};
const { id, email, username } = user;
safeSetAttribute(processedMetricAttributes, 'user.id', id, false);
safeSetAttribute(processedMetricAttributes, 'user.email', email, false);
safeSetAttribute(processedMetricAttributes, 'user.name', username, false);
// Add Sentry metadata
safeSetAttribute(processedMetricAttributes, 'sentry.release', release);
safeSetAttribute(processedMetricAttributes, 'sentry.environment', environment);
// Add SDK metadata
const { name, version } = client.getSdkMetadata()?.sdk ?? {};
safeSetAttribute(processedMetricAttributes, 'sentry.sdk.name', name);
safeSetAttribute(processedMetricAttributes, 'sentry.sdk.version', version);
// Add replay metadata
const replay = client.getIntegrationByName<
Integration & {
getReplayId: (onlyIfSampled?: boolean) => string;
getRecordingMode: () => 'session' | 'buffer' | undefined;
}
>('Replay');
const replayId = replay?.getReplayId(true);
safeSetAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);
if (replayId && replay?.getRecordingMode() === 'buffer') {
safeSetAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);
}
return {
...beforeMetric,
attributes: processedMetricAttributes,
};
}
/**
* 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.
*/
export function _INTERNAL_captureMetric(beforeMetric: Metric, options?: InternalCaptureMetricOptions): void {
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 { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();
// todo(v11): Remove the experimental flag
// eslint-disable-next-line deprecation/deprecation
const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;
if (!metricsEnabled) {
DEBUG_BUILD && debug.warn('metrics option not enabled, metric will not be captured.');
return;
}
const { user, attributes: scopeAttributes } = getFinalScopeData(currentScope);
// Enrich metric with contextual attributes
const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, user);
client.emit('processMetric', enrichedMetric);
// todo(v11): Remove the experimental `beforeSendMetric`
// eslint-disable-next-line deprecation/deprecation
const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;
const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;
if (!processedMetric) {
DEBUG_BUILD && debug.log('`beforeSendMetric` returned `null`, will not send metric.');
return;
}
const [, traceContext] = _getTraceInfoFromScope(client, currentScope);
const span = _getSpanForScope(currentScope);
const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;
const spanId = span ? span.spanContext().spanId : undefined;
const { name, type, unit, value, attributes: metricAttributes } = processedMetric;
const serializedMetric = {
timestamp: timestampInSeconds(),
trace_id: traceId ?? '',
span_id: spanId,
name,
type,
unit,
value,
attributes: {
...serializeAttributes(metricAttributes, true),
...serializeAttributes(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.
*/
export function _INTERNAL_flushMetricsBuffer(client: Client, maybeMetricBuffer?: Array<SerializedMetric>): void {
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());
// Clear the metric buffer after envelopes have been constructed.
_getBufferMap().set(client, []);
client.emit('flushMetrics');
// sendEnvelope should not throw
// eslint-disable-next-line @typescript-eslint/no-floating-promises
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.
*/
export function _INTERNAL_getMetricBuffer(client: Client): Array<SerializedMetric> | undefined {
return _getBufferMap().get(client);
}
function _getBufferMap(): WeakMap<Client, Array<SerializedMetric>> {
// The reference to the Client <> MetricBuffer map is stored on the carrier to ensure it's always the same
return getGlobalSingleton('clientToMetricBufferMap', () => new WeakMap<Client, Array<SerializedMetric>>());
}