forked from getsentry/sentry-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhubextensions.ts
228 lines (208 loc) · 8.2 KB
/
hubextensions.ts
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
221
222
223
224
225
226
227
228
import type { ClientOptions, CustomSamplingContext, Options, SamplingContext, TransactionContext } from '@sentry/types';
import { isNaN, logger } from '@sentry/utils';
import type { Hub } from '../';
import { getMainCarrier } from '../';
import { IdleTransaction } from './idletransaction';
import { Transaction } from './transaction';
import { hasTracingEnabled } from './utils';
/** Returns all trace headers that are currently on the top scope. */
function traceHeaders(this: Hub): { [key: string]: string } {
const scope = this.getScope();
if (scope) {
const span = scope.getSpan();
if (span) {
return {
'sentry-trace': span.toTraceparent(),
};
}
}
return {};
}
/**
* Makes a sampling decision for the given transaction and stores it on the transaction.
*
* Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be
* sent to Sentry.
*
* @param transaction: The transaction needing a sampling decision
* @param options: The current client's options, so we can access `tracesSampleRate` and/or `tracesSampler`
* @param samplingContext: Default and user-provided data which may be used to help make the decision
*
* @returns The given transaction with its `sampled` value set
*/
function sample<T extends Transaction>(
transaction: T,
options: Pick<Options, 'tracesSampleRate' | 'tracesSampler'>,
samplingContext: SamplingContext,
): T {
// nothing to do if tracing is not enabled
if (!hasTracingEnabled(options)) {
transaction.sampled = false;
return transaction;
}
// if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that
if (transaction.sampled !== undefined) {
transaction.setMetadata({
sampleRate: Number(transaction.sampled),
});
return transaction;
}
// we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should
// work; prefer the hook if so
let sampleRate;
if (typeof options.tracesSampler === 'function') {
sampleRate = options.tracesSampler(samplingContext);
transaction.setMetadata({
sampleRate: Number(sampleRate),
});
} else if (samplingContext.parentSampled !== undefined) {
sampleRate = samplingContext.parentSampled;
} else {
sampleRate = options.tracesSampleRate;
transaction.setMetadata({
sampleRate: Number(sampleRate),
});
}
// Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The
// only valid values are booleans or numbers between 0 and 1.)
if (!isValidSampleRate(sampleRate)) {
__DEBUG_BUILD__ && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');
transaction.sampled = false;
return transaction;
}
// if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped
if (!sampleRate) {
__DEBUG_BUILD__ &&
logger.log(
`[Tracing] Discarding transaction because ${
typeof options.tracesSampler === 'function'
? 'tracesSampler returned 0 or false'
: 'a negative sampling decision was inherited or tracesSampleRate is set to 0'
}`,
);
transaction.sampled = false;
return transaction;
}
// Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is
// a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.
transaction.sampled = Math.random() < (sampleRate as number | boolean);
// if we're not going to keep it, we're done
if (!transaction.sampled) {
__DEBUG_BUILD__ &&
logger.log(
`[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(
sampleRate,
)})`,
);
return transaction;
}
__DEBUG_BUILD__ && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);
return transaction;
}
/**
* Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).
*/
function isValidSampleRate(rate: unknown): boolean {
// we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {
__DEBUG_BUILD__ &&
logger.warn(
`[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(
rate,
)} of type ${JSON.stringify(typeof rate)}.`,
);
return false;
}
// in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false
if (rate < 0 || rate > 1) {
__DEBUG_BUILD__ &&
logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);
return false;
}
return true;
}
/**
* Creates a new transaction and adds a sampling decision if it doesn't yet have one.
*
* The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if
* it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an
* "extension method."
*
* @param this: The Hub starting the transaction
* @param transactionContext: Data used to configure the transaction
* @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)
*
* @returns The new transaction
*
* @see {@link Hub.startTransaction}
*/
function _startTransaction(
this: Hub,
transactionContext: TransactionContext,
customSamplingContext?: CustomSamplingContext,
): Transaction {
const client = this.getClient();
const options: Partial<ClientOptions> = (client && client.getOptions()) || {};
const configInstrumenter = options.instrumenter || 'sentry';
const transactionInstrumenter = transactionContext.instrumenter || 'sentry';
if (configInstrumenter !== transactionInstrumenter) {
__DEBUG_BUILD__ &&
logger.error(
`A transaction was started with instrumenter=\`${transactionInstrumenter}\`, but the SDK is configured with the \`${configInstrumenter}\` instrumenter.
The transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,
);
transactionContext.sampled = false;
}
let transaction = new Transaction(transactionContext, this);
transaction = sample(transaction, options, {
parentSampled: transactionContext.parentSampled,
transactionContext,
...customSamplingContext,
});
if (transaction.sampled) {
transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));
}
return transaction;
}
/**
* Create new idle transaction.
*/
export function startIdleTransaction(
hub: Hub,
transactionContext: TransactionContext,
idleTimeout: number,
finalTimeout: number,
onScope?: boolean,
customSamplingContext?: CustomSamplingContext,
heartbeatInterval?: number,
): IdleTransaction {
const client = hub.getClient();
const options: Partial<ClientOptions> = (client && client.getOptions()) || {};
let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);
transaction = sample(transaction, options, {
parentSampled: transactionContext.parentSampled,
transactionContext,
...customSamplingContext,
});
if (transaction.sampled) {
transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans as number));
}
return transaction;
}
/**
* Adds tracing extensions to the global hub.
*/
export function addTracingExtensions(): void {
const carrier = getMainCarrier();
if (!carrier.__SENTRY__) {
return;
}
carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};
if (!carrier.__SENTRY__.extensions.startTransaction) {
carrier.__SENTRY__.extensions.startTransaction = _startTransaction;
}
if (!carrier.__SENTRY__.extensions.traceHeaders) {
carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;
}
}